ANNFileDetect.EditNet.java Source code

Java tutorial

Introduction

Here is the source code for ANNFileDetect.EditNet.java

Source

/*
 * Copyright 2013 ragnar0k@fabytes.com.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package ANNFileDetect;

/**
 *
 * @author ragnar0k@fabytes.com
 */

import com.almworks.sqlite4java.SQLiteException;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Point;
import java.awt.geom.Rectangle2D;
import java.io.IOException;
import java.util.HashMap;
import java.util.TreeMap;
import java.util.concurrent.CountDownLatch;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.DefaultListModel;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import org.jfree.chart.ChartMouseEvent;
import org.jfree.chart.ChartMouseListener;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.XYPlot;
import org.jfree.data.xy.XYDataset;
import org.jfree.ui.RectangleEdge;

public class EditNet extends javax.swing.JFrame {

    private static SQLiteLib sqlite;
    private static String nDir;
    private String dir = "";
    double lastx;
    double lasty;
    int trainStatus = 0;
    String sqlFile;
    ChartPanel chdisp;
    EditNet en = this;

    /**
     * Creates new form EditNet
     */
    public EditNet(SQLiteLib sql, String networkDir) {
        initComponents();
        sqlite = sql;
        nDir = networkDir;
        sqlFile = sql.getDBFile();
        populateList();

    }

    public int getTrainStatus() {
        return trainStatus;
    }

    public void populateList() {
        String[] nnames = new String[] { "" };
        nnames = sqlite.GetNetworkNames();
        DefaultListModel mdl = new DefaultListModel();
        for (int i = 0; i < nnames.length; i++) {
            mdl.add(i, nnames[i]);
        }
        NetList.setModel(mdl);
        NetList.addListSelectionListener(new ListSelectionListener() {

            public void valueChanged(ListSelectionEvent evt) {
                if (evt.getValueIsAdjusting()) {
                    return;
                } else {
                    String[] images = {};
                    try {
                        images = sqlite.GetImagesForNetwork(NetList.getSelectedValue().toString());
                    } catch (Exception e) {
                        System.out.println("exception: " + e.toString());
                    }
                    DefaultListModel mdl2 = new DefaultListModel();
                    if (images.length > 0) {
                        for (int i = 0; i < images.length; i++) {
                            mdl2.add(i, images[i]);
                        }
                    } else {
                        mdl2.clear();
                        thresholdList.setModel(mdl2);
                    }
                    fileList.setModel(mdl2);
                }
            }
        });
        fileList.addListSelectionListener(new ListSelectionListener() {

            public void valueChanged(ListSelectionEvent evt) {
                if (evt.getValueIsAdjusting()) {
                    return;
                } else {
                    String[] thresh = sqlite.GetThresholds(NetList.getSelectedValue().toString(),
                            fileList.getSelectedValue().toString());
                    DefaultListModel mdl3 = new DefaultListModel();
                    if (thresh.length > 0) {
                        for (int i = 0; i < thresh.length; i++) {
                            String[] vals = thresh[i].split(",");
                            mdl3.add(i, "Range: " + vals[0] + "-" + vals[1] + " Score: " + vals[3] + " Weight: "
                                    + vals[2]);
                        }
                    } else {
                        mdl3.clear();
                    }
                    thresholdList.setModel(mdl3);
                }

            }
        });

    }

    /**
     * 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() {

        GraphPanel = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        NetList = new javax.swing.JList();
        DeleteNet = new javax.swing.JButton();
        TestContents = new javax.swing.JButton();
        jScrollPane2 = new javax.swing.JScrollPane();
        fileList = new javax.swing.JList();
        deleteType = new javax.swing.JButton();
        addType = new javax.swing.JButton();
        jScrollPane3 = new javax.swing.JScrollPane();
        thresholdList = new javax.swing.JList();
        addThreshold = new javax.swing.JButton();
        deleteThreshold = new javax.swing.JButton();
        modifyThreshold = new javax.swing.JButton();
        TrainBTN = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        javax.swing.GroupLayout GraphPanelLayout = new javax.swing.GroupLayout(GraphPanel);
        GraphPanel.setLayout(GraphPanelLayout);
        GraphPanelLayout.setHorizontalGroup(GraphPanelLayout
                .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGap(0, 0, Short.MAX_VALUE));
        GraphPanelLayout.setVerticalGroup(GraphPanelLayout
                .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGap(0, 285, Short.MAX_VALUE));

        NetList.setModel(new javax.swing.AbstractListModel() {
            String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };

            public int getSize() {
                return strings.length;
            }

            public Object getElementAt(int i) {
                return strings[i];
            }
        });
        jScrollPane1.setViewportView(NetList);

        DeleteNet.setText("Delete Net");
        DeleteNet.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                DeleteNetActionPerformed(evt);
            }
        });

        TestContents.setText("Test Dir Contents");
        TestContents.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                TestContentsActionPerformed(evt);
            }
        });

        jScrollPane2.setViewportView(fileList);

        deleteType.setText("Delete File Type");
        deleteType.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                deleteTypeActionPerformed(evt);
            }
        });

        addType.setText("Add File Type");
        addType.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                addTypeActionPerformed(evt);
            }
        });

        jScrollPane3.setViewportView(thresholdList);

        addThreshold.setText("Add threshold");
        addThreshold.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                addThresholdActionPerformed(evt);
            }
        });

        deleteThreshold.setText("Delete threshold");
        deleteThreshold.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                deleteThresholdActionPerformed(evt);
            }
        });

        modifyThreshold.setText("Modify threshold");
        modifyThreshold.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                modifyThresholdActionPerformed(evt);
            }
        });

        TrainBTN.setText("Add Training");
        TrainBTN.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                TrainBTNActionPerformed(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)
                        .addComponent(GraphPanel, javax.swing.GroupLayout.DEFAULT_SIZE,
                                javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addGroup(layout.createSequentialGroup().addContainerGap()
                                .addGroup(layout
                                        .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                        .addComponent(jScrollPane1)
                                        .addComponent(TestContents, javax.swing.GroupLayout.DEFAULT_SIZE, 294,
                                                Short.MAX_VALUE)
                                        .addGroup(layout.createSequentialGroup()
                                                .addComponent(DeleteNet, javax.swing.GroupLayout.PREFERRED_SIZE,
                                                        139, javax.swing.GroupLayout.PREFERRED_SIZE)
                                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                                .addComponent(TrainBTN, javax.swing.GroupLayout.DEFAULT_SIZE,
                                                        javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                                .addGap(26, 26, 26)
                                .addGroup(layout
                                        .createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                        .addComponent(deleteType, javax.swing.GroupLayout.Alignment.LEADING,
                                                javax.swing.GroupLayout.DEFAULT_SIZE, 196, Short.MAX_VALUE)
                                        .addComponent(jScrollPane2, javax.swing.GroupLayout.Alignment.LEADING,
                                                javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
                                        .addComponent(addType, javax.swing.GroupLayout.DEFAULT_SIZE,
                                                javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                                .addGap(18, 18, 18)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                        .addComponent(jScrollPane3, javax.swing.GroupLayout.Alignment.TRAILING)
                                        .addGroup(layout.createSequentialGroup().addGroup(layout
                                                .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING,
                                                        false)
                                                .addGroup(layout.createSequentialGroup()
                                                        .addComponent(addThreshold,
                                                                javax.swing.GroupLayout.PREFERRED_SIZE, 234,
                                                                javax.swing.GroupLayout.PREFERRED_SIZE)
                                                        .addPreferredGap(
                                                                javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                                        .addComponent(deleteThreshold,
                                                                javax.swing.GroupLayout.PREFERRED_SIZE, 238,
                                                                javax.swing.GroupLayout.PREFERRED_SIZE))
                                                .addComponent(modifyThreshold, javax.swing.GroupLayout.DEFAULT_SIZE,
                                                        javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                                                .addGap(0, 4, Short.MAX_VALUE)))))
                        .addContainerGap()));
        layout.setVerticalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(
                javax.swing.GroupLayout.Alignment.TRAILING,
                layout.createSequentialGroup().addContainerGap()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 293,
                                        Short.MAX_VALUE)
                                .addComponent(jScrollPane2).addComponent(jScrollPane3))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(DeleteNet).addComponent(deleteType).addComponent(addThreshold)
                                .addComponent(deleteThreshold).addComponent(TrainBTN))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(TestContents).addComponent(addType).addComponent(modifyThreshold))
                        .addGap(18, 18, 18)
                        .addComponent(GraphPanel, javax.swing.GroupLayout.PREFERRED_SIZE,
                                javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addContainerGap()));

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void DeleteNetActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_DeleteNetActionPerformed
        String selected = NetList.getSelectedValue().toString();
        String networkFile = sqlite.GetNetworkFile(selected);
        String networkFPFile = sqlite.GetNetworkFPFile(selected);
        new FileOperations().removeFile(nDir + "/" + networkFile);
        new FileOperations().removeFile(nDir + "/" + networkFPFile);
        sqlite.deleteNN(selected);
        populateList();
    }//GEN-LAST:event_DeleteNetActionPerformed

    private void TestContentsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_TestContentsActionPerformed
        new Thread(new TrainDir()).start();
    }//GEN-LAST:event_TestContentsActionPerformed

    private void addTypeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addTypeActionPerformed
        new Thread(new ThreshEdit(this, true, NetList.getSelectedValue().toString(), "", "", sqlite)).start();
    }//GEN-LAST:event_addTypeActionPerformed

    private void deleteTypeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deleteTypeActionPerformed
        String net = NetList.getSelectedValue().toString();
        String fileType = fileList.getSelectedValue().toString();
        sqlite.deleteFiletypeFromNet(fileType, net);
        populateList();
    }//GEN-LAST:event_deleteTypeActionPerformed

    private void deleteThresholdActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deleteThresholdActionPerformed
        String net = NetList.getSelectedValue().toString();
        String fileType = fileList.getSelectedValue().toString();
        String[] thtmp = thresholdList.getSelectedValue().toString().split("\\s");
        String[] stEnd = thtmp[1].split("-");
        sqlite.deleteSingleThreshold(fileType, net, stEnd[0], stEnd[1]);
        populateList();
    }//GEN-LAST:event_deleteThresholdActionPerformed

    private void addThresholdActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addThresholdActionPerformed
        new Thread(new ThreshEdit(this, false, NetList.getSelectedValue().toString(),
                fileList.getSelectedValue().toString(), "", sqlite)).start();
    }//GEN-LAST:event_addThresholdActionPerformed

    private void modifyThresholdActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_modifyThresholdActionPerformed
        new Thread(new ThreshEdit(this, false, NetList.getSelectedValue().toString(),
                fileList.getSelectedValue().toString(), thresholdList.getSelectedValue().toString(), sqlite))
                        .start();
    }//GEN-LAST:event_modifyThresholdActionPerformed

    private void TrainBTNActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_TrainBTNActionPerformed

        new Thread(new TrainNet()).start();
    }//GEN-LAST:event_TrainBTNActionPerformed

    private class TrainNet implements Runnable {
        CountDownLatch ctd;

        public void run() {
            String desTresh = JOptionPane.showInputDialog(null, "What is the threshold?",
                    "Enter the threshold (empty = 0.2)", JOptionPane.QUESTION_MESSAGE);
            if (desTresh.length() < 1)
                desTresh = "0.2";
            ctd = new CountDownLatch(1);
            SelectFiles sf = new SelectFiles(ctd);
            sf.setVisible(true);
            try {
                ctd.await();
            } catch (InterruptedException ex) {
                ex.printStackTrace();
            }
            dir = sf.returnSelected();
            sf.dispose();
            SQLiteLib sqli = new SQLiteLib(sqlFile);
            NNCreate nnc = new NNCreate(NetList.getSelectedValue().toString(), dir, nDir, sqli,
                    Double.parseDouble(desTresh));
        }
    }

    private class TrainDir implements Runnable {

        CountDownLatch ctd;

        public void run() {
            ctd = new CountDownLatch(1);
            SelectFiles sf = new SelectFiles(ctd);
            sf.setVisible(true);
            try {
                ctd.await();
            } catch (InterruptedException ex) {
                ex.printStackTrace();
            }
            dir = sf.returnSelected();
            sf.dispose();
            new Thread(new WaitBar(en)).start();
            String sqlFile = sqlite.getDBFile();
            SQLiteLib threadLib = new SQLiteLib(sqlFile);
            new FileOperations().createDirOrRemoveContents("tempTrainingFiles");
            EncogTestClass ect = new EncogTestClass();
            String net = NetList.getSelectedValue().toString();
            String[] filelist = new FileOperations().getFiles(dir);
            String nnetworkfile = threadLib.GetNetworkFile(net);
            double filesl = filelist.length;
            trainStatus = 0;
            int cnt = 1;
            double element = ((double) 100 / filelist.length);
            for (String file : filelist) {
                ect.runNet(dir + "/" + file, nDir + "/" + nnetworkfile, false, 0);
                cnt++;
                trainStatus = (int) (element * cnt);
            }
            String[] FPlist = new FileOperations().getFiles("tempTrainingFiles");
            String FPnetworkFile = threadLib.GetNetworkFPFile(net);
            TreeMap<String, TreeMap> hm = new TreeMap<String, TreeMap>();
            for (String fpfile : FPlist) {
                TreeMap<Double, Integer> tm = new TreeMap<Double, Integer>();
                String fileType = fpfile.substring(0, 3);
                double fileOut = ect.testFPfile(nDir + "/" + FPnetworkFile, "tempTrainingFiles/" + fpfile);
                if (hm.containsKey(fileType)) {
                    tm = hm.get(fileType);
                }
                int ccount = 0;
                if (tm.containsKey(fileOut)) {
                    ccount = tm.get(fileOut);
                }
                ccount++;
                tm.put(fileOut, ccount);
                hm.put(fileType, (TreeMap) tm.clone());
            }
            JFrame frame = new JFrame();
            JFreeChart jf = new GraphingClass().RenderFiles(hm);
            ChartPanel cp = new ChartPanel(jf);
            cp.setVisible(true);
            chdisp = cp;
            cp.addChartMouseListener(new ChartMouseListener() {

                public void chartMouseClicked(final ChartMouseEvent event) {
                    Point point = event.getTrigger().getPoint();
                    int x = point.x;
                    int y = point.y;

                    Rectangle2D dataArea = chdisp.getScreenDataArea();
                    lasty = chdisp.getChart().getXYPlot().getRangeAxis().java2DToValue(y, dataArea,
                            RectangleEdge.LEFT);
                    lastx = chdisp.getChart().getXYPlot().getDomainAxis().java2DToValue(x, dataArea,
                            RectangleEdge.BOTTOM);
                }

                public void chartMouseMoved(final ChartMouseEvent event) {
                    ;
                }
            });
            cp.setSize(new Dimension(GraphPanel.getWidth(), GraphPanel.getHeight()));
            //frame.add(cp);
            //frame.setVisible(true);
            GraphPanel.add(new JLabel("Hello!"));
            GraphPanel.removeAll();
            GraphPanel.add(cp);
            GraphPanel.repaint();
            GraphPanel.setVisible(true);

            System.out.println("Hello");

        }
    }

    public double[] getMouseLocation() {
        return new double[] { lastx, lasty };
    }

    /**
     * @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(EditNet.class.getName()).log(java.util.logging.Level.SEVERE, null,
                    ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(EditNet.class.getName()).log(java.util.logging.Level.SEVERE, null,
                    ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(EditNet.class.getName()).log(java.util.logging.Level.SEVERE, null,
                    ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(EditNet.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 EditNet().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton DeleteNet;
    private javax.swing.JPanel GraphPanel;
    private javax.swing.JList NetList;
    private javax.swing.JButton TestContents;
    private javax.swing.JButton TrainBTN;
    private javax.swing.JButton addThreshold;
    private javax.swing.JButton addType;
    private javax.swing.JButton deleteThreshold;
    private javax.swing.JButton deleteType;
    private javax.swing.JList fileList;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JButton modifyThreshold;
    private javax.swing.JList thresholdList;
    // End of variables declaration//GEN-END:variables
}