Example usage for weka.core Instances numInstances

List of usage examples for weka.core Instances numInstances

Introduction

In this page you can find the example usage for weka.core Instances numInstances.

Prototype


publicint numInstances() 

Source Link

Document

Returns the number of instances in the dataset.

Usage

From source file:MPCKMeans.java

License:Open Source License

public static void runFromCommandLine(String[] args) {
    MPCKMeans mpckmeans = new MPCKMeans();
    Instances data = null, clusterData = null;
    ArrayList labeledPairs = null;

    try {//from w ww  . j av a2s  .c om
        String optionString = Utils.getOption('D', args);
        if (optionString.length() != 0) {
            FileReader reader = new FileReader(optionString);
            data = new Instances(reader);
            System.out.println("Reading dataset: " + data.relationName());
        }

        int classIndex = data.numAttributes() - 1;
        optionString = Utils.getOption('K', args);
        if (optionString.length() != 0) {
            classIndex = Integer.parseInt(optionString);
            if (classIndex >= 0) {
                data.setClassIndex(classIndex); // starts with 0
                // Remove the class labels before clustering
                clusterData = new Instances(data);
                mpckmeans.setNumClusters(clusterData.numClasses());
                clusterData.deleteClassAttribute();
                System.out.println("Setting classIndex: " + classIndex);
            } else {
                clusterData = new Instances(data);
            }
        } else {
            data.setClassIndex(classIndex); // starts with 0
            // Remove the class labels before clustering
            clusterData = new Instances(data);
            mpckmeans.setNumClusters(clusterData.numClasses());
            clusterData.deleteClassAttribute();
            System.out.println("Setting classIndex: " + classIndex);
        }

        optionString = Utils.getOption('C', args);
        if (optionString.length() != 0) {
            labeledPairs = mpckmeans.readConstraints(optionString);
            System.out.println("Reading constraints from: " + optionString);
        } else {
            labeledPairs = new ArrayList(0);
        }

        mpckmeans.setTotalTrainWithLabels(data);
        mpckmeans.setOptions(args);
        System.out.println();
        mpckmeans.buildClusterer(labeledPairs, clusterData, data, mpckmeans.getNumClusters(),
                data.numInstances());
        mpckmeans.printClusterAssignments();

        if (mpckmeans.m_TotalTrainWithLabels.classIndex() > -1) {
            double nCorrect = 0;
            for (int i = 0; i < mpckmeans.m_TotalTrainWithLabels.numInstances(); i++) {
                for (int j = i + 1; j < mpckmeans.m_TotalTrainWithLabels.numInstances(); j++) {
                    int cluster_i = mpckmeans.m_ClusterAssignments[i];
                    int cluster_j = mpckmeans.m_ClusterAssignments[j];
                    double class_i = (mpckmeans.m_TotalTrainWithLabels.instance(i)).classValue();
                    double class_j = (mpckmeans.m_TotalTrainWithLabels.instance(j)).classValue();
                    //         System.out.println(cluster_i + "," + cluster_j + ":" + class_i + "," + class_j);
                    if (cluster_i == cluster_j && class_i == class_j
                            || cluster_i != cluster_j && class_i != class_j) {
                        nCorrect++;
                        //        System.out.println("nCorrect:" + nCorrect);
                    }
                }
            }
            int numInstances = mpckmeans.m_TotalTrainWithLabels.numInstances();
            double RandIndex = 100 * nCorrect / (numInstances * (numInstances - 1) / 2);
            System.err.println("Acc\t" + RandIndex);
        }

        //      if (mpckmeans.getTotalTrainWithLabels().classIndex() >= 0) {
        //    SemiSupClustererEvaluation eval = new SemiSupClustererEvaluation(mpckmeans.m_TotalTrainWithLabels,
        //                             mpckmeans.m_TotalTrainWithLabels.numClasses(),
        //                             mpckmeans.m_TotalTrainWithLabels.numClasses());
        //    eval.evaluateModel(mpckmeans, mpckmeans.m_TotalTrainWithLabels, mpckmeans.m_Instances);
        //    eval.mutualInformation();
        //    eval.pairwiseFMeasure();
        //      }
    } catch (Exception e) {
        System.out.println("Option not specified");
        e.printStackTrace();
    }
}

From source file:MPCKMeans.java

License:Open Source License

public static void testCase() {
    try {//from w w  w .  j a v a 2 s. co  m
        String dataset = new String("lowd");
        //String dataset = new String("highd");
        if (dataset.equals("lowd")) {
            //////// Low-D data

            //   String datafile = "/u/ml/data/bio/arffFromPhylo/ecoli_K12-100.arff";
            //   String datafile = "/u/sugato/weka/data/digits-0.1-389.arff";
            String datafile = "/u/sugato/weka/data/iris.arff";
            int numPairs = 200, num = 0;

            // set up the data
            FileReader reader = new FileReader(datafile);
            Instances data = new Instances(reader);

            // Make the last attribute be the class 
            int classIndex = data.numAttributes() - 1;
            data.setClassIndex(classIndex); // starts with 0
            System.out.println("ClassIndex is: " + classIndex);

            // Remove the class labels before clustering
            Instances clusterData = new Instances(data);
            clusterData.deleteClassAttribute();

            // create the pairs
            ArrayList labeledPair = InstancePair.getPairs(data, numPairs);

            System.out.println("Finished initializing constraint matrix");

            MPCKMeans mpckmeans = new MPCKMeans();
            mpckmeans.setUseMultipleMetrics(false);
            System.out.println("\nClustering the data using MPCKmeans...\n");

            WeightedEuclidean metric = new WeightedEuclidean();
            WEuclideanLearner metricLearner = new WEuclideanLearner();

            //     LearnableMetric metric = new WeightedDotP();
            //     MPCKMeansMetricLearner metricLearner = new DotPGDLearner();

            //     KL metric = new KL();
            //     KLGDLearner metricLearner = new KLGDLearner();
            //   ((KL)metric).setUseIDivergence(true);

            //   BarHillelMetric metric = new BarHillelMetric();
            //   BarHillelMetricMatlab metric = new BarHillelMetricMatlab();
            //     XingMetric metric = new XingMetric();
            //   WeightedMahalanobis metric = new WeightedMahalanobis(); 

            mpckmeans.setMetric(metric);
            mpckmeans.setMetricLearner(metricLearner);
            mpckmeans.setVerbose(false);
            mpckmeans.setRegularize(false);
            mpckmeans.setTrainable(new SelectedTag(TRAINING_INTERNAL, TAGS_TRAINING));
            mpckmeans.setSeedable(true);
            mpckmeans.buildClusterer(labeledPair, clusterData, data, data.numClasses(), data.numInstances());
            mpckmeans.getIndexClusters();
            mpckmeans.printIndexClusters();

            SemiSupClustererEvaluation eval = new SemiSupClustererEvaluation(mpckmeans.m_TotalTrainWithLabels,
                    mpckmeans.m_TotalTrainWithLabels.numClasses(),
                    mpckmeans.m_TotalTrainWithLabels.numClasses());
            eval.evaluateModel(mpckmeans, mpckmeans.m_TotalTrainWithLabels, mpckmeans.m_Instances);
            System.out.println("MI=" + eval.mutualInformation());
            System.out.print("FM=" + eval.pairwiseFMeasure());
            System.out.print("\tP=" + eval.pairwisePrecision());
            System.out.print("\tR=" + eval.pairwiseRecall());
        } else if (dataset.equals("highd")) {
            //////// Newsgroup data
            String datafile = "/u/ml/users/sugato/groupcode/weka335/data/arffFromCCS/sanitized/different-1000_sanitized.arff";
            //String datafile = "/u/ml/users/sugato/groupcode/weka335/data/20newsgroups/small-newsgroup_fromCCS.arff";
            //String datafile = "/u/ml/users/sugato/groupcode/weka335/data/20newsgroups/same-100_fromCCS.arff";

            // set up the data
            FileReader reader = new FileReader(datafile);
            Instances data = new Instances(reader);

            // Make the last attribute be the class 
            int classIndex = data.numAttributes() - 1;
            data.setClassIndex(classIndex); // starts with 0
            System.out.println("ClassIndex is: " + classIndex);

            // Remove the class labels before clustering
            Instances clusterData = new Instances(data);
            clusterData.deleteClassAttribute();

            // create the pairs
            int numPairs = 0, num = 0;
            ArrayList labeledPair = new ArrayList(numPairs);
            Random rand = new Random(42);
            System.out.println("Initializing constraint matrix:");
            while (num < numPairs) {
                int i = (int) (data.numInstances() * rand.nextFloat());
                int j = (int) (data.numInstances() * rand.nextFloat());
                int first = (i < j) ? i : j;
                int second = (i >= j) ? i : j;
                int linkType = (data.instance(first).classValue() == data.instance(second).classValue())
                        ? InstancePair.MUST_LINK
                        : InstancePair.CANNOT_LINK;
                InstancePair pair = new InstancePair(first, second, linkType);
                if (first != second && !labeledPair.contains(pair)) {
                    labeledPair.add(pair);
                    //System.out.println(num + "th entry is: " + pair);
                    num++;
                }
            }
            System.out.println("Finished initializing constraint matrix");

            MPCKMeans mpckmeans = new MPCKMeans();
            mpckmeans.setUseMultipleMetrics(false);
            System.out.println("\nClustering the highd data using MPCKmeans...\n");

            LearnableMetric metric = new WeightedDotP();
            MPCKMeansMetricLearner metricLearner = new DotPGDLearner();

            //     KL metric = new KL();
            //     KLGDLearner metricLearner = new KLGDLearner();

            mpckmeans.setMetric(metric);
            mpckmeans.setMetricLearner(metricLearner);
            mpckmeans.setVerbose(false);
            mpckmeans.setRegularize(true);
            mpckmeans.setTrainable(new SelectedTag(TRAINING_INTERNAL, TAGS_TRAINING));
            mpckmeans.setSeedable(true);
            mpckmeans.buildClusterer(labeledPair, clusterData, data, data.numClasses(), data.numInstances());
            mpckmeans.getIndexClusters();

            SemiSupClustererEvaluation eval = new SemiSupClustererEvaluation(mpckmeans.m_TotalTrainWithLabels,
                    mpckmeans.m_TotalTrainWithLabels.numClasses(),
                    mpckmeans.m_TotalTrainWithLabels.numClasses());

            mpckmeans.getMetric().resetMetric(); // Vital: to reset m_attrWeights to 1 for proper normalization
            eval.evaluateModel(mpckmeans, mpckmeans.m_TotalTrainWithLabels, mpckmeans.m_Instances);
            System.out.println("MI=" + eval.mutualInformation());
            System.out.print("FM=" + eval.pairwiseFMeasure());
            System.out.print("\tP=" + eval.pairwisePrecision());
            System.out.print("\tR=" + eval.pairwiseRecall());
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:WekaClassify.java

License:Open Source License

public void SplitRun(Instances anInstance, double split) throws Exception {

    anInstance.randomize(new java.util.Random(0));

    int trainSize = (int) Math.round(anInstance.numInstances() * split);
    int testSize = anInstance.numInstances() - trainSize;
    Instances train = new Instances(anInstance, 0, trainSize);
    Instances test = new Instances(anInstance, trainSize, testSize);

    NumberFormat percentFormat = NumberFormat.getPercentInstance();
    percentFormat.setMaximumFractionDigits(1);
    String result = percentFormat.format(split);

    System.out.println("Evaluating with : Split percentage : " + result);
    m_Evaluation.evaluateModel(m_Classifier, anInstance);
}

From source file:PCADetector.java

License:Apache License

public double[] getStandardDeviation(Instances Matrix) {
    int numAtts = Matrix.numAttributes();
    int numInsts = Matrix.numInstances();
    double[] att1 = new double[numInsts];
    double[] std = new double[numAtts];
    for (int i = 0; i < numAtts; i++) {
        for (int j = 0; j < numInsts; j++) {
            att1[j] = Matrix.instance(j).value(i);
        }//www .  jav a2s .com
        std[i] = Math.sqrt(Utils.variance(att1));
    }
    return std;
}

From source file:A_AdvanceMachineLearning.java

private void jButton10ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton10ActionPerformed
    UIManager.put("OptionPane.yesButtonText", "Confirm");
    UIManager.put("OptionPane.noButtonText", "Cancel");
    int dialogButton = JOptionPane.YES_NO_OPTION;
    int dialogResult = JOptionPane.showConfirmDialog(this, "The labels must be the same used in the weka model",
            "Advance Machine learning", dialogButton, JOptionPane.WARNING_MESSAGE);
    if (dialogResult == 0) {
        this.list.clear();
        //txtcodigo1.setText("hola");
        this.valor = txtcodigo1.getText();
        this.valor1 = txtcodigo2.getText();
        this.valor2 = txtcodigo3.getText();
        this.valor3 = txtcodigo4.getText();
        this.valor4 = txtcodigo5.getText();
        this.valor5 = txtcodigo6.getText();
        //IJ.showMessage("your label 1 is = "+valor+", "+valor1+", "+valor2+", "+valor3+", "+valor4);
        // Array list
        this.list.add(this.valor);
        this.list.add(this.valor1);
        this.list.add(this.valor2);
        this.list.add(this.valor3);
        this.list.add(this.valor4);
        this.list.add(this.valor5);
        this.list.removeAll(Arrays.asList("", null));
        System.out.println(this.list);
        this.liststring = "";

        for (String s : this.list) {
            this.liststring += s + ",";
        }/*from ww  w  . j a  va 2  s.  co m*/
        txtlabel.setText(this.liststring);

        System.out.println(this.liststring);
        txtarea.setText("Your labels are = " + this.list + "\nThe labels had been saved");
        //txtarea.setText("The labels had been saved");

        System.out.println(label);

    } else {
        System.out.println("No Option");

    }
    Instances data;
    try {
        System.out.println(this.file2 + "arff");
        FileReader reader = new FileReader(this.file2 + ".arff");
        BufferedReader br = new BufferedReader(reader);

        data = new Instances(br);
        System.out.println(data);
        Instances newData = null;
        Add filter;
        newData = new Instances(data);
        filter = new Add();
        filter.setAttributeIndex("last");
        filter.setNominalLabels(this.liststring);
        filter.setAttributeName(txtcodigo7.getText());
        filter.setInputFormat(newData);
        newData = Filter.useFilter(newData, filter);
        System.out.print("hola" + newData);
        Vector vec = new Vector();
        newData.setClassIndex(newData.numAttributes() - 1);
        if (!newData.equalHeaders(newData)) {
            throw new IllegalArgumentException("Train and test are not compatible!");
        }

        Classifier cls = (Classifier) weka.core.SerializationHelper.read(this.model);
        System.out.println("PROVANT MODEL.classifyInstance");
        for (int i = 0; i < newData.numInstances(); i++) {
            double pred = cls.classifyInstance(newData.instance(i));
            double[] dist = cls.distributionForInstance(newData.instance(i));
            System.out.print((i + 1) + " - ");
            System.out.print(newData.classAttribute().value((int) pred) + " - ");
            //txtarea2.setText(Utils.arrayToString(dist));

            System.out.println(Utils.arrayToString(dist));

            vec.add(newData.classAttribute().value((int) pred));

            classif.add(newData.classAttribute().value((int) pred));
        }

        classif.removeAll(Arrays.asList("", null));
        System.out.println(classif);
        String vecstring = "";

        for (Object s : classif) {
            vecstring += s + ",";

        }
        Map<String, Integer> seussCount = new HashMap<String, Integer>();
        for (String t : classif) {
            Integer i = seussCount.get(t);
            if (i == null) {
                i = 0;
            }
            seussCount.put(t, i + 1);
        }
        String s = vecstring;
        String in = vecstring;
        int i = 0;
        Pattern p = Pattern.compile(this.valor1);
        Matcher m = p.matcher(in);
        while (m.find()) {
            i++;
        }

        System.out.println("hola " + i); // Prints 2

        System.out.println(seussCount);
        txtarea2.append("Your file:" + this.file2 + "arff" + "\n is composed by" + seussCount);
        IJ.showMessage("Your file:" + this.file2 + "arff" + "\n is composed by" + seussCount);
    } catch (Exception ex) {
        Logger.getLogger(MachinLearningInterface.class.getName()).log(Level.SEVERE, null, ex);
    }

    //IJ.showMessage("analysing complete ");// TODO add your handling code here:
}

From source file:HierarchicalClusterer.java

License:Open Source License

@Override
public void buildClusterer(Instances data) throws Exception {
    //      /System.err.println("Method " + m_nLinkType);
    m_instances = data;//from w  w  w.j a v  a2  s.c  o  m
    int nInstances = m_instances.numInstances();
    if (nInstances == 0) {
        return;
    }
    m_DistanceFunction.setInstances(m_instances);
    // use array of integer vectors to store cluster indices,
    // starting with one cluster per instance
    Vector<Integer>[] nClusterID = new Vector[data.numInstances()];
    for (int i = 0; i < data.numInstances(); i++) {
        nClusterID[i] = new Vector<Integer>();
        nClusterID[i].add(i);
    }
    // calculate distance matrix
    int nClusters = data.numInstances();

    // used for keeping track of hierarchy
    Node[] clusterNodes = new Node[nInstances];
    if (m_nLinkType == NEIGHBOR_JOINING) {
        neighborJoining(nClusters, nClusterID, clusterNodes);
    } else {
        doLinkClustering(nClusters, nClusterID, clusterNodes);
    }

    // move all clusters in m_nClusterID array
    // & collect hierarchy
    int iCurrent = 0;
    m_clusters = new Node[m_nNumClusters];
    m_nClusterNr = new int[nInstances];
    for (int i = 0; i < nInstances; i++) {
        if (nClusterID[i].size() > 0) {
            for (int j = 0; j < nClusterID[i].size(); j++) {
                m_nClusterNr[nClusterID[i].elementAt(j)] = iCurrent;
            }
            m_clusters[iCurrent] = clusterNodes[i];
            iCurrent++;
        }
    }

}

From source file:ab.demo.AIAssignment2.java

License:Open Source License

public GameState solve() {

    // capture Image
    BufferedImage screenshot = ActionRobot.doScreenShot();

    // process image
    Vision vision = new Vision(screenshot);

    // find the slingshot
    Rectangle sling = vision.findSlingshotMBR();

    // confirm the slingshot
    while (sling == null && aRobot.getState() == GameState.PLAYING) {
        System.out.println("No slingshot detected. Please remove pop up or zoom out");
        ActionRobot.fullyZoomOut();/*from   w  ww.  j a v a  2s .  c om*/
        screenshot = ActionRobot.doScreenShot();
        vision = new Vision(screenshot);
        sling = vision.findSlingshotMBR();
    }

    // get all the pigs
    List<ABObject> pigs = vision.findPigsMBR();
    List<ABObject> blocks = vision.findBlocksMBR();

    GameState state = aRobot.getState();

    // if there is a sling, then play, otherwise just skip.
    if (sling != null) {

        if (!pigs.isEmpty()) { //if there are pigs in the level

            Point releasePoint = null;
            Shot shot = new Shot();
            int dx, dy;
            {
                //random pick up a pig
                ABObject pig = pigs.get(randomGenerator.nextInt(pigs.size()));
                Point _tpt = pig.getCenter();

                // estimate the trajectory
                ArrayList<Point> pts = tp.estimateLaunchPoint(sling, _tpt);

                //define all of the wood, ice and stone in the stage
                ArrayList<ABObject> wood = new ArrayList<ABObject>();
                ArrayList<ABObject> stone = new ArrayList<ABObject>();
                ArrayList<ABObject> ice = new ArrayList<ABObject>();
                ArrayList<ABObject> tnt = new ArrayList<ABObject>();

                //initialise counters to store how many times the trajectory intersects blocks of these types
                int woodCount = 0;
                int stoneCount = 0;
                int iceCount = 0;
                int pigsCount = 0;
                int tntCount = 0;

                //populate the wood, stone and ice ArrayLists with the correct materials
                for (int i = 0; i < blocks.size(); i++) {
                    if (blocks.get(i).type == ABType.Wood)
                        wood.add(blocks.get(i));
                    if (blocks.get(i).type == ABType.Stone)
                        stone.add(blocks.get(i));
                    if (blocks.get(i).type == ABType.Ice)
                        ice.add(blocks.get(i));
                    if (blocks.get(i).type == ABType.TNT)
                        tnt.add(blocks.get(i));
                }

                //check whether the trajectory intersects any wood blocks
                for (int i = 0; i < wood.size(); i++) {
                    for (int j = 0; j < pts.size(); j++) {
                        if (wood.get(i).contains(pts.get(j))) {
                            System.out.println("Trajectory intersects some wood");
                            woodCount++;
                        }
                        if (pig.contains(pts.get(j))) //if we find the pig on this point
                            j = pts.size() - 1; //stop looking for wood on the trajectory (escape for loop)
                    }
                }

                //check whether the trajectory intersects any ice blocks
                for (int i = 0; i < ice.size(); i++) {
                    for (int j = 0; j < pts.size(); j++) {
                        if (ice.get(i).contains(pts.get(j))) {
                            System.out.println("Trajectory intersects some ice");
                            iceCount++;
                        }
                        if (pig.contains(pts.get(j))) //if we find the pig on this point
                            j = pts.size() - 1; //stop looking for ice on the trajectory (escape for loop)
                    }
                }

                //check whether the trajectory intersects any stone blocks            
                for (int i = 0; i < stone.size(); i++) {
                    for (int j = 0; j < pts.size(); j++) {
                        if (stone.get(i).contains(pts.get(j))) {
                            System.out.println("Trajectory intersects some stone");
                            stoneCount++;
                        }
                        if (pig.contains(pts.get(j))) //if we find the pig on this point
                            j = pts.size() - 1; //stop looking for stone on the trajectory (escape for loop)
                    }
                }

                //how many pigs the trajectory intersects (this should always be at least 1)         
                for (int i = 0; i < pigs.size(); i++) {
                    for (int j = 0; j < pts.size(); j++) {
                        if (pigs.get(i).contains(pts.get(j))) {
                            System.out.println("Trajectory intersects a pig");
                            pigsCount++;
                        }
                    }
                }

                //how many tnt blocks the trajectory intersects            
                for (int i = 0; i < tnt.size(); i++) {
                    for (int j = 0; j < pts.size(); j++) {
                        if (tnt.get(i).contains(pts.get(j))) {
                            System.out.println("Trajectory intersects some tnt");
                            tntCount++;
                        }
                        if (pig.contains(pts.get(j))) //if we find the pig on this point
                            j = pts.size() - 1; //stop looking for tnt on the trajectory
                    }
                }

                StringBuilder sb = new StringBuilder();
                sb.append(pigsCount + "," + woodCount + "," + iceCount + "," + stoneCount + "," + tntCount
                        + ",?");
                String dataEntry = sb.toString();
                try (PrintWriter out = new PrintWriter(
                        new BufferedWriter(new FileWriter("dataset/birds.level.arff", true)))) {
                    out.println(dataEntry);
                } catch (IOException e) {
                    System.out.println("Error - dataset/birds.level.arff file not found or in use!");
                }

                //indicator of if the agent should continue this shot or not (used in the bayes classifier)
                ArrayList<Boolean> takeShot = new ArrayList<Boolean>();

                try {
                    DataSource source = new DataSource("dataset/birds.data.arff"); //initialise the learning set for the agent
                    Instances data = source.getDataSet();

                    // setting class attribute if the data format does not provide this information
                    // For example, the XRFF format saves the class attribute information as well
                    if (data.classIndex() == -1)
                        data.setClassIndex(data.numAttributes() - 1);

                    DataSource thisLevel = new DataSource("dataset/birds.level.arff"); //initialise the data retrieved from the current level for the agent
                    Instances thisLevelData = thisLevel.getDataSet();
                    if (thisLevelData.classIndex() == -1)
                        thisLevelData.setClassIndex(data.numAttributes() - 1);

                    //build a new NaiveBayes classifier
                    NaiveBayes bayes = new NaiveBayes();
                    bayes.buildClassifier(data);

                    for (int i = 0; i < thisLevelData.numInstances(); i++) { //for all instances in the current level
                        double label = bayes.classifyInstance(thisLevelData.instance(i)); //generate an outcome/classify an instance in the current level
                        thisLevelData.instance(i).setClassValue(label); //store this outcome
                        System.out.println(thisLevelData.instance(i).stringValue(5)); //print it
                        if (thisLevelData.instance(i).stringValue(5) != "?") { //if there is a decisive choice as to whether a shot should be taken
                            data.add(thisLevelData.instance(i)); //store it
                            if (thisLevelData.instance(i).stringValue(5) == "yes") {//if the classifier classifies a good shot, store it
                                takeShot.add(true);
                            } else { //if no, store this too
                                takeShot.add(false);
                            }
                        }
                    }

                    //add all non ? entries to the learning set
                    BufferedWriter writer = new BufferedWriter(new FileWriter("dataset/birds.data.arff"));
                    writer.write(data.toString());
                    writer.flush();
                    writer.close();

                } catch (Exception e) {
                    e.printStackTrace();
                    System.out.println("Exception caught - file handle error");
                }

                //TODO: roll a random number to determine whether we take a shot or not.
                //populated using the bayesian classification above.
                //if we roll true, continue with the random pig shot as usual.
                //if not, take a new random pig and try again.
                //TODO: implement a failsafe so the agent does not get stuck randomly choosing pigs which the bayesian classification does not allow.
                Random rng = new Random(takeShot.size());
                if (takeShot.get(rng.nextInt()))
                    System.out.println("Taking this shot.");
                else {
                    System.out.println("Not taking this shot. Finding another random pig.");
                    return state;
                }

                // if the target is very close to before, randomly choose a
                // point near it
                if (prevTarget != null && distance(prevTarget, _tpt) < 10) {
                    double _angle = randomGenerator.nextDouble() * Math.PI * 2;
                    _tpt.x = _tpt.x + (int) (Math.cos(_angle) * 10);
                    _tpt.y = _tpt.y + (int) (Math.sin(_angle) * 10);
                    System.out.println("Randomly changing to " + _tpt);
                }

                prevTarget = new Point(_tpt.x, _tpt.y);

                // do a high shot when entering a level to find an accurate velocity
                if (firstShot && pts.size() > 1) {
                    releasePoint = pts.get(1);
                } else if (pts.size() == 1)
                    releasePoint = pts.get(0);
                else if (pts.size() == 2) {
                    // randomly choose between the trajectories, with a 1 in
                    // 6 chance of choosing the high one
                    if (randomGenerator.nextInt(6) == 0)
                        releasePoint = pts.get(1);
                    else
                        releasePoint = pts.get(0);
                } else if (pts.isEmpty()) {
                    System.out.println("No release point found for the target");
                    System.out.println("Try a shot with 45 degree");
                    releasePoint = tp.findReleasePoint(sling, Math.PI / 4);
                }

                // Get the reference point
                Point refPoint = tp.getReferencePoint(sling);

                //Calculate the tapping time according the bird type 
                if (releasePoint != null) {
                    double releaseAngle = tp.getReleaseAngle(sling, releasePoint);
                    System.out.println("Release Point: " + releasePoint);
                    System.out.println("Release Angle: " + Math.toDegrees(releaseAngle));
                    int tapInterval = 0;
                    switch (aRobot.getBirdTypeOnSling()) {

                    case RedBird:
                        tapInterval = 0;
                        break; // start of trajectory
                    case YellowBird:
                        tapInterval = 65 + randomGenerator.nextInt(25);
                        break; // 65-90% of the way
                    case WhiteBird:
                        tapInterval = 70 + randomGenerator.nextInt(20);
                        break; // 70-90% of the way
                    case BlackBird:
                        tapInterval = 70 + randomGenerator.nextInt(20);
                        break; // 70-90% of the way
                    case BlueBird:
                        tapInterval = 65 + randomGenerator.nextInt(20);
                        break; // 65-85% of the way
                    default:
                        tapInterval = 60;
                    }

                    int tapTime = tp.getTapTime(sling, releasePoint, _tpt, tapInterval);
                    dx = (int) releasePoint.getX() - refPoint.x;
                    dy = (int) releasePoint.getY() - refPoint.y;
                    shot = new Shot(refPoint.x, refPoint.y, dx, dy, 0, tapTime);
                } else {
                    System.err.println("No Release Point Found");
                    return state;
                }
            }

            // check whether the slingshot is changed. the change of the slingshot indicates a change in the scale.
            {
                ActionRobot.fullyZoomOut();
                screenshot = ActionRobot.doScreenShot();
                vision = new Vision(screenshot);
                Rectangle _sling = vision.findSlingshotMBR();
                if (_sling != null) {
                    double scale_diff = Math.pow((sling.width - _sling.width), 2)
                            + Math.pow((sling.height - _sling.height), 2);
                    if (scale_diff < 25) {
                        if (dx < 0) {
                            aRobot.cshoot(shot);
                            state = aRobot.getState();
                            if (state == GameState.PLAYING) {
                                screenshot = ActionRobot.doScreenShot();
                                vision = new Vision(screenshot);
                                List<Point> traj = vision.findTrajPoints();
                                tp.adjustTrajectory(traj, sling, releasePoint);
                                firstShot = false;
                            }
                        }
                    } else
                        System.out.println(
                                "Scale is changed, can not execute the shot, will re-segement the image");
                } else
                    System.out
                            .println("no sling detected, can not execute the shot, will re-segement the image");
            }

        }

    }
    return state;
}

From source file:adams.data.conversion.WekaInstancesToSpreadSheet.java

License:Open Source License

/**
 * Performs the actual conversion.//  ww  w. j a v a2  s. c  o  m
 *
 * @return      the converted data
 * @throws Exception   if something goes wrong with the conversion
 */
@Override
protected Object doConvert() throws Exception {
    SpreadSheet result;
    Instances data;
    Row row;
    int i;
    int n;
    String str;

    data = (Instances) m_Input;

    // special case for InstancesViews
    if (m_SpreadSheetType instanceof InstancesView) {
        result = new InstancesView((Instances) m_Input);
        return result;
    }

    // create header
    result = m_SpreadSheetType.newInstance();
    result.setDataRowClass(m_DataRowType.getClass());
    row = result.getHeaderRow();
    for (n = 0; n < data.numAttributes(); n++)
        row.addCell("" + n).setContent(data.attribute(n).name());
    if (result instanceof Dataset) {
        if (data.classIndex() != -1)
            ((Dataset) result).setClassAttribute(data.classIndex(), true);
    }

    // fill spreadsheet
    for (i = 0; i < data.numInstances(); i++) {
        row = result.addRow("" + i);

        for (n = 0; n < data.numAttributes(); n++) {
            if (data.instance(i).isMissing(n))
                continue;
            if (data.attribute(n).type() == Attribute.DATE) {
                row.addCell("" + n).setContent(new DateTimeMsec(new Date((long) data.instance(i).value(n))));
            } else if (data.attribute(n).type() == Attribute.NUMERIC) {
                row.addCell("" + n).setContent(data.instance(i).value(n));
            } else {
                str = data.instance(i).stringValue(n);
                if (str.equals(SpreadSheet.MISSING_VALUE))
                    row.addCell("" + n).setContentAsString("'" + str + "'");
                else
                    row.addCell("" + n).setContentAsString(str);
            }
        }
    }

    return result;
}

From source file:adams.data.conversion.WekaInstancesToTimeseries.java

License:Open Source License

/**
 * Performs the actual conversion./*from   ww w .  j a v  a2s  .c o m*/
 *
 * @return      the converted data
 * @throws Exception   if something goes wrong with the conversion
 */
@Override
protected Object doConvert() throws Exception {
    Timeseries result;
    Instances input;
    Instance inst;
    int indexDate;
    int indexValue;
    TimeseriesPoint point;
    int i;
    Date timestamp;
    double value;

    input = (Instances) m_Input;

    // determine attribute indices
    m_DateAttribute.setData(input);
    indexDate = m_DateAttribute.getIntIndex();
    if (indexDate == -1)
        throw new IllegalStateException("Failed to located date attribute: " + m_DateAttribute.getIndex());
    m_ValueAttribute.setData(input);
    indexValue = m_ValueAttribute.getIntIndex();
    if (indexValue == -1)
        throw new IllegalStateException("Failed to located value attribute: " + m_ValueAttribute.getIndex());

    result = new Timeseries(input.relationName() + "-" + input.attribute(indexValue).name());
    for (i = 0; i < input.numInstances(); i++) {
        inst = input.instance(i);
        if (!inst.isMissing(indexDate) && !inst.isMissing(indexValue)) {
            timestamp = new Date((long) inst.value(indexDate));
            value = inst.value(indexValue);
            point = new TimeseriesPoint(timestamp, value);
            result.add(point);
        }
    }

    return result;
}

From source file:adams.data.id.AbstractInstanceIDGeneratorTestCase.java

License:Open Source License

/**
 * Loads the data to process.// w  w  w  .j a va  2 s .c o  m
 *
 * @param filename   the filename to load (without path)
 * @return      the data, null if it could not be loaded
 * @see      #getDataDirectory()
 */
protected D[] load(String filename) {
    Instance[] result;
    Instances data;
    int i;

    result = null;

    m_TestHelper.copyResourceToTmp(filename);

    try {
        data = DataSource.read(new TmpFile(filename).getAbsolutePath());
        result = new Instance[data.numInstances()];
        for (i = 0; i < data.numInstances(); i++) {
            result[i] = new Instance();
            result[i].set(data.instance(i));
            result[i].setID(new TmpFile(filename).getName() + "-" + i);
        }
    } catch (Exception e) {
        e.printStackTrace();
        result = new Instance[0];
    }

    m_TestHelper.deleteFileFromTmp(filename);

    return (D[]) result;
}