diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..45069bc --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +/Graphify/dist/ +/Graphify/build/ \ No newline at end of file diff --git a/Graphify/Result.png b/Graphify/Result.png new file mode 100644 index 0000000..620504c Binary files /dev/null and b/Graphify/Result.png differ diff --git a/Graphify/SSandFiles/Choices.PNG b/Graphify/SSandFiles/Choices.PNG new file mode 100644 index 0000000..0c3a552 Binary files /dev/null and b/Graphify/SSandFiles/Choices.PNG differ diff --git a/Graphify/SSandFiles/controls.PNG b/Graphify/SSandFiles/controls.PNG new file mode 100644 index 0000000..7d502aa Binary files /dev/null and b/Graphify/SSandFiles/controls.PNG differ diff --git a/Graphify/SSandFiles/sim.ser b/Graphify/SSandFiles/sim.ser new file mode 100644 index 0000000..450ddb1 Binary files /dev/null and b/Graphify/SSandFiles/sim.ser differ diff --git a/Graphify/SSandFiles/speed and cap.PNG b/Graphify/SSandFiles/speed and cap.PNG new file mode 100644 index 0000000..320ad97 Binary files /dev/null and b/Graphify/SSandFiles/speed and cap.PNG differ diff --git a/Graphify/best network.ser b/Graphify/best network.ser new file mode 100644 index 0000000..249c012 Binary files /dev/null and b/Graphify/best network.ser differ diff --git a/Graphify/build.xml b/Graphify/build.xml index b18dcdd..d3b1053 100644 --- a/Graphify/build.xml +++ b/Graphify/build.xml @@ -7,8 +7,8 @@ - - Builds, tests, and runs the project Graphify. + + Builds, tests, and runs the project GraphifyGUI. " + v); + return; + } + for (int i = e; i >= 0; i = Model.vertices.get(i).getParent().getId()) { + if (i == v) { + break; + } + if (Model.vertices.get(i).getParent().getId() != -1) { + Model.setShortestPath.put(Model.vertices.get(i).getParent(), Model.vertices.get(i)); + Model.Capacity += getWeight(Model.vertices.get(i).parent, Model.vertices.get(i)); + } + } + + Model.Gui.setlblCapTransferred(String.valueOf(Model.Capacity)); + if (Model.Capacity <= Model.vertices.get(e).getCapacity()) { + Model.Gui.setlblCapTransferredColor(Color.red); + } else { + Model.Gui.setlblCapTransferredColor(Color.blue); + } + Model.glowMap.clear(); + Model.glowMap = (HashMap) Model.setShortestPath.clone(); + Model.Gui.graph(); + } + + public static void reset() { + for (Vertex v : Model.vertices.values()) { + v.setVisited(false); + } + for (Edge e : Model.edges) { + e.setFailed(false); + } + Model.setShortestPath.clear(); + Model.glowMap.clear(); + } + + static boolean isConnected() { + Vertex s = Model.vertices.get(Model._source); + Bfs(s); + Iterator vert = Model.vertices.values().iterator(); + while (vert.hasNext()) { + Vertex key = vert.next(); + if (!key.visited()) { + return false; + } + } + return true; + } + + public static int hasPath(int v) { + return Model.visited.get(v); + } + + public static int distTo(int v) { + return Model.distTo.get(v); + } +} diff --git a/Graphify/src/graphify/Ant.java b/Graphify/src/graphify/Ant.java new file mode 100644 index 0000000..cb3befa --- /dev/null +++ b/Graphify/src/graphify/Ant.java @@ -0,0 +1,25 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package graphify; + +import java.util.HashSet; + +/** + * + * @author Ayomitunde + */ +public class Ant { + int antID; + String antName; + int currNode; + HashSet path; + public Ant(int id, String name, int currentNode){ + this.antID = id; + this.antName = name; + this.currNode = currentNode; + } + +} diff --git a/Graphify/src/graphify/Commands.java b/Graphify/src/graphify/Commands.java new file mode 100644 index 0000000..5cf8c58 --- /dev/null +++ b/Graphify/src/graphify/Commands.java @@ -0,0 +1,165 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package graphify; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; + +/** + * this class will be used for analyzing commands + * + * @author Ayomitunde + */ +enum Types { + Person, + Place, + City +} + +public class Commands { + + static ArrayList cutV; + + static String action(String query, Vertex source, HashMap v) { + String[] tokens = query.split(" "); + String first = tokens[0]; + if (first.equals("find")) { + return find(query, v, source); + } else if (first.equals("get")) { + return get(query, source); + } else if (first.equals("places")) { + return places(query, source); + } + return ""; + } + + static String find(String query, HashMap v, Vertex s) { + String result = ""; + String[] tokens = query.split(" "); + String sec = tokens[1]; + // not so wise implementation + String chec = String.valueOf(sec.charAt(sec.length() - 1)); + String n = null; + if (query.indexOf(chec) + 1 != query.length()) { + n = tokens[2]; + } + cutV = new ArrayList<>(); + //String n2 = tokens[3]; + if (sec.equals("all")) { + if (n != null) { + cutV.clear(); + if (n.equals("people") || n.equals("places") || n.equals("cities")) { + Iterator verts = v.values().iterator(); + while (verts.hasNext()) { + Vertex next = verts.next(); + if (next.getType().equals(Types.Person.toString()) && n.equals("people")) { // change to enumerable + cutV.add(next.getId()); + result += next.getLabel(); + //}else if(n2.equals("between")){ + + //} + } else if (next.getType().equals(Types.City.toString()) && n.equals("cities")) { + cutV.add(next.getId()); + result += next.getLabel(); + } else if (next.getType().equals(Types.Place.toString()) && n.equals("places")) { + cutV.add(next.getId()); + result += next.getLabel(); + } + } + } + } else { + // do nothing for now + } + } else if (sec.equals("my")) { + if (n != null) { + cutV.clear(); + result = ""; + if (n.equals("friends") || n.equals("places") || n.equals("cities")) { + Iterator mine = s.eList().iterator(); + while (mine.hasNext()) { + Edge t = mine.next(); + Vertex next = Algorithms.getConn(s, t); + if (next.getType().equals(Types.Person.toString()) && n.equals("friends")) { + cutV.add(next.getId()); + } else if (next.getType().equals(Types.City.toString()) && n.equals("cities")) { + cutV.add(next.getId()); + + } else if (next.getType().equals(Types.Place.toString()) && n.equals("places")) { + cutV.add(next.getId()); + } + } + } + } + } else if (sec.equals("friends") || sec.equals("places") || sec.equals("cities")) { + cutV.clear(); + result = ""; + switch (sec) { + case "friends": + cutV = Algorithms.BfsSuggeest(s, 0); + break; + case "places": + cutV = Algorithms.BfsSuggeest(s, 1); + break; + case "cities": + cutV = Algorithms.BfsSuggeest(s, 2); + break; + default: + break; + } + }else if(sec.equals("best")){ + if(n != null){ + cutV.clear(); + result = ""; + if(n.equals("places") || n.equals("cities")){ + if(n.equals("places")){ + cutV = Algorithms.BfsSuggeest(s, 3); + } + } + } + } + return result; + } + + static void between(String query) { + String[] tokens = query.split(" "); + } + + static String places(String query, Vertex source) { + String places = ""; + String[] tokens = query.split(" "); + String sec = tokens[1]; + if (sec.equals("i")) { + Iterator p = source.eList().iterator(); + while (p.hasNext()) { + Edge t = p.next(); + Vertex pla = Algorithms.getConn(source, t); + if (pla.getType().equals("Place")) { + places += pla.getName() + " "; + } + } + } + return places; + } + + static String get(String query, Vertex source) { + String[] tokens = query.split(" "); + String sec = tokens[1]; + String friendList = ""; + if (sec.equals("friends")) { + Iterator friends = source.eList().iterator(); + while (friends.hasNext()) { + Edge t = friends.next(); + Vertex f = Algorithms.getConn(source, t); + if (f.getType().equals("Person")) { + friendList += f.getName() + " "; + } + } + } + return friendList; + } + +} diff --git a/Graphify/src/graphify/GA.java b/Graphify/src/graphify/GA.java new file mode 100644 index 0000000..922756b --- /dev/null +++ b/Graphify/src/graphify/GA.java @@ -0,0 +1,123 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package graphify; + +/** + * + * @author Ayomitunde + */ +public class GA { + + private static final double _mutationRate = 0.015; + private static final int _tournamentSize = 10; + private static final boolean _elitism = true; + public static Tour parent1; + public static Tour parent2; + + public static Population evolvePopulation(Population pop) { + Population newPopulation = new Population(pop.populationSize(), false); + int elitismOffset = 0; + if (_elitism) { + newPopulation.saveTour(0, pop.getFittest(0)); + elitismOffset = 1; + } + + for (int i = elitismOffset; i < newPopulation.populationSize(); i++) { + tournamentSelection(pop); + parent1 = pop.getTour(0); + parent2 = pop.getTour(1); + Tour child = crossover(parent1, parent2); + Model.Gui.printlnConsole("Iteration " + Model.counter + "\nParent1 " + parent1.toString() + "\nParent2 " + parent2.toString() + "\nChild " + child.toString()); + TSP_GA.setPath(child); + child.getFitness(); + newPopulation.saveTour(i, child); + Model.Gui.setlblIterations(String.valueOf(Model.counter++)); + } + + for (int i = elitismOffset; i < newPopulation.populationSize(); i++) { + mutate(newPopulation.getTour(i)); + } + return newPopulation; + } + + public static Tour crossover(Tour parent1, Tour parent2) { + Tour child = new Tour(); + + int startPos = (int) (Math.random() * parent1.tourSize()); + int endPos = (int) (Math.random() * parent1.tourSize()); + + for (int i = 0; i < child.tourSize(); i++) { + if (startPos < endPos && i > startPos && i < endPos) { + child.setVertex(i, parent1.getVertex(i)); + } else if (startPos > endPos) { + if (!(i < startPos && i > endPos)) { + child.setVertex(i, parent1.getVertex(i)); + } + } + } + + + for (int i = 0; i < parent2.tourSize(); i++) { + if (!child.containsVertex(parent2.getVertex(i))) { + for (int j = 0; j < child.tourSize(); j++) { + if (child.getVertex(j) == null) { + child.setVertex(j, parent2.getVertex(i)); + break; + } + } + } + } + //authen(child); + return child; + } + + // if there is a null after crossover, pick a random node and add it + static void authen(Tour tour) { + for (int i = 0; i < tour.tourSize(); i++) { + if (tour.getVertex(i) == null) { + for (Integer v : Model.vertices.keySet()) { + Vertex vertex = Model.vertices.get(v); + if (tour.containsVertex(vertex) == false) { + tour.setVertex(i, vertex); + } + } + } + } + } + + private static void mutate(Tour tour) { + for (int tourPos1 = 0; tourPos1 < tour.tourSize(); tourPos1++) { + if (Math.random() < _mutationRate) { + int tourPos2 = (int) (tour.tourSize() * Math.random()); + Vertex vertex1 = tour.getVertex(tourPos1); + Vertex vertex2 = tour.getVertex(tourPos2); + + tour.setVertex(tourPos2, vertex1); + tour.setVertex(tourPos1, vertex2); + } + } + } + + private static Tour tourSelection(Population pop) { + Population tournament = new Population(_tournamentSize, false); + for (int i = 0; i < _tournamentSize; i++) { + int randomId = (int) (Math.random() * pop.populationSize()); + tournament.saveTour(i, pop.getTour(randomId)); + } + Tour fittest = tournament.getFittest(0); + return fittest; + } + + private static void tournamentSelection(Population pop) { + Population tournament = new Population(_tournamentSize, false); + for (int i = 0; i < _tournamentSize; i++) { + int randomId = (int) (Math.random() * pop.populationSize()); + tournament.saveTour(i, pop.getTour(randomId)); + } + tournament.getParents(); + } + +} diff --git a/Graphify/src/graphify/Graphify.form b/Graphify/src/graphify/Graphify.form deleted file mode 100644 index 3cb2d5c..0000000 --- a/Graphify/src/graphify/Graphify.form +++ /dev/null @@ -1,105 +0,0 @@ - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
diff --git a/Graphify/src/graphify/Graphify.java b/Graphify/src/graphify/Graphify.java deleted file mode 100644 index 6486a36..0000000 --- a/Graphify/src/graphify/Graphify.java +++ /dev/null @@ -1,386 +0,0 @@ -package graphify; - -import com.google.common.collect.BiMap; -import com.google.common.collect.HashBiMap; -import java.awt.Color; -import java.awt.Graphics; -import java.awt.Image; -import java.awt.Point; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.HashSet; -import java.util.LinkedList; -import java.util.Map; -import java.util.Queue; -import java.util.stream.Collectors; -import javax.swing.SwingUtilities; - -public class Graphify extends javax.swing.JFrame { - HashMap connectionCache = new HashMap<>(); - HashMap> nodes = new HashMap(); - private Queue queue; - HashMap locations = new HashMap(); - private HashMapdistTo; - private BiMap set = HashBiMap.create(); - HashMap visited; - ArrayList conn; - int _selectedNode = -1; - int _SIZE_OF_NODE = 20; - int id = 0; - static int _source = 0; - static int _dest = 0; - Image bufferImage; - Graphics bufferGraphic; - - public Graphify() { - initComponents(); - bufferImage = createImage(pnlGraph.getWidth(), pnlGraph.getHeight()); - bufferGraphic = bufferImage.getGraphics(); - queue = new LinkedList(); - } - - @SuppressWarnings("unchecked") - // //GEN-BEGIN:initComponents - private void initComponents() { - - pnlGraph = new javax.swing.JPanel(); - btnReset = new javax.swing.JButton(); - btnPrintList = new javax.swing.JButton(); - - setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); - - pnlGraph.setBackground(new java.awt.Color(255, 255, 255)); - pnlGraph.setBorder(javax.swing.BorderFactory.createEtchedBorder()); - pnlGraph.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() { - public void mouseDragged(java.awt.event.MouseEvent evt) { - pnlGraphMouseDragged(evt); - } - }); - pnlGraph.addMouseListener(new java.awt.event.MouseAdapter() { - public void mouseClicked(java.awt.event.MouseEvent evt) { - pnlGraphMouseClicked(evt); - } - public void mousePressed(java.awt.event.MouseEvent evt) { - pnlGraphMousePressed(evt); - } - public void mouseReleased(java.awt.event.MouseEvent evt) { - pnlGraphMouseReleased(evt); - } - }); - pnlGraph.addComponentListener(new java.awt.event.ComponentAdapter() { - public void componentResized(java.awt.event.ComponentEvent evt) { - pnlGraphComponentResized(evt); - } - }); - - javax.swing.GroupLayout pnlGraphLayout = new javax.swing.GroupLayout(pnlGraph); - pnlGraph.setLayout(pnlGraphLayout); - pnlGraphLayout.setHorizontalGroup( - pnlGraphLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) - .addGap(0, 0, Short.MAX_VALUE) - ); - pnlGraphLayout.setVerticalGroup( - pnlGraphLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) - .addGap(0, 249, Short.MAX_VALUE) - ); - - btnReset.setText("Reset"); - btnReset.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - btnResetActionPerformed(evt); - } - }); - - btnPrintList.setText("Print List"); - btnPrintList.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - btnPrintListActionPerformed(evt); - } - }); - - javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); - getContentPane().setLayout(layout); - layout.setHorizontalGroup( - layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) - .addGroup(layout.createSequentialGroup() - .addContainerGap() - .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) - .addGroup(layout.createSequentialGroup() - .addComponent(btnReset) - .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 205, Short.MAX_VALUE) - .addComponent(btnPrintList)) - .addComponent(pnlGraph, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) - .addContainerGap()) - ); - layout.setVerticalGroup( - layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) - .addGroup(layout.createSequentialGroup() - .addContainerGap() - .addComponent(pnlGraph, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) - .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) - .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) - .addComponent(btnReset) - .addComponent(btnPrintList)) - .addContainerGap()) - ); - - pack(); - }// //GEN-END:initComponents - - private void pnlGraphMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_pnlGraphMousePressed - _selectedNode = nodeSelected(evt.getX(), evt.getY()); - if (_selectedNode < 0 && SwingUtilities.isLeftMouseButton(evt)) { - nodes.put(id, new HashSet()); - locations.put(id++, new Point(evt.getX(), evt.getY())); - } else { - if (SwingUtilities.isLeftMouseButton(evt)) { - } else if (SwingUtilities.isRightMouseButton(evt)) { - nodes.remove(_selectedNode); - locations.remove(_selectedNode); - for (HashSet connections: nodes.values()) { - for (int j = 0; j < connections.size(); j++) { - Integer connection = (Integer) connections.toArray()[j]; - if (connection == _selectedNode) { - connections.remove(connection); - j--; - } - } - } - _selectedNode = -1; - } - } - graph(); - }//GEN-LAST:event_pnlGraphMousePressed - - private void pnlGraphMouseDragged(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_pnlGraphMouseDragged - if (_selectedNode >= 0) { - if (SwingUtilities.isLeftMouseButton(evt)) { - Image buff = createImage(pnlGraph.getWidth(), pnlGraph.getHeight()); - Graphics buffG = buff.getGraphics(); - buffG.drawImage(bufferImage, 0, 0, this); - Point source = locations.get(_selectedNode); - buffG.drawLine(source.x, source.y, - evt.getX(), evt.getY()); - pnlGraph.getGraphics().drawImage(buff, 0, 0, this); - } else if (SwingUtilities.isMiddleMouseButton(evt)) { - locations.get(_selectedNode).x = evt.getX(); - locations.get(_selectedNode).y = evt.getY(); - graph(); - } - } - }//GEN-LAST:event_pnlGraphMouseDragged - - private void pnlGraphComponentResized(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_pnlGraphComponentResized - bufferImage = createImage(pnlGraph.getWidth(), pnlGraph.getHeight()); - bufferGraphic = bufferImage.getGraphics(); - }//GEN-LAST:event_pnlGraphComponentResized - - private void pnlGraphMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_pnlGraphMouseReleased - if (_selectedNode >= 0) { - int destination = nodeSelected(evt.getX(), evt.getY()); - if (destination >= 0 && destination != _selectedNode) { - nodes.get(_selectedNode).add(destination); - nodes.get(destination).add(_selectedNode); - _selectedNode = -1; - } - } - graph(); - }//GEN-LAST:event_pnlGraphMouseReleased - - public HashSet getEdge(int source) { - return nodes.get(source); - } - - void bfs(int source) { - int V = nodes.size(); - distTo = new HashMap<>(); - visited = new HashMap<>(); - for (int i = 0; i < V; i++) { - Integer key = (Integer) nodes.keySet().toArray()[i]; - visited.put(key, -1); - distTo.put(key, 0); - } - conn = new ArrayList(); - int i, element; - visited.put(source, 0); - queue.add(source); - while (!queue.isEmpty()) { - element = queue.remove(); - System.out.println(element + " removed"); - i = element; - conn.add(element); - HashSet iList = getEdge(i); - int x = 0; - while (x < iList.size()) { - Integer key = (Integer) iList.toArray()[x]; - if (visited.get(key) == -1) { - queue.add((Integer) iList.toArray()[x]); - visited.put(key, i); - distTo.put(key, distTo.get(i) + 1); - } - x++; - } - } - System.out.println("Order is " + conn); - } - - public int hasPath(int v) { - return visited.get(v); - } - - public int distTo(int v) { - return distTo.get(v); - } - - public void shortestPath(int v, int e) { - if (e == v) { - System.out.println(v + "-->" + v); -// System.exit(0); - return; - } - for (int i = e; i > 0; i = visited.get(i)) { - if (i == v) { - break; - } - if (visited.get(i) != -1) { - set.put(i, visited.get(i)); - } - } - Map rset = set.entrySet() - .stream() - .collect(Collectors.toMap(Map.Entry::getValue, Map.Entry::getKey)); - System.out.println(rset.toString().replaceAll("=", "-->")); - - } - //[0, 2, 19, 5, 7, 9, 14] - - private void btnPrintListActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnPrintListActionPerformed - for (int i = 0; i < nodes.size(); i++) { - int key = (Integer) nodes.keySet().toArray()[i]; - System.out.println(key + "->" + getEdge(key)); - } - System.out.println("Source is: " + _source); - }//GEN-LAST:event_btnPrintListActionPerformed - - private void btnResetActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnResetActionPerformed - nodes = new HashMap(); - locations = new HashMap(); - id = 0; - graph(); - }//GEN-LAST:event_btnResetActionPerformed - - private void pnlGraphMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_pnlGraphMouseClicked - _selectedNode = nodeSelected(evt.getX(), evt.getY()); - if (evt.getClickCount() == 2) { - set.clear(); - _source = _selectedNode; - bfs(_source); - _dest = conn.get(conn.size()-1); - shortestPath(_source, _dest); - } - }//GEN-LAST:event_pnlGraphMouseClicked - - private void graph() { - bufferGraphic.setColor(Color.white); - bufferGraphic.fillRect(0, 0, pnlGraph.getWidth(), pnlGraph.getHeight()); - bufferGraphic.setColor(Color.black); - connectionCache.clear(); - for (int i = 0; i < locations.size(); i++) { - Integer sourceKey = (Integer) nodes.keySet().toArray()[i]; - Point thePoint = (Point) locations.values().toArray()[i]; - for (Integer destinationKey : - (HashSet) nodes.values().toArray()[i]) { - if (!(connectionCache.containsKey(sourceKey) - && connectionCache.get(sourceKey) == destinationKey - || connectionCache.containsKey(destinationKey) - && connectionCache.get(destinationKey) == sourceKey)) { - Point destinantionPoint = locations.get(destinationKey); - bufferGraphic.drawLine(thePoint.x, thePoint.y, - destinantionPoint.x, destinantionPoint.y); - connectionCache.put(sourceKey, destinationKey); - } - } - } - for (int i = 0; i < locations.size(); i++) { - Point thePoint = (Point) locations.values().toArray()[i]; - if (locations.keySet().toArray()[i] == (Integer) _selectedNode) { - bufferGraphic.setColor(Color.orange); - } else { - bufferGraphic.setColor(Color.red); - } - bufferGraphic.fillOval(thePoint.x - _SIZE_OF_NODE / 2, - thePoint.y - _SIZE_OF_NODE / 2, _SIZE_OF_NODE, _SIZE_OF_NODE); - } - - bufferGraphic.setColor(Color.blue); - for (int i = 0; i < locations.size(); i++) { - Point thePoint = (Point) locations.values().toArray()[i]; - bufferGraphic.drawString("V " + locations.keySet().toArray()[i], - thePoint.x + _SIZE_OF_NODE + 4, thePoint.y + _SIZE_OF_NODE + 4); - } - pnlGraph.getGraphics().drawImage(bufferImage, 0, 0, this); - } - - private int nodeSelected(int x, int y) { - for (int i = 0; i < locations.size(); i++) { - Point thePoint = (Point) locations.values().toArray()[i]; - int deltaX = x - (thePoint.x - _SIZE_OF_NODE / 2); - int deltaY = y - (thePoint.y - _SIZE_OF_NODE / 2); - if (Math.sqrt(deltaX * deltaX - + deltaY * deltaY) <= _SIZE_OF_NODE) { - return (int) locations.keySet().toArray()[i]; - } - } - return -1; - } - - @Override - public void paint(Graphics g) { - super.paint(g); - graph(); - } - - /** - * @param args the command line arguments - */ - public static void main(String args[]) { - /* Set the Nimbus look and feel */ - // - /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. - * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html - */ - try { - for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { - if ("Nimbus".equals(info.getName())) { - javax.swing.UIManager.setLookAndFeel(info.getClassName()); - break; - } - } - } catch (ClassNotFoundException ex) { - java.util.logging.Logger.getLogger(Graphify.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); - } catch (InstantiationException ex) { - java.util.logging.Logger.getLogger(Graphify.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); - } catch (IllegalAccessException ex) { - java.util.logging.Logger.getLogger(Graphify.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); - } catch (javax.swing.UnsupportedLookAndFeelException ex) { - java.util.logging.Logger.getLogger(Graphify.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); - } - // - - /* Create and display the form */ - java.awt.EventQueue.invokeLater(new Runnable() { - public void run() { - Graphify theGraph = new Graphify(); - theGraph.setLocationRelativeTo(null); - theGraph.show(); - } - }); - } - - // Variables declaration - do not modify//GEN-BEGIN:variables - private javax.swing.JButton btnPrintList; - private javax.swing.JButton btnReset; - private javax.swing.JPanel pnlGraph; - // End of variables declaration//GEN-END:variables -} diff --git a/Graphify/src/graphify/GraphifyGUI.form b/Graphify/src/graphify/GraphifyGUI.form new file mode 100644 index 0000000..a9a7e6f --- /dev/null +++ b/Graphify/src/graphify/GraphifyGUI.form @@ -0,0 +1,620 @@ + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Graphify/src/graphify/GraphifyGUI.java b/Graphify/src/graphify/GraphifyGUI.java new file mode 100644 index 0000000..880d750 --- /dev/null +++ b/Graphify/src/graphify/GraphifyGUI.java @@ -0,0 +1,1608 @@ +/* +* To change this license header, choose License Headers in Project Properties. +* To change this template file, choose Tools | Templates +* and open the template in the editor. + */ +package graphify; + +import java.awt.BasicStroke; +import java.awt.Color; +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.Image; +import java.awt.Point; +import java.awt.Polygon; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.KeyEvent; +import java.awt.event.WindowAdapter; +import java.awt.event.WindowEvent; +import java.awt.image.RenderedImage; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.logging.Level; +import java.util.logging.Logger; +import javax.imageio.ImageIO; +import javax.swing.JFileChooser; +import javax.swing.JOptionPane; +import javax.swing.JToggleButton; +import javax.swing.SwingUtilities; +import javax.swing.Timer; +import javax.swing.filechooser.FileNameExtensionFilter; + +/** + * + * @author Ayomitunde + */ +public class GraphifyGUI extends javax.swing.JFrame { + + private static final long serialVersionUID = 1L; + Image bufferImage; + Graphics2D bufferGraphic; + private ActionListener decreseWeights; + private JToggleButton[] tools = new JToggleButton[3]; + static boolean isWeighted = false; + static boolean isComplete = false; + + public GraphifyGUI() { + initComponents(); + bufferImage = createImage(pnlGraph.getWidth() - 2, pnlGraph.getHeight() - 2); + bufferGraphic = (Graphics2D) bufferImage.getGraphics(); + hider(); + Model.vertices = new HashMap<>(); + Model.edges = new ArrayList<>(); + Model.failed = new ArrayList<>(); + Model.vertexColors = new Color[]{Color.blue, Color.red, Color.yellow, Color.green, Color.magenta, Color.orange}; + Model.randomKeys = new HashSet<>(); + Model.glowMap = new HashMap<>(); + Model.cutV = new ArrayList<>(); + Model.set = new HashMap<>(); + Model.visited = new HashMap<>(); + Timer animationTimer = new Timer(30, (ActionEvent e) -> { + if (Model.glowMap.size() > 0) { + Model.dotOffset = (Model.dotOffset + .07) % 1; + graph(); + } + }); + animationTimer.start(); + this.addWindowListener(new WindowAdapter() { + @Override + public void windowClosing(WindowEvent e) { + if (checkForChange()) { + System.exit(0); + } + } + }); + + for (int i = 0; i < tools.length; i++) { + tools[i] = new JToggleButton(); + tools[i].setFocusable(false); + tools[i].setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); + tools[i].setPreferredSize(new java.awt.Dimension(40, 40)); + tools[i].setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM); + tools[i].addActionListener((ActionEvent e) -> { + for (JToggleButton tool : tools) { + if (tool != e.getSource()) { + tool.setSelected(false); + } + } + }); + jToolBar1.add(tools[i]); + } + tools[0].setIcon(new javax.swing.ImageIcon(getClass().getResource("/graphify/images/vertex.png"))); + tools[0].setToolTipText("Place Vertex"); + tools[1].setIcon(new javax.swing.ImageIcon(getClass().getResource("/graphify/images/bidirectional.png"))); + tools[1].setToolTipText("Bidirectonal"); + tools[2].setIcon(new javax.swing.ImageIcon(getClass().getResource("/graphify/images/directional.png"))); + tools[2].setToolTipText("Directional"); + } + + @SuppressWarnings("unchecked") + // //GEN-BEGIN:initComponents + private void initComponents() { + + buttonGroup1 = new javax.swing.ButtonGroup(); + btnReset = new javax.swing.JButton(); + lblInfo = new java.awt.Label(); + btnStart = new javax.swing.JButton(); + btnPrintList = new javax.swing.JButton(); + jSplitPane1 = new javax.swing.JSplitPane(); + pnlGraph = new javax.swing.JPanel(){ + @Override + public void paintComponent(Graphics g) { + graph(); + super.paintComponent(g); + } + }; + jScrollPane2 = new javax.swing.JScrollPane(); + txtConsole = new javax.swing.JTextArea(); + jToolBar1 = new javax.swing.JToolBar(); + sldrWeightSpeed = new javax.swing.JSlider(); + jLabel1 = new javax.swing.JLabel(); + lblCapacity = new javax.swing.JLabel(); + lblCapTransferred = new javax.swing.JLabel(); + lblInitalDistance = new javax.swing.JLabel(); + lblFinalDistance = new javax.swing.JLabel(); + lblInitalDistValue = new javax.swing.JLabel(); + lblFinalDistValue = new javax.swing.JLabel(); + btnGenResult = new javax.swing.JButton(); + jcbAlgo = new javax.swing.JComboBox<>(); + btnClearConsole = new javax.swing.JButton(); + rdnFailSim = new javax.swing.JRadioButton(); + jLabel2 = new javax.swing.JLabel(); + txtVertexLookUp = new javax.swing.JTextField(); + btnFindVertex = new javax.swing.JButton(); + lblNoIterations = new javax.swing.JLabel(); + txtIterNum = new javax.swing.JTextField(); + jLabel6 = new javax.swing.JLabel(); + lblTimeTaken = new javax.swing.JLabel(); + lblTemperature = new javax.swing.JLabel(); + txtTemperature = new javax.swing.JTextField(); + lblCoolingRate = new javax.swing.JLabel(); + txtCoolingRate = new javax.swing.JTextField(); + jLabel3 = new javax.swing.JLabel(); + lblIterationNum = new javax.swing.JLabel(); + jMenuBar1 = new javax.swing.JMenuBar(); + mnuFile = new javax.swing.JMenu(); + mnuNew = new javax.swing.JMenuItem(); + mnuOpen = new javax.swing.JMenuItem(); + mnuSave = new javax.swing.JMenuItem(); + mnuSaveAs = new javax.swing.JMenuItem(); + mnuQuit = new javax.swing.JMenuItem(); + mnuEdit = new javax.swing.JMenu(); + mnuUpdateWeight = new javax.swing.JMenuItem(); + jMenu1 = new javax.swing.JMenu(); + jMenuItem1 = new javax.swing.JMenuItem(); + jMenuItem2 = new javax.swing.JMenuItem(); + chkComplete = new javax.swing.JCheckBoxMenuItem(); + + setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); + + btnReset.setText("Reset"); + btnReset.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + btnResetActionPerformed(evt); + } + }); + + lblInfo.setText("Source: None - Destination: None"); + + btnStart.setText("Start"); + btnStart.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + btnStartActionPerformed(evt); + } + }); + + btnPrintList.setText("Print List"); + btnPrintList.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + btnPrintListActionPerformed(evt); + } + }); + + jSplitPane1.setDividerSize(3); + jSplitPane1.setOrientation(javax.swing.JSplitPane.VERTICAL_SPLIT); + jSplitPane1.setResizeWeight(0.7); + + pnlGraph.setBackground(new java.awt.Color(255, 255, 255)); + pnlGraph.setBorder(javax.swing.BorderFactory.createEtchedBorder()); + pnlGraph.setPreferredSize(new java.awt.Dimension(400, 500)); + pnlGraph.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() { + public void mouseDragged(java.awt.event.MouseEvent evt) { + pnlGraphMouseDragged(evt); + } + }); + pnlGraph.addMouseListener(new java.awt.event.MouseAdapter() { + public void mouseClicked(java.awt.event.MouseEvent evt) { + pnlGraphMouseClicked(evt); + } + public void mousePressed(java.awt.event.MouseEvent evt) { + pnlGraphMousePressed(evt); + } + public void mouseReleased(java.awt.event.MouseEvent evt) { + pnlGraphMouseReleased(evt); + } + }); + pnlGraph.addComponentListener(new java.awt.event.ComponentAdapter() { + public void componentResized(java.awt.event.ComponentEvent evt) { + pnlGraphComponentResized(evt); + } + }); + pnlGraph.addKeyListener(new java.awt.event.KeyAdapter() { + public void keyPressed(java.awt.event.KeyEvent evt) { + pnlGraphKeyPressed(evt); + } + }); + + javax.swing.GroupLayout pnlGraphLayout = new javax.swing.GroupLayout(pnlGraph); + pnlGraph.setLayout(pnlGraphLayout); + pnlGraphLayout.setHorizontalGroup( + pnlGraphLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGap(0, 1089, Short.MAX_VALUE) + ); + pnlGraphLayout.setVerticalGroup( + pnlGraphLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGap(0, 496, Short.MAX_VALUE) + ); + + jSplitPane1.setLeftComponent(pnlGraph); + + txtConsole.setEditable(false); + txtConsole.setColumns(20); + txtConsole.setFont(new java.awt.Font("Monospaced", 0, 18)); // NOI18N + txtConsole.setRows(5); + jScrollPane2.setViewportView(txtConsole); + + jSplitPane1.setRightComponent(jScrollPane2); + + jToolBar1.setBorder(javax.swing.BorderFactory.createEtchedBorder()); + jToolBar1.setFloatable(false); + jToolBar1.setOrientation(javax.swing.SwingConstants.VERTICAL); + jToolBar1.setRollover(true); + + sldrWeightSpeed.setMaximum(950); + sldrWeightSpeed.setValue(500); + + jLabel1.setText("Cost Change Speed"); + + lblCapacity.setText("Capacity Transferred"); + + lblCapTransferred.setText("0"); + + lblInitalDistance.setText("Initial Distance"); + + lblFinalDistance.setText("Final Distance"); + + lblInitalDistValue.setText("0"); + + lblFinalDistValue.setText("0"); + + btnGenResult.setText("Generate Result"); + btnGenResult.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + btnGenResultActionPerformed(evt); + } + }); + + jcbAlgo.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "BFS", "OtherBfs", "DFS", "Dijkstra", "Connectedness", "TSP-SA", "TSP-GA", "Nearest Neighbor" })); + jcbAlgo.setSelectedIndex(0); + jcbAlgo.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + jcbAlgoActionPerformed(evt); + } + }); + + btnClearConsole.setText("Clear Console"); + btnClearConsole.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + btnClearConsoleActionPerformed(evt); + } + }); + + rdnFailSim.setText("Fail Sim"); + rdnFailSim.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + rdnFailSimActionPerformed(evt); + } + }); + + jLabel2.setText("Select Simulation"); + + btnFindVertex.setText("Vertex LookUp"); + btnFindVertex.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + btnFindVertexActionPerformed(evt); + } + }); + + lblNoIterations.setText("Number of Iterations"); + + txtIterNum.setText("100"); + + jLabel6.setText("Time Taken"); + + lblTimeTaken.setText("0"); + + lblTemperature.setText("Temperature"); + + txtTemperature.setText("10000"); + + lblCoolingRate.setText("Cooling Rate"); + + txtCoolingRate.setText("0.003"); + + jLabel3.setText("Iteration"); + + lblIterationNum.setText("0"); + + mnuFile.setText("File"); + + mnuNew.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_N, java.awt.event.InputEvent.CTRL_MASK)); + mnuNew.setText("New"); + mnuNew.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + mnuNewActionPerformed(evt); + } + }); + mnuFile.add(mnuNew); + + mnuOpen.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_O, java.awt.event.InputEvent.CTRL_MASK)); + mnuOpen.setText("Open"); + mnuOpen.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + mnuOpenActionPerformed(evt); + } + }); + mnuFile.add(mnuOpen); + + mnuSave.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_S, java.awt.event.InputEvent.CTRL_MASK)); + mnuSave.setText("Save"); + mnuSave.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + mnuSaveActionPerformed(evt); + } + }); + mnuFile.add(mnuSave); + + mnuSaveAs.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_S, java.awt.event.InputEvent.SHIFT_MASK | java.awt.event.InputEvent.CTRL_MASK)); + mnuSaveAs.setText("Save as..."); + mnuSaveAs.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + mnuSaveAsActionPerformed(evt); + } + }); + mnuFile.add(mnuSaveAs); + + mnuQuit.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_Q, java.awt.event.InputEvent.CTRL_MASK)); + mnuQuit.setText("Quit"); + mnuQuit.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + mnuQuitActionPerformed(evt); + } + }); + mnuFile.add(mnuQuit); + + jMenuBar1.add(mnuFile); + + mnuEdit.setText("Edit"); + + mnuUpdateWeight.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_P, java.awt.event.InputEvent.CTRL_MASK)); + mnuUpdateWeight.setText("Node Properties"); + mnuUpdateWeight.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + mnuUpdateWeightActionPerformed(evt); + } + }); + mnuEdit.add(mnuUpdateWeight); + + jMenu1.setText("Graph Type"); + + jMenuItem1.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_W, java.awt.event.InputEvent.SHIFT_MASK)); + jMenuItem1.setText("Weighted"); + jMenuItem1.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + jMenuItem1ActionPerformed(evt); + } + }); + jMenu1.add(jMenuItem1); + + jMenuItem2.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_U, java.awt.event.InputEvent.SHIFT_MASK)); + jMenuItem2.setText("UnWeighted"); + jMenuItem2.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + jMenuItem2ActionPerformed(evt); + } + }); + jMenu1.add(jMenuItem2); + + chkComplete.setSelected(false); + chkComplete.setText("Complete"); + chkComplete.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + chkCompleteActionPerformed(evt); + } + }); + jMenu1.add(chkComplete); + + mnuEdit.add(jMenu1); + + jMenuBar1.add(mnuEdit); + + setJMenuBar(jMenuBar1); + + javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); + getContentPane().setLayout(layout); + layout.setHorizontalGroup( + layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(layout.createSequentialGroup() + .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) + .addComponent(jToolBar1, javax.swing.GroupLayout.PREFERRED_SIZE, 47, javax.swing.GroupLayout.PREFERRED_SIZE) + .addComponent(rdnFailSim) + .addComponent(btnStart, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addComponent(btnClearConsole, javax.swing.GroupLayout.DEFAULT_SIZE, 115, Short.MAX_VALUE) + .addComponent(btnReset, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addComponent(jcbAlgo, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addGroup(layout.createSequentialGroup() + .addContainerGap() + .addComponent(jLabel2))) + .addGap(10, 10, 10) + .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(layout.createSequentialGroup() + .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(layout.createSequentialGroup() + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 655, Short.MAX_VALUE) + .addComponent(lblInfo, javax.swing.GroupLayout.PREFERRED_SIZE, 197, javax.swing.GroupLayout.PREFERRED_SIZE)) + .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() + .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) + .addGroup(layout.createSequentialGroup() + .addComponent(lblInitalDistance) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(lblInitalDistValue, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE)) + .addGroup(layout.createSequentialGroup() + .addComponent(lblFinalDistance) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addComponent(lblFinalDistValue, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE))) + .addGap(43, 43, 43) + .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(jLabel6) + .addComponent(jLabel3)) + .addGap(18, 18, 18) + .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(lblTimeTaken, javax.swing.GroupLayout.PREFERRED_SIZE, 59, javax.swing.GroupLayout.PREFERRED_SIZE) + .addComponent(lblIterationNum, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(jLabel1) + .addComponent(lblCapacity)))) + .addGap(30, 30, 30) + .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(sldrWeightSpeed, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() + .addComponent(lblCapTransferred, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE) + .addGap(64, 64, 64)) + .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() + .addComponent(btnGenResult) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) + .addComponent(btnPrintList, javax.swing.GroupLayout.PREFERRED_SIZE, 83, javax.swing.GroupLayout.PREFERRED_SIZE) + .addGap(9, 9, 9)))) + .addComponent(jSplitPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 1095, Short.MAX_VALUE)) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) + .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) + .addComponent(lblTemperature, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addComponent(txtTemperature, javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(lblNoIterations, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addComponent(txtIterNum, javax.swing.GroupLayout.Alignment.LEADING)) + .addComponent(btnFindVertex) + .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) + .addComponent(txtCoolingRate, javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(txtVertexLookUp, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) + .addComponent(lblCoolingRate, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))) + .addContainerGap()) + ); + layout.setVerticalGroup( + layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(layout.createSequentialGroup() + .addContainerGap() + .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(layout.createSequentialGroup() + .addGap(10, 10, 10) + .addComponent(jToolBar1, javax.swing.GroupLayout.PREFERRED_SIZE, 141, javax.swing.GroupLayout.PREFERRED_SIZE) + .addGap(18, 18, 18) + .addComponent(rdnFailSim) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) + .addComponent(jLabel2) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(jcbAlgo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) + .addComponent(btnReset) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(btnClearConsole, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(btnStart) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) + .addGroup(layout.createSequentialGroup() + .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(layout.createSequentialGroup() + .addComponent(lblNoIterations) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(txtIterNum, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(lblTemperature) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(txtTemperature, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) + .addComponent(lblCoolingRate) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) + .addComponent(txtCoolingRate, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) + .addComponent(txtVertexLookUp, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(btnFindVertex) + .addGap(0, 0, Short.MAX_VALUE)) + .addComponent(jSplitPane1)) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED))) + .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(layout.createSequentialGroup() + .addComponent(sldrWeightSpeed, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(lblCapTransferred, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE) + .addGap(18, 18, 18) + .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(btnPrintList, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addComponent(btnGenResult, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))) + .addGroup(layout.createSequentialGroup() + .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(layout.createSequentialGroup() + .addGap(35, 35, 35) + .addComponent(lblCapacity)) + .addComponent(jLabel1) + .addGroup(layout.createSequentialGroup() + .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(lblInitalDistance) + .addComponent(lblInitalDistValue)) + .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(jLabel6) + .addComponent(lblTimeTaken))) + .addGap(18, 18, 18) + .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(lblFinalDistance) + .addComponent(lblFinalDistValue) + .addComponent(jLabel3) + .addComponent(lblIterationNum)))) + .addGap(15, 15, 15) + .addComponent(lblInfo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addGap(0, 0, Short.MAX_VALUE)))) + ); + + layout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {lblFinalDistValue, lblInitalDistValue}); + + pack(); + }// //GEN-END:initComponents + + private void hider() { + lblInitalDistance.setVisible(false); + lblFinalDistance.setVisible(false); + lblInitalDistValue.setVisible(false); + lblFinalDistValue.setVisible(false); +// lblPopulationSize.setVisible(false); +// txtPopSize.setVisible(false); + lblNoIterations.setVisible(false); + txtIterNum.setVisible(false); + lblTemperature.setVisible(false); + lblCoolingRate.setVisible(false); + txtTemperature.setVisible(false); + txtCoolingRate.setVisible(false); + btnGenResult.setVisible(false); + } + + private void Autodraw(Point dest) { + Image buff = createImage(pnlGraph.getWidth() - 1, pnlGraph.getHeight() - 1); + Graphics buffG = buff.getGraphics(); + buffG.drawImage(bufferImage, 0, 0, this); + Point source = Model.vertices.get(Model._selectedNode).getLocation(); + drawArrow(buffG, source.x, source.y, dest.x, dest.y); + drawArrow(buffG, dest.x, dest.y, source.x, source.y); + pnlGraph.getGraphics().drawImage(buff, 1, 1, this); + } + + private void AutoAddEdge(Vertex v) { + Model.weight = 0; + if (Model._selectedNode >= 0) { + for (Integer d : Model.vertices.keySet()) { + Vertex dest = null; + if (!Model.vertices.get(d).equals(v)) { + dest = Model.vertices.get(d); + } else { + continue; + } + Point point = dest.getLocation(); + int xDistance = Math.abs(v.getX() - dest.getX()); + int yDistance = Math.abs(v.getY() - dest.getY()); + Model.weight = (int) Math.sqrt((xDistance * xDistance) + (yDistance * yDistance)); + addEdge(Model.Edgeid, v.getId(), dest.getId(), Model.weight); + addEdge(Model.Edgeid, dest.getId(), v.getId(), Model.weight); + Autodraw(point); + //Model._selectedNode = -1; + Model.changesMade = true; + Model.Edgeid++; + //graph(); + } + } + graph(); + } + + private void pnlGraphMouseDragged(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_pnlGraphMouseDragged + if (SwingUtilities.isLeftMouseButton(evt)) { + if ((Model.toolType == Model.TOOL_BIDIRECTIONAL + || Model.toolType == Model.TOOL_DIRECTIONAL) + && Model._selectedNode >= 0) { + Image buff = createImage(pnlGraph.getWidth() - 1, pnlGraph.getHeight() - 1); + Graphics buffG = buff.getGraphics(); + buffG.drawImage(bufferImage, 0, 0, this); + Point source = Model.vertices.get(Model._selectedNode).getLocation(); + drawArrow(buffG, source.x, source.y, evt.getX(), evt.getY()); + if (Model.toolType == Model.TOOL_BIDIRECTIONAL) { + drawArrow(buffG, evt.getX(), evt.getY(), source.x, source.y); + } + pnlGraph.getGraphics().drawImage(buff, 1, 1, this); + } + if ((Model.toolType == Model.TOOL_NONE + || Model.toolType == Model.TOOL_VERTEX) + && Model._selectedNode >= 0) { + Vertex selectedVertex = Model.vertices.get(Model._selectedNode); + int dX = evt.getX() - selectedVertex.getLocation().x; + int dY = evt.getY() - selectedVertex.getLocation().y; + for (Iterator it + = Model.vertices.values().iterator(); + it.hasNext();) { + Vertex vertex = it.next(); + if (vertex.getSelected()) { + Point newLocation = vertex.getLocation(); + newLocation.x += dX; + newLocation.y += dY; + } + } + graph(); + Model.changesMade = true; + } + } + }//GEN-LAST:event_pnlGraphMouseDragged + + private void pnlGraphMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_pnlGraphMouseClicked + if (SwingUtilities.isLeftMouseButton(evt)) { + Model._selectedNode = nodeSelected(evt.getX(), evt.getY()); + if (evt.getClickCount() == 2) { + if (Model._source == -1 && Model._dest == -1 + || Model._source != -1 && Model._dest != -1) { + Model.glowMap.clear(); + Model._source = Model._selectedNode; + Model._dest = -1; + } else if (Model._source != Model._selectedNode) { + Model.glowMap.clear(); + Model._dest = Model._selectedNode; + Model.set.clear(); + Vertex dest = Model.vertices.get(Model._dest); + dest.setCapacity(150); + } + graph(); + } + } + }//GEN-LAST:event_pnlGraphMouseClicked + + private void pnlGraphMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_pnlGraphMousePressed + pnlGraph.requestFocus(); + if (SwingUtilities.isLeftMouseButton(evt)) { + Model.toolType = getTool(); + String[] types = new String[]{"Person", "City", "Place"}; + Model._selectedNode = nodeSelected(evt.getX(), evt.getY()); + if (Model.node1 == -1) { + Model.node1 = Model._selectedNode; + } + if (Model.toolType == Model.TOOL_VERTEX + || Model.toolType == Model.TOOL_NONE) { + if (!evt.isControlDown()) { + if (Model._selectedNode >= 0) { + Vertex selectedVertex + = Model.vertices.get(Model._selectedNode); + if (!selectedVertex.getSelected()) { + clearSelected(); + } + selectedVertex.setSelected(true); + return; + } else { + clearSelected(); + } + } else if (Model._selectedNode >= 0) { + Vertex selectedVertex + = Model.vertices.get(Model._selectedNode); + selectedVertex.setSelected(!selectedVertex.getSelected()); + if (!selectedVertex.getSelected()) { + Model._selectedNode = -1; + return; + } + } + } + if (Model.toolType == Model.TOOL_VERTEX) { + if (Model._selectedNode < 0) { + Model.changesMade = true; + if (isComplete == true) { + Vertex v = new Vertex(Model.id, new Point(evt.getX(), evt.getY()), String.valueOf(Model.id), types[(int) (Math.random() * types.length)], (int) (Math.random() * 50)); + Model.vertices.put(v.getId(), v); + Model._selectedNode = Model.id; + Model.id++; + AutoAddEdge(v); + } else { + Vertex v = new Vertex(Model.id, new Point(evt.getX(), evt.getY()), String.valueOf(Model.id), types[(int) (Math.random() * types.length)], (int) (Math.random() * 50)); + Model.vertices.put(v.getId(), v); + Model.id++; + } + } else if (evt.isControlDown() && evt.isShiftDown()) { // control shift to fail all edges leading out of a vertex + Vertex fail = Model.vertices.get(Model._selectedNode); + if (Model.failed.contains(fail)) { + Model.failed.remove(fail); + } else { + Model.failed.add(fail); + } + Iterator e = fail.eList().iterator(); + while (e.hasNext()) { + Edge next = e.next(); + next.setFailed(!next.isFailed()); //set it to opposite of what it is + } + Model.visited.clear(); + Model.glowMap.clear(); + Model.set.clear(); + if (null != Model.sim) { + switch (Model.sim) { + case "DFS": + Algorithms.Dfs(Model.vertices.get(Model._source)); + Algorithms.shortestPath(Model._source, Model._dest); + break; + case "BFS": + Algorithms.Bfs(Model.vertices.get(Model._source)); + Algorithms.shortestPath(Model._source, Model._dest); + break; + case "Dijkstra": + Algorithms.execute(Model.vertices.get(Model._source)); + Algorithms.shortestPath(Model._source, Model._dest); + break; + default: + break; + } + } + Model.changesMade = true; + } + } else if (Model.toolType != Model.TOOL_NONE) { + if (Model._selectedNode >= 0) { + Vertex selectedVertex + = Model.vertices.get(Model._selectedNode); + clearSelected(); + selectedVertex.setSelected(true); + } + } + graph(); + } + }//GEN-LAST:event_pnlGraphMousePressed + + private void pnlGraphMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_pnlGraphMouseReleased + if (SwingUtilities.isLeftMouseButton(evt)) { + Model.weight = 0; + if (Model._selectedNode >= 0) { + int destination = nodeSelected(evt.getX(), evt.getY()); + if (destination >= 0 && destination != Model._selectedNode) { + int xDistance = Math.abs(Model.vertices.get(Model._selectedNode).getX() - Model.vertices.get(destination).getX()); + int yDistance = Math.abs(Model.vertices.get(Model._selectedNode).getY() - Model.vertices.get(destination).getY()); + Model.weight = (int) Math.sqrt((xDistance * xDistance) + (yDistance * yDistance)); + addEdge(Model.Edgeid, Model._selectedNode, destination, Model.weight); + Model._selectedNode = -1; + Model.changesMade = true; + Model.Edgeid++; + } + } + graph(); + } + }//GEN-LAST:event_pnlGraphMouseReleased + + private void btnResetActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnResetActionPerformed + Model.changesMade = true; + reset(); + }//GEN-LAST:event_btnResetActionPerformed + + private void btnClearConsoleActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnClearConsoleActionPerformed + txtConsole.setText(""); + }//GEN-LAST:event_btnClearConsoleActionPerformed + + private void jcbAlgoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jcbAlgoActionPerformed + // TODO add your handling code here: + hider(); + String selected = jcbAlgo.getSelectedItem().toString(); + if (selected.equals("TSP-GA")) { + lblInitalDistance.setVisible(true); + lblFinalDistance.setVisible(true); + lblInitalDistValue.setVisible(true); + lblFinalDistValue.setVisible(true); +// lblPopulationSize.setVisible(true); +// txtPopSize.setVisible(true); + lblNoIterations.setVisible(true); + txtIterNum.setVisible(true); +// if (Model.vertices.size() != -1) { +// txtPopSize.setText(String.valueOf(Model.vertices.size())); +// } + } else if (selected.equals("TSP-SA")) { + lblInitalDistance.setVisible(true); + lblFinalDistance.setVisible(true); + lblInitalDistValue.setVisible(true); + lblFinalDistValue.setVisible(true); + lblTemperature.setVisible(true); + lblCoolingRate.setVisible(true); + txtTemperature.setVisible(true); + txtCoolingRate.setVisible(true); + }else if(selected.equals("Nearest Neighbor")){ + lblFinalDistance.setVisible(true); + lblFinalDistValue.setVisible(true); + } + }//GEN-LAST:event_jcbAlgoActionPerformed + + private void btnStartActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnStartActionPerformed + String x = String.valueOf(jcbAlgo.getSelectedItem()); + Model.sim = x; + Model.glowMap.clear(); + txtConsole.setText(""); + Model.visited.clear(); + Model.set.clear(); + Model.cutV.clear(); + switch (x) { + case "DFS": + txtConsole.setText(""); + if (Model._source == -1 || Model._dest == -1 || Model.vertices.get(Model._source).eList().isEmpty()) { + if (Model._source == -1) { + printlnConsole("Please choose a source by double clicking a node\nMake sure source has connections"); + } else { + printlnConsole("Please choose a destination by double clicking a node"); + } + return; + } + Algorithms.Dfs(Model.vertices.get(Model._source)); + Algorithms.shortestPath(Model._source, Model._dest); + break; + case "BFS": + txtConsole.setText(""); + if (Model._source == -1 || Model._dest == -1 || Model.vertices.get(Model._source).eList().isEmpty()) { + if (Model._source == -1) { + printlnConsole("Please choose a source by double clicking a node\nMake sure source has connections"); + } else { + printlnConsole("Please choose a destination by double clicking a node"); + } + return; + } + Algorithms.Bfs(Model.vertices.get(Model._source)); + Algorithms.shortestPath(Model._source, Model._dest); + break; + case "OtherBfs": + txtConsole.setText(""); + Algorithms.disJointshortestPath(Model._source, Model._dest); + break; + case "Dijkstra": + txtConsole.setText(""); + if (Model._source == -1 || Model._dest == -1 || Model.vertices.get(Model._source).eList().isEmpty() || Model.vertices.get(Model._dest).eList().isEmpty()) { + if (Model._source == -1) { + printlnConsole("Please choose a source by double clicking a node\nMake sure source has connections"); + } else { + printlnConsole("Please choose a destination by double clicking a node\nMake sure destination has connections"); + } + return; + } + Algorithms.execute(Model.vertices.get(Model._source)); + Algorithms.shortestPath(Model._source, Model._dest); + break; + case "Connectedness": + txtConsole.setText(""); + if (Model._source == -1) { + printlnConsole("Please select a source to begin"); + return; + } + if (Algorithms.isConnected()) { + printlnConsole("Graph is Connected"); + } else { + printlnConsole("Graph is a disconnected Graph"); + } + break; + case "TSP-SA": + txtConsole.setText(""); + TSP_SA.start(); + lblInitalDistValue.setText(String.valueOf(Model.InitialDistanceValue)); + lblFinalDistValue.setText(String.valueOf(Model.FinalDistanceValue)); + break; + case "TSP-GA": + txtConsole.setText(""); + TSP_GA.start(); + lblInitalDistValue.setText(String.valueOf(Model.InitialDistanceValue)); + lblFinalDistValue.setText(String.valueOf(Model.FinalDistanceValue)); + break; + case "Nearest Neighbor": + txtConsole.setText(""); + Algorithms.NearestNeighbor(); + lblFinalDistValue.setText(String.valueOf(Model.FinalDistanceValue)); + break; + default: + break; + } + btnGenResult.setVisible(true); + }//GEN-LAST:event_btnStartActionPerformed + + private void btnPrintListActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnPrintListActionPerformed + Iterator verts = Model.vertices.values().iterator(); + while (verts.hasNext()) { + Vertex next = verts.next(); + printlnConsole(next.getName() + "->" + next.eList()); + } + if (Model._source != -1) { + printlnConsole("Source is: " + Model._source); + } + }//GEN-LAST:event_btnPrintListActionPerformed + + private void pnlGraphComponentResized(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_pnlGraphComponentResized + bufferImage = createImage(pnlGraph.getWidth() - 2, pnlGraph.getHeight() - 2); + bufferGraphic = (Graphics2D) bufferImage.getGraphics(); + }//GEN-LAST:event_pnlGraphComponentResized + + private void mnuQuitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mnuQuitActionPerformed + if (checkForChange()) { + System.exit(0); + } + }//GEN-LAST:event_mnuQuitActionPerformed + + private void saveResult() throws IOException { + ImageIO.write((RenderedImage) bufferImage, "PNG", new File("Result.png")); + } + private void mnuSaveAsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mnuSaveAsActionPerformed + saveAs(); + }//GEN-LAST:event_mnuSaveAsActionPerformed + + private void mnuSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mnuSaveActionPerformed + justSave(); + }//GEN-LAST:event_mnuSaveActionPerformed + + private void mnuOpenActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mnuOpenActionPerformed + if (checkForChange()) { + JFileChooser theChooser = new JFileChooser(); + theChooser.setFileFilter(new FileNameExtensionFilter("GraphifyGUI files", "ser")); + if (theChooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) { + try { + Model.changesMade = false; + reset(); + Model.currentProject = theChooser.getSelectedFile().getPath(); + File theFile = new File(Model.currentProject); + Open(theFile); + graph(); + } catch (FileNotFoundException ex) { + Logger.getLogger(GraphifyGUI.class.getName()).log(Level.SEVERE, null, ex); + } catch (IOException ex) { + Logger.getLogger(GraphifyGUI.class.getName()).log(Level.SEVERE, null, ex); + } + + } + } + }//GEN-LAST:event_mnuOpenActionPerformed + + private void mnuNewActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mnuNewActionPerformed + if (checkForChange()) { + reset(); + Model.currentProject = null; + Model.changesMade = false; + } + }//GEN-LAST:event_mnuNewActionPerformed + + private void pnlGraphKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_pnlGraphKeyPressed + switch (evt.getKeyCode()) { + case KeyEvent.VK_DELETE: + Model.glowMap.clear(); + Integer[] keys = new Integer[Model.vertices.size()]; + Model.vertices.keySet().toArray(keys); + for (Integer key : keys) { + Vertex remove = Model.vertices.get(key); + if (remove.getSelected()) { + Model.changesMade = true; + Model.cutV.clear(); + Model._source = -1; + Model._dest = -1; + + for (Iterator e = Model.edges.iterator(); e.hasNext();) { + Edge next = e.next(); + if (next.getSource() == remove || next.getDest() == remove) { + next.getSource().eList().remove(next); + next.getDest().eList().remove(next); + e.remove(); + } + } + Model.vertices.remove(key); + + if (Model._selectedNode == Model._dest) { + Model._dest = -1; + Model.glowMap.clear(); + } + if (Model._selectedNode == Model._source) { + Model._source = -1; + Model._dest = -1; + Model.glowMap.clear(); + } + Model._selectedNode = -1; + } + } + break; + case KeyEvent.VK_V: + clearTools(); + tools[0].setSelected(true); + break; + case KeyEvent.VK_B: + clearTools(); + tools[1].setSelected(true); + break; + case KeyEvent.VK_D: + clearTools(); + tools[2].setSelected(true); + break; + case KeyEvent.VK_N: + clearTools(); + break; + case KeyEvent.VK_I: + if (Model._selectedNode != -1) { + if (Model.node1 != -1) { + Model.node2 = Model._selectedNode; + try { + String newWeight = JOptionPane.showInputDialog(this, "Input Weight:"); + if (newWeight == null) { + break; + } + Integer weight = Integer.parseInt(newWeight); + for (Edge edge : Model.vertices.get(Model.node1).eList()) { + if (edge.getDest() == Model.vertices.get(Model.node2)) { + edge.setWeight(weight); + break; + } + } + } catch (NumberFormatException e) { + JOptionPane.showMessageDialog(null, "Value must be an integer!"); + } + + } + + } + break; + default: + break; + } + graph(); + }//GEN-LAST:event_pnlGraphKeyPressed + + private void btnGenResultActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnGenResultActionPerformed + // TODO add your handling code here: + try { + saveResult(); + } catch (IOException ex) { + Logger.getLogger(GraphifyGUI.class.getName()).log(Level.SEVERE, null, ex); + } + }//GEN-LAST:event_btnGenResultActionPerformed + + private void mnuUpdateWeightActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mnuUpdateWeightActionPerformed + // TODO add your handling code here: + NodeEdit.run(); + }//GEN-LAST:event_mnuUpdateWeightActionPerformed + + private void rdnFailSimActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_rdnFailSimActionPerformed + // TODO add your handling code here: + Timer exe = new Timer(1, null); + if (rdnFailSim.isSelected()) { + decreseWeights = (ActionEvent e) -> { + if ("Dijkstra".equals(Model.sim)) { + if (Model.decreaseWeightEllapse < (1000 - sldrWeightSpeed.getValue())) { + Model.decreaseWeightEllapse++; + } else { + Model.decreaseWeightEllapse = 0; + reduceIncreaseWeight(); + autoFailure(); + autoHeal(); + graph(); + } + } + }; + exe = new Timer(1, decreseWeights); + exe.start(); + } + }//GEN-LAST:event_rdnFailSimActionPerformed + + boolean isInteger(String s) { + try { + Integer.parseInt(s); + return true; + } catch (NumberFormatException ex) { + } + return false; + } + private void btnFindVertexActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnFindVertexActionPerformed + // TODO add your handling code here: + String vertexNum = txtVertexLookUp.getText(); + if (isInteger(vertexNum)) { + Model._findNode = Integer.parseInt(vertexNum); + for (Integer i : Model.vertices.keySet()) { + if (i.equals(Model._findNode)) { + graph(); + break; + } + } + } else { + JOptionPane.showMessageDialog(this, + "Value should be an Integer", + "Value Error!", + JOptionPane.ERROR_MESSAGE); + } + + + }//GEN-LAST:event_btnFindVertexActionPerformed + + private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem1ActionPerformed + // TODO add your handling code here: + isWeighted = true; + }//GEN-LAST:event_jMenuItem1ActionPerformed + + private void jMenuItem2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem2ActionPerformed + // TODO add your handling code here: + isWeighted = false; + }//GEN-LAST:event_jMenuItem2ActionPerformed + + private void chkCompleteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_chkCompleteActionPerformed + // TODO add your handling code here: + if (chkComplete.isSelected()) { + isComplete = true; + } else { + isComplete = false; + } + + }//GEN-LAST:event_chkCompleteActionPerformed + + private void addEdge(Integer edgeId, Integer sourceid, Integer destid, int weight) { + Edge newEdge = new Edge(edgeId, Model.vertices.get(sourceid), Model.vertices.get(destid), weight, false); + Model.vertices.get(sourceid).eList().add(newEdge); + if (Model.toolType == Model.TOOL_BIDIRECTIONAL) { + newEdge.setBidirectional(true); + Edge tempEdge = new Edge(edgeId, Model.vertices.get(destid), Model.vertices.get(sourceid), weight, false); + Model.vertices.get(destid).eList().add(tempEdge); + } + Model.edges.add(newEdge); + } + + private void reduceIncreaseWeight() { + if (Model._source > -1 && Model._dest > -1) { + int edgeSize = Model.edges.size(); + int rand = (int) (Math.random() * edgeSize); + Edge e = Model.edges.get(rand); + int cost = e.getWeight() + (int) (Math.sqrt(e.getWeight())) * (Math.random() > .5 ? -1 : 1); + if (cost <= 0) { + cost += 5; + } + e.setWeight(cost); // changes it + Model.glowMap.clear(); + Algorithms.execute(Model.vertices.get(Model._source)); + Algorithms.shortestPath(Model._source, Model._dest); + e.setGlowLevel(1); + } + + //graph(); + } + + private void autoFailure() { // randomly fail nodes in the network + if (Model._source > -1 && Model._dest > -1) { + if (0.2 >= Math.random()) { // make probability of a node failure low + int vertexSize = Model.vertices.size(); + Vertex v = null; + int rand = 0; + while (v == null) { + rand = (int) (Math.random() * vertexSize); + v = Model.vertices.get(rand); + } + if (!(rand == Model._source || rand == Model._dest)) { // do not fail source or destination + if (Model.failed.contains(v)) { + Model.failed.remove(v); + } else { + Model.failed.add(v); + printlnConsole(v.getName() + " has failed"); + } +// Iterator e = v.eList().iterator(); +// while (e.hasNext()) { +// Edge next = e.next(); +// next.setFailed(!next.isFailed()); //set it to opposite of what it is +// } + Model.glowMap.clear(); + Algorithms.execute(Model.vertices.get(Model._source)); + Algorithms.shortestPath(Model._source, Model._dest); + } + } + } + } + + private void autoHeal() { + if (!Model.failed.isEmpty()) { + for (Iterator it = Model.failed.iterator(); it.hasNext();) { + Vertex v = it.next(); + if (Math.random() > 0.5) { + it.remove(); + printlnConsole(v.getName() + " has been healed"); + v.eList().stream().forEach((next) -> { + next.setFailed(!next.isFailed()); + }); + } + } + } + } + + void Open(File file) throws FileNotFoundException, IOException { + try { + try (FileInputStream fis = new FileInputStream(file)) { + ObjectInputStream ois = new ObjectInputStream(fis); + Model.vertices = (HashMap) ois.readObject(); + Model.edges = (ArrayList) ois.readObject(); + Model.id = (int) ois.readObject(); + Model.failed = (ArrayList) ois.readObject(); + ois.close(); + } + } catch (IOException ioe) { + } catch (ClassNotFoundException c) { + printlnConsole("Class not found"); + } + } + + private void reset() { + Model.vertices = new HashMap(); + Model.edges = new ArrayList(); + Model.id = 0; + Model.cutV = new ArrayList<>(); + Model._colors2 = new HashSet<>(); + Model.glowMap.clear(); + Model.glowMap.clear(); + Model._source = -1; + Model._dest = -1; + graph(); + } + + private String getNodeInfo(int nodeId) { + if (nodeId == -1) { + return "None"; + } + return "" + nodeId; + } + + public void graph() { + bufferGraphic.setColor(Color.white); + bufferGraphic.fillRect(0, 0, pnlGraph.getWidth(), pnlGraph.getHeight()); + Model.connectionCache.clear(); + // Regular connections + int xmid = 0; + int ymid = 0; + bufferGraphic.setColor(Color.black); + bufferGraphic.setStroke(new BasicStroke(1)); + for (Iterator edge = Model.edges.iterator(); edge.hasNext();) { + Edge e = edge.next(); + Point source = (Point) e.getSource().getLocation().clone(); + Point dest = (Point) e.getDest().getLocation().clone(); + double dx = dest.x - source.x; + double dy = source.y - dest.y; + double angle = Math.atan2(dy, dx); + source.x += (int) (Math.cos(angle) * Model._SIZE_OF_NODE / 2); + source.y -= (int) (Math.sin(angle) * Model._SIZE_OF_NODE / 2); + dest.x -= (int) (Math.cos(angle) * Model._SIZE_OF_NODE / 2); + dest.y += (int) (Math.sin(angle) * Model._SIZE_OF_NODE / 2); + xmid = (source.x + dest.x) / 2 + 5; + ymid = (source.y + dest.y) / 2 + 5; + drawArrowOnGraphics(bufferGraphic, source.x, source.y, dest.x, dest.y); + if (e.getBidirectional()) { + drawArrowOnGraphics(bufferGraphic, dest.x, dest.y, source.x, source.y); + } + int edgeWeight = e.getWeight(); + if (!(edgeWeight == -1)) { + bufferGraphic.setColor( + new Color(180, 30, 255, (int) (e.getGlowLevel() * 255))); + bufferGraphic.fillRect(xmid - 6, ymid - 14, 50, 20); + bufferGraphic.setColor(Color.black); +// if(isComplete == true){ +// bufferGraphic.setStroke(new BasicStroke(1)); +// }else{ +// bufferGraphic.setStroke(new BasicStroke(1)); +// } + bufferGraphic.setStroke(new BasicStroke(1)); + + if (isWeighted == true) { + bufferGraphic.drawString(String.valueOf(edgeWeight), xmid, ymid); + } else { + bufferGraphic.drawString("", xmid, ymid); + } + e.glowDie(.05); + } + } + + // Glowing connections + bufferGraphic.setColor(new Color(10, 230, 40)); + bufferGraphic.setStroke(new BasicStroke(4)); + + if (!btnReset.isSelected()) { + for (Iterator it = Model.glowMap.keySet().iterator(); + it.hasNext();) { + Vertex sourceVertex = it.next(); + Vertex destinationVertex = Model.glowMap.get(sourceVertex); + Point sourcePoint = sourceVertex.getLocation(); + Point destPoint = destinationVertex.getLocation(); + drawDottedLine(bufferGraphic, sourcePoint, destPoint, Model.dotOffset); + } + } + + // Nodes - red circles. + Model.vertices.values().stream().forEach((v) -> { + Point thePoint = v.getLocation(); + if (v.getId() == Model._source) { + bufferGraphic.setColor(Color.green); + } else if (v.getId() == Model._dest) { + bufferGraphic.setColor(Color.blue); + } else if (v.getId() == Model._selectedNode || v.getSelected()) { + bufferGraphic.setColor(Color.orange); + } else if (Model._findNode != -1 && v.getId() == Model._findNode) { + bufferGraphic.setColor(Color.BLUE.brighter()); + } else { + bufferGraphic.setColor(Color.red); + } + if (!Model.failed.isEmpty()) { + if (Model.failed.contains(v)) { + bufferGraphic.setColor(Color.gray); + } + } + if (!Model.cutV.isEmpty()) { + if (Model.cutV.contains(v.getId())) { + bufferGraphic.setColor(Color.green); + } + } + + bufferGraphic.fillOval(thePoint.x - Model._SIZE_OF_NODE / 2, + thePoint.y - Model._SIZE_OF_NODE / 2, Model._SIZE_OF_NODE, Model._SIZE_OF_NODE); + }); + // Node labels. + bufferGraphic.setColor(Color.blue); + Model.vertices.values().stream().forEach((v) -> { + Point thePoint = v.getLocation(); + bufferGraphic.drawString("" + v.getId(), + thePoint.x - Model._SIZE_OF_NODE / 2, + thePoint.y - Model._SIZE_OF_NODE / 2); + }); + pnlGraph.getGraphics().drawImage(bufferImage, 1, 1, this); + lblInfo.setText("Source: " + getNodeInfo(Model._source) + + " - Destination: " + getNodeInfo(Model._dest)); + } + + void drawArrow(Graphics g1, int x1, int y1, int x2, int y2) { + Graphics2D g = (Graphics2D) g1.create(); + drawArrowOnGraphics(g, x1, y1, x2, y2); + } + + private void drawArrowOnGraphics(Graphics2D g1, int x1, int y1, int x2, int y2) { + double dx = x2 - x1, dy = y1 - y2; + double angle = Math.atan2(dy, dx); + int len = (int) Math.sqrt(dx * dx + dy * dy); + + int p1X = (int) (x2 + Math.cos(angle + Math.PI * 3 / 4) * Model.ARR_SIZE); + int p1Y = (int) (y2 - Math.sin(angle + Math.PI * 3 / 4) * Model.ARR_SIZE); + int p2X = (int) (x2 + Math.cos(angle - Math.PI * 3 / 4) * Model.ARR_SIZE); + int p2Y = (int) (y2 - Math.sin(angle - Math.PI * 3 / 4) * Model.ARR_SIZE); + // Draw horizontal arrow starting in (0, 0) + g1.drawLine(x1, y1, x2, y2); + Polygon polygon = new Polygon(); + polygon.addPoint(x2, y2); + polygon.addPoint(p1X, p1Y); + polygon.addPoint(p2X, p2Y); + g1.fillPolygon(polygon); + } + + private void drawDottedLine(Graphics2D g, Point p1, Point p2, double offset) { + long total = (p2.x - p1.x) * (p2.x - p1.x) + (p2.y - p1.y) * (p2.y - p1.y); + total = (long) Math.sqrt(total); + for (long i = (long) (offset * 20); i <= total; i += 20) { + int x1 = (int) (p1.x + (p2.x - p1.x) * i / total); + int y1 = (int) (p1.y + (p2.y - p1.y) * i / total); + int x2 = (int) (p1.x + (p2.x - p1.x) * Math.min(i + 5, total) / total); + int y2 = (int) (p1.y + (p2.y - p1.y) * Math.min(i + 5, total) / total); + g.drawLine(x1, y1, x2, y2); + } + } + + private int nodeSelected(int x, int y) { + for (Vertex v : Model.vertices.values()) { + Point thePoint = v.getLocation(); + int deltaX = x - (thePoint.x - Model._SIZE_OF_NODE / 2); + int deltaY = y - (thePoint.y - Model._SIZE_OF_NODE / 2); + if (Math.sqrt(deltaX * deltaX + + deltaY * deltaY) <= Model._SIZE_OF_NODE + 6) { + return v.getId(); + } + } + return -1; + } + + public void printConsole(String string) { + txtConsole.append(string); + } + + public void printlnConsole(String string) { + txtConsole.append(string + "\n"); + txtConsole.setCaretPosition(txtConsole.getText().length()); + } + + static Vertex getConn(Vertex s, Edge e) { + if (s == e.getSource()) { + return e.getDest(); + } else { + return e.getSource(); + } + } + + private void save(String path) { + try { + try (FileOutputStream fileOut = new FileOutputStream(path); ObjectOutputStream out = new ObjectOutputStream(fileOut)) { + out.writeObject(Model.vertices); + out.writeObject(Model.edges); + out.writeObject(Model.id); + out.writeObject(Model.failed); + } + + } catch (IOException ex) { + Logger.getLogger(GraphifyGUI.class.getName()).log(Level.SEVERE, null, ex); + } + } + + private void saveAs() { + JFileChooser theChooser = new JFileChooser(); + theChooser.setFileFilter(new FileNameExtensionFilter("GraphifyGUI files", "ser")); + if (theChooser.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) { + String nominatedPath = theChooser.getSelectedFile().getPath(); + if (!nominatedPath.endsWith(".ser")) { + nominatedPath += ".ser"; + } + Model.currentProject = nominatedPath; + save(Model.currentProject); + } + } + + private void justSave() { + if (Model.currentProject == null) { + saveAs(); + } else { + save(Model.currentProject); + } + } + + private boolean checkForChange() { + if (Model.changesMade) { + int option = JOptionPane.showConfirmDialog(this, + "Changes have been made. Do you want to save before continuing?", "", JOptionPane.YES_NO_CANCEL_OPTION); + switch (option) { + case JOptionPane.YES_OPTION: + justSave(); + return true; + case JOptionPane.CANCEL_OPTION: + return false; + case JOptionPane.NO_OPTION: + return true; + default: + break; + } + } + return true; + } + + private int getTool() { + for (int i = 0; i < tools.length; i++) { + if (tools[i].isSelected()) { + return i; + } + } + return -1; + } + + private void clearTools() { + for (JToggleButton tool : tools) { + tool.setSelected(false); + } + } + + private void clearSelected() { + for (Vertex vertex : Model.vertices.values()) { + vertex.setSelected(false); + } + } + + public void setlblCapTransferred(String txt) { + lblCapTransferred.setText(txt); + } + + public void setlblCapTransferredColor(Color c) { + lblCapTransferred.setForeground(c); + } + + public void setlblIterations(String txt) { + lblIterationNum.setText(txt); + } + + @Override + public void paint(Graphics g) { + super.paint(g); + graph(); + } + + /** + * @param args the command line arguments + */ + public static void main(String args[]) { + /* Set the Nimbus look and feel */ + // + /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. + * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html + */ + try { + for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { + if ("Nimbus".equals(info.getName())) { + javax.swing.UIManager.setLookAndFeel(info.getClassName()); + break; + } + } + } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) { + java.util.logging.Logger.getLogger(GraphifyGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); + } + // + + // + /* Create and display the form */ + java.awt.EventQueue.invokeLater(() -> { + Model.Gui = new GraphifyGUI(); + Model.Gui.setLocationRelativeTo(null); + Model.Gui.setExtendedState(MAXIMIZED_BOTH); + Model.Gui.show(); + }); + } + + // Variables declaration - do not modify//GEN-BEGIN:variables + private javax.swing.JButton btnClearConsole; + private javax.swing.JButton btnFindVertex; + private javax.swing.JButton btnGenResult; + private javax.swing.JButton btnPrintList; + private javax.swing.JButton btnReset; + private javax.swing.JButton btnStart; + private javax.swing.ButtonGroup buttonGroup1; + private javax.swing.JCheckBoxMenuItem chkComplete; + private javax.swing.JLabel jLabel1; + private javax.swing.JLabel jLabel2; + private javax.swing.JLabel jLabel3; + private javax.swing.JLabel jLabel6; + private javax.swing.JMenu jMenu1; + private javax.swing.JMenuBar jMenuBar1; + private javax.swing.JMenuItem jMenuItem1; + private javax.swing.JMenuItem jMenuItem2; + private javax.swing.JScrollPane jScrollPane2; + private javax.swing.JSplitPane jSplitPane1; + private javax.swing.JToolBar jToolBar1; + private javax.swing.JComboBox jcbAlgo; + private javax.swing.JLabel lblCapTransferred; + private javax.swing.JLabel lblCapacity; + private javax.swing.JLabel lblCoolingRate; + private javax.swing.JLabel lblFinalDistValue; + private javax.swing.JLabel lblFinalDistance; + private java.awt.Label lblInfo; + private javax.swing.JLabel lblInitalDistValue; + private javax.swing.JLabel lblInitalDistance; + public static javax.swing.JLabel lblIterationNum; + private javax.swing.JLabel lblNoIterations; + private javax.swing.JLabel lblTemperature; + public static javax.swing.JLabel lblTimeTaken; + private javax.swing.JMenu mnuEdit; + private javax.swing.JMenu mnuFile; + private javax.swing.JMenuItem mnuNew; + private javax.swing.JMenuItem mnuOpen; + private javax.swing.JMenuItem mnuQuit; + private javax.swing.JMenuItem mnuSave; + private javax.swing.JMenuItem mnuSaveAs; + private javax.swing.JMenuItem mnuUpdateWeight; + private javax.swing.JPanel pnlGraph; + private javax.swing.JRadioButton rdnFailSim; + private javax.swing.JSlider sldrWeightSpeed; + private javax.swing.JTextArea txtConsole; + public static javax.swing.JTextField txtCoolingRate; + public static javax.swing.JTextField txtIterNum; + public static javax.swing.JTextField txtTemperature; + private javax.swing.JTextField txtVertexLookUp; + // End of variables declaration//GEN-END:variables +} diff --git a/Graphify/src/graphify/Model.java b/Graphify/src/graphify/Model.java new file mode 100644 index 0000000..9632a65 --- /dev/null +++ b/Graphify/src/graphify/Model.java @@ -0,0 +1,87 @@ +package graphify; + +import java.awt.Color; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Queue; +import java.util.Stack; + +/** + * + * @author Jack + */ +public abstract class Model { + public static HashMap connectionCache = new HashMap<>(); + public static Queue queue; + public static Stack stack; + public static String sim = null; + public static boolean startSA = false; + public static HashMap distTo; + public static HashMap visited; + public static HashMap color; + public static HashMap fcolors; + public static HashMap greedyresult; + public static HashMap glowMap; + public static HashSet _colors2; + public static HashSet randomKeys; + public static ArrayList cutV; + public static ArrayList failed; + public static Color[] vertexColors; + public static int _selectedNode = -1; + public static int id = 0; + public static int Edgeid = 0; + public static int weight = 0; + public static Integer maxColors = 0; + public static int _source = -1; + public static int _dest = -1; + public static int _findNode = -1; + public static String currentProject = null; + public static boolean changesMade = false; + public static boolean algCalled = false; + public static double dotOffset = 0.0; + public static Algorithms alg; + public static int time = 0; + public static int toolType = -1; + public static HashMap vertices; + public static ArrayList edges; + public static Queue suggestQueue; + public static HashMap> nodes; + public static HashMap setShortestPath = new HashMap<>(); + public static Map set; + public static ArrayList conn; + public static HashSet bconn; + public static int pathvalue = 0; + public static HashMap tempShortPath; + public static HashMap> disjointPaths = new HashMap<>(); + //for dijkstra + public static int Capacity = 0; + public static int node1 = -1; + public static int node2 = -1; + public static HashSet uSNodes; // unsettled + public static HashSet sNodes; // settled + public static HashMap dist; // distance + public static int decreaseWeightEllapse = 0; + //classes + public static GraphifyGUI Gui; + public static TSP_SA tsp_sa; + public static TSP_GA tsp_ga; + // distances + public static int InitialDistanceValue = 0; + public static int FinalDistanceValue = 0; + + //timer + public static long startTime = 0; + public static long endTime = 0; + + public static int counter = 0; + + + public static final int TOOL_NONE = -1; + public static final int TOOL_VERTEX = 0; + public static final int TOOL_BIDIRECTIONAL = 1; + public static final int TOOL_DIRECTIONAL = 2; + public static final int ARR_SIZE = 8; + public static int _SIZE_OF_NODE = 20; +} diff --git a/Graphify/src/graphify/NodeEdit.form b/Graphify/src/graphify/NodeEdit.form new file mode 100644 index 0000000..beb3ca2 --- /dev/null +++ b/Graphify/src/graphify/NodeEdit.form @@ -0,0 +1,164 @@ + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + <Editor/> + <Renderer/> + </Column> + <Column maxWidth="-1" minWidth="-1" prefWidth="-1" resizable="true"> + <Title/> + <Editor/> + <Renderer/> + </Column> + <Column maxWidth="-1" minWidth="-1" prefWidth="-1" resizable="true"> + <Title/> + <Editor/> + <Renderer/> + </Column> + <Column maxWidth="-1" minWidth="-1" prefWidth="-1" resizable="true"> + <Title/> + <Editor/> + <Renderer/> + </Column> + </TableColumnModel> + </Property> + <Property name="tableHeader" type="javax.swing.table.JTableHeader" editor="org.netbeans.modules.form.editors2.JTableHeaderEditor"> + <TableHeader reorderingAllowed="true" resizingAllowed="true"/> + </Property> + </Properties> + </Component> + </SubComponents> + </Container> + <Component class="javax.swing.JButton" name="btnUpdate"> + <Properties> + <Property name="text" type="java.lang.String" value="Update Weight"/> + </Properties> + <Events> + <EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="btnUpdateActionPerformed"/> + </Events> + </Component> + <Component class="javax.swing.JButton" name="btnRouteInfo"> + <Properties> + <Property name="text" type="java.lang.String" value="Routing Info"/> + </Properties> + <Events> + <EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="btnRouteInfoActionPerformed"/> + </Events> + </Component> + </SubComponents> + </Container> + </SubComponents> +</Form> diff --git a/Graphify/src/graphify/NodeEdit.java b/Graphify/src/graphify/NodeEdit.java new file mode 100644 index 0000000..4e0d141 --- /dev/null +++ b/Graphify/src/graphify/NodeEdit.java @@ -0,0 +1,265 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package graphify; + +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; +import java.util.Iterator; +import javax.swing.ListSelectionModel; +import javax.swing.table.DefaultTableModel; + +/** + * + * @author Ayomitunde + */ +public class NodeEdit extends javax.swing.JFrame { + + /** + * Creates new form NodeEdit + */ + static String[] lstMod = {"Destination Node(s)", "Weight"}; + static DefaultTableModel _listerModel = new DefaultTableModel(0, 0); + Vertex _current = null; + Vertex _dest = null; + Integer _selectedRow = null; + Integer _selectedColumn = null; + + public NodeEdit() { + initComponents(); + tblProperties.getTableHeader().setResizingAllowed(false); + tblProperties.getTableHeader().setReorderingAllowed(false); + tblProperties.setColumnSelectionAllowed(true); + tblProperties.setRowSelectionAllowed(true); + tblProperties.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); + _listerModel.setColumnIdentifiers(lstMod); + tblProperties.setModel(_listerModel); + tblProperties.addMouseListener(new MouseAdapter() { + @Override + public void mousePressed(MouseEvent e) { + _selectedRow = tblProperties.getSelectedRow(); + _selectedColumn = tblProperties.getSelectedColumn(); + Object v = _listerModel.getValueAt(_selectedRow, 0); + int vert = Integer.parseInt(String.valueOf(v).trim()); + _dest = Model.vertices.get(vert); + } + }); + lstAllNodes.addMouseListener(new MouseAdapter() { + String selected = ""; + + @Override + public void mousePressed(MouseEvent e) { + if (e.getClickCount() == 2) { + _listerModel.setRowCount(0); + selected = lstAllNodes.getSelectedItem(); + if (selected != null) { + selected = selected.replace("Vertex ", "").trim(); + _current = Model.vertices.get(Integer.parseInt(selected)); + Model.edges.stream().filter((edge) -> (edge.getSource().equals(_current))).forEach((edge) -> { + _dest = edge.getDest(); + _listerModel.addRow(new Object[]{edge.getDest().getLabel(), edge.getWeight()}); + }); + } + } + } + +// @Override +// public void mouseReleased(MouseEvent e) { +// +// } + }); + + } + + /** + * This method is called from within the constructor to initialize the form. + * WARNING: Do NOT modify this code. The content of this method is always + * regenerated by the Form Editor. + */ + @SuppressWarnings("unchecked") + // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents + private void initComponents() { + + jPanel1 = new javax.swing.JPanel(); + jLabel1 = new javax.swing.JLabel(); + lstAllNodes = new java.awt.List(); + jScrollPane1 = new javax.swing.JScrollPane(); + tblProperties = new javax.swing.JTable(); + btnUpdate = new javax.swing.JButton(); + btnRouteInfo = new javax.swing.JButton(); + + setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); + + jPanel1.setBackground(new java.awt.Color(153, 204, 255)); + + jLabel1.setFont(new java.awt.Font("Tempus Sans ITC", 3, 18)); // NOI18N + jLabel1.setText("Node Properties"); + + jScrollPane1.setViewportView(tblProperties); + + btnUpdate.setText("Update Weight"); + btnUpdate.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + btnUpdateActionPerformed(evt); + } + }); + + btnRouteInfo.setText("Routing Info"); + btnRouteInfo.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + btnRouteInfoActionPerformed(evt); + } + }); + + javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); + jPanel1.setLayout(jPanel1Layout); + jPanel1Layout.setHorizontalGroup( + jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(jPanel1Layout.createSequentialGroup() + .addContainerGap() + .addComponent(lstAllNodes, javax.swing.GroupLayout.PREFERRED_SIZE, 75, javax.swing.GroupLayout.PREFERRED_SIZE) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 324, javax.swing.GroupLayout.PREFERRED_SIZE) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) + .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(btnRouteInfo, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addComponent(btnUpdate, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))) + .addGroup(jPanel1Layout.createSequentialGroup() + .addGap(190, 190, 190) + .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addGap(219, 219, 219)) + ); + jPanel1Layout.setVerticalGroup( + jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(jPanel1Layout.createSequentialGroup() + .addContainerGap() + .addComponent(jLabel1) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 32, Short.MAX_VALUE) + .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) + .addComponent(lstAllNodes, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 318, Short.MAX_VALUE)) + .addGroup(jPanel1Layout.createSequentialGroup() + .addComponent(btnUpdate) + .addGap(18, 18, 18) + .addComponent(btnRouteInfo)))) + ); + + javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); + getContentPane().setLayout(layout); + layout.setHorizontalGroup( + layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(layout.createSequentialGroup() + .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addGap(0, 0, Short.MAX_VALUE)) + ); + layout.setVerticalGroup( + layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + ); + + pack(); + }// </editor-fold>//GEN-END:initComponents + + private void btnUpdateActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnUpdateActionPerformed + // TODO add your handling code here: + if (_selectedRow != null) { + Object w = _listerModel.getValueAt(_selectedRow, 1); + int weight = 0; + if (w != null) { + weight = Integer.parseInt(w.toString()); + if (_current != null && _dest != null) { + for (Edge e : Model.edges) { + if (e.getSource().equals(_current) && e.getDest().equals(_dest)) { + e.setWeight(weight); + } + } + Model.Gui.graph(); + } + } + } + }//GEN-LAST:event_btnUpdateActionPerformed + + void routeInfo() { + lstAllNodes.setVisible(false); + btnUpdate.setVisible(false); + for (Vertex v : Model.setShortestPath.keySet()) { + //for (Edge e : v.eList()) { + _listerModel.addRow(new Object[]{v.label, Model.setShortestPath.get(v).label, "blah"}); + //} + } + } + private void btnRouteInfoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnRouteInfoActionPerformed + // TODO add your handling code here: + String[] lstMod2 = {"Node", "Parent", "Weight"}; + if (!"Node Properties".equals(btnRouteInfo.getText())) { + _listerModel.setColumnIdentifiers(lstMod2); + routeInfo(); + btnRouteInfo.setText("Node Properties"); + } else { + lstAllNodes.setVisible(true); + btnUpdate.setVisible(true); + _listerModel.setColumnIdentifiers(lstMod); + btnRouteInfo.setText("Routing Info"); + } + }//GEN-LAST:event_btnRouteInfoActionPerformed + + /** + * @param args the command line arguments + */ + public static void load() { + for (Iterator<Integer> v = Model.vertices.keySet().iterator(); v.hasNext();) { + Integer n = v.next(); + Vertex vert = Model.vertices.get(n); + lstAllNodes.add("Vertex " + vert.getLabel()); + } + } + + public static void run() { + new NodeEdit().setVisible(true); + load(); + } +// public static void run() { +// /* Set the Nimbus look and feel */ +// //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> +// /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. +// * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html +// */ +// try { +// for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { +// if ("Nimbus".equals(info.getName())) { +// javax.swing.UIManager.setLookAndFeel(info.getClassName()); +// break; +// } +// } +// } catch (ClassNotFoundException ex) { +// java.util.logging.Logger.getLogger(NodeEdit.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); +// } catch (InstantiationException ex) { +// java.util.logging.Logger.getLogger(NodeEdit.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); +// } catch (IllegalAccessException ex) { +// java.util.logging.Logger.getLogger(NodeEdit.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); +// } catch (javax.swing.UnsupportedLookAndFeelException ex) { +// java.util.logging.Logger.getLogger(NodeEdit.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); +// } +// //</editor-fold> +// +// /* Create and display the form */ +// java.awt.EventQueue.invokeLater(new Runnable() { +// public void run() { +// new NodeEdit().setVisible(true); +// } +// }); +// } + + // Variables declaration - do not modify//GEN-BEGIN:variables + private javax.swing.JButton btnRouteInfo; + private javax.swing.JButton btnUpdate; + private javax.swing.JLabel jLabel1; + private javax.swing.JPanel jPanel1; + private javax.swing.JScrollPane jScrollPane1; + private static java.awt.List lstAllNodes; + private javax.swing.JTable tblProperties; + // End of variables declaration//GEN-END:variables +} diff --git a/Graphify/src/graphify/Population.java b/Graphify/src/graphify/Population.java new file mode 100644 index 0000000..1a8f4d5 --- /dev/null +++ b/Graphify/src/graphify/Population.java @@ -0,0 +1,62 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package graphify; + +/** + * + * @author Ayomitunde + */ +public class Population { + Tour[] tours; + + public Population(int populationSize, boolean initialize){ + tours = new Tour[populationSize]; + if(initialize == true){ + for(int i = 0; i < populationSize; i++){ + Tour newTour = new Tour(); + newTour.generateIndividual(); + saveTour(i, newTour); + } + } + } + + public Tour[] getTours(){ + return tours; + } + public final void saveTour(int index, Tour tour){ + tours[index] = tour; + } + + public Tour getTour(int index){ + return tours[index]; + } + + public void getParents(){ + getFittest(0); + getFittest(1); + } + + public Tour getFittest(int index){ + Tour fittest = tours[index]; + int fittestIndex = 0; + for(int i = index > 0 ? 2 : 1; i < populationSize(); i++){ + Tour next = getTour(i); + if(fittest.getFitness() <= next.getFitness()){ + fittest = next; + fittestIndex = i; + } + } + //swap fittest with location index specified + tours[fittestIndex] = getTour(index); + tours[index] = fittest; + return fittest; + } + + public int populationSize(){ + return tours.length; + } + +} diff --git a/Graphify/src/graphify/TSP_GA.java b/Graphify/src/graphify/TSP_GA.java new file mode 100644 index 0000000..37ffbb6 --- /dev/null +++ b/Graphify/src/graphify/TSP_GA.java @@ -0,0 +1,58 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package graphify; + +/** + * + * @author Ayomitunde + */ +public class TSP_GA { + private static void reset(){ + Model.InitialDistanceValue = 0; + Model.FinalDistanceValue = 0; + } + + public static void setPath(Tour best) { + Model.glowMap.clear(); + for (int i = 0; i < best.getTour().size(); i++) { + Vertex next = best.getTour().get(i); + Vertex parent; + if (i + 1 != best.getTour().size()) { + parent = best.getTour().get(i + 1); + } else { + parent = best.getTour().get(0); + } + Model.glowMap.put(next, parent); + } + Model.Gui.graph(); + } + + + public static void start(){ + reset(); + Model.counter = 1; + //String txtPopSize = GraphifyGUI.txtPopSize.getText(); + String txtIterNum = GraphifyGUI.txtIterNum.getText(); + int vertexSize = Model.vertices.size(); + int popSize = vertexSize; + int iterations = !txtIterNum.equals("100") ? Integer.parseInt(txtIterNum) : 100; + Model.startTime = System.currentTimeMillis(); + Population pop = new Population(popSize, true); + Algorithms.startGANN(pop); + Model.InitialDistanceValue = pop.getFittest(0).getTourDistance(); + + //pop = GA.evolvePopulation(pop); + for(int i = 0; i < iterations; i++){ + pop = GA.evolvePopulation(pop); + //Model.Gui.setlblIterations(String.valueOf(Model.counter++)); + } + Model.endTime = System.currentTimeMillis(); + GraphifyGUI.lblTimeTaken.setText(String.valueOf((Model.endTime - Model.startTime))+" ms"); + Model.Gui.printlnConsole("Solution: \n"+pop.getFittest(0)); + Model.FinalDistanceValue = pop.getFittest(0).getTourDistance(); + setPath(pop.getFittest(0)); + } +} diff --git a/Graphify/src/graphify/TSP_SA.java b/Graphify/src/graphify/TSP_SA.java new file mode 100644 index 0000000..9ce465e --- /dev/null +++ b/Graphify/src/graphify/TSP_SA.java @@ -0,0 +1,109 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package graphify; + +/** + * + * @author Ayomitunde + */ +public class TSP_SA { + + static double temp = 10000; + static double coolingRate = 0.003; + + private static void reset() { + String tempRate = GraphifyGUI.txtTemperature.getText(); + String coolRate = GraphifyGUI.txtCoolingRate.getText(); + temp = !tempRate.equals("10000") ? Double.parseDouble(tempRate) : 10000; + coolingRate = !coolRate.equals("0.003") ? Double.parseDouble(coolRate) : 0.003; + Model.InitialDistanceValue = 0; + Model.FinalDistanceValue = 0; + } + + public static double acceptanceProbablity(int energy, int newEnergy, double temperature) { + if (newEnergy < energy) { + return 1.0; + } + return Math.exp(energy - newEnergy) / temperature; + } + + public static void setPath(Tour best) { + Model.glowMap.clear(); + for (int i = 0; i < best.getTour().size(); i++) { + Vertex next = best.getTour().get(i); + Vertex parent; + if (i + 1 != best.getTour().size()) { + parent = best.getTour().get(i + 1); + } else { + parent = best.getTour().get(0); + } + Model.glowMap.put(next, parent); + } + Model.Gui.graph(); + } + + public static void printTour(Tour best){ + for(int i = 0; i < best.getTour().size(); i++){ + Vertex next = best.getTour().get(i); + Vertex parent; + if (i + 1 != best.getTour().size()) { + parent = best.getTour().get(i + 1); + } else { + parent = best.getTour().get(0); + } + Model.Gui.printConsole(next.getName()+"->"+parent.getName()+" |"); + } + } + + public static void start() { + reset(); + Model.counter = 0; + Model.startTime = System.currentTimeMillis(); + Tour currentSolution = new Tour(); + currentSolution.generateIndividual(); + Model.Gui.printlnConsole("Initial Solution distance: " + currentSolution.getTourDistance()); + Model.InitialDistanceValue = currentSolution.getTourDistance(); + Tour best = new Tour(currentSolution.getTour()); + setPath(best); + while (temp > 1) { + Tour newSolution = new Tour(currentSolution.getTour()); + + int tourPos1 = (int) (newSolution.tourSize() * Math.random()); + int tourPos2 = (int) (newSolution.tourSize() * Math.random()); + + Vertex vertexSwap1 = newSolution.getVertex(tourPos1); + Vertex vertexSwap2 = newSolution.getVertex(tourPos2); + + newSolution.setVertex(tourPos1, vertexSwap2); + newSolution.setVertex(tourPos2, vertexSwap1); + + int currentEnergy = currentSolution.getTourDistance(); + int neighborEnergy = newSolution.getTourDistance(); + + if (acceptanceProbablity(currentEnergy, neighborEnergy, temp) > Math.random()) { + currentSolution = new Tour(newSolution.getTour()); + } + + if (currentSolution.getTourDistance() < best.getTourDistance()) { + best = new Tour(currentSolution.getTour()); + setPath(best); + } + + temp *= 1 - coolingRate; + Model.Gui.setlblIterations(String.valueOf(++Model.counter)); + } + Model.endTime = System.currentTimeMillis(); + GraphifyGUI.lblTimeTaken.setText(String.valueOf((Model.endTime - Model.startTime))+" ms"); + Model.Gui.printlnConsole("Final Solution: " + best.getTourDistance()); + Model.FinalDistanceValue = best.getTourDistance(); + + printTour(best); + Model.Gui.printlnConsole("Tour: " + best); + setPath(best); + + } + +} diff --git a/Graphify/src/graphify/Tour.java b/Graphify/src/graphify/Tour.java new file mode 100644 index 0000000..6fd0420 --- /dev/null +++ b/Graphify/src/graphify/Tour.java @@ -0,0 +1,113 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package graphify; + +import java.util.ArrayList; +import java.util.Collections; + +/** + * + * @author Ayomitunde + */ +public class Tour { + + private ArrayList<Vertex> tour = new ArrayList<>(); + private double fitness = 0; + private int distance = 0; + + public Tour() { + for (int i = 0; i < Model.vertices.size(); i++) { + tour.add(null); + } + } + + public Tour(ArrayList<Vertex> tour) { + this.tour = tour; + } + + public void generateIndividual() { + Model.vertices.keySet().stream().forEach((vertexIndex) -> { + setVertex(vertexIndex, Model.vertices.get(vertexIndex)); + }); + Collections.shuffle(tour); + } + + public boolean isSafe(Vertex s, Vertex d) { + for (Edge e : s.eList()) { + if (!tour.contains(d) && e.getDest() == d) { + return true; + } + } + return false; + } + + public Vertex getVertex(int vertexIndex) { + return (Vertex) (tour.get(vertexIndex)); + } + + public void setVertex(int tourPosition, Vertex vertex) { + tour.set(tourPosition, vertex); + fitness = 0; + distance = 0; + } + + public int getDistance(Vertex source, Vertex destination) { + for (Edge e : Model.edges) { + if ((e.getSource().equals(source) && e.getDest().equals(destination)) + || (e.getDest().equals(source) && e.getSource().equals(destination))) { + return e.getWeight(); + } + } + return -1; + } + + public double getFitness() { + if (fitness == 0) { + fitness = 1 / (double) getTourDistance(); + } + return fitness; + } + + public int getTourDistance() { + if (distance == 0) { + for (int vertexIndex = 0; vertexIndex < tourSize(); vertexIndex++) { + Vertex fromVertex = getVertex(vertexIndex); + Vertex destinationVertex; + if (vertexIndex + 1 < tourSize()) { + destinationVertex = getVertex(vertexIndex + 1); + } else { + destinationVertex = getVertex(0); + } + int dist = getDistance(fromVertex, destinationVertex); + if (dist != -1) { // means there is a connection + distance += dist; + } + } + } + return distance; + } + + public int tourSize() { + return tour.size(); + } + + public boolean containsVertex(Vertex vertex) { + return tour.contains(vertex); + } + + @Override + public String toString() { + String geneString = "| "; + for (int i = 0; i < tourSize(); i++) { + geneString += getVertex(i).label + " | "; + } + return geneString; + } + + public ArrayList<Vertex> getTour() { + return this.tour; + } +} diff --git a/Graphify/src/graphify/Vertex.java b/Graphify/src/graphify/Vertex.java new file mode 100644 index 0000000..34dbf6d --- /dev/null +++ b/Graphify/src/graphify/Vertex.java @@ -0,0 +1,306 @@ +package graphify; + +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +/** + * + * @author Ayomitunde + */ +import java.awt.Point; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Queue; +import java.io.Serializable; + +public class Vertex implements Serializable, IVertex { + + public String label; + private boolean wasVisited; + public Vertex parent; + private Point location; + private HashSet<Edge> eList; + private HashMap<Integer, Edge> path; + private int id; + private int cap; + private String type; + private boolean selected = false; + + public Vertex(GraphifyGUI GG) { + + } + + public Vertex(int id, Point loc, String vertexLabel, String type, int capacity) { + this.label = vertexLabel; + this.wasVisited = false; + this.type = type; + this.parent = this; // change this to vertex + this.id = id; + this.cap = capacity; + this.location = loc; + this.eList = new HashSet<>(); + } + + + @Override + public int getX(){ + return this.location.x; + } + + @Override + public int getY(){ + return this.location.y; + } + @Override + public String getLabel() { + return (this.label + " "); + } + + @Override + public HashMap getPath(){ + return this.path; + } + + /** + * + * @return + * returns name assigned to this vertex + */ + @Override + public String getName() { + return this.label; + } + + @Override + public boolean visited(){ + return this.wasVisited; + } + + @Override + public void setVisited(boolean bool){ + this.wasVisited = bool; + } + /** + * + * @return + * returns type of this vertex + */ + @Override + public String getType() { + return this.type; + } + + @Override + public int getId() { + return this.id; + } + + void setId(int id) { + this.id = id; + } + + /** + * + * @return + * returns the capacity of this vertex + */ + @Override + public int getCapacity() { + return this.cap; + } + + /** + * + * @param x + * sets capacity of vertex to x + */ + @Override + public void setCapacity(int x){ + this.cap = x; + } + + @Override + public Vertex getVertex(int id) { + return this; + } + + /** + * + * @return + * returns x,y coordinate of vertex + */ + @Override + public Point getLocation() { + return this.location; + } + + /** + * + * @return + * returns edges connected to this vertex + */ + @Override + public HashSet<Edge> eList() { + return this.eList; + } + + /** + * + * @return + * returns the parent of this vertex + */ + @Override + public Vertex getParent() { + return this.parent; + } + + @Override + public boolean getSelected() { + return selected; + } + + @Override + public void setSelected(boolean sel) { + selected = sel; + } +// public int hashCode(){ +// final int prime = 31; +// int result = 1; +// if(id < 0){ +// result = 0; +// }else{ +// prime * result + String.valueOf(id).hashCode(); +// } +// result = prime * result + ((id < 0) ? 0 :id.hashCode()); +// return result; +// } +// +// public boolean equals(Object v){ +// if(this == v) return true; +// if(v == null) return false; +// if(getClass() != v.getClass()) return false; +// Vertex x = (Vertex) v; +// if(id == null){ +// if(x.id != null) return false; +// }else if (!id.equals(x.id)){ +// return false; +// } +// return true; +// } +} + +class Edge implements Serializable, IEdge { + + private final int id; + private final Vertex source; + private final Vertex dest; + private int weight; + private boolean fail; + private double glowLevel = 0; + private boolean bidirectional; + + public Edge(int id, Vertex source, Vertex dest, int weight, boolean fail) { + this.id = id; + this.source = source; + this.dest = dest; + this.weight = weight; + this.fail = fail; + bidirectional = false; + } + + @Override + public boolean getBidirectional() { + return bidirectional; + } + + @Override + public void setBidirectional(boolean bi) { + bidirectional = bi; + } + + @Override + public int getId() { + return id; + } + + @Override + public Vertex getDest() { + return dest; + } + + @Override + public Vertex getSource() { + return source; + } + + @Override + public int getWeight() { + return weight; + } + + @Override + public void setWeight(int w){ + this.weight = w; + } + + @Override + public String getConnections() { + return source.getId() + "," + dest.getId(); + } + + @Override + public double getGlowLevel() { + return glowLevel; + } + + @Override + public void glowDie(double decrement) { + glowLevel = Math.max(glowLevel - decrement, 0); + } + + @Override + public void setGlowLevel(double newGlow) { + glowLevel = newGlow; + } + + @Override + public boolean isFailed() { + return this.fail; + } + + @Override + public void setFailed(boolean bool) { + this.fail = bool; + } + + @Override + public String toString() { + return this.getId() + " " + source.getName() + " " + dest.getName() + " " + this.getWeight() + " " + this.isFailed(); + } +} + +class Graph { + + private final List<Vertex> vertices; + private final HashSet<Edge> edges; + HashMap<Integer, Vertex> nodes; + private Queue<Vertex> queue; + + public Graph(List<Vertex> vertices, HashSet<Edge> edges) { + this.vertices = vertices; + this.edges = edges; + } + + public List<Vertex> getVertices() { + return vertices; + } + + public HashSet<Edge> getEdges() { + return edges; + } + + // get all people with age between 18 to 20 and show their parents +} diff --git a/Graphify/src/graphify/images/bidirectional.png b/Graphify/src/graphify/images/bidirectional.png new file mode 100644 index 0000000..52e8dad Binary files /dev/null and b/Graphify/src/graphify/images/bidirectional.png differ diff --git a/Graphify/src/graphify/images/directional.png b/Graphify/src/graphify/images/directional.png new file mode 100644 index 0000000..11d4b40 Binary files /dev/null and b/Graphify/src/graphify/images/directional.png differ diff --git a/Graphify/src/graphify/images/vertex.png b/Graphify/src/graphify/images/vertex.png new file mode 100644 index 0000000..043de18 Binary files /dev/null and b/Graphify/src/graphify/images/vertex.png differ diff --git a/README.md b/README.md new file mode 100644 index 0000000..d4a7b41 --- /dev/null +++ b/README.md @@ -0,0 +1,41 @@ +# GraphGUI +##Purpose +**To visualize graph algorithms** + +The application is written in *java programming language - compile with Netbeans*, please suggest changes if you think any should be made. +Several algorithms have been added to this application are visualized. + +**Algorithms covered so far:** +- Bfs +- Dfs +- Dijkstra +- Check connectedness +- TSP (Simulated annealing) + +**How to Use** +- Clone source +- Open project in Netbeans or your favorite Java IDE +- Run the application + +**Controls** +- Tools like placing vertex, edges can be selected from the side panel + +![Toos](https://github.com/afafore1/GraphGUI/blob/Bugs/Graphify/SSandFiles/controls.PNG) +- Select what algorithm to run from the bottom panel - - - + +![Algos](https://github.com/afafore1/GraphGUI/blob/Bugs/Graphify/SSandFiles/Choices.PNG) +- Choosing speed for dijkstra's algorithm, select from right most panel - + +![speed](https://github.com/afafore1/GraphGUI/blob/Bugs/Graphify/SSandFiles/speed%20and%20cap.PNG) + + +**Test file** + +[Test File](https://github.com/afafore1/GraphGUI/blob/Bugs/Graphify/SSandFiles/new.ser) to try out + + + + +*Contributors* +- Ayomitunde Fafore +- Jack Le