Gnuplot.java
001 /*
002  * Java Genetic Algorithm Library (jenetics-3.7.0).
003  * Copyright (c) 2007-2016 Franz Wilhelmstötter
004  *
005  * Licensed under the Apache License, Version 2.0 (the "License");
006  * you may not use this file except in compliance with the License.
007  * You may obtain a copy of the License at
008  *
009  *      http://www.apache.org/licenses/LICENSE-2.0
010  *
011  * Unless required by applicable law or agreed to in writing, software
012  * distributed under the License is distributed on an "AS IS" BASIS,
013  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014  * See the License for the specific language governing permissions and
015  * limitations under the License.
016  *
017  * Author:
018  *    Franz Wilhelmstötter (franz.wilhelmstoetter@gmx.at)
019  */
020 package org.jenetics.tool.trial;
021 
022 import static java.io.File.createTempFile;
023 import static java.lang.String.format;
024 import static java.nio.file.Files.deleteIfExists;
025 import static java.util.Objects.requireNonNull;
026 
027 import java.io.IOException;
028 import java.nio.file.Files;
029 import java.nio.file.Path;
030 import java.nio.file.Paths;
031 import java.util.Arrays;
032 import java.util.HashMap;
033 import java.util.List;
034 import java.util.Map;
035 import java.util.stream.Collectors;
036 
037 /**
038  * Helper class for creating <i>Gnuplot</i> graphs.
039  *
040  @author <a href="mailto:franz.wilhelmstoetter@gmx.at">Franz Wilhelmstötter</a>
041  @version 3.7
042  @since 3.4
043  */
044 public class Gnuplot {
045 
046     private static final String DATA_NAME = "data";
047     private static final String OUTPUT_NAME = "output";
048 
049     private final Path _template;
050 
051     private final Map<String, String> _parameters = new HashMap<>();
052     private final Map<String, String> _environment = new HashMap<>();
053 
054     /**
055      * Create a new {@code Gnuplot} object with the given <i>template</i> path.
056      *
057      @param template the Gnuplot template path
058      */
059     public Gnuplot(final Path template) {
060         _template = requireNonNull(template);
061     }
062 
063     /**
064      * Set an environment value.
065      *
066      @param name the environment name
067      @param value the environment value
068      */
069     public void setEnv(final String name, final String value) {
070         _environment.put(name, value);
071     }
072 
073     public void setEnv(final Map<String, String> env) {
074         for (Map.Entry<String, String> entry : env.entrySet()) {
075             setEnv(entry.getKey(), entry.getValue());
076         }
077     }
078 
079     /**
080      * Generate the Gnuplot graph.
081      *
082      @param data the input data file
083      @param output the output path of the graph
084      @throws IOException if the Gnuplot generation fails
085      */
086     public void create(final Path data, final Path output)
087         throws IOException
088     {
089         _parameters.put(DATA_NAME, data.toString());
090         _parameters.put(OUTPUT_NAME, output.toString());
091 
092         final String params = _parameters.entrySet().stream()
093             .map(Gnuplot::toParamString)
094             .collect(Collectors.joining("; "));
095 
096         String script = new String(Files.readAllBytes(_template));
097         for (Map.Entry<String, String> entry : _environment.entrySet()) {
098             final String key = format("${%s}", entry.getKey());
099             script = script.replace(key, entry.getValue());
100         }
101 
102         final Path scriptPath = tempPath();
103         try {
104             IO.write(script, scriptPath);
105             final List<String> command = Arrays.
106                 asList("gnuplot""-e", params, scriptPath.toString());
107 
108             final Process process = new ProcessBuilder()
109                 .command(command)
110                 .start();
111 
112             System.out.println(IO.toText(process.getErrorStream()));
113             try {
114                 process.waitFor();
115             catch (InterruptedException e) {
116                 Thread.currentThread().interrupt();
117             }
118         finally {
119             deleteIfExists(scriptPath);
120         }
121     }
122 
123     private static String toParamString(final Map.Entry<String, String> entry) {
124         return format("%s='%s'", entry.getKey(), entry.getValue());
125     }
126 
127     private static Path tempPath() throws IOException {
128         return createTempFile("__gnuplot_template__""__.gp").toPath();
129     }
130 
131     public static void main(final String[] args)
132         throws IOException, InterruptedException
133     {
134         final String base = "/home/fwilhelm/Workspace/Development/Projects/" +
135             "Jenetics/org.jenetics/src/tool/resources/org/jenetics/trial/";
136 
137         final Path data = Paths.get(base, "knapsack_execution_time.dat");
138         final Path output = Paths.get(base, "knapsack_execution_time.svg");
139 
140         final Gnuplot gnuplot = new Gnuplot(Paths.get(base, "sub_fitness.gp"));
141         gnuplot.create(data, output);
142     }
143 
144 }