PopulationXML.java
1 package pep; 2 3 import genetics.Individual; 4 import genetics.Population; 5 import hlt.Log; 6 import org.w3c.dom.*; 7 import javax.xml.parsers.DocumentBuilder; 8 import javax.xml.parsers.DocumentBuilderFactory; 9 import javax.xml.parsers.ParserConfigurationException; 10 import javax.xml.transform.OutputKeys; 11 import javax.xml.transform.Transformer; 12 import javax.xml.transform.TransformerFactory; 13 import javax.xml.transform.dom.DOMSource; 14 import javax.xml.transform.stream.StreamResult; 15 import java.io.File; 16 import java.util.HashMap; 17 18 /** 19 * Writes/reads populations to/from XML 20 */ 21 public class PopulationXML { 22 23 private static final String directory = "C:\\Users\\Pep\\Documents\\HaliteIII_519\\benchmark\\"; 24 private static DocumentBuilder documentBuilder; 25 static int currentIndividual; 26 27 private static void initializeDocBuilder(){ 28 try { 29 DocumentBuilderFactory documentFactory = DocumentBuilderFactory.newInstance(); 30 documentBuilder = documentFactory.newDocumentBuilder(); 31 } catch (ParserConfigurationException e) { 32 e.printStackTrace(); 33 } 34 } 35 36 public static void writeToXML(String fileName, Population population, int currentId){ 37 try { 38 if (documentBuilder == null){ 39 initializeDocBuilder(); 40 } 41 Document document = documentBuilder.newDocument(); 42 43 // root element 44 Element root = document.createElement("population"); 45 document.appendChild(root); 46 root.setAttribute("generation", Integer.toString(population.getGeneration())); 47 root.setAttribute("currentId", Integer.toString(currentId)); 48 root.setAttribute("avgFitness", Double.toString(population.getAverageFitness())); 49 root.setAttribute("fittest", Double.toString(population.getFittest().getFitness())); 50 51 Individual[] individuals = population.getIndividuals(); 52 for (int i = 0; i < individuals.length; i++){ 53 Individual individual = individuals[i]; 54 Element indElt = document.createElement("individual"); 55 root.appendChild(indElt); 56 indElt.setAttribute("id", Integer.toString(i)); 57 indElt.setAttribute("fitness", Double.toString(individual.getFitness())); 58 Element genes = document.createElement("genes"); 59 indElt.appendChild(genes); 60 for (HashMap.Entry<String, Double> entry : individual.getChromosome().entrySet()){ 61 genes.setAttribute(entry.getKey(), entry.getValue().toString()); 62 } 63 } 64 65 //transform the DOM Object to an XML File 66 TransformerFactory transformerFactory = TransformerFactory.newInstance(); 67 Transformer transformer = transformerFactory.newTransformer(); 68 transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); 69 transformer.setOutputProperty(OutputKeys.INDENT, "yes"); 70 DOMSource domSource = new DOMSource(document); 71 StreamResult streamResult = new StreamResult(new File(directory + fileName)); 72 transformer.transform(domSource, streamResult); 73 } catch (Exception e) { 74 Log.log(e.getMessage()); 75 } 76 } 77 78 /** 79 * Saves the current individual in static field 'currentIndividual' 80 * @return The population stored in the given XML file 81 */ 82 public static Population readXML(String fileName){ 83 Population population = null; 84 85 try { 86 if (documentBuilder == null){ 87 initializeDocBuilder(); 88 } 89 File file = new File(directory + fileName); 90 Document document = documentBuilder.parse(file); 91 92 Element root = document.getDocumentElement(); 93 int generation = Integer.parseInt((root.getAttribute("generation"))); 94 population = new Population(GA.POPULATION_SIZE, generation); 95 int currentId = Integer.parseInt((root.getAttribute("currentId"))); 96 currentIndividual = currentId; 97 98 NodeList indNodes = document.getElementsByTagName("individual"); 99 for (int i = 0; i < indNodes.getLength(); i++){ 100 HashMap<String, Double> chromosome = new HashMap<>(); 101 Node indNode = indNodes.item(i); 102 Node genesNode = indNode.getFirstChild().getNextSibling(); 103 NamedNodeMap genes = genesNode.getAttributes(); 104 for (int iGene = 0; iGene < genes.getLength(); iGene++){ 105 Node gene = genes.item(iGene); 106 chromosome.put(gene.getNodeName(), Double.parseDouble(gene.getNodeValue())); 107 } 108 double fitness = Double.parseDouble(indNode.getAttributes().getNamedItem("fitness").getNodeValue()); 109 Individual individual = new Individual(chromosome); 110 individual.setFitness(fitness); 111 population.setIndividual(i, individual); 112 } 113 } catch (Exception e) { 114 Log.log(e.getMessage()); 115 } 116 return population; 117 } 118 }