#!/usr/bin/env bash

# ==============================================================================
# =                       DO NOT TOUCH THIS PART                               =
# ==============================================================================

# classpath for the weka jar
cp="/usr/share/java/weka.jar"

# classifier
method="weka.classifiers.functions.MultilayerPerceptron"

# training set and validation set names
ts="ts.arff"
vs="vs.arff"

# OPTIONS
opts=""

# ==============================================================================
# =                    CHANGE THE OPTIONS AS YOU WISH                          =
# ==============================================================================

# -N <number of epochs>
# 	Number of epochs to train through.
# 	(Default = 500).
opts="$opts -N 500"

# -H <comma seperated numbers for nodes on each layer>
# 	The hidden layers to be created for the network.
# 	(Value should be a list of comma separated Natural 
# 	numbers or the letters 'a' = (attribs + classes) / 2, 
# 	'i' = attribs, 'o' = classes, 't' = attribs .+ classes)
# 	for wildcard values, Default = a).
opts="$opts -H a"

# -V <percentage size of validation set>
# 	Percentage size of validation set to use to terminate
# 	training (if this is non zero it can pre-empt num of epochs.
# 	(Value should be between 0 - 100, Default = 0).
opts="$opts -V 0" 


# ==============================================================================
# =                       DO NOT TOUCH THIS PART                               =
# ==============================================================================

opts="$opts -S 0" # seed for the random number generator
opts="$opts -I" # do not normalize the attributes

script="
import os
import shutil
import sys

# idenfy the instances for which some error occurred
misclassified = []
for l in sys.stdin:
    if l.find('+') >= 0:
        # get instance number
        inum = int(l.split()[0])
        misclassified.append(inum)
            
# find the corresponding file names
icount = 0
parsing_data = False
with open('vs.arff') as inf:
    for l in inf:
        if l.startswith('@data'):
            parsing_data = True
        elif parsing_data:
            icount += 1 # one more example
            if icount in misclassified:
                fname = l.split('%')[1].strip()
                print fname
"

# learn the ANN and produce error statistics
java -Xmx1024m -cp $cp $method -t $ts -T $vs $opts -d 'ann.dat'

# output the predictions
misclassified=`java -Xmx1024m -cp $cp $method -T $vs -p 0 -l 'ann.dat' | python -c "$script"`

# delete the ANN file
rm ann.dat

# remove the error directory
rm -rf errors

# build the error directory, if it does not exist
mkdir errors

for fname in $misclassified; do
	cp ts_images/$fname errors/$fnanme
done