$darkmode
DENOPTIM
DenoptimIO.java
Go to the documentation of this file.
1/*
2 * DENOPTIM
3 * Copyright (C) 2019 Vishwesh Venkatraman <vishwesh.venkatraman@ntnu.no> and
4 * Marco Foscato <marco.foscato@uib.no>
5 *
6 * This program is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU Affero General Public License as published
8 * by the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU Affero General Public License for more details.
15 *
16 * You should have received a copy of the GNU Affero General Public License
17 * along with this program. If not, see <http://www.gnu.org/licenses/>.
18 */
19
20package denoptim.io;
21
22
23import java.io.BufferedReader;
24import java.io.BufferedWriter;
25import java.io.File;
26import java.io.FileNotFoundException;
27import java.io.FileReader;
28import java.io.FileWriter;
29import java.io.IOException;
30import java.io.PrintWriter;
31import java.text.DateFormat;
32import java.text.SimpleDateFormat;
33import java.util.ArrayList;
34import java.util.Arrays;
35import java.util.Collections;
36import java.util.Comparator;
37import java.util.Date;
38import java.util.HashMap;
39import java.util.HashSet;
40import java.util.Hashtable;
41import java.util.LinkedHashMap;
42import java.util.List;
43import java.util.Map;
44import java.util.Set;
45import java.util.SortedSet;
46import java.util.TreeSet;
47import java.util.logging.Level;
48import java.util.logging.Logger;
49
50import org.apache.commons.io.FilenameUtils;
51import org.jmol.adapter.smarter.SmarterJmolAdapter;
52import org.jmol.viewer.Viewer;
53import org.openscience.cdk.AtomContainerSet;
54import org.openscience.cdk.CDKConstants;
55import org.openscience.cdk.DefaultChemObjectBuilder;
56import org.openscience.cdk.exception.CDKException;
57import org.openscience.cdk.interfaces.IAtomContainer;
58import org.openscience.cdk.interfaces.IAtomContainerSet;
59import org.openscience.cdk.interfaces.IChemObjectBuilder;
60import org.openscience.cdk.io.DefaultChemObjectReader;
61import org.openscience.cdk.io.FormatFactory;
62import org.openscience.cdk.io.IChemObjectReaderErrorHandler;
63import org.openscience.cdk.io.Mol2Writer;
64import org.openscience.cdk.io.SDFWriter;
65import org.openscience.cdk.io.XYZWriter;
66import org.openscience.cdk.io.formats.CIFFormat;
67import org.openscience.cdk.io.formats.IChemFormat;
68import org.openscience.cdk.io.iterator.IteratingSDFReader;
69import org.openscience.cdk.silent.SilentChemObjectBuilder;
70import org.openscience.cdk.tools.ILoggingTool;
71import org.openscience.cdk.tools.LoggingToolFactory;
72
73import com.google.gson.Gson;
74import com.google.gson.JsonSyntaxException;
75import com.google.gson.reflect.TypeToken;
76
77import denoptim.constants.DENOPTIMConstants;
78import denoptim.exception.DENOPTIMException;
79import denoptim.files.FileFormat;
80import denoptim.files.FileUtils;
81import denoptim.files.UndetectedFileFormatException;
82import denoptim.fragmenter.BridgeHeadFindingRule;
83import denoptim.fragspace.FragmentSpace;
84import denoptim.graph.APClass;
85import denoptim.graph.AttachmentPoint;
86import denoptim.graph.Candidate;
87import denoptim.graph.CandidateLW;
88import denoptim.graph.DGraph;
89import denoptim.graph.Template;
90import denoptim.graph.Vertex;
91import denoptim.graph.Vertex.BBType;
92import denoptim.json.DENOPTIMgson;
93import denoptim.logging.StaticLogger;
94import denoptim.molecularmodeling.ThreeDimTreeBuilder;
95import denoptim.programs.fragmenter.CuttingRule;
96import denoptim.utils.GraphConversionTool;
97import denoptim.utils.GraphEdit;
98import denoptim.utils.GraphUtils;
99import denoptim.utils.Randomizer;
100
101
109public class DenoptimIO
110{
111
115 public static final String FS = System.getProperty("file.separator");
116
120 public static final String NL = System.getProperty("line.separator");
121
122 private static final IChemObjectBuilder builder =
123 SilentChemObjectBuilder.getInstance();
124
125//------------------------------------------------------------------------------
126
136 public static Object readDENOPTIMData(String pathname)
137 throws Exception
138 {
139 Object data = null;
140 File file = new File(pathname);
142 format = FileUtils.detectFileFormat(file);
143 if (format == FileFormat.UNRECOGNIZED)
144 {
145 throw new UndetectedFileFormatException(file);
146 }
147 switch (format)
148 {
149 case VRTXSDF:
150 {
151 ArrayList<Vertex> vrtxs = readVertexes(file, BBType.FRAGMENT);
152 if (vrtxs.size()>1)
153 data = vrtxs;
154 else
155 data = vrtxs.get(0);
156 break;
157 }
158
159 case VRTXJSON:
160 {
161 ArrayList<Vertex> vrtxs = readVertexes(file, BBType.FRAGMENT);
162 if (vrtxs.size()>1)
163 data = vrtxs;
164 else
165 data = vrtxs.get(0);
166 break;
167 }
168
169 case CANDIDATESDF:
170 {
171 ArrayList<Candidate> cands = readCandidates(file, true);
172 if (cands.size()>1)
173 data = cands;
174 else
175 data = cands.get(0);
176 break;
177 }
178
179 case GRAPHSDF:
180 {
181 ArrayList<DGraph> graphs = readDENOPTIMGraphsFromFile(file,
182 format);
183 if (graphs.size()>1)
184 data = graphs;
185 else
186 data = graphs.get(0);
187 break;
188 }
189
190 case GRAPHJSON:
191 {
192 ArrayList<DGraph> graphs = readDENOPTIMGraphsFromFile(file,
193 format);
194 if (graphs.size()>1)
195 data = graphs;
196 else
197 data = graphs.get(0);
198 break;
199 }
200
201 case GENSUMMARY:
202 {
203 List<Candidate> cands = readGenerationFromSummary(file);
204 if (cands.size()>1)
205 data = cands;
206 else
207 data = cands.get(0);
208 break;
209 }
210
211 default:
212 throw new DENOPTIMException("Data from file of format '"
213 + format + "' cannot be loaded yet. Please, contact"
214 + "the development team.");
215 }
216 return data;
217 }
218
219//------------------------------------------------------------------------------
220
234 public static List<Candidate> readGenerationFromSummary(File file)
235 throws DENOPTIMException
236 {
237 ArrayList<Candidate> cands = new ArrayList<Candidate>();
238 List<String> pathnames = readPopulationMemberPathnames(file);
239 String genSummaryParentDir = file.getParent(); // GenXXX folder
240 for (String candPathname : pathnames)
241 {
242 File candFile = new File(candPathname);
243 if (candFile.exists())
244 {
245 cands.add(readCandidates(candFile).get(0));
246 } else if (genSummaryParentDir!=null) {
247 // Extract the possibly non-existing pathname where the
248 // candidates files were originally generated
249 String runFolderPathname =
250 candFile.getParentFile() // GenXXX
251 .getParent(); // RUN###
252 if (runFolderPathname==null)
253 throw new DENOPTIMException("Unable to find parent "
254 + "folder for '"+ genSummaryParentDir +"'");
255
256 String genAndMolPath = candFile.getAbsolutePath()
257 .substring(runFolderPathname.length());
258
259 cands.add(readCandidates(new File(
260 genSummaryParentDir+genAndMolPath)).get(0));
261 }
262 }
263 return cands;
264 }
265
266//------------------------------------------------------------------------------
267
279 public static List<IAtomContainer> readAllAtomContainers(File file)
280 throws IOException, CDKException, DENOPTIMException
281 {
282 List<IAtomContainer> results = null;
283
284 FileReader formatReader = new FileReader(file);
285 IChemFormat chemFormat = new FormatFactory().guessFormat(
286 new BufferedReader(formatReader));
287 formatReader.close();
288
289 if (chemFormat instanceof CIFFormat)
290 {
292 // WARNING
294 //
295 // * CDK's CIFReader is broken (skips lines _audit, AND ignores
296 // connectivity)
297 // * BioJava's fails on CIF files that do not complain to mmCIF
298 // format. Try this:
299 // CifStructureConverter.fromPath(f.toPath());
300 //
301 // The workaround unit CDK's implementation is fixed, is to use Jmol
302 // to read the CIF and make an SDF that can then be read normally.
303 // In fact, Jmol's reader is more robust than CDK's and more
304 // versatile than BioJava's.
305 // Moreover it reads also the bonds defined in the CIF
306 // (which OpenBabel does not read).
307 // Yet, Jmol's methods are not visible and require spinning a
308 // a viewer.
309
310 Map<String, Object> info = new Hashtable<String, Object>();
311 info.put("adapter", new SmarterJmolAdapter());
312 info.put("isApp", false);
313 info.put("silent", "");
314 Viewer v = new Viewer(info);
315 v.loadModelFromFile(null, file.getAbsolutePath(), null, null,
316 false, null, null, null, 0, " ");
317 String tmp = FileUtils.getTempFolder() + FS + "convertedCIF.sdf";
318 v.scriptWait("write " + tmp + " as sdf");
319 v.dispose();
320
321 results = readAllAtomContainers(new File(tmp));
322 } else {
323 results = readSDFFile(file.getAbsolutePath());
324 }
325
326 return results;
327 }
328
329//------------------------------------------------------------------------------
330
339 public static ArrayList<IAtomContainer> readSDFFile(String fileName)
340 throws DENOPTIMException
341 {
342 ArrayList<IAtomContainer> lstContainers = new ArrayList<>();
343
344 File file = new File(fileName);
345 IteratingSDFReader reader = null;
346 try {
347 reader = new IteratingSDFReader(
348 new BufferedReader(new FileReader(file)),
349 DefaultChemObjectBuilder.getInstance());
350 reader.setErrorHandler(new PartlySilencedChemObjReaderErrorHandler(
351 DefaultChemObjectReader.class));
352 while (reader.hasNext()) {
353 lstContainers.add((IAtomContainer)reader.next());
354 }
355 } catch (IOException cdke) {
356 throw new DENOPTIMException(cdke);
357 } finally {
358 try {
359 if (reader != null) {
360 reader.close();
361 }
362 } catch (IOException ioe) {
363 throw new DENOPTIMException(ioe);
364 }
365 }
366
367 if (lstContainers.isEmpty()) {
368 throw new DENOPTIMException("No data found in " + fileName);
369 }
370
371 return lstContainers;
372 }
373
374//------------------------------------------------------------------------------
375
383 private static class PartlySilencedChemObjReaderErrorHandler implements IChemObjectReaderErrorHandler
384 {
385 private final ILoggingTool logger;
386
392 public PartlySilencedChemObjReaderErrorHandler(final Class<?> clazz) {
393 this(LoggingToolFactory.createLoggingTool(clazz));
394 }
395
402 this.logger = logger;
403 }
404
405 @Override
406 public void handleError(String message) {
407 if (!isInvalidSymbolMessage(message)) logger.error(message);
408 }
409
410 @Override
411 public void handleError(String message, Exception exception) {
412 if (!isInvalidSymbolMessage(message)) logger.error(message, ", ", exception);
413 }
414
415 @Override
416 public void handleError(String message, int row, int colStart, int colEnd) {
417 if (!isInvalidSymbolMessage(message)) logger.error(message, ", row ", row, " column ", colStart, "-", colEnd);
418 }
419
420 @Override
421 public void handleError(String message, int row, int colStart, int colEnd, Exception exception) {
422 if (!isInvalidSymbolMessage(message)) logger.error(message + ", row ", row, " column ", colStart, "-", colEnd, ", ", exception);
423 }
424
425 @Override
426 public void handleFatalError(String message) {
427 logger.fatal(message);
428 }
429
430 @Override
431 public void handleFatalError(String message, Exception exception) {
432 logger.fatal(message + ", " + exception);
433 }
434
435 @Override
436 public void handleFatalError(String message, int row, int colStart, int colEnd) {
437 logger.fatal(message + ", row " + row + " column " + colStart + "-" + colEnd);
438 }
439
440 @Override
441 public void handleFatalError(String message, int row, int colStart, int colEnd, Exception exception) {
442 logger.fatal(message + ", row " + row + " column " + colStart + "-" + colEnd + ", " + exception);
443 }
444
445 private boolean isInvalidSymbolMessage(String message)
446 {
447 return message.contains("invalid symbol:");
448 }
449 }
450
451//------------------------------------------------------------------------------
452
461 public static File writeVertexesToFile(File file, FileFormat format,
462 List<Vertex> vertexes) throws DENOPTIMException
463 {
464 return writeVertexesToFile(file, format, vertexes, false);
465 }
466
467//------------------------------------------------------------------------------
468
477 public static File writeVertexToFile(File file, FileFormat format,
478 Vertex vertex, boolean append) throws DENOPTIMException
479 {
480 ArrayList<Vertex> lst = new ArrayList<Vertex>();
481 lst.add(vertex);
482 return writeVertexesToFile(file, format, lst, append);
483 }
484
485//------------------------------------------------------------------------------
486
495 public static File writeVertexesToFile(File file, FileFormat format,
496 List<Vertex> vertexes, boolean append) throws DENOPTIMException
497 {
498 if (FilenameUtils.getExtension(file.getName()).equals(""))
499 {
500 file = new File(file.getAbsoluteFile()+"."+format.getExtension());
501 }
502 switch (format)
503 {
504 case VRTXJSON:
505 writeVertexesToJSON(file, vertexes, append);
506 break;
507
508 case VRTXSDF:
509 writeVertexesToSDF(file, vertexes, append);
510 break;
511
512 default:
513 throw new DENOPTIMException("Cannot write vertexes with format '"
514 + format + "'.");
515 }
516 return file;
517 }
518
519//------------------------------------------------------------------------------
520
528 public static void writeVertexesToJSON(File file,
529 List<Vertex> vertexes) throws DENOPTIMException
530 {
531 writeVertexesToJSON(file, vertexes, false);
532 }
533
534//------------------------------------------------------------------------------
535
545 public static void writeVertexesToJSON(File file,
546 List<Vertex> vertexes, boolean append) throws DENOPTIMException
547 {
548 Gson writer = DENOPTIMgson.getWriter();
549 if (append)
550 {
551 ArrayList<Vertex> allVertexes = readDENOPTIMVertexesFromJSONFile(
552 file.getAbsolutePath());
553 allVertexes.addAll(vertexes);
554 writeData(file.getAbsolutePath(), writer.toJson(allVertexes), false);
555 } else {
556 writeData(file.getAbsolutePath(), writer.toJson(vertexes), false);
557 }
558 }
559
560//------------------------------------------------------------------------------
561
570 public static void writeVertexToSDF(String pathName, Vertex vertex)
571 throws DENOPTIMException
572 {
573 List<Vertex> lst = new ArrayList<Vertex>();
574 lst.add(vertex);
575 writeVertexesToSDF(new File(pathName), lst, false);
576 }
577
578//------------------------------------------------------------------------------
579
588 public static void writeVertexesToSDF(File file,
589 List<Vertex> vertexes, boolean append)
590 throws DENOPTIMException
591 {
592 List<IAtomContainer> lst = new ArrayList<IAtomContainer>();
593 for (Vertex v : vertexes)
594 {
595 lst.add(v.getIAtomContainer());
596 }
597 writeSDFFile(file.getAbsolutePath(), lst, append);
598 }
599
600//------------------------------------------------------------------------------
601
609 public static void writeSDFFile(String fileName, IAtomContainer mol)
610 throws DENOPTIMException {
611 List<IAtomContainer> mols = new ArrayList<IAtomContainer>();
612 mols.add(mol);
613 writeSDFFile(fileName, mols, false);
614 }
615
616//------------------------------------------------------------------------------
617
625 public static void writeSDFFile(String fileName, List<IAtomContainer> mols)
626 throws DENOPTIMException {
627 writeSDFFile(fileName,mols, false);
628 }
629
630//------------------------------------------------------------------------------
631
640 public static void writeSDFFile(String fileName, List<IAtomContainer> mols,
641 boolean append) throws DENOPTIMException
642 {
643 SDFWriter sdfWriter = null;
644 try {
645 IAtomContainerSet molSet = new AtomContainerSet();
646 for (int idx = 0; idx < mols.size(); idx++) {
647 molSet.addAtomContainer(mols.get(idx));
648 }
649 sdfWriter = new SDFWriter(new FileWriter(new File(fileName),append));
650 sdfWriter.write(molSet);
651 } catch (CDKException | IOException cdke) {
652 throw new DENOPTIMException(cdke);
653 } finally {
654 try {
655 if (sdfWriter != null) {
656 sdfWriter.close();
657 }
658 } catch (IOException ioe) {
659 throw new DENOPTIMException(ioe);
660 }
661 }
662 }
663
664//------------------------------------------------------------------------------
665
674 public static void writeSDFFile(String fileName, IAtomContainer mol,
675 boolean append) throws DENOPTIMException {
676 SDFWriter sdfWriter = null;
677 try {
678 sdfWriter = new SDFWriter(new FileWriter(new File(fileName), append));
679 sdfWriter.write(mol);
680 } catch (CDKException | IOException cdke) {
681 throw new DENOPTIMException(cdke);
682 } finally {
683 try {
684 if (sdfWriter != null) {
685 sdfWriter.close();
686 }
687 } catch (IOException ioe) {
688 throw new DENOPTIMException(ioe);
689 }
690 }
691 }
692
693//------------------------------------------------------------------------------
694
695 public static void writeMol2File(String fileName, IAtomContainer mol,
696 boolean append) throws DENOPTIMException {
697 Mol2Writer mol2Writer = null;
698 try {
699 mol2Writer = new Mol2Writer(new FileWriter(new File(fileName), append));
700 mol2Writer.write(mol);
701 } catch (CDKException cdke) {
702 throw new DENOPTIMException(cdke);
703 } catch (IOException ioe) {
704 throw new DENOPTIMException(ioe);
705 } finally {
706 try {
707 if (mol2Writer != null) {
708 mol2Writer.close();
709 }
710 } catch (IOException ioe) {
711 throw new DENOPTIMException(ioe);
712 }
713 }
714 }
715
716//------------------------------------------------------------------------------
717
718 public static void writeXYZFile(String fileName, IAtomContainer mol,
719 boolean append) throws DENOPTIMException {
720 XYZWriter xyzWriter = null;
721 try {
722 xyzWriter = new XYZWriter(new FileWriter(new File(fileName), append));
723 xyzWriter.write(mol);
724 } catch (CDKException cdke) {
725 throw new DENOPTIMException(cdke);
726 } catch (IOException ioe) {
727 throw new DENOPTIMException(ioe);
728 } finally {
729 try {
730 if (xyzWriter != null) {
731 xyzWriter.close();
732 }
733 } catch (IOException ioe) {
734 throw new DENOPTIMException(ioe);
735 }
736 }
737 }
738
739//------------------------------------------------------------------------------
740
750 public static void writeSmilesSet(String fileName, String[] smiles,
751 boolean append) throws DENOPTIMException {
752 FileWriter fw = null;
753 try {
754 fw = new FileWriter(new File(fileName), append);
755 for (int i = 0; i < smiles.length; i++) {
756 fw.write(smiles[i] + NL);
757 fw.flush();
758 }
759 } catch (IOException ioe) {
760 throw new DENOPTIMException(ioe);
761 } finally {
762 try {
763 if (fw != null) {
764 fw.close();
765 }
766 } catch (IOException ioe) {
767 throw new DENOPTIMException(ioe);
768 }
769 }
770 }
771
772//------------------------------------------------------------------------------
773
783 public static void writeSmiles(String fileName, String smiles,
784 boolean append) throws DENOPTIMException {
785 FileWriter fw = null;
786 try {
787 fw = new FileWriter(new File(fileName), append);
788 fw.write(smiles + NL);
789 fw.flush();
790 } catch (IOException ioe) {
791 throw new DENOPTIMException(ioe);
792 } finally {
793 try {
794 if (fw != null) {
795 fw.close();
796 }
797 } catch (IOException ioe) {
798 throw new DENOPTIMException(ioe);
799 }
800 }
801 }
802
803//------------------------------------------------------------------------------
804
813 public static void writeData(String fileName, String data, boolean append)
814 throws DENOPTIMException {
815 FileWriter fw = null;
816 try {
817 fw = new FileWriter(new File(fileName), append);
818 fw.write(data + NL);
819 fw.flush();
820 } catch (IOException ioe) {
821 throw new DENOPTIMException(ioe);
822 } finally {
823 try {
824 if (fw != null) {
825 fw.close();
826 }
827 } catch (IOException ioe) {
828 throw new DENOPTIMException(ioe);
829 }
830 }
831 }
832
833//------------------------------------------------------------------------------
834
844 public static List<CandidateLW> readLightWeightCandidate(File file)
845 throws DENOPTIMException
846 {
847 List<String> propNames = new ArrayList<String>(Arrays.asList(
849 CDKConstants.TITLE
850 ));
851 List<String> optionalPropNames = new ArrayList<String>(Arrays.asList(
856 ));
857 propNames.addAll(optionalPropNames);
858 List<Map<String, Object>> propsPerItem = readSDFProperties(
859 file.getAbsolutePath(), propNames);
860
861 List<CandidateLW> items = new ArrayList<CandidateLW>();
862 for (Map<String, Object> props : propsPerItem)
863 {
864 Object uidObj = props.get(DENOPTIMConstants.UNIQUEIDTAG);
865 if (uidObj==null )
866 {
867 throw new DENOPTIMException("Cannot create item if SDF tag "
868 + DENOPTIMConstants.UNIQUEIDTAG + " is null!");
869 }
870 Object nameObj = props.get(CDKConstants.TITLE);
871 if (nameObj==null)
872 {
873 throw new DENOPTIMException("Cannot create item is SDF tag "
874 + CDKConstants.TITLE + " is null!");
875 }
876 CandidateLW item = new CandidateLW(uidObj.toString(),
877 nameObj.toString(),file.getAbsolutePath());
878
879 for (String propName : optionalPropNames)
880 {
881 Object obj = props.get(propName);
882 if (obj != null)
883 {
884 switch (propName)
885 {
887 item.setFitness(Double.parseDouble(obj.toString()));
888 break;
889
891 item.setError(obj.toString());
892 break;
893
895 item.setGeneratingSource(obj.toString());
896 break;
897
899 item.setLevel(Integer.parseInt(obj.toString()));
900 break;
901 }
902 }
903 }
904 items.add(item);
905 }
906 return items;
907 }
908
909//------------------------------------------------------------------------------
910
919 public static double[] readPopulationProps(File file)
920 throws DENOPTIMException {
921 double[] vals = new double[4];
922 ArrayList<String> txt = readList(file.getAbsolutePath());
923 for (String line : txt) {
924 if (line.trim().length() < 8) {
925 continue;
926 }
927
928 String key = line.toUpperCase().trim().substring(0, 8);
929 switch (key) {
930 case ("MIN: "):
931 vals[0] = Double.parseDouble(line.split("\\s+")[1]);
932 break;
933
934 case ("MAX: "):
935 vals[1] = Double.parseDouble(line.split("\\s+")[1]);
936 break;
937
938 case ("MEAN: "):
939 vals[2] = Double.parseDouble(line.split("\\s+")[1]);
940 break;
941
942 case ("MEDIAN: "):
943 vals[3] = Double.parseDouble(line.split("\\s+")[1]);
944 break;
945 }
946 }
947 return vals;
948 }
949
950//------------------------------------------------------------------------------
951
960 public static List<String> readPopulationMemberPathnames(File file)
961 throws DENOPTIMException
962 {
963 List<String> vals = new ArrayList<String>();
964 ArrayList<String> txt = readList(file.getAbsolutePath());
965 for (String line : txt)
966 {
967 if (!line.contains(FS))
968 continue;
969
970 String[] words = line.trim().split("\\s+");
971 if (words.length < 5)
972 continue;
973
974 // NB: there is no keyword for population members!
975 vals.add(words[4]);
976 }
977 return vals;
978 }
979
980//------------------------------------------------------------------------------
981
993 public static List<CandidateLW> readPopulationMembersTraces(File file)
994 throws DENOPTIMException
995 {
996 List<CandidateLW> members = new ArrayList<CandidateLW>();
997 List<String> txt = readList(file.getAbsolutePath());
998
999 // Skip the header, i.e., the first line
1000 for (int i=1; i<txt.size(); i++)
1001 {
1002 String line = txt.get(i);
1003
1004 // WARNING: here we set strong expectation on the format of the
1005 // gensummary files!
1006
1007 if (line.startsWith("#"))
1008 break;
1009
1010 if (line.isBlank())
1011 continue;
1012
1013 String[] words = line.trim().split("\\s+");
1014 String pathname = "nofile";
1015 if (words.length >= 5)
1016 {
1017 pathname = words[4];
1018 }
1019 CandidateLW member = new CandidateLW(words[2], words[0], pathname);
1020 member.setFitness(Double.parseDouble(words[3]));
1021 members.add(member);
1022 }
1023 return members;
1024 }
1025
1026//------------------------------------------------------------------------------
1027
1035 public static ArrayList<String> readList(String fileName)
1036 throws DENOPTIMException {
1037 return readList(fileName, false);
1038 }
1039
1040//------------------------------------------------------------------------------
1041
1051 public static ArrayList<String> readList(String fileName,
1052 boolean allowEmpty) throws DENOPTIMException {
1053 ArrayList<String> lst = new ArrayList<>();
1054 BufferedReader br = null;
1055 String line = null;
1056 try {
1057 br = new BufferedReader(new FileReader(fileName));
1058 while ((line = br.readLine()) != null) {
1059 if (line.trim().length() == 0) {
1060 continue;
1061 }
1062 lst.add(line.trim());
1063 }
1064 } catch (IOException ioe) {
1065 throw new DENOPTIMException(ioe);
1066 } finally {
1067 try {
1068 if (br != null) {
1069 br.close();
1070 }
1071 } catch (IOException ioe) {
1072 throw new DENOPTIMException(ioe);
1073 }
1074 }
1075
1076 if (lst.isEmpty() && !allowEmpty) {
1077 throw new DENOPTIMException("No data found in file: " + fileName);
1078 }
1079
1080 return lst;
1081 }
1082
1083//------------------------------------------------------------------------------
1084
1092 public static String readText(String fileName) throws DENOPTIMException {
1093 StringBuilder sb = new StringBuilder();
1094 BufferedReader br = null;
1095 String line = null;
1096 try {
1097 br = new BufferedReader(new FileReader(fileName));
1098 while ((line = br.readLine()) != null) {
1099 sb.append(line).append(NL);
1100 }
1101 } catch (IOException ioe) {
1102 throw new DENOPTIMException(ioe);
1103 } finally {
1104 try {
1105 if (br != null) {
1106 br.close();
1107 }
1108 } catch (IOException ioe) {
1109 throw new DENOPTIMException(ioe);
1110 }
1111 }
1112
1113 return sb.toString();
1114 }
1115
1116//------------------------------------------------------------------------------
1117
1126 public static List<Map<String, Object>> readSDFProperties(String pathName,
1127 List<String> propNames) throws DENOPTIMException
1128 {
1129 List<Map<String,Object>> results = new ArrayList<Map<String,Object>>();
1130 ArrayList<IAtomContainer> iacs = DenoptimIO.readSDFFile(pathName);
1131 for (IAtomContainer iac : iacs)
1132 {
1133 Map<String,Object> properties = new HashMap<String,Object>();
1134 for (String propName : propNames)
1135 {
1136 properties.put(propName, iac.getProperty(propName));
1137 }
1138 results.add(properties);
1139 }
1140 return results;
1141 }
1142
1143//------------------------------------------------------------------------------
1144
1145 public static Set<APClass> readAllAPClasses(File fragLib) {
1146 Set<APClass> allCLasses = new HashSet<APClass>();
1147 try {
1148 for (Vertex v : DenoptimIO.readVertexes(fragLib, BBType.UNDEFINED))
1149 {
1150 for (AttachmentPoint ap : v.getAttachmentPoints()) {
1151 allCLasses.add(ap.getAPClass());
1152 }
1153 }
1154 } catch (DENOPTIMException | IllegalArgumentException
1155 | UndetectedFileFormatException | IOException e) {
1156 System.out.println("Could not read data from '" + fragLib + "'. "
1157 + "Cause: " + e.getMessage());
1158 }
1159
1160 return allCLasses;
1161 }
1162
1163//------------------------------------------------------------------------------
1164
1173 public static void writeCompatibilityMatrix(String fileName,
1174 HashMap<APClass, ArrayList<APClass>> cpMap,
1175 HashMap<APClass, APClass> capMap,
1176 HashSet<APClass> ends) throws DENOPTIMException {
1177 DateFormat dateFormat = new SimpleDateFormat("dd/MM/yy HH:mm:ss");
1178 Date date = new Date();
1179 String dateStr = dateFormat.format(date);
1180
1181 StringBuilder sb = new StringBuilder();
1183 sb.append(" Compatibility matrix data").append(NL);
1185 sb.append(" Written by DENOPTIM-GUI on ").append(dateStr).append(NL);
1187 sb.append(" APCLass Compatibility rules").append(NL);
1188 SortedSet<APClass> keysCPMap = new TreeSet<APClass>();
1189 keysCPMap.addAll(cpMap.keySet());
1190 for (APClass srcAPC : keysCPMap) {
1191 sb.append(DENOPTIMConstants.APCMAPCOMPRULE).append(" ");
1192 sb.append(srcAPC).append(" ");
1193 for (int i = 0; i < cpMap.get(srcAPC).size(); i++) {
1194 APClass trgAPC = cpMap.get(srcAPC).get(i);
1195 sb.append(trgAPC);
1196 if (i != (cpMap.get(srcAPC).size() - 1)) {
1197 sb.append(",");
1198 }
1199 }
1200 sb.append(NL);
1201 }
1202
1204 sb.append(" Capping rules").append(NL);
1205 SortedSet<APClass> keysCap = new TreeSet<APClass>();
1206 keysCap.addAll(capMap.keySet());
1207 for (APClass apc : keysCap) {
1208 sb.append(DENOPTIMConstants.APCMAPCAPPING).append(" ");
1209 sb.append(apc).append(" ").append(capMap.get(apc)).append(NL);
1210 }
1211
1213 sb.append(" Forbidden ends").append(NL);
1214 SortedSet<APClass> sortedFE = new TreeSet<APClass>();
1215 sortedFE.addAll(ends);
1216 for (APClass apc : sortedFE) {
1217 sb.append(DENOPTIMConstants.APCMAPFORBIDDENEND).append(" ");
1218 sb.append(apc).append(" ").append(NL);
1219 }
1220
1221 DenoptimIO.writeData(fileName, sb.toString(), false);
1222 }
1223
1224//------------------------------------------------------------------------------
1225
1235 public static void readCompatibilityMatrix(String fileName,HashMap<APClass,
1236 ArrayList<APClass>> compatMap,
1237 HashMap<APClass, APClass> cappingMap, Set<APClass> forbiddenEndList)
1238 throws DENOPTIMException {
1239
1240 BufferedReader br = null;
1241 String line = null;
1242 try {
1243 br = new BufferedReader(new FileReader(fileName));
1244 while ((line = br.readLine()) != null) {
1245 if (line.trim().length() == 0) {
1246 continue;
1247 }
1248
1249 if (line.startsWith(DENOPTIMConstants.APCMAPIGNORE)) {
1250 continue;
1251 }
1252
1253 if (line.startsWith(DENOPTIMConstants.APCMAPCOMPRULE)) {
1254 String str[] = line.split("\\s+");
1255 if (str.length < 3) {
1256 String err = "Incomplete APClass compatibility line '"
1257 + line + "'.";
1258 throw new DENOPTIMException(err + " " + fileName);
1259 }
1260
1261 APClass srcAPC = APClass.make(str[1]);
1262 ArrayList<APClass> trgAPCs = new ArrayList<APClass>();
1263 for (String s : str[2].split(","))
1264 {
1265 trgAPCs.add(APClass.make(s.trim()));
1266 }
1267 compatMap.put(srcAPC, trgAPCs);
1268 } else {
1269 if (line.startsWith(DENOPTIMConstants.APCMAPCAPPING)) {
1270 String str[] = line.split("\\s+");
1271 if (str.length != 3) {
1272 String err = "Incomplete capping line '"
1273 + line +"'.";
1274 throw new DENOPTIMException(err + " "+fileName);
1275 }
1276 APClass srcAPC = APClass.make(str[1]);
1277 APClass trgAPC = APClass.make(str[2]);
1278 cappingMap.put(srcAPC, trgAPC);
1279 } else {
1280 if (line.startsWith(
1282 String str[] = line.split("\\s+");
1283 if (str.length != 2) {
1284 for (int is = 1; is < str.length; is++) {
1285 forbiddenEndList.add(
1286 APClass.make(str[is]));
1287 }
1288 } else {
1289 forbiddenEndList.add(APClass.make(str[1]));
1290 }
1291 }
1292 }
1293 }
1294 }
1295 } catch (NumberFormatException | IOException nfe) {
1296 throw new DENOPTIMException(nfe);
1297 } finally {
1298 try {
1299 if (br != null) {
1300 br.close();
1301 }
1302 } catch (IOException ioe) {
1303 throw new DENOPTIMException(ioe);
1304 }
1305 }
1306
1307 if (compatMap.isEmpty()) {
1308 String err = "No reaction compatibility data found in file: ";
1309 throw new DENOPTIMException(err + " " + fileName);
1310 }
1311 }
1312
1313//------------------------------------------------------------------------------
1314
1329 public static void readRCCompatibilityMatrix(String fileName,
1330 HashMap<APClass, ArrayList<APClass>> rcCompatMap)
1331 throws DENOPTIMException {
1332 BufferedReader br = null;
1333 String line = null;
1334 try {
1335 br = new BufferedReader(new FileReader(fileName));
1336 while ((line = br.readLine()) != null) {
1337 if (line.trim().length() == 0) {
1338 continue;
1339 }
1340
1341 if (line.startsWith(DENOPTIMConstants.APCMAPIGNORE)) {
1342 continue;
1343 }
1344
1345 if (line.startsWith(DENOPTIMConstants.APCMAPCOMPRULE)) {
1346 String str[] = line.split("\\s+");
1347 if (str.length < 3) {
1348 String err = "Incomplete reaction compatibility data.";
1349 throw new DENOPTIMException(err + " " + fileName);
1350 }
1351
1352 APClass srcAPC = APClass.make(str[1]);
1353
1354 String strRcn[] = str[2].split(",");
1355 for (int i = 0; i < strRcn.length; i++) {
1356 strRcn[i] = strRcn[i].trim();
1357
1358 APClass trgAPC = APClass.make(strRcn[i]);
1359 if (rcCompatMap.containsKey(srcAPC)) {
1360 rcCompatMap.get(srcAPC).add(trgAPC);
1361 } else {
1362 ArrayList<APClass> list = new ArrayList<APClass>();
1363 list.add(trgAPC);
1364 rcCompatMap.put(srcAPC, list);
1365 }
1366
1367 if (rcCompatMap.containsKey(trgAPC)) {
1368 rcCompatMap.get(trgAPC).add(srcAPC);
1369 } else {
1370 ArrayList<APClass> list = new ArrayList<APClass>();
1371 list.add(srcAPC);
1372 rcCompatMap.put(trgAPC, list);
1373 }
1374 }
1375 }
1376 }
1377 } catch (NumberFormatException | IOException nfe) {
1378 throw new DENOPTIMException(nfe);
1379 } finally {
1380 try {
1381 if (br != null) {
1382 br.close();
1383 }
1384 } catch (IOException ioe) {
1385 throw new DENOPTIMException(ioe);
1386 }
1387 }
1388
1389 if (rcCompatMap.isEmpty()) {
1390 String err = "No reaction compatibility data found in file: ";
1391 throw new DENOPTIMException(err + " " + fileName);
1392 }
1393 }
1394
1395//------------------------------------------------------------------------------
1396
1408 public static ArrayList<Candidate> readCandidates(File file)
1409 throws DENOPTIMException {
1410 return readCandidates(file,false);
1411 }
1412
1413//------------------------------------------------------------------------------
1414
1427 public static ArrayList<Candidate> readCandidates(File file,
1428 boolean allowNoUID) throws DENOPTIMException {
1429 String filename = file.getAbsolutePath();
1430 ArrayList<Candidate> candidates = new ArrayList<>();
1431 ArrayList<IAtomContainer> iacs = readSDFFile(file.getAbsolutePath());
1432
1433 // Try to identify the generation at which this candidate was generated
1434 int genID = -1;
1435 if (file.getParentFile()!=null
1436 && file.getParentFile().getName().startsWith(
1438 {
1439 String genFolderName = file.getParentFile().getName();
1440 genID = Integer.valueOf(genFolderName.substring(
1442 }
1443
1444 for (IAtomContainer iac : iacs) {
1445 Candidate cand = new Candidate(iac, false, allowNoUID);
1446 cand.setSDFFile(filename);
1447 if (genID!=-1)
1448 cand.setGeneration(genID);
1449 candidates.add(cand);
1450 }
1451 return candidates;
1452 }
1453
1454//------------------------------------------------------------------------------
1455
1463 public static void writeCandidatesToFile(File file,
1464 List<Candidate> popMembers, boolean append)
1465 throws DENOPTIMException
1466 {
1467 if (FilenameUtils.getExtension(file.getName()).equals(""))
1468 {
1469 file = new File(file.getAbsoluteFile() + "."
1470 + FileFormat.CANDIDATESDF.getExtension());
1471 }
1472 ArrayList<IAtomContainer> lst = new ArrayList<IAtomContainer>();
1473 for (Candidate g : popMembers)
1474 {
1475 lst.add(g.getFitnessProviderOutputRepresentation());
1476 }
1477 writeSDFFile(file.getAbsolutePath(), lst, append);
1478 }
1479
1480//------------------------------------------------------------------------------
1481
1489 public static void writeCandidateToFile(File file, Candidate candidate,
1490 boolean append)
1491 throws DENOPTIMException
1492 {
1493 if (FilenameUtils.getExtension(file.getName()).equals(""))
1494 {
1495 file = new File(file.getAbsoluteFile() + "."
1496 + FileFormat.CANDIDATESDF.getExtension());
1497 }
1498 writeSDFFile(file.getAbsolutePath(),
1499 candidate.getFitnessProviderOutputRepresentation(), append);
1500 }
1501
1502//------------------------------------------------------------------------------
1503
1511 public static ArrayList<GraphEdit> readDENOPTIMGraphEditFromFile(
1512 String fileName) throws DENOPTIMException
1513 {
1514 ArrayList<GraphEdit> graphEditTasks = new ArrayList<>();
1515 Gson reader = DENOPTIMgson.getReader();
1516
1517 BufferedReader br = null;
1518 try
1519 {
1520 br = new BufferedReader(new FileReader(fileName));
1521 graphEditTasks = reader.fromJson(br,
1522 new TypeToken<ArrayList<GraphEdit>>(){}.getType());
1523 }
1524 catch (FileNotFoundException fnfe)
1525 {
1526 throw new DENOPTIMException("File '" + fileName + "' not found.");
1527 }
1528 catch (JsonSyntaxException jse)
1529 {
1530 String msg = "Expected BEGIN_ARRAY but was BEGIN_OBJECT";
1531 if (jse.getMessage().contains(msg))
1532 {
1533 // The file contains a single object, not a list. We try to read
1534 // that single object as a DENOPTIMGraph
1535 try
1536 {
1537 br.close();
1538 br = new BufferedReader(new FileReader(fileName));
1539 }
1540 catch (FileNotFoundException fnfe)
1541 {
1542 //cannot happen
1543 } catch (IOException ioe)
1544 {
1545 throw new DENOPTIMException(ioe);
1546 }
1547 GraphEdit graphEditTask = reader.fromJson(br,
1548 GraphEdit.class);
1549 graphEditTasks.add(graphEditTask);
1550 } else {
1551 jse.printStackTrace();
1552 throw new DENOPTIMException("ERROR! Unable to read JSON file "
1553 + "that defines a graph enditing task.",jse);
1554 }
1555 }
1556 finally
1557 {
1558 try {
1559 if (br != null)
1560 {
1561 br.close();
1562 }
1563 } catch (IOException ioe) {
1564 throw new DENOPTIMException(ioe);
1565 }
1566 }
1567
1568 return graphEditTasks;
1569 }
1570
1571//------------------------------------------------------------------------------
1572
1581 public static ArrayList<DGraph> readDENOPTIMGraphsFromFile(File inFile)
1582 throws Exception
1583 {
1585 return readDENOPTIMGraphsFromFile(inFile, ff);
1586 }
1587
1588//------------------------------------------------------------------------------
1589
1601 public static ArrayList<DGraph> readDENOPTIMGraphsFromFile(File inFile,
1602 FileFormat format) throws Exception
1603 {
1604 switch (format)
1605 {
1606 case GRAPHJSON:
1608 inFile.getAbsolutePath());
1609
1610 case GRAPHSDF:
1612 inFile.getAbsolutePath());
1613
1614 case GRAPHTXT:
1615 throw new DENOPTIMException("Use of string representation '"
1616 + DENOPTIMConstants.GRAPHTAG + "' is deprecated. Use "
1617 + "JSON format instead.");
1618
1619 case CANDIDATESDF:
1621 inFile.getAbsolutePath());
1622
1623 case VRTXSDF:
1624 ArrayList<DGraph> graphs = new ArrayList<DGraph>();
1625 ArrayList<Vertex> vertexes = readVertexes(inFile,
1627 for (Vertex v : vertexes)
1628 {
1629 if (v instanceof Template)
1630 {
1631 graphs.add(((Template)v).getInnerGraph());
1632 }
1633 }
1634 System.out.println("WARNING: Reading graphs from "
1635 + FileFormat.VRTXSDF + " file can only read the "
1636 + "templates' inner graphs. Importing "
1637 + graphs.size() + " graphs "
1638 + "from " + vertexes.size() + " vertexes.");
1639 return graphs;
1640
1641 default:
1642 throw new Exception("Format '" + format + "' could not be used "
1643 + "to read graphs from file '" + inFile + "'.");
1644 }
1645 }
1646
1647//------------------------------------------------------------------------------
1648
1656 public static ArrayList<DGraph> readDENOPTIMGraphsFromSDFile(
1657 String fileName) throws DENOPTIMException
1658 {
1659 ArrayList<DGraph> lstGraphs = new ArrayList<DGraph>();
1660 ArrayList<IAtomContainer> mols = DenoptimIO.readSDFFile(fileName);
1661 int i = 0;
1662 for (IAtomContainer mol : mols)
1663 {
1664 i++;
1665 DGraph g = readGraphFromSDFileIAC(mol,i,fileName);
1666 lstGraphs.add(g);
1667 }
1668 return lstGraphs;
1669 }
1670
1671//------------------------------------------------------------------------------
1672
1682 public static DGraph readGraphFromSDFileIAC(IAtomContainer mol)
1683 throws DENOPTIMException
1684 {
1685 return readGraphFromSDFileIAC(mol, -1, "");
1686 }
1687
1688//------------------------------------------------------------------------------
1689
1699 public static DGraph readGraphFromSDFileIAC(IAtomContainer mol,
1700 int molId) throws DENOPTIMException
1701 {
1702 return readGraphFromSDFileIAC(mol, molId, "");
1703 }
1704
1705//------------------------------------------------------------------------------
1706
1720 public static DGraph readGraphFromSDFileIAC(IAtomContainer mol,
1721 int molId, String fileName) throws DENOPTIMException
1722 {
1723 // Something very similar is done also in Candidate
1724 DGraph g = null;
1725 Object json = mol.getProperty(DENOPTIMConstants.GRAPHJSONTAG);
1726 if (json == null) {
1727 Object graphEnc = mol.getProperty(DENOPTIMConstants.GRAPHTAG);
1728 if (graphEnc!=null)
1729 {
1730 throw new DENOPTIMException("Use of '"
1731 + DENOPTIMConstants.GRAPHTAG + "' is deprecated. SDF "
1732 + "files containing graphs must include the "
1733 + "tag '" + DENOPTIMConstants.GRAPHJSONTAG + "'.");
1734 }
1735 String msg = "Attempt to load graph form "
1736 + "SDF that has no '" + DENOPTIMConstants.GRAPHJSONTAG
1737 + "' tag.";
1738 if (molId>-1)
1739 {
1740 msg = msg + " Check molecule " + molId;
1741 if (!fileName.isEmpty())
1742 {
1743 msg = msg + " in the SDF file '" + fileName + "'";
1744 } else {
1745 msg = msg + ".";
1746 }
1747 }
1748 throw new DENOPTIMException(msg);
1749 } else {
1750 String js = json.toString();
1751 try
1752 {
1753 g = DGraph.fromJson(js);
1754 } catch (Exception e)
1755 {
1756 String msg = e.getMessage();
1757 if (molId>-1)
1758 {
1759 msg = msg + " Check molecule " + molId;
1760 if (!fileName.isEmpty())
1761 {
1762 msg = msg + " in the SDF file '" + fileName + "'";
1763 } else {
1764 msg = msg + ".";
1765 }
1766 }
1767 throw new DENOPTIMException(msg, e);
1768 }
1769 }
1770 return g;
1771 }
1772
1773//------------------------------------------------------------------------------
1774
1782 public static ArrayList<DGraph> readDENOPTIMGraphsFromTxtFile(
1783 String fileName, FragmentSpace fragSpace, Logger logger)
1784 throws DENOPTIMException
1785 {
1786 ArrayList<DGraph> lstGraphs = new ArrayList<DGraph>();
1787 BufferedReader br = null;
1788 String line = null;
1789 try {
1790 br = new BufferedReader(new FileReader(fileName));
1791 while ((line = br.readLine()) != null) {
1792 if (line.trim().length() == 0) {
1793 continue;
1794 }
1795
1796 if (line.startsWith(DENOPTIMConstants.APCMAPIGNORE)) {
1797 continue;
1798 }
1799
1800 DGraph g;
1801 try {
1802 g = GraphConversionTool.getGraphFromString(line.trim(),
1803 fragSpace);
1804 } catch (Throwable t) {
1805 String msg = "Cannot convert string to DENOPTIMGraph. "
1806 + "Check line '" + line.trim() + "'";
1807 logger.log(Level.SEVERE, msg);
1808 throw new DENOPTIMException(msg, t);
1809 }
1810 lstGraphs.add(g);
1811 }
1812 } catch (IOException ioe) {
1813 String msg = "Cannot read file " + fileName;
1814 logger.log(Level.SEVERE, msg);
1815 throw new DENOPTIMException(msg, ioe);
1816 } finally {
1817 try {
1818 if (br != null) {
1819 br.close();
1820 }
1821 } catch (IOException ioe) {
1822 throw new DENOPTIMException(ioe);
1823 }
1824 }
1825 return lstGraphs;
1826 }
1827
1828//------------------------------------------------------------------------------
1829
1830 //TODO-v3+ this method should be almost a copy of the one working on graphs.
1831 // It should be possible to have one method do both tasks.
1832
1839 public static ArrayList<Vertex> readDENOPTIMVertexesFromJSONFile(
1840 String fileName) throws DENOPTIMException
1841 {
1842 ArrayList<Vertex> result = new ArrayList<Vertex>();
1843 Gson reader = DENOPTIMgson.getReader();
1844
1845 BufferedReader br = null;
1846 try
1847 {
1848 br = new BufferedReader(new FileReader(fileName));
1849 result = reader.fromJson(br,
1850 new TypeToken<ArrayList<Vertex>>(){}.getType());
1851 }
1852 catch (FileNotFoundException fnfe)
1853 {
1854 throw new DENOPTIMException("File '" + fileName + "' not found.");
1855 }
1856 catch (JsonSyntaxException jse)
1857 {
1858 String msg = "Expected BEGIN_ARRAY but was BEGIN_OBJECT";
1859 if (jse.getMessage().contains(msg))
1860 {
1861 // The file contains a single object, not a list. We try to read
1862 // that single object as a DENOPTIMVertex
1863 try
1864 {
1865 br.close();
1866 br = new BufferedReader(new FileReader(fileName));
1867 }
1868 catch (FileNotFoundException fnfe)
1869 {
1870 //cannot happen
1871 } catch (IOException ioe)
1872 {
1873 throw new DENOPTIMException(ioe);
1874 }
1875 Vertex v = reader.fromJson(br,Vertex.class);
1876 result.add(v);
1877 } else {
1878 throw new DENOPTIMException("ERROR! Unable to read vertex from '"
1879 + fileName + "'.", jse);
1880 }
1881 }
1882 finally
1883 {
1884 try {
1885 if (br != null)
1886 {
1887 br.close();
1888 }
1889 } catch (IOException ioe) {
1890 throw new DENOPTIMException(ioe);
1891 }
1892 }
1893
1894 return result;
1895 }
1896
1897//------------------------------------------------------------------------------
1898
1905 public static ArrayList<DGraph> readDENOPTIMGraphsFromJSONFile(
1906 String fileName) throws DENOPTIMException
1907 {
1908 ArrayList<DGraph> list_of_graphs = new ArrayList<DGraph>();
1909 Gson reader = DENOPTIMgson.getReader();
1910
1911 BufferedReader br = null;
1912 try
1913 {
1914 br = new BufferedReader(new FileReader(fileName));
1915 list_of_graphs = reader.fromJson(br,
1916 new TypeToken<ArrayList<DGraph>>(){}.getType());
1917 }
1918 catch (FileNotFoundException fnfe)
1919 {
1920 throw new DENOPTIMException("File '" + fileName + "' not found.");
1921 }
1922 catch (JsonSyntaxException jse)
1923 {
1924 String msg = "Expected BEGIN_ARRAY but was BEGIN_OBJECT";
1925 if (jse.getMessage().contains(msg))
1926 {
1927 // The file contains a single object, not a list. We try to read
1928 // that single object as a DENOPTIMGraph
1929 try
1930 {
1931 br.close();
1932 br = new BufferedReader(new FileReader(fileName));
1933 }
1934 catch (FileNotFoundException fnfe)
1935 {
1936 //cannot happen
1937 } catch (IOException ioe)
1938 {
1939 throw new DENOPTIMException(ioe);
1940 }
1941 DGraph g = reader.fromJson(br,DGraph.class);
1942 list_of_graphs.add(g);
1943 } else {
1944 throw new DENOPTIMException("ERROR! Unable to read graph from "
1945 + "JSON '" + fileName + "'", jse);
1946 }
1947 }
1948 finally
1949 {
1950 try {
1951 if (br != null)
1952 {
1953 br.close();
1954 }
1955 } catch (IOException ioe) {
1956 throw new DENOPTIMException(ioe);
1957 }
1958 }
1959
1960 return list_of_graphs;
1961 }
1962
1963//------------------------------------------------------------------------------
1964
1973 public static File writeGraphToFile(File file, FileFormat format,
1974 DGraph graph) throws DENOPTIMException
1975 {
1976 return writeGraphToFile(file, format, graph, StaticLogger.appLogger,
1977 new Randomizer());
1978 }
1979
1980//------------------------------------------------------------------------------
1981
1990 public static File writeGraphToFile(File file, FileFormat format,
1991 DGraph graph, Logger logger, Randomizer randomizer)
1992 throws DENOPTIMException
1993 {
1994 if (FilenameUtils.getExtension(file.getName()).equals(""))
1995 {
1996 file = new File(file.getAbsoluteFile()+"."+format.getExtension());
1997 }
1998 switch (format)
1999 {
2000 case GRAPHJSON:
2001 writeGraphToJSON(file, graph);
2002 break;
2003
2004 case GRAPHSDF:
2005 writeGraphToSDF(file, graph, false, true, logger, randomizer);
2006 break;
2007
2008 default:
2009 throw new DENOPTIMException("Cannot write graph with format '"
2010 + format + "'.");
2011 }
2012 return file;
2013 }
2014
2015//------------------------------------------------------------------------------
2016
2026 public static File writeGraphsToFile(File file, FileFormat format,
2027 List<DGraph> modGraphs, Logger logger, Randomizer randomizer)
2028 throws DENOPTIMException
2029 {
2030 if (FilenameUtils.getExtension(file.getName()).equals(""))
2031 {
2032 file = new File(file.getAbsoluteFile()+"."+format.getExtension());
2033 }
2034 switch (format)
2035 {
2036 case GRAPHJSON:
2037 writeGraphsToJSON(file, modGraphs);
2038 break;
2039
2040 case GRAPHSDF:
2041 writeGraphsToSDF(file, modGraphs, false, true, logger, randomizer);
2042 break;
2043
2044 default:
2045 throw new DENOPTIMException("Cannot write graphs with format '"
2046 + format + "'.");
2047 }
2048 return file;
2049 }
2050
2051//------------------------------------------------------------------------------
2052
2060 public static void writeGraphsToSDF(File file,
2061 List<DGraph> graphs, Logger logger, Randomizer randomizer)
2062 throws DENOPTIMException
2063 {
2064 writeGraphsToSDF(file, graphs, false, logger, randomizer);
2065 }
2066
2067//------------------------------------------------------------------------------
2068
2078 public static void writeGraphToSDF(File file, DGraph graph,
2079 boolean append, boolean make3D, Logger logger, Randomizer randomizer)
2080 throws DENOPTIMException
2081 {
2082 List<DGraph> lst = new ArrayList<>(1);
2083 lst.add(graph);
2084 writeGraphsToSDF(file, lst, append, make3D, logger, randomizer);
2085 }
2086
2087//------------------------------------------------------------------------------
2088
2097 public static void writeGraphToSDF(File file, DGraph graph,
2098 boolean append, Logger logger, Randomizer randomizer)
2099 throws DENOPTIMException
2100 {
2101 ArrayList<DGraph> lst = new ArrayList<>(1);
2102 lst.add(graph);
2103 writeGraphsToSDF(file, lst, append, logger, randomizer);
2104 }
2105
2106//------------------------------------------------------------------------------
2107
2116 public static void writeGraphsToSDF(File file,
2117 List<DGraph> graphs, boolean append,
2118 Logger logger, Randomizer randomizer) throws DENOPTIMException
2119 {
2120 writeGraphsToSDF(file, graphs, append, false, logger, randomizer);
2121 }
2122
2123//------------------------------------------------------------------------------
2124
2135 public static void writeGraphsToSDF(File file,
2136 List<DGraph> modGraphs, boolean append, boolean make3D,
2137 Logger logger, Randomizer randomizer) throws DENOPTIMException
2138 {
2139 ArrayList<IAtomContainer> lst = new ArrayList<IAtomContainer>();
2140 for (DGraph g : modGraphs)
2141 {
2142 ThreeDimTreeBuilder tb = new ThreeDimTreeBuilder(logger, randomizer);
2143 IAtomContainer iac = builder.newAtomContainer();
2144 if (make3D)
2145 {
2146 try {
2147 iac = tb.convertGraphTo3DAtomContainer(g, true);
2148 } catch (Throwable t) {
2149 t.printStackTrace();
2150 logger.log(Level.WARNING,"Couldn't make 3D-tree "
2151 + "representation: " + t.getMessage());
2152 }
2153 } else {
2154 GraphUtils.writeSDFFields(iac, g);
2155 }
2156 lst.add(iac);
2157 }
2158 writeSDFFile(file.getAbsolutePath(), lst, append);
2159 }
2160
2161//------------------------------------------------------------------------------
2162
2170 public static void writeGraphToJSON(File file, DGraph graph)
2171 throws DENOPTIMException
2172 {
2173 ArrayList<DGraph> graphs = new ArrayList<DGraph>();
2174 graphs.add(graph);
2175 writeGraphsToJSON(file, graphs);
2176 }
2177
2178//------------------------------------------------------------------------------
2179
2187 public static void writeGraphsToJSON(File file,
2188 List<DGraph> graphs) throws DENOPTIMException
2189 {
2190 Gson writer = DENOPTIMgson.getWriter();
2191 writeData(file.getAbsolutePath(), writer.toJson(graphs), false);
2192 }
2193
2194//------------------------------------------------------------------------------
2195
2204 public static void writeGraphsToJSON(File file,
2205 List<DGraph> graphs, boolean append) throws DENOPTIMException
2206 {
2207 Gson writer = DENOPTIMgson.getWriter();
2208 writeData(file.getAbsolutePath(), writer.toJson(graphs), append);
2209 }
2210
2211//------------------------------------------------------------------------------
2212
2221 public static void writeGraphToFile(String fileName, DGraph graph,
2222 boolean append) throws DENOPTIMException
2223 {
2224 writeData(fileName, graph.toString(), append);
2225 }
2226
2227//------------------------------------------------------------------------------
2228
2236 public static Map<File, FileFormat> readRecentFilesMap()
2237 {
2238 Map<File, FileFormat> map = new LinkedHashMap<File, FileFormat>();
2239 if (!DENOPTIMConstants.RECENTFILESLIST.exists())
2240 {
2241 return map;
2242 }
2243 try
2244 {
2245 for (String line : DenoptimIO.readList(
2246 DENOPTIMConstants.RECENTFILESLIST.getAbsolutePath(), true))
2247 {
2248 line = line.trim();
2249 String[] parts = line.split("\\s+");
2250 String ffStr = parts[0];
2251 FileFormat ff = null;
2252 try
2253 {
2254 ff = FileFormat.valueOf(FileFormat.class, ffStr);
2255 } catch (Exception e)
2256 {
2257 throw new DENOPTIMException("Unable to convert '" + ffStr
2258 + "' to a known file format.");
2259 }
2260 String fileName = line.substring(ffStr.length()).trim();
2261 if (FileUtils.checkExists(fileName))
2262 {
2263 map.put(new File(fileName), ff);
2264 }
2265 }
2266 } catch (DENOPTIMException e)
2267 {
2268 StaticLogger.appLogger.log(Level.WARNING, "WARNING: unable to "
2269 + "fetch list of recent files.", e);
2270 map = new HashMap<File, FileFormat>();
2271 }
2272 return map;
2273 }
2274
2275//------------------------------------------------------------------------------
2276
2290 public static ArrayList<Vertex> readVertexes(File file,
2292 IOException, IllegalArgumentException, DENOPTIMException
2293 {
2294 ArrayList<Vertex> vertexes = new ArrayList<Vertex>();
2296 switch (ff)
2297 {
2298 case VRTXSDF:
2300 file.getAbsolutePath(),bbt);
2301 break;
2302
2303 case VRTXJSON:
2305 file.getAbsolutePath());
2306 break;
2307
2308 case GRAPHSDF:
2309 ArrayList<DGraph> lstGraphs =
2310 readDENOPTIMGraphsFromSDFile(file.getAbsolutePath());
2311 for (DGraph g : lstGraphs)
2312 {
2313 Template t = new Template(bbt);
2314 t.setInnerGraph(g);
2315 vertexes.add(t);
2316 }
2317 break;
2318
2319 case GRAPHJSON:
2320 ArrayList<DGraph> lstGraphs2 =
2321 readDENOPTIMGraphsFromJSONFile(file.getAbsolutePath());
2322 for (DGraph g : lstGraphs2)
2323 {
2324 Template t = new Template(bbt);
2325 t.setInnerGraph(g);
2326 vertexes.add(t);
2327 }
2328 break;
2329
2330 default:
2331 throw new DENOPTIMException("Format '" + ff
2332 + "' could not be used to "
2333 + "read in vertices from file '" + file + "'.");
2334 }
2335 return vertexes;
2336 }
2337
2338//------------------------------------------------------------------------------
2339
2347 public static ArrayList<Vertex> readDENOPTIMVertexesFromSDFile(
2348 String fileName, Vertex.BBType bbt) throws DENOPTIMException
2349 {
2350 ArrayList<Vertex> vertexes = new ArrayList<Vertex>();
2351 int i=0;
2352 Gson reader = DENOPTIMgson.getReader();
2353 for (IAtomContainer mol : readSDFFile(fileName))
2354 {
2355 i++;
2356 Vertex v = null;
2357 try
2358 {
2359 v = Vertex.parseVertexFromSDFFormat(mol, reader, bbt);
2360 } catch (DENOPTIMException e)
2361 {
2362 throw new DENOPTIMException("Unable to read vertex " + i
2363 + " in file " + fileName,e);
2364 }
2365 vertexes.add(v);
2366 }
2367 return vertexes;
2368 }
2369
2370//------------------------------------------------------------------------------
2371
2388 public static LinkedHashMap<String, String> readCSDFormulae(File file)
2389 throws DENOPTIMException
2390 {
2391 LinkedHashMap<String, String> allFormulae = new LinkedHashMap<String,String>();
2392 BufferedReader buffRead = null;
2393 try {
2394 //Read the file line by line
2395 buffRead = new BufferedReader(new FileReader(file));
2396 String lineAll = null;
2397 String refcode = "";
2398 String formula = "";
2399 while ((lineAll = buffRead.readLine()) != null)
2400 {
2401 String[] lineArgs = lineAll.split(":");
2402 //Get the name
2403 if (lineArgs[0].equals("REFCODE"))
2404 refcode = lineArgs[1].trim();
2405
2406 //Get the formula
2407 if (lineArgs[0].equals(" Formula"))
2408 {
2409 formula = lineArgs[1].trim();
2410 //Store formula
2411 allFormulae.put(refcode,formula);
2412 //Clean fields
2413 refcode = "";
2414 formula = "";
2415 }
2416 }
2417 } catch (FileNotFoundException fnf) {
2418 throw new DENOPTIMException("File Not Found: " + file, fnf);
2419 } catch (IOException ioex) {
2420 throw new DENOPTIMException("Error reading file: " + file, ioex);
2421 } finally {
2422 try {
2423 if (buffRead != null)
2424 buffRead.close();
2425 } catch (IOException e) {
2426 throw new DENOPTIMException("Error closing buffer to "+file, e);
2427 }
2428 }
2429
2430 return allFormulae;
2431 }
2432
2433//------------------------------------------------------------------------------
2434
2446 public static void readCuttingRules(BufferedReader reader,
2447 List<CuttingRule> cutRules, String source) throws DENOPTIMException
2448 {
2449 ArrayList<String> cutRulLines = new ArrayList<String>();
2450 try
2451 {
2452 String line = null;
2453 while ((line = reader.readLine()) != null)
2454 {
2455 if (line.trim().startsWith(DENOPTIMConstants.CUTRULKEYWORD))
2456 cutRulLines.add(line.trim());
2457 }
2458 } catch (IOException e)
2459 {
2460 throw new DENOPTIMException(e);
2461 } finally {
2462 if (reader != null)
2463 try
2464 {
2465 reader.close();
2466 } catch (IOException e)
2467 {
2468 throw new DENOPTIMException(e);
2469 }
2470 }
2471 readCuttingRules(cutRulLines, cutRules, source);
2472 }
2473
2474//------------------------------------------------------------------------------
2475
2484 public static void readCuttingRules(File file,
2485 List<CuttingRule> cutRules) throws DENOPTIMException
2486 {
2487 ArrayList<String> allLines = readList(file.getAbsolutePath());
2488
2489 //Now get the list of cutting rules
2490 ArrayList<String> cutRulLines = new ArrayList<String>();
2491 allLines.stream()
2492 .filter(line -> line.trim().startsWith(
2494 .forEach(line -> cutRulLines.add(line.trim()));
2495
2496 readCuttingRules(cutRulLines, cutRules, "file '"
2497 + file.getAbsolutePath()+ "'");
2498 }
2499
2500//------------------------------------------------------------------------------
2501
2515 public static void readCuttingRules(ArrayList<String> cutRulLines,
2516 List<CuttingRule> cutRules, String source) throws DENOPTIMException
2517 {
2518 Set<Integer> usedPriorities = new HashSet<Integer>();
2519 for (int i = 0; i<cutRulLines.size(); i++)
2520 {
2521 String[] words = cutRulLines.get(i).split("\\s+");
2522 String name = words[1]; //name of the rule
2523 if (words.length < 6)
2524 {
2525 throw new DENOPTIMException("ERROR in getting cutting rule."
2526 + " Found " + words.length + " parts inctead of 6."
2527 + "Check line '" + cutRulLines.get(i) + "'"
2528 + "in " + source + ".");
2529 }
2530
2531 // further details in map of options
2532 ArrayList<String> opts = new ArrayList<String>();
2533 if (words.length >= 7)
2534 {
2535 for (int wi=6; wi<words.length; wi++)
2536 {
2537 opts.add(words[wi]);
2538 }
2539 }
2540
2541 int priority = Integer.parseInt(words[2]);
2542 if (usedPriorities.contains(priority))
2543 {
2544 throw new DENOPTIMException("ERROR in getting cutting rule."
2545 + " Duplicate priority index " + priority + ". "
2546 + "Check line '" + cutRulLines.get(i) + "'"
2547 + "in " + source + ".");
2548 } else {
2549 usedPriorities.add(priority);
2550 }
2551
2552 CuttingRule rule = new CuttingRule(name,
2553 words[3], //atom1
2554 words[4], //atom2
2555 words[5], //bond between 1 and 2
2556 priority,
2557 opts);
2558
2559 cutRules.add(rule);
2560 }
2561
2562 Collections.sort(cutRules, new Comparator<CuttingRule>() {
2563
2564 @Override
2565 public int compare(CuttingRule r1, CuttingRule r2)
2566 {
2567 return Integer.compare(r1.getPriority(), r2.getPriority());
2568 }
2569
2570 });
2571 }
2572
2573//------------------------------------------------------------------------------
2574
2581 public static void writeCuttingRules(File file,
2582 List<CuttingRule> cutRules) throws DENOPTIMException
2583 {
2584 StringBuilder sb = new StringBuilder();
2585 for (CuttingRule r : cutRules)
2586 {
2587 sb.append(DENOPTIMConstants.CUTRULKEYWORD).append(" ");
2588 sb.append(r.getName()).append(" ");
2589 sb.append(r.getPriority()).append(" ");
2590 sb.append(r.getSMARTSAtom0()).append(" ");
2591 sb.append(r.getSMARTSAtom1()).append(" ");
2592 sb.append(r.getSMARTSBnd()).append(" ");
2593 if (r.getOptions()!=null)
2594 {
2595 for (String opt : r.getOptions())
2596 sb.append(opt).append(" ");
2597 }
2598 sb.append(NL);
2599 }
2600 writeData(file.getAbsolutePath(), sb.toString(), false);
2601 }
2602
2603//------------------------------------------------------------------------------
2604
2611 public static void appendTxtFiles(File f1, List<File> files) throws IOException
2612 {
2613 FileWriter fw;
2614 BufferedWriter bw;
2615 PrintWriter pw = null;
2616 try
2617 {
2618 fw = new FileWriter(f1, true);
2619 bw = new BufferedWriter(fw);
2620 pw = new PrintWriter(bw);
2621 for (File inFile : files)
2622 {
2623 FileReader fr;
2624 BufferedReader br = null;
2625 try
2626 {
2627 fr = new FileReader(inFile);
2628 br = new BufferedReader(fr);
2629 String line = null;
2630 while ((line = br.readLine()) != null)
2631 {
2632 pw.println(line);
2633 }
2634 } finally {
2635 if (br != null)
2636 br.close();
2637 }
2638 }
2639 } finally {
2640 if (pw!=null)
2641 pw.close();
2642 }
2643 }
2644
2645//------------------------------------------------------------------------------
2646
2655 public static List<BridgeHeadFindingRule> readBridgeHesFindingRules(
2656 String fileName) throws DENOPTIMException
2657 {
2658 List<BridgeHeadFindingRule> rules = null;
2659 BufferedReader br = null;
2660 try {
2661 br = new BufferedReader(new FileReader(fileName));
2662 rules = readBridgeHesFindingRules(br);
2663 }
2664 catch (FileNotFoundException fnfe)
2665 {
2666 throw new DENOPTIMException("File '" + fileName + "' not found.");
2667 } catch (IOException ioe)
2668 {
2669 throw new DENOPTIMException(ioe);
2670 }
2671 finally
2672 {
2673 try {
2674 if (br != null)
2675 {
2676 br.close();
2677 }
2678 } catch (IOException ioe) {
2679 throw new DENOPTIMException(ioe);
2680 }
2681 }
2682 return rules;
2683 }
2684
2685//------------------------------------------------------------------------------
2686
2696 public static List<BridgeHeadFindingRule> readBridgeHesFindingRules(
2697 BufferedReader br) throws IOException
2698 {
2699 List<BridgeHeadFindingRule> rules = new ArrayList<>();
2700 Gson reader = DENOPTIMgson.getReader();
2701 try
2702 {
2703 rules = reader.fromJson(br,
2704 new TypeToken<ArrayList<BridgeHeadFindingRule>>(){}.getType());
2705 }
2706 finally
2707 {
2708 if (br != null)
2709 {
2710 br.close();
2711 }
2712 }
2713 return rules;
2714 }
2715
2716
2717//------------------------------------------------------------------------------
2718
2724 public static void scanLoggingLevels(Logger logger)
2725 {
2726 logger.log(Level.ALL, "ALL");
2727 logger.log(Level.SEVERE, "SEVERE");
2728 logger.log(Level.WARNING, "WARN");
2729 logger.log(Level.INFO, "INFO");
2730 logger.log(Level.CONFIG, "CONGIF");
2731 logger.log(Level.FINE, "Fine");
2732 logger.log(Level.FINER, "FINER");
2733 logger.log(Level.FINEST, "FIENEST");
2734 }
2735
2736//------------------------------------------------------------------------------
2737
2738}
General set of constants used in DENOPTIM.
static final String GRAPHTAG
SDF tag containing graph encoding.
static final File RECENTFILESLIST
List of recent files.
static final String APCMAPIGNORE
Keyword identifying compatibility matrix file lines with comments.
static final String PROVENANCE
SDF tag containing provenance data for a graph.
static final String APCMAPCAPPING
Keyword identifying compatibility matrix file lines with capping rules.
static final String GRAPHLEVELTAG
SDF tag defining the graph generating level in an FSE run.
static final String UNIQUEIDTAG
SDF tag containing the unique identifier of a candidate.
static final String GAGENDIRNAMEROOT
Prefix for generation folders.
static final String CUTRULKEYWORD
Keyword that identifies rows defining cutting rules in files collecting cutting rules.
static final String GRAPHJSONTAG
SDF tag containing graph encoding in JSON format.
static final String APCMAPFORBIDDENEND
Keyword identifying compatibility matrix file lines with forbidden ends.
static final String MOLERRORTAG
SDF tag containing errors during execution of molecule specific tasks.
static final String APCMAPCOMPRULE
Keyword identifying compatibility matrix file lines with APClass compatibility rules.
static final String FITNESSTAG
SDF tag containing the fitness of a candidate.
static boolean checkExists(String fileName)
Definition: FileUtils.java:241
static FileFormat detectFileFormat(File inFile)
Inspects a file/folder and tries to detect if there is one of the data sources that is recognized by ...
Definition: FileUtils.java:399
static String getTempFolder()
Looks for a writable location where to put temporary files and returns an absolute pathname to the fo...
Definition: FileUtils.java:204
Exception thrown when the format of a file is not recognized.
Class defining a space of building blocks.
static APClass make(String ruleAndSubclass)
Creates an APClass if it does not exist already, or returns the reference to the existing instance.
Definition: APClass.java:164
An attachment point (AP) is a possibility to attach a Vertex onto the vertex holding the AP (i....
A candidate is the combination of a denoptim graph with molecular representation and may include also...
Definition: Candidate.java:40
void setSDFFile(String molFile)
Definition: Candidate.java:445
void setGeneration(int genId)
Definition: Candidate.java:565
A light-weight candidate is a very low-demanding collection of data upon a specific candidate item.
void setFitness(double fitness)
void setError(String error)
void setLevel(int lev)
Sets level that generated this graph in a fragment space exploration experiment.
void setGeneratingSource(String source)
Container for the list of vertices and the edges that connect them.
Definition: DGraph.java:104
static DGraph fromJson(String json)
Reads a JSON string and returns an instance of this class.
Definition: DGraph.java:7355
void setInnerGraph(DGraph innerGraph)
Definition: Template.java:298
A vertex is a data structure that has an identity and holds a list of AttachmentPoints.
Definition: Vertex.java:61
static Vertex parseVertexFromSDFFormat(IAtomContainer mol, Gson reader, BBType bbt)
Created a Vertex from the SDF representation, i.e., from an IAtomContainer.
Definition: Vertex.java:1460
static Vertex fromJson(String json)
Definition: Vertex.java:1289
This differs from DefaultChemObjectReaderErrorHandler just by ignoring messages about invalid symbol.
PartlySilencedChemObjReaderErrorHandler(final Class<?> clazz)
Constructs a new instance using a given class as the source for logging purposes.
void handleFatalError(String message, int row, int colStart, int colEnd)
void handleError(String message, Exception exception)
void handleFatalError(String message, int row, int colStart, int colEnd, Exception exception)
void handleFatalError(String message, Exception exception)
PartlySilencedChemObjReaderErrorHandler(final ILoggingTool logger)
Constructs a new instance using the provided logging tool.
void handleError(String message, int row, int colStart, int colEnd, Exception exception)
void handleError(String message, int row, int colStart, int colEnd)
Utility methods for input/output.
static ArrayList< Candidate > readCandidates(File file)
Reads SDF files that represent one or more tested candidates.
static File writeVertexesToFile(File file, FileFormat format, List< Vertex > vertexes)
Writes vertexes to file.
static File writeGraphToFile(File file, FileFormat format, DGraph graph, Logger logger, Randomizer randomizer)
Writes the a graph to file.
static LinkedHashMap< String, String > readCSDFormulae(File file)
Read molecular formula from TXT data representation produced by Cambridge Structural Database tools (...
static List< Candidate > readGenerationFromSummary(File file)
Reads a FileFormat#GENSUMMARY file and searches all the files defining each member of the population.
static void readCuttingRules(ArrayList< String > cutRulLines, List< CuttingRule > cutRules, String source)
Read cutting rules from a properly formatted text file.
static void readRCCompatibilityMatrix(String fileName, HashMap< APClass, ArrayList< APClass > > rcCompatMap)
Reads the APclass compatibility matrix for ring-closing connections (the RC-CPMap).
static ArrayList< DGraph > readDENOPTIMGraphsFromFile(File inFile, FileFormat format)
Reads a list of DGraphs from file.
static List< String > readPopulationMemberPathnames(File file)
Read the pathnames to the population members from a FileFormat#GENSUMMARY file.
static void writeSDFFile(String fileName, IAtomContainer mol, boolean append)
Writes an IAtomContainer to SDF file.
static void writeGraphToFile(String fileName, DGraph graph, boolean append)
Writes the string representation of a graph to file.
static void writeGraphToSDF(File file, DGraph graph, boolean append, Logger logger, Randomizer randomizer)
Writes the graph to SDF file.
static void writeSDFFile(String fileName, List< IAtomContainer > mols)
Writes IAtomContainers to SDF file.
static void writeSDFFile(String fileName, IAtomContainer mol)
Writes IAtomContainer to SDF file.
static void readCuttingRules(File file, List< CuttingRule > cutRules)
Read cutting rules from a properly formatted text file.
static DGraph readGraphFromSDFileIAC(IAtomContainer mol, int molId, String fileName)
Converts an atom container read in from an SDF file into a graph, if possible.
static void writeXYZFile(String fileName, IAtomContainer mol, boolean append)
static ArrayList< Vertex > readDENOPTIMVertexesFromJSONFile(String fileName)
Reads a list of Vertexes from a JSON file.
static DGraph readGraphFromSDFileIAC(IAtomContainer mol)
Converts an atom container read in from an SDF file into a graph, if possible.
static final IChemObjectBuilder builder
static Map< File, FileFormat > readRecentFilesMap()
Reads the file defined in DENOPTIMConstants#RECENTFILESLIST and makes a map that contains the pathnam...
static ArrayList< DGraph > readDENOPTIMGraphsFromTxtFile(String fileName, FragmentSpace fragSpace, Logger logger)
Reads a list of <DGraphs from a text file.
static ArrayList< IAtomContainer > readSDFFile(String fileName)
Reads a file containing multiple molecules.
static void writeGraphsToSDF(File file, List< DGraph > graphs, Logger logger, Randomizer randomizer)
Writes the graphs to SDF file.
static File writeGraphToFile(File file, FileFormat format, DGraph graph)
Writes the a graph to file.
static void readCuttingRules(BufferedReader reader, List< CuttingRule > cutRules, String source)
Read cutting rules from a stream.
static void writeCandidateToFile(File file, Candidate candidate, boolean append)
Writes one candidate item to file.
static void writeGraphToSDF(File file, DGraph graph, boolean append, boolean make3D, Logger logger, Randomizer randomizer)
Writes the graph to SDF file.
static void writeCuttingRules(File file, List< CuttingRule > cutRules)
Writes a formatted text file that collects cutting rule.
static void writeSDFFile(String fileName, List< IAtomContainer > mols, boolean append)
Writes a set of IAtomContainers to SDF file.
static void writeGraphsToSDF(File file, List< DGraph > modGraphs, boolean append, boolean make3D, Logger logger, Randomizer randomizer)
Writes the graphs to SDF file.
static Object readDENOPTIMData(String pathname)
Reads any content of a given pathname and tries to read DENOPTIM data from it.
static File writeVertexToFile(File file, FileFormat format, Vertex vertex, boolean append)
Writes vertexes to file.
static void readCompatibilityMatrix(String fileName, HashMap< APClass, ArrayList< APClass > > compatMap, HashMap< APClass, APClass > cappingMap, Set< APClass > forbiddenEndList)
Read the APclass compatibility matrix data from file.
static void writeSmilesSet(String fileName, String[] smiles, boolean append)
Writes multiple smiles string array to the specified file.
static void writeVertexesToJSON(File file, List< Vertex > vertexes, boolean append)
Writes vertexes to JSON file.
static double[] readPopulationProps(File file)
Read the min, max, mean, and median of a population from FileFormat#GENSUMMARY file.
static Set< APClass > readAllAPClasses(File fragLib)
static void scanLoggingLevels(Logger logger)
Utility to trigger logging at all known levels.
static ArrayList< DGraph > readDENOPTIMGraphsFromJSONFile(String fileName)
Reads a list of DGraphs from a JSON file.
static ArrayList< String > readList(String fileName, boolean allowEmpty)
Read list of data as text.
static File writeGraphsToFile(File file, FileFormat format, List< DGraph > modGraphs, Logger logger, Randomizer randomizer)
Writes the graphs to file.
static List< BridgeHeadFindingRule > readBridgeHesFindingRules(BufferedReader br)
Reads a list of rules for identifying potential bridge-head sites.
static ArrayList< DGraph > readDENOPTIMGraphsFromFile(File inFile)
Reads a list of DGraphs from file.
static final String NL
Newline character from system.
static List< CandidateLW > readLightWeightCandidate(File file)
Read only selected data from a GA produced items.
static void writeGraphsToJSON(File file, List< DGraph > graphs, boolean append)
Writes the graphs to JSON file.
static List< Map< String, Object > > readSDFProperties(String pathName, List< String > propNames)
Extract selected properties from SDF files.
static void writeGraphToJSON(File file, DGraph graph)
Writes the graph to JSON file.
static void writeSmiles(String fileName, String smiles, boolean append)
Writes a single smiles string to the specified file.
static String readText(String fileName)
Read text from file.
static void writeGraphsToSDF(File file, List< DGraph > graphs, boolean append, Logger logger, Randomizer randomizer)
Writes the graphs to SDF file.
static void writeVertexToSDF(String pathName, Vertex vertex)
Writes a vertex to an SDF file.
static ArrayList< DGraph > readDENOPTIMGraphsFromSDFile(String fileName)
Reads a list of <DGraphs from a SDF file.
static void writeVertexesToJSON(File file, List< Vertex > vertexes)
Writes vertexes to JSON file.
static void writeMol2File(String fileName, IAtomContainer mol, boolean append)
static List< BridgeHeadFindingRule > readBridgeHesFindingRules(String fileName)
Reads a list of rules for identifying potential bridge-head sites.
static ArrayList< String > readList(String fileName)
Read list of data as text.
static void appendTxtFiles(File f1, List< File > files)
Appends the second file to the first.
static DGraph readGraphFromSDFileIAC(IAtomContainer mol, int molId)
Converts an atom container read in from an SDF file into a graph, if possible.
static ArrayList< Vertex > readVertexes(File file, Vertex.BBType bbt)
Reads Vertexes from any file that can contain such items.
static void writeData(String fileName, String data, boolean append)
Write text-like data file.
static void writeGraphsToJSON(File file, List< DGraph > graphs)
Writes the graphs to JSON file.
static List< IAtomContainer > readAllAtomContainers(File file)
Returns a single collection with all atom containers found in a file of any format.
static List< CandidateLW > readPopulationMembersTraces(File file)
Read the minimal info that can be found in a FileFormat#GENSUMMARY file about the members of a popula...
static void writeCandidatesToFile(File file, List< Candidate > popMembers, boolean append)
Writes candidate items to file.
static void writeCompatibilityMatrix(String fileName, HashMap< APClass, ArrayList< APClass > > cpMap, HashMap< APClass, APClass > capMap, HashSet< APClass > ends)
The class compatibility matrix.
static File writeVertexesToFile(File file, FileFormat format, List< Vertex > vertexes, boolean append)
Writes vertexes to file.
static final String FS
File separator from system.
static ArrayList< GraphEdit > readDENOPTIMGraphEditFromFile(String fileName)
Reads a list of graph editing tasks from a JSON file.
static void writeVertexesToSDF(File file, List< Vertex > vertexes, boolean append)
Write a list of vertexes to file.
static ArrayList< Vertex > readDENOPTIMVertexesFromSDFile(String fileName, Vertex.BBType bbt)
Reads a list of Vertexes from a SDF file.
static ArrayList< Candidate > readCandidates(File file, boolean allowNoUID)
Reads SDF files that represent one or more tested or to be tested candidates.
Class for de/serializing DENOPTIM graphs from/to JSON format.
Logger class for DENOPTIM.
static final Logger appLogger
Tool to build build three-dimensional (3D) tree-like molecular structures from DGraph.
IAtomContainer convertGraphTo3DAtomContainer(DGraph graph)
Created a three-dimensional molecular representation from a given DGraph.
A cutting rule with three SMARTS queries (atom 1, bond, atom2) and options.
Tool to convert string into graphs and into molecular representation.
static DGraph getGraphFromString(String strGraph, FragmentSpace fragSpace)
Given a formatted string-like representation of a DENOPTIM graph create the corresponding DENOPTIMGra...
Definition of a graph editing task.
Definition: GraphEdit.java:40
Utilities for graphs.
Definition: GraphUtils.java:40
static void writeSDFFields(IAtomContainer iac, DGraph g)
Tool to generate random numbers and random decisions.
Definition: Randomizer.java:35
File formats identified by DENOPTIM.
Definition: FileFormat.java:32
The type of building block.
Definition: Vertex.java:86