From 9508dda2a328d559c242a04f84ad0338f826c2e6 Mon Sep 17 00:00:00 2001 From: Rohan Sircar Date: Sat, 18 Jan 2020 22:09:52 +0530 Subject: [PATCH] first commit --- .classpath | 36 + .gitignore | 4 + .project | 23 + ID3.iml | 38 + SplitDataSet.cl | 308 +++++++ SumReduction.cl | 13 + pom.xml | 37 + programSource.cl | 5 + properties.txt | 7 + src/com/AI/Attribute.java | 44 + src/com/AI/ID3.java | 727 ++++++++++++++++ src/com/AI/Main.java | 255 ++++++ src/com/AI/MySwing.java | 439 ++++++++++ src/com/AI/NaryTree.java | 221 +++++ src/com/AI/Row.java | 65 ++ src/com/AI/jocl.java | 1302 +++++++++++++++++++++++++++++ src/com/DBpackage/MyDatabase.java | 318 +++++++ 17 files changed, 3842 insertions(+) create mode 100755 .classpath create mode 100644 .gitignore create mode 100755 .project create mode 100755 ID3.iml create mode 100755 SplitDataSet.cl create mode 100755 SumReduction.cl create mode 100755 pom.xml create mode 100755 programSource.cl create mode 100755 properties.txt create mode 100755 src/com/AI/Attribute.java create mode 100755 src/com/AI/ID3.java create mode 100755 src/com/AI/Main.java create mode 100755 src/com/AI/MySwing.java create mode 100755 src/com/AI/NaryTree.java create mode 100755 src/com/AI/Row.java create mode 100755 src/com/AI/jocl.java create mode 100755 src/com/DBpackage/MyDatabase.java diff --git a/.classpath b/.classpath new file mode 100755 index 0000000..4d2f892 --- /dev/null +++ b/.classpath @@ -0,0 +1,36 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..6b5d85e --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +.settings/ +.idea/ +.vscode/ +target/ \ No newline at end of file diff --git a/.project b/.project new file mode 100755 index 0000000..a4edc11 --- /dev/null +++ b/.project @@ -0,0 +1,23 @@ + + + DecisionTree-ID3 + + + + + + org.eclipse.jdt.core.javabuilder + + + + + org.eclipse.m2e.core.maven2Builder + + + + + + org.eclipse.m2e.core.maven2Nature + org.eclipse.jdt.core.javanature + + diff --git a/ID3.iml b/ID3.iml new file mode 100755 index 0000000..d85c567 --- /dev/null +++ b/ID3.iml @@ -0,0 +1,38 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/SplitDataSet.cl b/SplitDataSet.cl new file mode 100755 index 0000000..92af5ec --- /dev/null +++ b/SplitDataSet.cl @@ -0,0 +1,308 @@ +__kernel void splitDataSet(__global char *in, __global int *out, const int rowSpan, + const int colSpan, __global char *pat, const int pat_length, __global char* out_char, + __global char* nullChar) + { + const int idx = get_global_id(0); + int start = (idx * rowSpan); + int end = start + rowSpan; + int N = rowSpan; + int M = pat_length; + bool found = false; + char nullCharTemp = nullChar[0]; + if(in[start]!=nullCharTemp) + { + for(int k=start;k + 4.0.0 + org.nova + id3 + 0.0.1-SNAPSHOT + ID3 + + src + + + maven-compiler-plugin + 3.8.0 + + 11 + + + + + + + + + mysql + mysql-connector-java + 6.0.6 + + + + org.jocl + jocl + 2.0.1 + + + + \ No newline at end of file diff --git a/programSource.cl b/programSource.cl new file mode 100755 index 0000000..5810731 --- /dev/null +++ b/programSource.cl @@ -0,0 +1,5 @@ +__kernel void sampleKernel(__global const float *a, __global const float* b, __global float* c) +{ + int gid = get_global_id(0); + c[gid] = a[gid]+b[gid]; +} \ No newline at end of file diff --git a/properties.txt b/properties.txt new file mode 100755 index 0000000..e210bc1 --- /dev/null +++ b/properties.txt @@ -0,0 +1,7 @@ +display=select * from Adult2 +insert=insert into Climate values (?,?,?,?,?) +insertTree = insert into DecisionTree(Parent, Edge, Child) values (?,?,?) +resetAutoIncrement = alter table DecisionTree AUTO_INCREMENT = 0 +deleteAll = delete from DecisionTree +delete= delete from Climate where Day = ? +update= update Climate set Play=? where Day=? diff --git a/src/com/AI/Attribute.java b/src/com/AI/Attribute.java new file mode 100755 index 0000000..cbc8451 --- /dev/null +++ b/src/com/AI/Attribute.java @@ -0,0 +1,44 @@ +package com.AI; +import java.util.HashSet; +import java.util.Set; + +class Attribute +{ + private String attributeName; + private int attributeIndex; + private Set valuesSet; + + void addToValuesSet(String value) + { + valuesSet.add(value); + } + + public Attribute() + { + valuesSet = new HashSet<>(); + } + + public Set getValuesSet() { + return valuesSet; + } + + public void setValuesSet(Set valuesSet) { + this.valuesSet = valuesSet; + } + + public String getAttributeName() { + return attributeName; + } + + public void setAttributeName(String attributeName) { + this.attributeName = attributeName; + } + + public int getAttributeIndex() { + return attributeIndex; + } + + public void setAttributeIndex(int attributeIndex) { + this.attributeIndex = attributeIndex; + } +} \ No newline at end of file diff --git a/src/com/AI/ID3.java b/src/com/AI/ID3.java new file mode 100755 index 0000000..a6f8691 --- /dev/null +++ b/src/com/AI/ID3.java @@ -0,0 +1,727 @@ +package com.AI; + +import java.util.*; +class ID3 +{ + private ArrayList attributesList; + private Set attributesSet; + private double P, N; + private String modeOfTargetAttribute; + private MyJOCL myJocl; + private Attribute targetAttribute; + private String modeOfCurrentAttribute; + int examplesSize; + int maxLength; + int cellSpan; + + ID3() + { + attributesList = new ArrayList<>(); + attributesSet = new LinkedHashSet<>(); + targetAttribute = new Attribute(); + P = 1; + N = 1; + } + + + public Set getAttributesSet() { + return attributesSet; + } + + public void setAttributesSet(Set attributesSet) { + this.attributesSet = attributesSet; + } + + public double getP() { + return P; + } + + public void setP(double p) { + this.P = p; + } + + public double getN() { + return N; + } + + public void setN(double n) { + this.N = n; + } + + public ArrayList getAttributesList() { + return attributesList; + } + + public void setAttributesList(ArrayList attribute) { + this.attributesList = attribute; + } + + public Attribute getTargetAttribute() { + return targetAttribute; + } + + public void setTargetAttribute(Attribute targetAttribute) { + this.targetAttribute = targetAttribute; + } + + public String getModeOfTargetAttribute() { + return modeOfTargetAttribute; + } + + public void setModeOfTargetAttribute(String modeOfTargetAttribute) { + this.modeOfTargetAttribute = modeOfTargetAttribute; + } + + public int getExamplesSize() { + return examplesSize; + } + + public void setExamplesSize(int examplesSize) { + this.examplesSize = examplesSize; + } + + public int getMaxLength() { + return maxLength; + } + + public void setMaxLength(int maxLength) { + this.maxLength = maxLength; + } + + public int getCellSpan() { + return cellSpan; + } + + public void setCellSpan(int cellSpan) { + this.cellSpan = cellSpan; + } + + public MyJOCL getMyJocl() { + return myJocl; + } + + public void setMyJocl(MyJOCL myJocl) { + this.myJocl = myJocl; + } + + Set getUniqueAttributes(String targetAttribute, String indexAttribute, ArrayList examples) + { + attributesSet = new LinkedHashSet<>(); + Row row = examples.get(0); + for (Cell cell : row.getCellsList()) { +// System.out.print(cell.getAttributeName() + " " + cell.getValue() + " "); + if (cell.getAttributeName().equals(targetAttribute) || + cell.getAttributeName().equalsIgnoreCase(indexAttribute)) + continue; + attributesSet.add(cell.getAttributeName()); + } + this.targetAttribute.setAttributeName(targetAttribute); + return attributesSet; + } + + void setAttributesNew(ArrayList examples) + { + attributesList = new ArrayList<>(); + Attribute attribute; + for (String s : attributesSet) { + attribute = new Attribute(); + attribute.setAttributeName(s); + for (Row row :examples) { + for (Cell cell : row.getCellsList()) { + if(cell.getAttributeName().equalsIgnoreCase(s)) + attribute.addToValuesSet(cell.getValue()); + } + } + attributesList.add(attribute); + } + } + + void setAttributesIndex(List attributesList) + { + int i = 1; + for(Attribute a: attributesList) + { + a.setAttributeIndex(i++); + } + targetAttribute.setAttributeIndex(i); + } + void displayAttributesList(List attributeList) + { + for(Attribute a: attributeList) + { + System.out.println("Attribute: " + a.getAttributeName()); + for(String value: a.getValuesSet()) + { + System.out.print("Value: " + value); + } + System.out.println(); + } + } + + static double calcEntropy(double p, double n) { + if (p == 0 || n == 0) + return 0; + else + return ((-p / (p + n)) * Logarithms.log2(p / (p + n))) - ((n / (p + n)) * Logarithms.log2(n / (p + n))); + } + + + + Node createDecisionTree(NaryTree tree, Set attributesSet, ArrayList examples) { + + + String targetAttributeValue = allOneValues(examples); + if(targetAttributeValue.equalsIgnoreCase("Yes")) + return new Node("Yes"); + else if(targetAttributeValue.equalsIgnoreCase("No")) + return new Node("No"); + if (attributesSet.isEmpty()) { + return new Node(modeOfCurrentAttribute); + } + Node node; + String attributeName; + attributeName = getBestAttribute(examples,attributesSet); + + Attribute attribute = new Attribute(); + + for (Attribute a : getAttributesList()) { + if (a.getAttributeName().equalsIgnoreCase(attributeName)) + attribute = a; + } + + + Set uniqueValues = attribute.getValuesSet(); + + node = new Node(attributeName); + +// node.setAttributeName(attributeName); + if (tree.getHead() == null) { + tree.setHead(node); + + } + + for (String s : uniqueValues) { +// System.out.println("For value: " + s); + ArrayList examplesVi = splitDataSet(examples,s,attributeName); + +// System.out.println("Displaying examplesVi"); +// for(Row row: examplesVi) +// { +// for(Cell cell : row.getCellsList()) +// { +// System.out.print(cell.getAttributeName() + " " + cell.getValue() + ", "); +// } +// System.out.println(); +// } + + if(examplesVi.isEmpty()) + { + tree.createNode(null,node,s,new Node(modeOfTargetAttribute)); + } + + else + { + for (Iterator it = attributesSet.iterator(); it.hasNext(); ) + { + String str = it.next(); + if (str.equalsIgnoreCase(attributeName)) + { + System.out.println("Removed: " + str); + it.remove(); + } + } + Node temp = createDecisionTree(tree, attributesSet, examplesVi); + tree.createNode(null, node, s, temp); + } + } + + + return node; + } + + void setModeAndPN(ArrayList examples) + { + int yesCounter = 0, noCounter = 0; + for(Row row: examples) + { + for(Cell cell: row.getCellsList()) + { + if(cell.getValue().equalsIgnoreCase("Yes")) + yesCounter++; + else if(cell.getValue().equalsIgnoreCase("No")) + noCounter++; + } + } + this.P = yesCounter; + this.N = noCounter; + if(P > N) + modeOfTargetAttribute = "Yes"; + else + modeOfTargetAttribute = "No"; + + System.out.println("Most common value: " + modeOfTargetAttribute); + } + double getClassEntropy(ArrayList examples) + { + int yesCounter = 0, noCounter = 0; + double classEntropy; + for(Row row: examples) + { + for(Cell cell: row.getCellsList()) + { + if(cell.getValue().equalsIgnoreCase("Yes")) + yesCounter++; + else if(cell.getValue().equalsIgnoreCase("No")) + noCounter++; + } + } + P = yesCounter; + N = noCounter; + classEntropy = calcEntropy(yesCounter,noCounter); + return classEntropy; + } + + String getBestAttribute(ArrayList examples, Set attributesSet) + { + if(attributesSet.isEmpty()) + return "Attributes set is empty"; + double classEntropy = getClassEntropy(examples); + System.out.println("Class Entropy = " + classEntropy); + double attributeEntropy, maxGain=0, valueEntropy=0, gain = 0; + int p, n; + String bestAttribute = ""; + Set uniqueValues; + + for(String attributeName: attributesSet) + { + attributeEntropy =0; + + Attribute attribute = new Attribute(); + for (Attribute a : getAttributesList()) { + if (a.getAttributeName().equalsIgnoreCase(attributeName)) + attribute = a; + } + + int attributeIndex = attribute.getAttributeIndex(); + int targetAttributeIntex = targetAttribute.getAttributeIndex(); + uniqueValues = attribute.getValuesSet(); + + for(String value: uniqueValues) { + p=0; + n=0; + for (Row row : examples) { +// boolean flag = false; +// for (Cell cell : row.getCellsList()) { +// if (cell.getValue().equalsIgnoreCase(value) && cell.getAttributeName().equalsIgnoreCase(attributeName)) +// flag= true; +// } +// for (Cell cell : row.getCellsList()) { +// if(flag && cell.getValue().equalsIgnoreCase("Yes")) +// p++; +// else if(flag && cell.getValue().equalsIgnoreCase("No")) +// n++; +// } + Cell cell = row.getCellsList().get(attributeIndex); + Cell targetCell = row.getCellsList().get(targetAttributeIntex); + if (cell.getValue().equalsIgnoreCase(value) && targetCell.getValue().equalsIgnoreCase("Yes")) + p++; + else if(cell.getValue().equalsIgnoreCase(value) && targetCell.getValue().equalsIgnoreCase("No")) + n++; +// + } + +// System.out.println("P = " + P + " " + "N = " + N); + valueEntropy = calcEntropy(p, n); +// System.out.println("Value Entropy = " + valueEntropy); + attributeEntropy = attributeEntropy + ((p + n) / (P + N)) * valueEntropy; + + } + System.out.println("Attribute Entropy" + "(" + attributeName + ") = " + attributeEntropy); + gain = classEntropy - attributeEntropy; + if(gain >= maxGain) + { +// System.out.println("1"); + maxGain = gain; + bestAttribute = attributeName; + } + System.out.println("Gain = " + gain + " " + "Max Gain = " + maxGain); + + } + System.out.println("Best Attribute = " + bestAttribute); + return bestAttribute; + } + + void test(ArrayList examples, Set attributesSet) + { + double classEntropy = getClassEntropy(examples); + String bestAttribute = getBestAttribute(examples,attributesSet); + + System.out.println("Class Entropy = " + classEntropy + " Best Attribute = " + bestAttribute); + } + + ArrayList splitDataSet(ArrayList examples, String value, String attributeName) + { + ArrayList examplesVi = new ArrayList<>(); + int attributeIndex = targetAttribute.getAttributeIndex(); + + for (Row row : examples) + { + boolean flag = false; + for (Cell cell : row.getCellsList()) + { + if (cell.getValue().equalsIgnoreCase(value) && cell.getAttributeName().equalsIgnoreCase(attributeName)) + flag= true; + } +// Cell cell = row.getCellsList().get(attributeIndex); +// if (cell.getValue().equalsIgnoreCase(value) && cell.getAttributeName().equalsIgnoreCase(attributeName)) +// examplesVi.add(row); + + if(flag) + examplesVi.add(row); + } + + return examplesVi; + } + + private String allOneValues(ArrayList examples) + { + int yesCount = 0; + int noCount = 0; + for (Row row : examples) + { + + for (Cell cell : row.getCellsList()) + { + if(cell.getValue().equalsIgnoreCase("Yes")) + yesCount++; + else if(cell.getValue().equalsIgnoreCase("No")) + noCount++; + } + } + + if(yesCount > noCount) + modeOfCurrentAttribute = "Yes"; + else + modeOfCurrentAttribute = "No"; + + if(yesCount == 0) + return "No"; + else if(noCount == 0) + return "Yes"; + else + return ""; + } + + String allOneValuesParallel(int [] examplesInt, int examplesSize, int maxLength, int cellSpan) + { + + int yesCount = myJocl.getCount(examplesInt, examplesSize,maxLength,"Yes", cellSpan, targetAttribute); +// System.out.println("P = " + yesCount); + int noCount = myJocl.getCount(examplesInt, examplesSize,maxLength,"No", cellSpan, targetAttribute); +// System.out.println("N = " + noCount); + + if(yesCount > noCount) + modeOfCurrentAttribute = "Yes"; + else + modeOfCurrentAttribute = "No"; + + if(yesCount == 0) + return "No"; + else if(noCount == 0) + return "Yes"; + else + return ""; + } + + double getClassEntropyParallel(int [] examplesInt, int examplesSize, int maxLength, int cellSpan) + { + double classEntropy; + int yesCounter = myJocl.getCount(examplesInt, examplesSize,maxLength,"Yes", cellSpan, targetAttribute); + int noCounter = myJocl.getCount(examplesInt, examplesSize,maxLength,"No", cellSpan, targetAttribute); + P = yesCounter; + N = noCounter; + classEntropy = calcEntropy(yesCounter,noCounter); + return classEntropy; + } + + int[] splitDataSetParallel(int[] examplesInt, String value, String attributeName, int examplesSize, int maxLength, int cellSpan) + { +// int[] examplesVi = new ArrayList<>(); + int attributeIndex = targetAttribute.getAttributeIndex(); + + ReturnObj returnObj = myJocl.testDataSetParallel(examplesInt, examplesSize, maxLength, cellSpan, attributeName, value, attributesList, targetAttribute); + + return returnObj.getExamplesInt(); + } + + String getBestAttributeParallel(Set attributesSet, + int[] examplesInt,int examplesSize, int maxLength, int cellSpan) + { + if(attributesSet.isEmpty()) + return "Attributes set is empty"; + double classEntropy = getClassEntropyParallel(examplesInt,examplesSize,maxLength,cellSpan); + System.out.println("Class Entropy = " + classEntropy); + double attributeEntropy, maxGain=0, valueEntropy=0, gain = 0; + int p, n; + String bestAttribute = ""; + Set uniqueValues; + for(String attributeName: attributesSet) + { + attributeEntropy =0; + p=0; + n=0; + Attribute attribute = new Attribute(); + for (Attribute a : getAttributesList()) { + if (a.getAttributeName().equalsIgnoreCase(attributeName)) + attribute = a; + } + + uniqueValues = attribute.getValuesSet(); + + for(String value: uniqueValues) { + + ReturnObj returnObj = myJocl.testDataSetParallel2(examplesInt,examplesSize,maxLength,cellSpan + ,attributeName,value,attributesList,targetAttribute); + p = returnObj.getYesCount(); +// System.out.println("Yes count = " + p); + n = returnObj.getNoCount(); +// System.out.println("No count = " + n); + + +// System.out.println("P = " + P + " " + "N = " + N); + valueEntropy = calcEntropy(p, n); +// System.out.println("Value Entropy = " + valueEntropy); + attributeEntropy = attributeEntropy + ((p + n) / (P + N)) * valueEntropy; + + } + System.out.println("Attribute Entropy" + "(" + attributeName + ") = " + attributeEntropy); + gain = classEntropy - attributeEntropy; + if(gain >= maxGain) + { +// System.out.println("1"); + maxGain = gain; + bestAttribute = attributeName; + } + System.out.println("Gain = " + gain + " " + "Max Gain = " + maxGain); + + } + System.out.println("Best Attribute = " + bestAttribute); + return bestAttribute; + } + + Node createDecisionTreeParallel(NaryTree tree, Set attributesSet, int[] examplesInt) { + + + String targetAttributeValue = allOneValuesParallel(examplesInt,examplesSize,maxLength,cellSpan); + if(targetAttributeValue.equalsIgnoreCase("Yes")) + return new Node("Yes"); + else if(targetAttributeValue.equalsIgnoreCase("No")) + return new Node("No"); + if (attributesSet.isEmpty()) { + return new Node(modeOfCurrentAttribute); + } + Node node; + String attributeName; + attributeName = getBestAttributeParallel(attributesSet,examplesInt,examplesSize,maxLength,cellSpan); + + Attribute attribute = new Attribute(); + + for (Attribute a : getAttributesList()) { + if (a.getAttributeName().equalsIgnoreCase(attributeName)) + attribute = a; + } + + + Set uniqueValues = attribute.getValuesSet(); + + node = new Node(attributeName); + +// node.setAttributeName(attributeName); + if (tree.getHead() == null) { + tree.setHead(node); + + } + + for (String s : uniqueValues) { + System.out.println("For value: " + s); + int[] examplesViInt = splitDataSetParallel(examplesInt,s,attributeName,examplesSize,maxLength,cellSpan); + +// System.out.println("Displaying examplesVi"); +// for(Row row: examplesVi) +// { +// for(Cell cell : row.getCellsList()) +// { +// System.out.print(cell.getAttributeName() + " " + cell.getValue() + ", "); +// } +// System.out.println(); +// } + + if(reduceArray(examplesViInt) == 0) + { +// System.out.println("Array size 0"); + tree.createNode(null, node, s, new Node(modeOfTargetAttribute)); + } + + else + { + for (Iterator it = attributesSet.iterator(); it.hasNext(); ) + { + String str = it.next(); + if (str.equalsIgnoreCase(attributeName)) + { + System.out.println("Removed: " + str); + it.remove(); + } + } + Node temp = createDecisionTreeParallel(tree, attributesSet, examplesViInt); +// System.out.println("Test: " + temp.getAttributeName()); + tree.createNode(null, node, s, temp); + } + } + + + return node; + } + + Node createDecisionTreeParallel2(ArrayList examples, NaryTree tree, Set attributesSet, int[] examplesInt) { + + + String targetAttributeValue = allOneValues(examples); + if(targetAttributeValue.equalsIgnoreCase("Yes")) + return new Node("Yes"); + else if(targetAttributeValue.equalsIgnoreCase("No")) + return new Node("No"); + if (attributesSet.isEmpty()) { + return new Node(modeOfCurrentAttribute); + } + Node node; + String attributeName; + attributeName = getBestAttributeParallel(attributesSet,examplesInt,examplesSize,maxLength,cellSpan); + + Attribute attribute = new Attribute(); + + for (Attribute a : getAttributesList()) { + if (a.getAttributeName().equalsIgnoreCase(attributeName)) + attribute = a; + } + + + Set uniqueValues = attribute.getValuesSet(); + + node = new Node(attributeName); + +// node.setAttributeName(attributeName); + if (tree.getHead() == null) { + tree.setHead(node); + + } + + for (String s : uniqueValues) { +// System.out.println("For value: " + s); + ArrayList examplesVi = splitDataSet(examples,s,attributeName); + +// System.out.println("Displaying examplesVi"); +// for(Row row: examplesVi) +// { +// for(Cell cell : row.getCellsList()) +// { +// System.out.print(cell.getAttributeName() + " " + cell.getValue() + ", "); +// } +// System.out.println(); +// } + + if(examplesVi.isEmpty()) + { + tree.createNode(null,node,s,new Node(modeOfTargetAttribute)); + } + + else + { + for (Iterator it = attributesSet.iterator(); it.hasNext(); ) + { + String str = it.next(); + if (str.equalsIgnoreCase(attributeName)) + { + System.out.println("Removed: " + str); + it.remove(); + } + } + Node temp = createDecisionTree(tree, attributesSet, examplesVi); + tree.createNode(null, node, s, temp); + } + } + + + return node; + } + + void setModeAndPNParallel(int[] examplesInt) + { + this.P = myJocl.getCount(examplesInt,examplesSize,maxLength,"Yes",cellSpan,targetAttribute); + this.N = myJocl.getCount(examplesInt,examplesSize,maxLength,"No",cellSpan,targetAttribute); + if(P > N) + modeOfTargetAttribute = "Yes"; + else + modeOfTargetAttribute = "No"; + + System.out.println("Most common value: " + modeOfTargetAttribute); + } + + private int reduceArray(int[] array) + { + int sum = 0; + for (int value : array) { + sum += value; + } + return sum; + } + +} + +class ReturnObj +{ + private int [] examplesInt; + private int size; + private int yesCount; + private int noCount; + + ReturnObj() + { + size = 0; + } + + public int[] getExamplesInt() { + return examplesInt; + } + + public void setExamplesInt(int[] examplesInt) { + this.examplesInt = examplesInt; + } + + public int getSize() { + return size; + } + + public void setSize(int size) { + this.size = size; + } + + public int getYesCount() { + return yesCount; + } + + public void setYesCount(int yesCount) { + this.yesCount = yesCount; + } + + public int getNoCount() { + return noCount; + } + + public void setNoCount(int noCount) { + this.noCount = noCount; + } +} + + + diff --git a/src/com/AI/Main.java b/src/com/AI/Main.java new file mode 100755 index 0000000..e8d0e94 --- /dev/null +++ b/src/com/AI/Main.java @@ -0,0 +1,255 @@ +package com.AI; + +import com.DBpackage.MyDatabase; + +//import java.io.BufferedReader; +//import java.io.IOException; +//import java.io.InputStreamReader; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Set; + +class Main +{ + + public static void main(String[] args) { + MyDatabase myDatabase = new MyDatabase(); + myDatabase.connectDatabase(); +// MySwing mySwing = new MySwing(myDatabase); +// mySwing.start(); +// String indexAttribute, targetAttribute; + +// try { +// BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in)); +// System.out.println("Enter index attribute"); +// indexAttribute = bufferedReader.readLine(); +// System.out.println("Enter target attribute"); +// +// } +// catch(IOException e) +// { +// e.printStackTrace(); +// } +// + + NaryTree tree = new NaryTree(); + ID3 id3 = new ID3(); + try { + ArrayList examples = myDatabase.storeValues(); +// for (Row row : examples) { +// for (Cell cell : row.getCellsList()) { +// System.out.print(cell.getAttributeName() + " " + cell.getValue() + ", "); +// } +// System.out.println(); +// } + Set attributesSet = id3.getUniqueAttributes("Income", "Person", examples); +// Set attributesSet = id3.getUniqueAttributes("Play", "Day", examples); +// Set attributesSet = id3.getUniqueAttributes("Result_of_Treatment", "Patient", examples); + + + for(String s: attributesSet) + System.out.println(s); + + id3.setAttributesNew(examples); +// System.out.println(id3.getAttributesList().size()); + List attributesList = id3.getAttributesList(); + id3.setAttributesIndex(attributesList); + for(Attribute a: id3.getAttributesList()) + System.out.printf("Attribute = %s Index = %d \n",a.getAttributeName(),a.getAttributeIndex()); + id3.displayAttributesList(attributesList); + +// id3.setModeAndPN(examples); +// id3.createDecisionTree(tree, attributesSet, examples); +// tree.displayTree(); +// myDatabase.deleteTree(); +// tree.dbTest(myDatabase); + + + MyJOCL myJocl = new MyJOCL(); + int examplesSize = examples.size(); + int maxLength = 1000; + int cellSpan = 20; + char[] examplesChar = new char[examplesSize*maxLength]; + + id3.setMaxLength(maxLength); + id3.setExamplesSize(examplesSize); + id3.setCellSpan(cellSpan); + + myJocl.setMaxLength(maxLength); + myJocl.setExamplesSize(examplesSize); + + + + + +// for (Row row : examples) { +// for (Cell cell : row.getCellsList()) { +// System.out.print(cell.getAttributeName() + " " + cell.getValue() + ", "); +// } +// System.out.println(); +// } + System.out.println("Examples size = " + examplesSize); +// Row row = examples.get(0); +// System.out.print("Row size = " + row.getCellsList().size()); + long start = System.nanoTime(); + + for(int i=0;i0) + examplesChar[i*maxLength-1] = '\n'; + +// temp.append("\n"); +// System.out.print("Temp = " + temp); +// for(int j=0;j climateArrayList = myDatabase.storeValues(); + + id3 = new ID3(); +// id3.setTableData(climateArrayList); + //id3.createNode(); + +// for (Row c : climateArrayList) { +// System.out.println(c.getDay() + " " + +// c.getWeather() + " " + c.getTemperature() + " " + +// c.getHumidity() + " " + c.getWind()); +// } + } + catch(SQLException se) + { + se.printStackTrace(); + } + } + }); + } + + } + + private class DecisionTreePanel extends JPanel + { + private static final int DISTANCE_X = 4; + private static final int DISTANCE_Y = 65; + private static final int radius = 20; + private static final int diameter = radius * 2; + private int treeArity = 3; + private int treeDepth = 3; + private int childDistanceX; + + private JPanel treeDisplayPanel; + char status; + + private NaryTree createDecisionTree() + { + NaryTree tree = new NaryTree(); + try { + ArrayList examples = myDatabase.storeValues(); + for (Row row : examples) { + for (Cell cell : row.getCellsList()) { + System.out.print(cell.getAttributeName() + " " + cell.getValue() + ", "); + } + System.out.println(); + } + Set attributesSet = id3.getUniqueAttributes("Play", "Day", examples); + + id3.setAttributesNew(examples); + id3.setModeAndPN(examples); + id3.createDecisionTree(tree, attributesSet, examples); + tree.displayTree(); + myDatabase.deleteTree(); + tree.dbTest(myDatabase); + + } catch (SQLException se) { + se.printStackTrace(); + } + return tree; + } + DecisionTreePanel() + { +// setLayout(new FlowLayout()); +// setSize(800,600); + status = 'n'; + JButton displayButton = new JButton(); + JButton clearButton = new JButton(); + JButton createTreeButton = new JButton(); + displayButton.setText("Display Tree"); + clearButton.setText("Clear"); + createTreeButton.setText("Create Tree"); + displayButton.addActionListener(new ActionListener() + { + public void actionPerformed(ActionEvent e) + { + status = 'y'; + repaint(); + } + }); + clearButton.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + status = 'n'; + repaint(); + } + }); + createTreeButton.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + decisionTree = createDecisionTree(); + } + }); + add(displayButton); + add(clearButton); + add(createTreeButton); + childDistanceX = 100; + } + + public void paintComponent(Graphics g) { + super.paintComponent(g); +// System.out.println("Inside paintcomponent"); + Dimension size = getSize(); + int x = size.width / 2; + int y = ( treeDepth * DISTANCE_Y) / 2; + +// drawTree(g, x, y, treeArity, treeDepth); + if(status == 'y') + { +// g.drawOval(x,y,diameter,diameter); + System.out.println("Inside if"); +// drawMyTree(g, x, y); + displayTree(g,x,y); + } + } + +// public void drawTree(Graphics g, int x, int y, int arity, int depth) { +// if (depth > 0) { +// int childDistanceX = (int) (Math.pow(arity, depth) * DISTANCE_X); +// int childX = x - (arity - 1) * childDistanceX / 2; +// int childY = y - DISTANCE_Y; +// +// for (int child = 0; child < arity; child++) { +// g.drawLine(x, y, childX, childY); +// drawTree(g, childX, childY, arity, depth - 1); +// childX += childDistanceX; +// } +// } +// } + + public void drawMyTree(Graphics g, int x, int y) + { + System.out.println("Inside drawmytree"); + g.drawOval(x,y,diameter,diameter); + int childX = x - childDistanceX / 2; + int childY = y + DISTANCE_Y; + g.drawLine(x + radius ,y + diameter,childX + childDistanceX + radius,childY); + g.drawLine(x + radius ,y + diameter,childX + radius,childY); + + + g.drawOval(childX,childY,diameter,diameter); + g.drawOval(childX+childDistanceX,childY,diameter,diameter); + + } + + ////////////////////////////////////////////////////////////////////////////////// + private void traverse(Node node, Graphics g, int x, int y, int i) + { + if(node == null) + { + System.out.println(); + return; + } + int childX = x - childDistanceX; + int childY = y + DISTANCE_Y; + i++; + g.drawOval(x,y,diameter,diameter); + if(node.getAttributeName().equalsIgnoreCase("Yes") || + node.getAttributeName().equalsIgnoreCase("No")) + if(node.getValuesList() == null) { + return; + } + for(Node.Value v: node.getValuesList()) + { +// g.drawOval(childX,y,diameter,diameter); + g.drawLine(x+radius, y + diameter,childX + radius, childY); + traverse(v.getNext(), g, childX, childY, i); + childX = childX + childDistanceX; + } + + } + void displayTree(Graphics g, int x, int y) + { + System.out.println("Displaying tree"); + if(decisionTree.getHead()!=null) { + int i = 0; + traverse(decisionTree.getHead(), g, x, y, i); + } + else + { + System.out.println("Head node not created/initialized"); + } + } + ////////////////////////////////////////////////////////////////////////////////////////////////////////// + } + + public void start() + { + JTabbedPane jtp = new JTabbedPane(); + + //This creates the template on the windowed application that we will be using + jtp.setBounds(10,10,1030,640); + + InsertPanel insertPanel = new InsertPanel(); + com.AI.MySwing.UpdatePanel updatePanel = new com.AI.MySwing.UpdatePanel(); + com.AI.MySwing.DeletePanel deletePanel = new com.AI.MySwing.DeletePanel(); + com.AI.MySwing.DisplayPanel displayPanel = new com.AI.MySwing.DisplayPanel(); + com.AI.MySwing.StorePanel storePanel = new com.AI.MySwing.StorePanel(); + DecisionTreePanel decisionTreePanel = new DecisionTreePanel(); + + //This adds the first and second tab to our tabbed pane object and names it + jtp.addTab("Insert", insertPanel); + jtp.addTab("Update", updatePanel); + jtp.addTab("Delete", deletePanel); + jtp.addTab("Display", displayPanel); + jtp.addTab("Store", storePanel); + jtp.addTab("Decision-Tree", decisionTreePanel); + + getContentPane().add(jtp); + setLayout(null); + setVisible(true); + setSize(1050,700); + addWindowListener(new WindowAdapter() + { + @Override + public void windowClosing(WindowEvent e) + { + + System.out.println("Closing"); + myDatabase.closeConnection(); + dispose(); + } + + }); + setDefaultCloseOperation(DO_NOTHING_ON_CLOSE); + } + +} \ No newline at end of file diff --git a/src/com/AI/NaryTree.java b/src/com/AI/NaryTree.java new file mode 100755 index 0000000..b7cc2cf --- /dev/null +++ b/src/com/AI/NaryTree.java @@ -0,0 +1,221 @@ +package com.AI; +import com.DBpackage.MyDatabase; + +import java.util.ArrayList; + +class Node +{ + private String attributeName; + private ArrayList valuesList; + + class Value + { + private String value; + private Node next; + + public Value() + { + next = null; + } + + String getValue() { + return value; + } + + void setValue(String value) { + this.value = value; + } + + Node getNext() { + return next; + } + + void setNext(Node next) { + this.next = next; + } + + } + + public Node() + { + valuesList = new ArrayList<>(); + } + public Node(String attributeName) + { + this.setAttributeName(attributeName); + valuesList = new ArrayList<>(); + } + public String getAttributeName() + { + return attributeName; + } + + public void setAttributeName(String attributeName) + { + this.attributeName = attributeName; + } + + public ArrayList getValuesList() { + return valuesList; + } + + public void setValuesList(ArrayList valuesList) { + this.valuesList = valuesList; + } + + void setVal(String value, Node obj) + { + + Value valueObj = new Value(); + valueObj.setValue(value); + valueObj.setNext(obj); + //obj.getValuesList().get(0).setPrevious(this); + //if(obj.getPrevious().getValuesList().get(0).isVisited() == true); + valuesList.add(valueObj); + } + +} + +class NaryTree +{ + private Node head; + + NaryTree() + { + head = null; + } + + public Node getHead() { + return head; + } + + public void setHead(Node head) { + this.head = head; + } + + + ////////////////////////////////////////////////////////////////////////////////// + /*Node createNode(Node h, Node parent, String edgeName, Node child) { + if (head == null) + { + System.out.println("Initializing head node"); +// h = new Node(parentName); +// this.setHead(h); +// System.out.println("Head: " + h.getAttributeName()); +// return h; + head = parent; + return head; + } + else + { + createLink(parent, child, edgeName); + return child; + } + }*/ + Node createNode(Node h, Node parent, String edgeName, Node child) { + if (head == null) + { + System.out.println("Initializing head node"); +// h = new Node(parentName); +// this.setHead(h); +// System.out.println("Head: " + h.getAttributeName()); +// return h; + head = parent; + return head; + } + else + { + createLink(parent, child, edgeName); + return child; + } + } + + private void createLink(Node parent, Node child, String value) + { +// System.out.println("Edge: " + value + " Child: " + child.getAttributeName() ); + parent.setVal(value, child); + } + ////////////////////////////////////////////////////////////////////////////////// + private void traverse(Node node) + { + if(node == null) + { + System.out.println(); + return; + } + System.out.print(" " + node.getAttributeName() + " "); + if(node.getAttributeName().equalsIgnoreCase("Yes") || + node.getAttributeName().equalsIgnoreCase("No")) + System.out.println(); + if(node.getValuesList() == null) { + System.out.print(node.getAttributeName()); + return; + } + + for(Node.Value v: node.getValuesList()) + { + System.out.print(" " + v.getValue()); + traverse(v.getNext()); + } + + } + void displayTree() + { + System.out.println("Displaying tree(pre-order):"); + System.out.println("------------------"); + if(head!=null) { + traverse(head); + } + else + { + System.out.println("Head node not created/initialized"); + } + System.out.println(); + System.out.print("------------------"); + System.out.println(); + } + ////////////////////////////////////////////////////////////////////////////////////////////////////////// + + private void traverseDBTest(Node node, MyDatabase myDatabase) + { + if(node == null) + { + System.out.println(); + return; + } + + //System.out.print(" " + node.getAttributeName()); + if(node.getValuesList() == null) { +// System.out.print(node.getAttributeName()); + return; + } + for(Node.Value value : node.getValuesList()) + { +// System.out.print(" " + sn.getValue()); + if(value.getNext().getAttributeName() == null) + System.out.println("null"); + else { + myDatabase.insertTree(node.getAttributeName(), value.getValue(), value.getNext().getAttributeName()); + System.out.println("Parent: " + node.getAttributeName() + + " Edge: " + value.getValue() + + " Child: " + value.getNext().getAttributeName()); + } + traverseDBTest(value.getNext(),myDatabase); + } + //System.out.println("Node named" + nodeName + "does not exist in the tree"); + + } + + void dbTest(MyDatabase myDatabase) + { + if(head!=null) { + traverseDBTest(head, myDatabase); + } + else + { + System.out.println("Head node not created/initialized"); + } + System.out.println(); + } + ////////////////////////////////////////////////////////////////////////////////////////////////////////// +} \ No newline at end of file diff --git a/src/com/AI/Row.java b/src/com/AI/Row.java new file mode 100755 index 0000000..3bb2d20 --- /dev/null +++ b/src/com/AI/Row.java @@ -0,0 +1,65 @@ +package com.AI; + +import java.util.*; + +class Cell +{ + private String attributeName; + private String value; + + public String getAttributeName() { + return attributeName; + } + + public void setAttributeName(String attributeName) { + this.attributeName = attributeName; + } + + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } +} +public class Row +{ + private ArrayList cellsList; + + public ArrayList getCellsList() { + return cellsList; + } + + public void setCellsList(ArrayList cellsList) { + this.cellsList = cellsList; + } + + + + public Row() + { + cellsList = new ArrayList<>(); + } + + public void setRow(String attributeName, String value) + { + Cell cell = new Cell(); + cell.setAttributeName(attributeName); + cell.setValue(value); + cellsList.add(cell); + + } +} + + + + + +class Logarithms +{ + public static double log2(double exponent) + { + return Math.log10(exponent) / 0.3010299956639812; + } +} diff --git a/src/com/AI/jocl.java b/src/com/AI/jocl.java new file mode 100755 index 0000000..e309d01 --- /dev/null +++ b/src/com/AI/jocl.java @@ -0,0 +1,1302 @@ +/* + * JOCL - Java bindings for OpenCL + * + * Copyright 2009 Marco Hutter - http://www.jocl.org/ + */ + +package com.AI; +import static org.jocl.CL.*; + +import org.jocl.*; + +import java.io.BufferedReader; +import java.io.FileReader; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +class Kernel +{ + private String kernelName; + private cl_kernel kernel; + private cl_program program; + + public String getKernelName() { + return kernelName; + } + + public void setKernelName(String kernelName) { + this.kernelName = kernelName; + } + + public cl_kernel getKernel() { + return kernel; + } + + public void setKernel(cl_kernel kernel) { + this.kernel = kernel; + } + + public cl_program getProgram() { + return program; + } + + public void setProgram(cl_program program) { + this.program = program; + } +} + +class MyJOCL +{ + /** + * The source code of the OpenCL program to execute + */ + + private int platformIndex; + private long deviceType; + private int deviceIndex; + private cl_device_id device; + + private cl_context context; + private cl_kernel kernel; + private cl_program program; + private ArrayList kernelsList; + private cl_command_queue commandQueue; + + private cl_mem examplesCharBuffer; + + private cl_mem nullCharMemObject; + + private int maxLength; + private int examplesSize; + + public cl_context getContext() { + return context; + } + + public void setContext(cl_context context) { + this.context = context; + } + + public int getMaxLength() { + return maxLength; + } + + public void setMaxLength(int maxLength) { + this.maxLength = maxLength; + } + + public int getExamplesSize() { + return examplesSize; + } + + public void setExamplesSize(int examplesSize) { + this.examplesSize = examplesSize; + } + + MyJOCL() + { + platformIndex = 0; + deviceType = CL_DEVICE_TYPE_ALL; + deviceIndex = 0; + + kernelsList = new ArrayList<>(); + + // Enable exceptions and subsequently omit error checks in this sample + CL.setExceptionsEnabled(true); + + // Obtain the number of platforms + int[] numPlatformsArray = new int[1]; + clGetPlatformIDs(0, null, numPlatformsArray); + int numPlatforms = numPlatformsArray[0]; + + // Obtain a platform ID + cl_platform_id platforms[] = new cl_platform_id[numPlatforms]; + clGetPlatformIDs(platforms.length, platforms, null); + cl_platform_id platform = platforms[platformIndex]; + + // Initialize the context properties + cl_context_properties contextProperties = new cl_context_properties(); + contextProperties.addProperty(CL_CONTEXT_PLATFORM, platform); + + // Obtain the number of devices for the platform + int numDevicesArray[] = new int[1]; + clGetDeviceIDs(platform, deviceType, 0, null, numDevicesArray); + int numDevices = numDevicesArray[0]; + + // Obtain a device ID + cl_device_id devices[] = new cl_device_id[numDevices]; + clGetDeviceIDs(platform, deviceType, numDevices, devices, null); + device = devices[deviceIndex]; + + // Create a context for the selected device + context = clCreateContext( + contextProperties, 1, new cl_device_id[]{device}, + null, null, null); + + // Create a command-queue for the selected device + //noinspection deprecation + commandQueue = clCreateCommandQueue(context, device, 0, null); + + + + char[] nullChar = new char['\n']; + + Pointer nullCharPointer = Pointer.to(nullChar); + + + nullCharMemObject = clCreateBuffer(context, + CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR, + Sizeof.cl_char2 * nullChar.length, nullCharPointer, null); + + setKernels(); + + // Enable exceptions and subsequently omit error checks in this sample + CL.setExceptionsEnabled(true); + + // Obtain the number of platforms + + } + + void setExamplesCharBuffer(char[] examplesChar) + { + Pointer examplesCharPointer = Pointer.to(examplesChar); + examplesCharBuffer = clCreateBuffer(context, + CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR, + Sizeof.cl_char2 * examplesSize * maxLength, examplesCharPointer, null); + } + + void setKernels() + { + + Kernel kernelTemp = new Kernel(); + String programSource = readFile("SplitDataSet.cl"); + // Create the program from the source code + program = clCreateProgramWithSource(context, + 1, new String[]{ programSource }, null, null); + + // Build the program + clBuildProgram(program, 0, null, null, null, null); + +// // Create the kernel +// kernel = clCreateKernel(program, "splitDataSet", null); +// +// kernelTemp.setKernelName("splitDataSet"); +// kernelTemp.setKernel(kernel); +// kernelsList.add(0,kernelTemp); + + +// programSource = readFile("SumReduction.cl"); +// // Create the program from the source code +// program = clCreateProgramWithSource(context, +// 1, new String[]{ programSource }, null, null); +// +// // Build the program +// clBuildProgram(program, 0, null, null, null, null); +// +// // Create the kernel +// kernel = clCreateKernel(program, "sumReduction", null); +// kernelTemp.setKernelName("sumReduction"); +// kernelTemp.setKernel(kernel); +// kernelsList.add(1,kernelTemp); + } + static boolean isPowerOfTwo(int n) + { + return (int)(Math.ceil((Math.log(n) / Math.log(2)))) == + (int)(Math.floor(((Math.log(n) / Math.log(2))))); + } + + + static int nextPowerOf2(int n) + { + int count = 0; + + // First n in the below + // condition is for the + // case where n is 0 + if (n > 0 && (n & (n - 1)) == 0) + return n; + + while(n != 0) + { + n >>= 1; + count += 1; + } + + return 1 << count; + } + + ReturnObj testDataSetParallel(int[] examplesInt, int examplesSize, int maxLength, int cellSpan, + String attributeName, String value, List attributesList, Attribute targetAttribute) + { +// kernel = kernelsList.get(0).getKernel(); +// initCL(); + // Create input- and examplesViInt data + + + +// for(int i=0;i attributesList, Attribute targetAttribute) + { +// kernel = kernelsList.get(0).getKernel(); +// initCL(); + // Create input- and examplesViInt data + + + + int[] yesArray = new int[examplesSize]; + int[] noArray = new int[examplesSize]; + + char[] yes = "Yes".toCharArray(); + +// for(int i=0;i attributesList) + { +// if(!MyJOCL.isPowerOfTwo(examplesSize)) +// examplesSize = MyJOCL.nextPowerOf2(examplesSize); +// System.out.println("Examples size power of 2 is: " + examplesSize); +// kernel = kernelsList.get(0).getKernel(); +// initCL(); + // Create input- and output data + + + +// for(int i=0;i=offset: +// c = np.zeros(np.int32(len(a)/offset), dtype=cl.cltypes.uint) +// a_dev = cl.Buffer(ctx, cl.mem_flags.READ_ONLY | cl.mem_flags.COPY_HOST_PTR, hostbuf=a) +// c_dev = cl.Buffer(ctx, cl.mem_flags.READ_WRITE | cl.mem_flags.COPY_HOST_PTR, hostbuf=c) +// event = prg.summation(queue, (np.int32(len(a)/offset),),None, a_dev,c_dev, np.uint32(offset)) +// event.wait() +// cl.enqueue_copy(queue, c, c_dev) +// print(c) +// a = c +// print("Length of a = {}".format(len(a))) + + clEnqueueNDRangeKernel(commandQueue, kernel, 1, null, + global_work_size, local_work_size, 0, null, null); + + System.out.println(Arrays.toString(destArray)); + + clEnqueueReadBuffer(commandQueue, dstArray, CL_TRUE, 0, + Sizeof.cl_int * destArray.length, dstArrayPointer, 0, null, null); + + System.out.println(Arrays.toString(destArray)); + + clReleaseMemObject(srcArray); + clReleaseMemObject(dstArray); + + + } + + void sumReduction2(int ARRAYSIZE, int[] testArray) + { + kernel = clCreateKernel(program, "foldKernel", null); +// int ARRAYSIZE = 10; + + + if(!isPowerOfTwo(ARRAYSIZE)) + ARRAYSIZE = nextPowerOf2(ARRAYSIZE); + + +// int[] testArray = new int[ARRAYSIZE]; +// for(int i=0;i 1) { + int m = t / 2; + int n = (t + 1) / 2; + clSetKernelArg(kernel, 0, Sizeof.cl_mem, Pointer.to(srcArray)); + clSetKernelArg(kernel, 1, Sizeof.cl_int, Pointer.to(new int[]{n})); + cl_event evFold = new cl_event(); + clEnqueueNDRangeKernel(commandQueue, kernel, 1, null, new long[]{m}, null, 0, null, evFold); + clWaitForEvents(1, new cl_event[]{evFold}); + t = n; + } + + +// while len(a)>=offset: +// c = np.zeros(np.int32(len(a)/offset), dtype=cl.cltypes.uint) +// a_dev = cl.Buffer(ctx, cl.mem_flags.READ_ONLY | cl.mem_flags.COPY_HOST_PTR, hostbuf=a) +// c_dev = cl.Buffer(ctx, cl.mem_flags.READ_WRITE | cl.mem_flags.COPY_HOST_PTR, hostbuf=c) +// event = prg.summation(queue, (np.int32(len(a)/offset),),None, a_dev,c_dev, np.uint32(offset)) +// event.wait() +// cl.enqueue_copy(queue, c, c_dev) +// print(c) +// a = c +// print("Length of a = {}".format(len(a))) + + + + + clEnqueueReadBuffer(commandQueue, srcArray, CL_TRUE, 0, + Sizeof.cl_int * testArray.length, srcArrayPointer, 0, null, null); + + System.out.println("After " + Arrays.toString(testArray)); + + clReleaseMemObject(srcArray); + } + + + void initCL() + { + + } + + void endCL() + { + clReleaseMemObject(examplesCharBuffer); + clReleaseKernel(kernel); + clReleaseProgram(program); + clReleaseCommandQueue(commandQueue); + clReleaseContext(context); + } + private static String readFile(String fileName) + { + BufferedReader bufferedReader = null; + try + { + bufferedReader = new BufferedReader(new FileReader(fileName)); + StringBuilder sb = new StringBuilder(); + String line; + while (true) + { + line = bufferedReader.readLine(); + if (line == null) + { + break; + } + sb.append(line).append("\n"); + } + return sb.toString(); + } + catch (IOException e) + { + e.printStackTrace(); + return ""; + } + finally + { + if (bufferedReader != null) + { + try + { + bufferedReader.close(); + } + catch (IOException ex) + { + ex.printStackTrace(); + } + } + } + } +} \ No newline at end of file diff --git a/src/com/DBpackage/MyDatabase.java b/src/com/DBpackage/MyDatabase.java new file mode 100755 index 0000000..7403950 --- /dev/null +++ b/src/com/DBpackage/MyDatabase.java @@ -0,0 +1,318 @@ +package com.DBpackage; + +import java.io.FileInputStream; +import java.io.IOException; +import java.sql.*; +import java.util.ArrayList; +import java.util.Properties; + +import com.AI.*; + +class myProperties +{ + Properties loadConfig() throws IOException + { + FileInputStream fis = new FileInputStream("properties.txt"); + Properties prop = new Properties(); + prop.load(fis); + return prop; + } +} + +public class MyDatabase +{ + + + + + // JDBC driver name and database URL + //private static final String JDBC_DRIVER = "com.mysql.jdbc.Driver"; + private static final String DB_URL = "jdbc:mysql://localhost/ID3?autoReconnect=true&useSSL=false"; + + // Database credentials + private static final String USER = "id3"; + private static final String PASS = "id3"; + + private Properties prop = new Properties(); + + private Connection conn = null; + private Statement stmt = null; + + private PreparedStatement preparedStatement; + + + public MyDatabase() + { + try + { + System.out.println("Loading properties file"); + myProperties mp = new myProperties(); + this.prop = mp.loadConfig(); + } + catch(IOException e) + { + e.printStackTrace(); + } + } + + public void connectDatabase() + { + try + { + //STEP 2: Register JDBC driver + Class.forName("com.mysql.jdbc.Driver"); + + //STEP 3: Open a connection + System.out.println("Connecting to selected database..."); + conn = DriverManager.getConnection(DB_URL, USER, PASS); + System.out.println("Connected to database successfully..."); + + } + catch(SQLException se) + { + //Handle errors for JDBC + se.printStackTrace(); + System.exit(1); + } + catch(Exception e) + { + //Handle errors for Class.forName + e.printStackTrace(); + System.exit(2); + } + } + + /*public void storeValues() + { + String sql = prop.getProperty("display"); + System.out.println("Displaying Table"); + try + { + preparedStatement = conn.prepareStatement(sql); + ResultSet resultSet = preparedStatement.executeQuery(sql); + ResultSetMetaData rsmd = resultSet.getMetaData(); + int columnsNumber = rsmd.getColumnCount(); + while (resultSet.next()) + { + for (int i = 1; i <= columnsNumber; i++) + { + String columnValue = resultSet.getString(i); + System.out.print(columnValue + " " + rsmd.getAttributeName(i)); + + } + System.out.println(""); + } + } + catch(SQLException se) + { + se.printStackTrace(); + } + }*/ + + public void insertValues(int r,String fn, String ln, int m) + { + //String sql = "insert into Registration values (?,?,?,?)"; + String sql = prop.getProperty("insert"); + System.out.println("Inserting records into the table..."); + try + { + /* + stmt = conn.createStatement(); + stmt.executeUpdate(str); + */ + preparedStatement = conn.prepareStatement(sql); + preparedStatement.setInt(1,r); + preparedStatement.setString(2,fn); + preparedStatement.setString(3,ln); + preparedStatement.setInt(4,m); + + int nodesAffected = preparedStatement.executeUpdate(); + + System.out.println("Number of nodes affected:" + nodesAffected); + } + catch(Exception e) + { + e.printStackTrace(); + System.exit(2); + } + System.out.println("Records inserted successfully"); + } + + public void deleteTree() + { + String sql = prop.getProperty("deleteAll"); + System.out.println("Deleting all rows from table"); + try{ + preparedStatement = conn.prepareStatement(sql); + int deletedRows = preparedStatement.executeUpdate(); + + if(deletedRows > 0) + System.out.println("All rows deleted"); + else + System.out.println("Table already empty"); + } + catch(Exception e) + { + e.printStackTrace(); + System.exit(2); + } + sql = prop.getProperty("resetAutoIncrement"); + try { + preparedStatement = conn.prepareStatement(sql); + preparedStatement.executeUpdate(); + } + catch(Exception e) + { + e.printStackTrace(); + System.exit(2); + } + } + + public void insertTree( String parent, String edge, String child) + { + String sql = prop.getProperty("insertTree"); +// System.out.println("Inserting tree records into the table..."); + try + { + /* + stmt = conn.createStatement(); + stmt.executeUpdate(str); + */ + preparedStatement = conn.prepareStatement(sql); + preparedStatement.setString(1,parent); + preparedStatement.setString(2,edge); + preparedStatement.setString(3,child); + + preparedStatement.executeUpdate(); + +// System.out.println("Number of nodes affected:" + rowsAffected); + } + catch(Exception e) + { + e.printStackTrace(); + System.exit(2); + } + } + + public void deleteValues(int id) + { + String sql = prop.getProperty("delete"); + System.out.println("Deleting value from table"); + try + { + preparedStatement = conn.prepareStatement(sql); + //preparedStatement.setInt(1,"id"); + preparedStatement.setInt(1,id); + System.out.println("SQL command = " + preparedStatement); + int nodesAffected = preparedStatement.executeUpdate(); + System.out.println("Number of nodes affected:" + nodesAffected); + } + catch(SQLException se) + { + se.printStackTrace(); + } + + + } + public void updateValues(String fname_new, int id) + { + String sql = prop.getProperty("update"); + System.out.println("Updating value fname with id = " + id ); + try + { + preparedStatement = conn.prepareStatement(sql); + //preparedStatement.setInt(1,"id"); + preparedStatement.setString(1,fname_new); + preparedStatement.setInt(2,id); + System.out.println("SQL command = " + preparedStatement); + int nodesAffected = preparedStatement.executeUpdate(); + System.out.println("Number of nodes affected:" + nodesAffected); + } + catch(SQLException se) + { + se.printStackTrace(); + } + + } + + public void displayValues() + { + String sql = prop.getProperty("display"); + System.out.println("Displaying Table"); + try + { + preparedStatement = conn.prepareStatement(sql); + ResultSet resultSet = preparedStatement.executeQuery(sql); + ResultSetMetaData rsmd = resultSet.getMetaData(); + int columnsNumber = rsmd.getColumnCount(); + while (resultSet.next()) + { + for (int i = 1, j = 0; i <= columnsNumber ; i++,j++) + { + if (i > 1) System.out.print(", "); + String columnValue = resultSet.getString(i); + System.out.print(columnValue + " " + rsmd.getColumnName(i)); + } + System.out.println(); + } + } + catch(SQLException se) + { + se.printStackTrace(); + } + } + + + public ArrayList storeValues() throws SQLException + { + String sql = prop.getProperty("display"); + PreparedStatement preparedStatement = conn.prepareStatement(sql); + System.out.println("Storing Table"); + + ResultSet resultSet; + resultSet = preparedStatement.executeQuery(sql); + ResultSetMetaData rsmd = resultSet.getMetaData(); + int columnCount = rsmd.getColumnCount(); + +// ArrayList hotelResultList = new ArrayList<>(columnCount); +// while (results.next()) { +// int i = 1; +// while(i <= columnCount) { +// hotelResultList.add(results.getString(i++)); + + ArrayList tableData = new ArrayList<>(columnCount); + while (resultSet.next()) { + int i = 1; + Row row = new Row(); + while(i<= columnCount) + { + row.setRow(rsmd.getColumnName(i),resultSet.getString(rsmd.getColumnName(i++))); + } + tableData.add(row); + } + return tableData; + } + public void closeConnection() + { + + try + { + if(stmt!=null) + conn.close(); + } + catch(SQLException se) + { + }// do nothing + try + { + if(conn!=null) + conn.close(); + } + catch(SQLException se) + { + se.printStackTrace(); + } + System.out.println("Database connection closed successfully"); + } + +} \ No newline at end of file