Debian Codegraph @

src/dr/app/util/Utils.java

raw symbols SCIP
1 /*
2 * Utils.java
3 *
4 * Copyright (c) 2002-2015 Alexei Drummond, Andrew Rambaut and Marc Suchard
5 *
6 * This file is part of BEAST.
7 * See the NOTICE file distributed with this work for additional
8 * information regarding copyright ownership and licensing.
9 *
10 * BEAST is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU Lesser General Public License as
12 * published by the Free Software Foundation; either version 2
13 * of the License, or (at your option) any later version.
14 *
15 * BEAST is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU Lesser General Public License for more details.
19 *
20 * You should have received a copy of the GNU Lesser General Public
21 * License along with BEAST; if not, write to the
22 * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
23 * Boston, MA 02110-1301 USA
24 */
25
26 package dr.app.util;
27
28 import javax.swing.*;
29 import javax.swing.filechooser.FileNameExtensionFilter;
30 import java.awt.*;
31 import java.io.BufferedReader;
32 import java.io.File;
33 import java.io.FileReader;
34 import java.io.IOException;
35 import java.lang.reflect.Constructor;
36 import java.util.*;
37 import java.util.List;
38
39 /**
40 * @author adru001
41 */
42 public class Utils {
43 public static final String TRAITS = "traits";
44
45 public static String absName(File file) {
46 return (file != null) ? file.getAbsolutePath() : null;
47 }
48
49 public static String getLoadFileName(String message) {
50 return absName(getLoadFile(message));
51 }
52
53 public static String getSaveFileName(String message) {
54 return absName(getSaveFile(message));
55 }
56
57 public static File getLoadFile(String message) {
58 // No file name in the arguments so throw up a dialog box...
59 java.awt.Frame frame = new java.awt.Frame();
60 java.awt.FileDialog chooser = new java.awt.FileDialog(frame, message,
61 java.awt.FileDialog.LOAD);
62 // chooser.show();
63 chooser.setVisible(true);
64 if (chooser.getFile() == null) return null;
65 java.io.File file = new java.io.File(chooser.getDirectory(), chooser.getFile());
66 chooser.dispose();
67 frame.dispose();
68
69 return file;
70 }
71
72 public static File[] getLoadFiles(String message, File openDefaultDirectory, String description, String... extensions) {
73 // No file name in the arguments so throw up a dialog box...
74 java.awt.Frame frame = new java.awt.Frame();
75 frame.setTitle(message);
76 final JFileChooser chooser = new JFileChooser(openDefaultDirectory);
77 chooser.setMultiSelectionEnabled(true);
78 chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
79
80 FileNameExtensionFilter filter = new FileNameExtensionFilter(description, extensions);
81 chooser.setFileFilter(filter);
82
83 final int returnVal = chooser.showOpenDialog(frame);
84 File[] files = null;
85 if (returnVal == JFileChooser.APPROVE_OPTION) {
86 files = chooser.getSelectedFiles();
87
88 }
89 frame.dispose();
90 return files;
91 }
92
93 public static File getSaveFile(String message) {
94 // No file name in the arguments so throw up a dialog box...
95 java.awt.Frame frame = new java.awt.Frame();
96 java.awt.FileDialog chooser = new java.awt.FileDialog(frame, message,
97 java.awt.FileDialog.SAVE);
98 // chooser.show();
99 chooser.setVisible(true);
100 java.io.File file = new java.io.File(chooser.getDirectory(), chooser.getFile());
101 chooser.dispose();
102 frame.dispose();
103
104 return file;
105 }
106
107 // detect type of text value - return class of type
108
109 public static Class detectType(final String valueString) {
110 if (valueString.equalsIgnoreCase("TRUE") || valueString.equalsIgnoreCase("FALSE")) {
111 return Boolean.class;
112 }
113
114 try {
115 final double number = Double.parseDouble(valueString);
116 if (Math.round(number) == number) {
117 return Integer.class;
118 }
119 return Double.class;
120 } catch (NumberFormatException pe) {
121 return String.class;
122 }
123 }
124
125 // New object of type cl from text.
126 // return null if can't be done of value can't be converted.
127
128 public static Object constructFromString(Class cl, String value) {
129 for (Constructor c : cl.getConstructors()) {
130 final Class[] classes = c.getParameterTypes();
131 if (classes.length == 1 && classes[0].equals(String.class)) {
132 try {
133 return c.newInstance(value);
134 } catch (Exception e) {
135 return null;
136 }
137 }
138 }
139 return null;
140 }
141
142 // skip over comment and empty lines
143
144 public static String nextNonCommentLine(BufferedReader reader) throws IOException {
145 String line;
146 do {
147 line = reader.readLine();
148 // ignore empty or comment lines
149 } while (line != null && (line.trim().length() == 0 || line.trim().charAt(0) == '#'));
150 return line;
151 }
152
153 /**
154 * Load traits from file.
155 *
156 * @param file File
157 * @param delimiter String
158 * @return A map whose key is the trait. The value is a list of <taxa, value> as a string array of size 2.
159 * @throws java.io.IOException IOException
160 * @throws dr.app.util.Arguments.ArgumentException
161 * ArgumentException
162 */
163 public static Map<String, List<String[]>> importTraitsFromFile(File file, final String delimiter)
164 throws IOException, Arguments.ArgumentException {
165 final BufferedReader reader = new BufferedReader(new FileReader(file));
166
167 String line = nextNonCommentLine(reader);
168
169 // define where is the trait keyword in the 1st row of file
170 final int startAt = 1;
171
172 final String[] traitNames = line.split(delimiter);
173 for (int k = 0; k < traitNames.length; ++k) {
174 traitNames[k] = traitNames[k].trim();
175 }
176
177 if (!(traitNames[0].equalsIgnoreCase(TRAITS) || traitNames[0].length() < 1))
178 throw new Arguments.ArgumentException("Wrong file format:\ntrait key word should be declared in the 1st row");
179
180 Map<String, List<String[]>> traits = new HashMap<String, List<String[]>>();
181 for (int i = startAt; i < traitNames.length; i++) {
182 traits.put(traitNames[i], new ArrayList<String[]>());
183 }
184
185 line = nextNonCommentLine(reader);
186 while (line != null) {
187 String[] values = line.split(delimiter);
188
189 assert (values.length > 0);
190 if (values.length != traitNames.length)
191 throw new Arguments.ArgumentException("Wrong file format:\neach trait should have its corresponding value");
192
193 try {
194 if (traitNames[0].equalsIgnoreCase(TRAITS)) {
195 importStatesMoreThanTaxon(traits, values, traitNames, startAt);
196 } else {
197 importSpecies(traits, values, traitNames, startAt);
198 }
199 } catch (Arguments.ArgumentException e) {
200 e.printStackTrace();
201 }
202
203 line = nextNonCommentLine(reader);
204 }
205 return traits;
206 }
207
208 private static void importSpecies(Map<String, List<String[]>> traits, String[] values, String[] traitNames, int startAt)
209 throws Arguments.ArgumentException {
210 // first column is label for the redundant "taxa" name
211 final String first = values[0].trim();
212 int k = Arrays.asList(traitNames).indexOf(first);
213 if (k >= 0) {
214 List<String[]> trait = traits.get(first);
215 if (trait == null) {
216 throw new Arguments.ArgumentException("undefined trait " + first);
217 }
218 final String traitVal = values[1].trim();
219 for (int i = 2; i < values.length; i++) {
220 trait.add(new String[]{values[i], traitVal}); // {taxon_name, trait}
221 }
222 } else {
223 for (int i = startAt; i < values.length; i++) {
224 if (i < traitNames.length) {
225 List<String[]> column = traits.get(traitNames[i]);
226 column.add(new String[]{first, values[i].trim()});
227 }
228 }
229 }
230 }
231
232 private static void importStatesMoreThanTaxon(Map<String, List<String[]>> traits, String[] values, String[] traitNames, int startAt)
233 throws Arguments.ArgumentException {
234 // first column is label taxon name
235
236 if (traitNames.length < 2) {
237 throw new Arguments.ArgumentException("Wrong file format:\ntrait key words in the 1st row are loaded improperly");
238 } else if (traitNames.length - startAt < 1) {
239 throw new Arguments.ArgumentException("startAt set improperly");
240 }
241
242 for (int i = 0; i < (traitNames.length - startAt); i++) {
243 List<String[]> trait = traits.get(traitNames[i + startAt]);
244 if (trait == null) throw new Arguments.ArgumentException("undefined trait " + traitNames[i + startAt]);
245
246 trait.add(new String[]{values[0].trim(), values[i + startAt].trim()}); // {taxon_name, trait}
247 }
248 }
249
250 /**
251 * This function takes a file name and an array of extensions (specified
252 * without the leading '.'). If the file name ends with one of the extensions
253 * then it is returned with this trimmed off. Otherwise the file name is
254 * return as it is.
255 *
256 * @param fileName String
257 * @param extensions String[]
258 * @return the trimmed filename
259 */
260 public static String trimExtensions(String fileName, String[] extensions) {
261
262 String newName = null;
263
264 for (String extension : extensions) {
265 final String ext = "." + extension;
266 if (fileName.toUpperCase().endsWith(ext.toUpperCase())) {
267 newName = fileName.substring(0, fileName.length() - ext.length());
268 }
269 }
270
271 return (newName != null) ? newName : fileName;
272 }
273
274 /**
275 * @param caller Object
276 * @param name String
277 * @return a named image from file or resource bundle.
278 */
279 public static Image getImage(Object caller, String name) {
280
281 java.net.URL url = caller.getClass().getResource(name);
282 if (url != null) {
283 return Toolkit.getDefaultToolkit().createImage(url);
284 } else {
285 if (caller instanceof Component) {
286 Component c = (Component) caller;
287 Image i = c.createImage(100, 20);
288 Graphics g = c.getGraphics();
289 g.drawString("Not found!", 1, 15);
290 return i;
291 } else return null;
292 }
293 }
294
295 public static File getCWD() {
296 final String f = System.getProperty("user.dir");
297 return new File(f);
298 }
299
300 // enum Platform {
301 // WINDOWS,
302 // MACOSX,
303 // LINUX;
304 //
305 // Platform detect() {
306 //
307 // final String os = System.getProperty("os.name");
308 //
309 // if( os.equals("Linux") ) {
310 // return LINUX;
311 // }
312 // // todo probably wrong, please check on windows
313 // if( os.equals("Windows") ) {
314 // return WINDOWS;
315 // }
316 //
317 // if( System.getProperty("os.name").toLowerCase().startsWith("mac os x") ) {
318 // return MACOSX;
319 // }
320 //
321 // return null;
322 // }
323 // }
324 }