$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.io.StringWriter;
32import java.text.DateFormat;
33import java.text.SimpleDateFormat;
34import java.util.ArrayList;
35import java.util.Arrays;
36import java.util.Collections;
37import java.util.Comparator;
38import java.util.Date;
39import java.util.HashMap;
40import java.util.HashSet;
41import java.util.Hashtable;
42import java.util.LinkedHashMap;
43import java.util.List;
44import java.util.Map;
45import java.util.Set;
46import java.util.SortedSet;
47import java.util.TreeSet;
48import java.util.logging.Level;
49import java.util.logging.Logger;
50
51import org.apache.commons.io.FilenameUtils;
52import org.jmol.adapter.smarter.SmarterJmolAdapter;
53import org.jmol.viewer.Viewer;
54import org.openscience.cdk.AtomContainerSet;
55import org.openscience.cdk.CDKConstants;
56import org.openscience.cdk.ChemFile;
57import org.openscience.cdk.ChemObject;
58import org.openscience.cdk.exception.CDKException;
59import org.openscience.cdk.interfaces.IAtomContainer;
60import org.openscience.cdk.interfaces.IAtomContainerSet;
61import org.openscience.cdk.interfaces.IChemFile;
62import org.openscience.cdk.interfaces.IChemObject;
63import org.openscience.cdk.interfaces.IChemObjectBuilder;
64import org.openscience.cdk.io.DefaultChemObjectReader;
65import org.openscience.cdk.io.FormatFactory;
66import org.openscience.cdk.io.IChemObjectReaderErrorHandler;
67import org.openscience.cdk.io.ISimpleChemObjectReader;
68import org.openscience.cdk.io.MDLV2000Reader;
69import org.openscience.cdk.io.MDLV2000Writer;
70import org.openscience.cdk.io.Mol2Writer;
71import org.openscience.cdk.io.ReaderFactory;
72import org.openscience.cdk.io.SDFWriter;
73import org.openscience.cdk.io.XYZWriter;
74import org.openscience.cdk.io.formats.CIFFormat;
75import org.openscience.cdk.io.formats.IChemFormat;
76import org.openscience.cdk.silent.SilentChemObjectBuilder;
77import org.openscience.cdk.tools.ILoggingTool;
78import org.openscience.cdk.tools.LoggingToolFactory;
79import org.openscience.cdk.tools.manipulator.ChemFileManipulator;
80
81import com.google.gson.Gson;
82import com.google.gson.JsonSyntaxException;
83import com.google.gson.reflect.TypeToken;
84
85import denoptim.constants.DENOPTIMConstants;
86import denoptim.exception.DENOPTIMException;
87import denoptim.files.FileFormat;
88import denoptim.files.FileUtils;
89import denoptim.files.UndetectedFileFormatException;
90import denoptim.fragmenter.BridgeHeadFindingRule;
91import denoptim.fragspace.FragmentSpace;
92import denoptim.graph.APClass;
93import denoptim.graph.AttachmentPoint;
94import denoptim.graph.Candidate;
95import denoptim.graph.CandidateLW;
96import denoptim.graph.DGraph;
97import denoptim.graph.Template;
98import denoptim.graph.Vertex;
99import denoptim.graph.Vertex.BBType;
100import denoptim.json.DENOPTIMgson;
101import denoptim.logging.StaticLogger;
102import denoptim.molecularmodeling.ThreeDimTreeBuilder;
103import denoptim.programs.fragmenter.CuttingRule;
104import denoptim.utils.GraphConversionTool;
105import denoptim.utils.GraphEdit;
106import denoptim.utils.GraphUtils;
107import denoptim.utils.Randomizer;
108
109
117public class DenoptimIO
118{
119
123 public static final String FS = System.getProperty("file.separator");
124
128 public static final String NL = System.getProperty("line.separator");
129
130 private static final IChemObjectBuilder builder =
131 SilentChemObjectBuilder.getInstance();
132
133//------------------------------------------------------------------------------
134
144 public static Object readDENOPTIMData(String pathname)
145 throws Exception
146 {
147 Object data = null;
148 File file = new File(pathname);
150 format = FileUtils.detectFileFormat(file);
151 if (format == FileFormat.UNRECOGNIZED)
152 {
153 throw new UndetectedFileFormatException(file);
154 }
155 switch (format)
156 {
157 case VRTXSDF:
158 {
159 ArrayList<Vertex> vrtxs = readVertexes(file, BBType.FRAGMENT);
160 if (vrtxs.size()>1)
161 data = vrtxs;
162 else
163 data = vrtxs.get(0);
164 break;
165 }
166
167 case VRTXJSON:
168 {
169 ArrayList<Vertex> vrtxs = readVertexes(file, BBType.FRAGMENT);
170 if (vrtxs.size()>1)
171 data = vrtxs;
172 else
173 data = vrtxs.get(0);
174 break;
175 }
176
177 case CANDIDATESDF:
178 {
179 ArrayList<Candidate> cands = readCandidates(file, true);
180 if (cands.size()>1)
181 data = cands;
182 else
183 data = cands.get(0);
184 break;
185 }
186
187 case GRAPHSDF:
188 {
189 ArrayList<DGraph> graphs = readDENOPTIMGraphsFromFile(file,
190 format);
191 if (graphs.size()>1)
192 data = graphs;
193 else
194 data = graphs.get(0);
195 break;
196 }
197
198 case GRAPHJSON:
199 {
200 ArrayList<DGraph> graphs = readDENOPTIMGraphsFromFile(file,
201 format);
202 if (graphs.size()>1)
203 data = graphs;
204 else
205 data = graphs.get(0);
206 break;
207 }
208
209 case GENSUMMARY:
210 {
211 List<Candidate> cands = readGenerationFromSummary(file);
212 if (cands.size()>1)
213 data = cands;
214 else
215 data = cands.get(0);
216 break;
217 }
218
219 default:
220 throw new DENOPTIMException("Data from file of format '"
221 + format + "' cannot be loaded yet. Please, contact"
222 + "the development team.");
223 }
224 return data;
225 }
226
227//------------------------------------------------------------------------------
228
242 public static List<Candidate> readGenerationFromSummary(File file)
243 throws DENOPTIMException
244 {
245 ArrayList<Candidate> cands = new ArrayList<Candidate>();
246 List<String> pathnames = readPopulationMemberPathnames(file);
247 String genSummaryParentDir = file.getParent(); // GenXXX folder
248 for (String candPathname : pathnames)
249 {
250 File candFile = new File(candPathname);
251 if (candFile.exists())
252 {
253 cands.add(readCandidates(candFile).get(0));
254 } else if (genSummaryParentDir!=null) {
255 // Extract the possibly non-existing pathname where the
256 // candidates files were originally generated
257 String runFolderPathname =
258 candFile.getParentFile() // GenXXX
259 .getParent(); // RUN###
260 if (runFolderPathname==null)
261 throw new DENOPTIMException("Unable to find parent "
262 + "folder for '"+ genSummaryParentDir +"'");
263
264 String genAndMolPath = candFile.getAbsolutePath()
265 .substring(runFolderPathname.length());
266
267 cands.add(readCandidates(new File(
268 genSummaryParentDir+genAndMolPath)).get(0));
269 }
270 }
271 return cands;
272 }
273
274//------------------------------------------------------------------------------
275
287 public static List<IAtomContainer> readAllAtomContainers(File file)
288 throws IOException, CDKException
289 {
290 List<IAtomContainer> results = null;
291
292 FileReader formatReader = new FileReader(file);
293 IChemFormat chemFormat = new FormatFactory().guessFormat(
294 new BufferedReader(formatReader));
295 formatReader.close();
296
297 if (chemFormat instanceof CIFFormat)
298 {
300 // WARNING
302 //
303 // * CDK's CIFReader is broken (skips lines _audit, AND ignores
304 // connectivity)
305 // * BioJava's fails on CIF files that do not complain to mmCIF
306 // format. Try this:
307 // CifStructureConverter.fromPath(f.toPath());
308 //
309 // The workaround unit CDK's implementation is fixed, is to use Jmol
310 // to read the CIF and make an SDF that can then be read normally.
311 // In fact, Jmol's reader is more robust than CDK's and more
312 // versatile than BioJava's.
313 // Moreover it reads also the bonds defined in the CIF
314 // (which OpenBabel does not read).
315 // Yet, Jmol's methods are not visible and require spinning a
316 // a viewer.
317
318 Map<String, Object> info = new Hashtable<String, Object>();
319 info.put("adapter", new SmarterJmolAdapter());
320 info.put("isApp", false);
321 info.put("silent", "");
322 Viewer v = new Viewer(info);
323 v.loadModelFromFile(null, file.getAbsolutePath(), null, null,
324 false, null, null, null, 0, " ");
325 String tmp = FileUtils.getTempFolder() + FS + "convertedCIF.sdf";
326 v.scriptWait("write " + tmp + " as sdf");
327 v.dispose();
328
329 results = readAllAtomContainers(new File(tmp));
330 } else {
331 FileReader fileReader = new FileReader(file);
332 ReaderFactory readerFact = new ReaderFactory();
333 ISimpleChemObjectReader reader = readerFact.createReader(fileReader);
334 reader.setErrorHandler(new PartlySilencedChemObjReaderErrorHandler(
335 DefaultChemObjectReader.class));
336 IChemFile chemFile = (IChemFile) reader.read(
337 (IChemObject) new ChemFile());
338 results = ChemFileManipulator.getAllAtomContainers(chemFile);
339 fileReader.close();
340 }
341
342 return results;
343 }
344
345//------------------------------------------------------------------------------
346
354 public static ArrayList<IAtomContainer> readSDFFile(String fileName)
355 throws DENOPTIMException {
356 MDLV2000Reader mdlreader = null;
357 ArrayList<IAtomContainer> lstContainers = new ArrayList<>();
358
359 try {
360 mdlreader = new MDLV2000Reader(new FileReader(new File(fileName)));
361 mdlreader.setErrorHandler(new PartlySilencedChemObjReaderErrorHandler(
362 DefaultChemObjectReader.class));
363 ChemFile chemFile = (ChemFile) mdlreader.read((ChemObject) new ChemFile());
364 lstContainers.addAll(
365 ChemFileManipulator.getAllAtomContainers(chemFile));
366 } catch (CDKException | IOException cdke) {
367 throw new DENOPTIMException(cdke);
368 } finally {
369 try {
370 if (mdlreader != null) {
371 mdlreader.close();
372 }
373 } catch (IOException ioe) {
374 throw new DENOPTIMException(ioe);
375 }
376 }
377
378 if (lstContainers.isEmpty()) {
379 throw new DENOPTIMException("No data found in " + fileName);
380 }
381
382 return lstContainers;
383 }
384
385//------------------------------------------------------------------------------
386
394 private static class PartlySilencedChemObjReaderErrorHandler implements IChemObjectReaderErrorHandler
395 {
396 private final ILoggingTool logger;
397
403 public PartlySilencedChemObjReaderErrorHandler(final Class<?> clazz) {
404 this(LoggingToolFactory.createLoggingTool(clazz));
405 }
406
413 this.logger = logger;
414 }
415
416 @Override
417 public void handleError(String message) {
418 if (!isInvalidSymbolMessage(message)) logger.error(message);
419 }
420
421 @Override
422 public void handleError(String message, Exception exception) {
423 if (!isInvalidSymbolMessage(message)) logger.error(message, ", ", exception);
424 }
425
426 @Override
427 public void handleError(String message, int row, int colStart, int colEnd) {
428 if (!isInvalidSymbolMessage(message)) logger.error(message, ", row ", row, " column ", colStart, "-", colEnd);
429 }
430
431 @Override
432 public void handleError(String message, int row, int colStart, int colEnd, Exception exception) {
433 if (!isInvalidSymbolMessage(message)) logger.error(message + ", row ", row, " column ", colStart, "-", colEnd, ", ", exception);
434 }
435
436 @Override
437 public void handleFatalError(String message) {
438 logger.fatal(message);
439 }
440
441 @Override
442 public void handleFatalError(String message, Exception exception) {
443 logger.fatal(message + ", " + exception);
444 }
445
446 @Override
447 public void handleFatalError(String message, int row, int colStart, int colEnd) {
448 logger.fatal(message + ", row " + row + " column " + colStart + "-" + colEnd);
449 }
450
451 @Override
452 public void handleFatalError(String message, int row, int colStart, int colEnd, Exception exception) {
453 logger.fatal(message + ", row " + row + " column " + colStart + "-" + colEnd + ", " + exception);
454 }
455
456 private boolean isInvalidSymbolMessage(String message)
457 {
458 return message.contains("invalid symbol:");
459 }
460 }
461
462//------------------------------------------------------------------------------
463
472 public static File writeVertexesToFile(File file, FileFormat format,
473 List<Vertex> vertexes) throws DENOPTIMException
474 {
475 return writeVertexesToFile(file, format, vertexes, false);
476 }
477
478//------------------------------------------------------------------------------
479
488 public static File writeVertexToFile(File file, FileFormat format,
489 Vertex vertex, boolean append) throws DENOPTIMException
490 {
491 ArrayList<Vertex> lst = new ArrayList<Vertex>();
492 lst.add(vertex);
493 return writeVertexesToFile(file, format, lst, append);
494 }
495
496//------------------------------------------------------------------------------
497
506 public static File writeVertexesToFile(File file, FileFormat format,
507 List<Vertex> vertexes, boolean append) throws DENOPTIMException
508 {
509 if (FilenameUtils.getExtension(file.getName()).equals(""))
510 {
511 file = new File(file.getAbsoluteFile()+"."+format.getExtension());
512 }
513 switch (format)
514 {
515 case VRTXJSON:
516 writeVertexesToJSON(file, vertexes, append);
517 break;
518
519 case VRTXSDF:
520 writeVertexesToSDF(file, vertexes, append);
521 break;
522
523 default:
524 throw new DENOPTIMException("Cannot write vertexes with format '"
525 + format + "'.");
526 }
527 return file;
528 }
529
530//------------------------------------------------------------------------------
531
539 public static void writeVertexesToJSON(File file,
540 List<Vertex> vertexes) throws DENOPTIMException
541 {
542 writeVertexesToJSON(file, vertexes, false);
543 }
544
545//------------------------------------------------------------------------------
546
556 public static void writeVertexesToJSON(File file,
557 List<Vertex> vertexes, boolean append) throws DENOPTIMException
558 {
559 Gson writer = DENOPTIMgson.getWriter();
560 if (append)
561 {
562 ArrayList<Vertex> allVertexes = readDENOPTIMVertexesFromJSONFile(
563 file.getAbsolutePath());
564 allVertexes.addAll(vertexes);
565 writeData(file.getAbsolutePath(), writer.toJson(allVertexes), false);
566 } else {
567 writeData(file.getAbsolutePath(), writer.toJson(vertexes), false);
568 }
569 }
570
571//------------------------------------------------------------------------------
572
581 public static void writeVertexToSDF(String pathName, Vertex vertex)
582 throws DENOPTIMException
583 {
584 List<Vertex> lst = new ArrayList<Vertex>();
585 lst.add(vertex);
586 writeVertexesToSDF(new File(pathName), lst, false);
587 }
588
589//------------------------------------------------------------------------------
590
599 public static void writeVertexesToSDF(File file,
600 List<Vertex> vertexes, boolean append)
601 throws DENOPTIMException
602 {
603 List<IAtomContainer> lst = new ArrayList<IAtomContainer>();
604 for (Vertex v : vertexes)
605 {
606 lst.add(v.getIAtomContainer());
607 }
608 writeSDFFile(file.getAbsolutePath(), lst, append);
609 }
610
611//------------------------------------------------------------------------------
612
620 public static void writeSDFFile(String fileName, IAtomContainer mol)
621 throws DENOPTIMException {
622 List<IAtomContainer> mols = new ArrayList<IAtomContainer>();
623 mols.add(mol);
624 writeSDFFile(fileName, mols, false);
625 }
626
627//------------------------------------------------------------------------------
628
636 public static void writeSDFFile(String fileName, List<IAtomContainer> mols)
637 throws DENOPTIMException {
638 writeSDFFile(fileName,mols, false);
639 }
640
641//------------------------------------------------------------------------------
642
651 public static void writeSDFFile(String fileName, List<IAtomContainer> mols,
652 boolean append) throws DENOPTIMException
653 {
654 SDFWriter sdfWriter = null;
655 try {
656 IAtomContainerSet molSet = new AtomContainerSet();
657 for (int idx = 0; idx < mols.size(); idx++) {
658 molSet.addAtomContainer(mols.get(idx));
659 }
660 sdfWriter = new SDFWriter(new FileWriter(new File(fileName),append));
661 sdfWriter.write(molSet);
662 } catch (CDKException | IOException cdke) {
663 throw new DENOPTIMException(cdke);
664 } finally {
665 try {
666 if (sdfWriter != null) {
667 sdfWriter.close();
668 }
669 } catch (IOException ioe) {
670 throw new DENOPTIMException(ioe);
671 }
672 }
673 }
674
675//------------------------------------------------------------------------------
676
685 public static void writeSDFFile(String fileName, IAtomContainer mol,
686 boolean append) throws DENOPTIMException {
687 SDFWriter sdfWriter = null;
688 try {
689 sdfWriter = new SDFWriter(new FileWriter(new File(fileName), append));
690 sdfWriter.write(mol);
691 } catch (CDKException | IOException cdke) {
692 throw new DENOPTIMException(cdke);
693 } finally {
694 try {
695 if (sdfWriter != null) {
696 sdfWriter.close();
697 }
698 } catch (IOException ioe) {
699 throw new DENOPTIMException(ioe);
700 }
701 }
702 }
703
704//------------------------------------------------------------------------------
705
706 public static void writeMol2File(String fileName, IAtomContainer mol,
707 boolean append) throws DENOPTIMException {
708 Mol2Writer mol2Writer = null;
709 try {
710 mol2Writer = new Mol2Writer(new FileWriter(new File(fileName), append));
711 mol2Writer.write(mol);
712 } catch (CDKException cdke) {
713 throw new DENOPTIMException(cdke);
714 } catch (IOException ioe) {
715 throw new DENOPTIMException(ioe);
716 } finally {
717 try {
718 if (mol2Writer != null) {
719 mol2Writer.close();
720 }
721 } catch (IOException ioe) {
722 throw new DENOPTIMException(ioe);
723 }
724 }
725 }
726
727//------------------------------------------------------------------------------
728
729 public static void writeXYZFile(String fileName, IAtomContainer mol,
730 boolean append) throws DENOPTIMException {
731 XYZWriter xyzWriter = null;
732 try {
733 xyzWriter = new XYZWriter(new FileWriter(new File(fileName), append));
734 xyzWriter.write(mol);
735 } catch (CDKException cdke) {
736 throw new DENOPTIMException(cdke);
737 } catch (IOException ioe) {
738 throw new DENOPTIMException(ioe);
739 } finally {
740 try {
741 if (xyzWriter != null) {
742 xyzWriter.close();
743 }
744 } catch (IOException ioe) {
745 throw new DENOPTIMException(ioe);
746 }
747 }
748 }
749
750//------------------------------------------------------------------------------
751
761 public static void writeSmilesSet(String fileName, String[] smiles,
762 boolean append) throws DENOPTIMException {
763 FileWriter fw = null;
764 try {
765 fw = new FileWriter(new File(fileName), append);
766 for (int i = 0; i < smiles.length; i++) {
767 fw.write(smiles[i] + NL);
768 fw.flush();
769 }
770 } catch (IOException ioe) {
771 throw new DENOPTIMException(ioe);
772 } finally {
773 try {
774 if (fw != null) {
775 fw.close();
776 }
777 } catch (IOException ioe) {
778 throw new DENOPTIMException(ioe);
779 }
780 }
781 }
782
783//------------------------------------------------------------------------------
784
794 public static void writeSmiles(String fileName, String smiles,
795 boolean append) throws DENOPTIMException {
796 FileWriter fw = null;
797 try {
798 fw = new FileWriter(new File(fileName), append);
799 fw.write(smiles + NL);
800 fw.flush();
801 } catch (IOException ioe) {
802 throw new DENOPTIMException(ioe);
803 } finally {
804 try {
805 if (fw != null) {
806 fw.close();
807 }
808 } catch (IOException ioe) {
809 throw new DENOPTIMException(ioe);
810 }
811 }
812 }
813
814//------------------------------------------------------------------------------
815
824 public static void writeData(String fileName, String data, boolean append)
825 throws DENOPTIMException {
826 FileWriter fw = null;
827 try {
828 fw = new FileWriter(new File(fileName), append);
829 fw.write(data + NL);
830 fw.flush();
831 } catch (IOException ioe) {
832 throw new DENOPTIMException(ioe);
833 } finally {
834 try {
835 if (fw != null) {
836 fw.close();
837 }
838 } catch (IOException ioe) {
839 throw new DENOPTIMException(ioe);
840 }
841 }
842 }
843
844//------------------------------------------------------------------------------
845
855 public static List<CandidateLW> readLightWeightCandidate(File file)
856 throws DENOPTIMException
857 {
858 List<String> propNames = new ArrayList<String>(Arrays.asList(
860 CDKConstants.TITLE
861 ));
862 List<String> optionalPropNames = new ArrayList<String>(Arrays.asList(
867 ));
868 propNames.addAll(optionalPropNames);
869 List<Map<String, Object>> propsPerItem = readSDFProperties(
870 file.getAbsolutePath(), propNames);
871
872 List<CandidateLW> items = new ArrayList<CandidateLW>();
873 for (Map<String, Object> props : propsPerItem)
874 {
875 Object uidObj = props.get(DENOPTIMConstants.UNIQUEIDTAG);
876 if (uidObj==null )
877 {
878 throw new DENOPTIMException("Cannot create item if SDF tag "
879 + DENOPTIMConstants.UNIQUEIDTAG + " is null!");
880 }
881 Object nameObj = props.get(CDKConstants.TITLE);
882 if (nameObj==null)
883 {
884 throw new DENOPTIMException("Cannot create item is SDF tag "
885 + CDKConstants.TITLE + " is null!");
886 }
887 CandidateLW item = new CandidateLW(uidObj.toString(),
888 nameObj.toString(),file.getAbsolutePath());
889
890 for (String propName : optionalPropNames)
891 {
892 Object obj = props.get(propName);
893 if (obj != null)
894 {
895 switch (propName)
896 {
898 item.setFitness(Double.parseDouble(obj.toString()));
899 break;
900
902 item.setError(obj.toString());
903 break;
904
906 item.setGeneratingSource(obj.toString());
907 break;
908
910 item.setLevel(Integer.parseInt(obj.toString()));
911 break;
912 }
913 }
914 }
915 items.add(item);
916 }
917 return items;
918 }
919
920//------------------------------------------------------------------------------
921
930 public static double[] readPopulationProps(File file)
931 throws DENOPTIMException {
932 double[] vals = new double[4];
933 ArrayList<String> txt = readList(file.getAbsolutePath());
934 for (String line : txt) {
935 if (line.trim().length() < 8) {
936 continue;
937 }
938
939 String key = line.toUpperCase().trim().substring(0, 8);
940 switch (key) {
941 case ("MIN: "):
942 vals[0] = Double.parseDouble(line.split("\\s+")[1]);
943 break;
944
945 case ("MAX: "):
946 vals[1] = Double.parseDouble(line.split("\\s+")[1]);
947 break;
948
949 case ("MEAN: "):
950 vals[2] = Double.parseDouble(line.split("\\s+")[1]);
951 break;
952
953 case ("MEDIAN: "):
954 vals[3] = Double.parseDouble(line.split("\\s+")[1]);
955 break;
956 }
957 }
958 return vals;
959 }
960
961//------------------------------------------------------------------------------
962
971 public static List<String> readPopulationMemberPathnames(File file)
972 throws DENOPTIMException
973 {
974 List<String> vals = new ArrayList<String>();
975 ArrayList<String> txt = readList(file.getAbsolutePath());
976 for (String line : txt)
977 {
978 if (!line.contains(FS))
979 continue;
980
981 String[] words = line.trim().split("\\s+");
982 if (words.length < 5)
983 continue;
984
985 // NB: there is no keyword for population members!
986 vals.add(words[4]);
987 }
988 return vals;
989 }
990
991//------------------------------------------------------------------------------
992
1004 public static List<CandidateLW> readPopulationMembersTraces(File file)
1005 throws DENOPTIMException
1006 {
1007 List<CandidateLW> members = new ArrayList<CandidateLW>();
1008 List<String> txt = readList(file.getAbsolutePath());
1009
1010 // Skip the header, i.e., the first line
1011 for (int i=1; i<txt.size(); i++)
1012 {
1013 String line = txt.get(i);
1014
1015 // WARNING: here we set strong expectation on the format of the
1016 // gensummary files!
1017
1018 if (line.startsWith("#"))
1019 break;
1020
1021 if (line.isBlank())
1022 continue;
1023
1024 String[] words = line.trim().split("\\s+");
1025 String pathname = "nofile";
1026 if (words.length >= 5)
1027 {
1028 pathname = words[4];
1029 }
1030 CandidateLW member = new CandidateLW(words[2], words[0], pathname);
1031 member.setFitness(Double.parseDouble(words[3]));
1032 members.add(member);
1033 }
1034 return members;
1035 }
1036
1037//------------------------------------------------------------------------------
1038
1046 public static ArrayList<String> readList(String fileName)
1047 throws DENOPTIMException {
1048 return readList(fileName, false);
1049 }
1050
1051//------------------------------------------------------------------------------
1052
1062 public static ArrayList<String> readList(String fileName,
1063 boolean allowEmpty) throws DENOPTIMException {
1064 ArrayList<String> lst = new ArrayList<>();
1065 BufferedReader br = null;
1066 String line = null;
1067 try {
1068 br = new BufferedReader(new FileReader(fileName));
1069 while ((line = br.readLine()) != null) {
1070 if (line.trim().length() == 0) {
1071 continue;
1072 }
1073 lst.add(line.trim());
1074 }
1075 } catch (IOException ioe) {
1076 throw new DENOPTIMException(ioe);
1077 } finally {
1078 try {
1079 if (br != null) {
1080 br.close();
1081 }
1082 } catch (IOException ioe) {
1083 throw new DENOPTIMException(ioe);
1084 }
1085 }
1086
1087 if (lst.isEmpty() && !allowEmpty) {
1088 throw new DENOPTIMException("No data found in file: " + fileName);
1089 }
1090
1091 return lst;
1092 }
1093
1094//------------------------------------------------------------------------------
1095
1103 public static String readText(String fileName) throws DENOPTIMException {
1104 StringBuilder sb = new StringBuilder();
1105 BufferedReader br = null;
1106 String line = null;
1107 try {
1108 br = new BufferedReader(new FileReader(fileName));
1109 while ((line = br.readLine()) != null) {
1110 sb.append(line).append(NL);
1111 }
1112 } catch (IOException ioe) {
1113 throw new DENOPTIMException(ioe);
1114 } finally {
1115 try {
1116 if (br != null) {
1117 br.close();
1118 }
1119 } catch (IOException ioe) {
1120 throw new DENOPTIMException(ioe);
1121 }
1122 }
1123
1124 return sb.toString();
1125 }
1126
1127//------------------------------------------------------------------------------
1128
1137 public static List<Map<String, Object>> readSDFProperties(String pathName,
1138 List<String> propNames) throws DENOPTIMException
1139 {
1140 List<Map<String,Object>> results = new ArrayList<Map<String,Object>>();
1141 ArrayList<IAtomContainer> iacs = DenoptimIO.readSDFFile(pathName);
1142 for (IAtomContainer iac : iacs)
1143 {
1144 Map<String,Object> properties = new HashMap<String,Object>();
1145 for (String propName : propNames)
1146 {
1147 properties.put(propName, iac.getProperty(propName));
1148 }
1149 results.add(properties);
1150 }
1151 return results;
1152 }
1153
1154//------------------------------------------------------------------------------
1155
1163 public static String getChemDoodleString(IAtomContainer mol)
1164 throws DENOPTIMException {
1165 StringWriter stringWriter = new StringWriter();
1166 MDLV2000Writer mw = null;
1167 try {
1168 mw = new MDLV2000Writer(stringWriter);
1169 mw.write(mol);
1170 } catch (CDKException cdke) {
1171 throw new DENOPTIMException(cdke);
1172 } finally {
1173 try {
1174 if (mw != null) {
1175 mw.close();
1176 }
1177 } catch (IOException ioe) {
1178 throw new DENOPTIMException(ioe);
1179 }
1180 }
1181
1182 String MoleculeString = stringWriter.toString();
1183
1184 //System.out.print(stringWriter.toString());
1185 //now split MoleculeString into multiple lines to enable explicit printout of \n
1186 String Moleculelines[] = MoleculeString.split("\\r?\\n");
1187
1188 StringBuilder sb = new StringBuilder(1024);
1189 sb.append("var molFile = '");
1190 for (int i = 0; i < Moleculelines.length; i++) {
1191 sb.append(Moleculelines[i]);
1192 sb.append("\\n");
1193 }
1194 sb.append("';");
1195 return sb.toString();
1196 }
1197
1198//------------------------------------------------------------------------------
1199
1200 public static Set<APClass> readAllAPClasses(File fragLib) {
1201 Set<APClass> allCLasses = new HashSet<APClass>();
1202 try {
1203 for (Vertex v : DenoptimIO.readVertexes(fragLib, BBType.UNDEFINED))
1204 {
1205 for (AttachmentPoint ap : v.getAttachmentPoints()) {
1206 allCLasses.add(ap.getAPClass());
1207 }
1208 }
1209 } catch (DENOPTIMException | IllegalArgumentException
1210 | UndetectedFileFormatException | IOException e) {
1211 System.out.println("Could not read data from '" + fragLib + "'. "
1212 + "Cause: " + e.getMessage());
1213 }
1214
1215 return allCLasses;
1216 }
1217
1218//------------------------------------------------------------------------------
1219
1228 public static void writeCompatibilityMatrix(String fileName,
1229 HashMap<APClass, ArrayList<APClass>> cpMap,
1230 HashMap<APClass, APClass> capMap,
1231 HashSet<APClass> ends) throws DENOPTIMException {
1232 DateFormat dateFormat = new SimpleDateFormat("dd/MM/yy HH:mm:ss");
1233 Date date = new Date();
1234 String dateStr = dateFormat.format(date);
1235
1236 StringBuilder sb = new StringBuilder();
1238 sb.append(" Compatibility matrix data").append(NL);
1240 sb.append(" Written by DENOPTIM-GUI on ").append(dateStr).append(NL);
1242 sb.append(" APCLass Compatibility rules").append(NL);
1243 SortedSet<APClass> keysCPMap = new TreeSet<APClass>();
1244 keysCPMap.addAll(cpMap.keySet());
1245 for (APClass srcAPC : keysCPMap) {
1246 sb.append(DENOPTIMConstants.APCMAPCOMPRULE).append(" ");
1247 sb.append(srcAPC).append(" ");
1248 for (int i = 0; i < cpMap.get(srcAPC).size(); i++) {
1249 APClass trgAPC = cpMap.get(srcAPC).get(i);
1250 sb.append(trgAPC);
1251 if (i != (cpMap.get(srcAPC).size() - 1)) {
1252 sb.append(",");
1253 } else {
1254 sb.append(NL);
1255 }
1256 }
1257 }
1258
1260 sb.append(" Capping rules").append(NL);
1261 SortedSet<APClass> keysCap = new TreeSet<APClass>();
1262 keysCap.addAll(capMap.keySet());
1263 for (APClass apc : keysCap) {
1264 sb.append(DENOPTIMConstants.APCMAPCAPPING).append(" ");
1265 sb.append(apc).append(" ").append(capMap.get(apc)).append(NL);
1266 }
1267
1269 sb.append(" Forbidden ends").append(NL);
1270 SortedSet<APClass> sortedFE = new TreeSet<APClass>();
1271 sortedFE.addAll(ends);
1272 for (APClass apc : sortedFE) {
1273 sb.append(DENOPTIMConstants.APCMAPFORBIDDENEND).append(" ");
1274 sb.append(apc).append(" ").append(NL);
1275 }
1276
1277 DenoptimIO.writeData(fileName, sb.toString(), false);
1278 }
1279
1280//------------------------------------------------------------------------------
1281
1291 public static void readCompatibilityMatrix(String fileName,HashMap<APClass,
1292 ArrayList<APClass>> compatMap,
1293 HashMap<APClass, APClass> cappingMap, Set<APClass> forbiddenEndList)
1294 throws DENOPTIMException {
1295
1296 BufferedReader br = null;
1297 String line = null;
1298 try {
1299 br = new BufferedReader(new FileReader(fileName));
1300 while ((line = br.readLine()) != null) {
1301 if (line.trim().length() == 0) {
1302 continue;
1303 }
1304
1305 if (line.startsWith(DENOPTIMConstants.APCMAPIGNORE)) {
1306 continue;
1307 }
1308
1309 if (line.startsWith(DENOPTIMConstants.APCMAPCOMPRULE)) {
1310 String str[] = line.split("\\s+");
1311 if (str.length < 3) {
1312 String err = "Incomplete APClass compatibility line '"
1313 + line + "'.";
1314 throw new DENOPTIMException(err + " " + fileName);
1315 }
1316
1317 APClass srcAPC = APClass.make(str[1]);
1318 ArrayList<APClass> trgAPCs = new ArrayList<APClass>();
1319 for (String s : str[2].split(","))
1320 {
1321 trgAPCs.add(APClass.make(s.trim()));
1322 }
1323 compatMap.put(srcAPC, trgAPCs);
1324 } else {
1325 if (line.startsWith(DENOPTIMConstants.APCMAPCAPPING)) {
1326 String str[] = line.split("\\s+");
1327 if (str.length != 3) {
1328 String err = "Incomplete capping line '"
1329 + line +"'.";
1330 throw new DENOPTIMException(err + " "+fileName);
1331 }
1332 APClass srcAPC = APClass.make(str[1]);
1333 APClass trgAPC = APClass.make(str[2]);
1334 cappingMap.put(srcAPC, trgAPC);
1335 } else {
1336 if (line.startsWith(
1338 String str[] = line.split("\\s+");
1339 if (str.length != 2) {
1340 for (int is = 1; is < str.length; is++) {
1341 forbiddenEndList.add(
1342 APClass.make(str[is]));
1343 }
1344 } else {
1345 forbiddenEndList.add(APClass.make(str[1]));
1346 }
1347 }
1348 }
1349 }
1350 }
1351 } catch (NumberFormatException | IOException nfe) {
1352 throw new DENOPTIMException(nfe);
1353 } finally {
1354 try {
1355 if (br != null) {
1356 br.close();
1357 }
1358 } catch (IOException ioe) {
1359 throw new DENOPTIMException(ioe);
1360 }
1361 }
1362
1363 if (compatMap.isEmpty()) {
1364 String err = "No reaction compatibility data found in file: ";
1365 throw new DENOPTIMException(err + " " + fileName);
1366 }
1367 }
1368
1369//------------------------------------------------------------------------------
1370
1385 public static void readRCCompatibilityMatrix(String fileName,
1386 HashMap<APClass, ArrayList<APClass>> rcCompatMap)
1387 throws DENOPTIMException {
1388 BufferedReader br = null;
1389 String line = null;
1390 try {
1391 br = new BufferedReader(new FileReader(fileName));
1392 while ((line = br.readLine()) != null) {
1393 if (line.trim().length() == 0) {
1394 continue;
1395 }
1396
1397 if (line.startsWith(DENOPTIMConstants.APCMAPIGNORE)) {
1398 continue;
1399 }
1400
1401 if (line.startsWith(DENOPTIMConstants.APCMAPCOMPRULE)) {
1402 String str[] = line.split("\\s+");
1403 if (str.length < 3) {
1404 String err = "Incomplete reaction compatibility data.";
1405 throw new DENOPTIMException(err + " " + fileName);
1406 }
1407
1408 APClass srcAPC = APClass.make(str[1]);
1409
1410 String strRcn[] = str[2].split(",");
1411 for (int i = 0; i < strRcn.length; i++) {
1412 strRcn[i] = strRcn[i].trim();
1413
1414 APClass trgAPC = APClass.make(strRcn[i]);
1415 if (rcCompatMap.containsKey(srcAPC)) {
1416 rcCompatMap.get(srcAPC).add(trgAPC);
1417 } else {
1418 ArrayList<APClass> list = new ArrayList<APClass>();
1419 list.add(trgAPC);
1420 rcCompatMap.put(srcAPC, list);
1421 }
1422
1423 if (rcCompatMap.containsKey(trgAPC)) {
1424 rcCompatMap.get(trgAPC).add(srcAPC);
1425 } else {
1426 ArrayList<APClass> list = new ArrayList<APClass>();
1427 list.add(srcAPC);
1428 rcCompatMap.put(trgAPC, list);
1429 }
1430 }
1431 }
1432 }
1433 } catch (NumberFormatException | IOException nfe) {
1434 throw new DENOPTIMException(nfe);
1435 } finally {
1436 try {
1437 if (br != null) {
1438 br.close();
1439 }
1440 } catch (IOException ioe) {
1441 throw new DENOPTIMException(ioe);
1442 }
1443 }
1444
1445 if (rcCompatMap.isEmpty()) {
1446 String err = "No reaction compatibility data found in file: ";
1447 throw new DENOPTIMException(err + " " + fileName);
1448 }
1449 }
1450
1451//------------------------------------------------------------------------------
1452
1464 public static ArrayList<Candidate> readCandidates(File file)
1465 throws DENOPTIMException {
1466 return readCandidates(file,false);
1467 }
1468
1469//------------------------------------------------------------------------------
1470
1483 public static ArrayList<Candidate> readCandidates(File file,
1484 boolean allowNoUID) throws DENOPTIMException {
1485 String filename = file.getAbsolutePath();
1486 ArrayList<Candidate> candidates = new ArrayList<>();
1487 ArrayList<IAtomContainer> iacs = readSDFFile(file.getAbsolutePath());
1488
1489 // Try to identify the generation at which this candidate was generated
1490 int genID = -1;
1491 if (file.getParentFile()!=null
1492 && file.getParentFile().getName().startsWith(
1494 {
1495 String genFolderName = file.getParentFile().getName();
1496 genID = Integer.valueOf(genFolderName.substring(
1498 }
1499
1500 for (IAtomContainer iac : iacs) {
1501 Candidate cand = new Candidate(iac, false, allowNoUID);
1502 cand.setSDFFile(filename);
1503 if (genID!=-1)
1504 cand.setGeneration(genID);
1505 candidates.add(cand);
1506 }
1507 return candidates;
1508 }
1509
1510//------------------------------------------------------------------------------
1511
1519 public static void writeCandidatesToFile(File file,
1520 List<Candidate> popMembers, boolean append)
1521 throws DENOPTIMException
1522 {
1523 if (FilenameUtils.getExtension(file.getName()).equals(""))
1524 {
1525 file = new File(file.getAbsoluteFile() + "."
1526 + FileFormat.CANDIDATESDF.getExtension());
1527 }
1528 ArrayList<IAtomContainer> lst = new ArrayList<IAtomContainer>();
1529 for (Candidate g : popMembers)
1530 {
1531 lst.add(g.getFitnessProviderOutputRepresentation());
1532 }
1533 writeSDFFile(file.getAbsolutePath(), lst, append);
1534 }
1535
1536//------------------------------------------------------------------------------
1537
1545 public static void writeCandidateToFile(File file, Candidate candidate,
1546 boolean append)
1547 throws DENOPTIMException
1548 {
1549 if (FilenameUtils.getExtension(file.getName()).equals(""))
1550 {
1551 file = new File(file.getAbsoluteFile() + "."
1552 + FileFormat.CANDIDATESDF.getExtension());
1553 }
1554 writeSDFFile(file.getAbsolutePath(),
1555 candidate.getFitnessProviderOutputRepresentation(), append);
1556 }
1557
1558//------------------------------------------------------------------------------
1559
1567 public static ArrayList<GraphEdit> readDENOPTIMGraphEditFromFile(
1568 String fileName) throws DENOPTIMException
1569 {
1570 ArrayList<GraphEdit> graphEditTasks = new ArrayList<>();
1571 Gson reader = DENOPTIMgson.getReader();
1572
1573 BufferedReader br = null;
1574 try
1575 {
1576 br = new BufferedReader(new FileReader(fileName));
1577 graphEditTasks = reader.fromJson(br,
1578 new TypeToken<ArrayList<GraphEdit>>(){}.getType());
1579 }
1580 catch (FileNotFoundException fnfe)
1581 {
1582 throw new DENOPTIMException("File '" + fileName + "' not found.");
1583 }
1584 catch (JsonSyntaxException jse)
1585 {
1586 String msg = "Expected BEGIN_ARRAY but was BEGIN_OBJECT";
1587 if (jse.getMessage().contains(msg))
1588 {
1589 // The file contains a single object, not a list. We try to read
1590 // that single object as a DENOPTIMGraph
1591 try
1592 {
1593 br.close();
1594 br = new BufferedReader(new FileReader(fileName));
1595 }
1596 catch (FileNotFoundException fnfe)
1597 {
1598 //cannot happen
1599 } catch (IOException ioe)
1600 {
1601 throw new DENOPTIMException(ioe);
1602 }
1603 GraphEdit graphEditTask = reader.fromJson(br,
1604 GraphEdit.class);
1605 graphEditTasks.add(graphEditTask);
1606 } else {
1607 jse.printStackTrace();
1608 throw new DENOPTIMException("ERROR! Unable to read JSON file "
1609 + "that defines a graph enditing task.",jse);
1610 }
1611 }
1612 finally
1613 {
1614 try {
1615 if (br != null)
1616 {
1617 br.close();
1618 }
1619 } catch (IOException ioe) {
1620 throw new DENOPTIMException(ioe);
1621 }
1622 }
1623
1624 return graphEditTasks;
1625 }
1626
1627//------------------------------------------------------------------------------
1628
1637 public static ArrayList<DGraph> readDENOPTIMGraphsFromFile(File inFile)
1638 throws Exception
1639 {
1641 return readDENOPTIMGraphsFromFile(inFile, ff);
1642 }
1643
1644//------------------------------------------------------------------------------
1645
1657 public static ArrayList<DGraph> readDENOPTIMGraphsFromFile(File inFile,
1658 FileFormat format) throws Exception
1659 {
1660 switch (format)
1661 {
1662 case GRAPHJSON:
1664 inFile.getAbsolutePath());
1665
1666 case GRAPHSDF:
1668 inFile.getAbsolutePath());
1669
1670 case GRAPHTXT:
1671 throw new DENOPTIMException("Use of string representation '"
1672 + DENOPTIMConstants.GRAPHTAG + "' is deprecated. Use "
1673 + "JSON format instead.");
1674
1675 case CANDIDATESDF:
1677 inFile.getAbsolutePath());
1678
1679 case VRTXSDF:
1680 ArrayList<DGraph> graphs = new ArrayList<DGraph>();
1681 ArrayList<Vertex> vertexes = readVertexes(inFile,
1683 for (Vertex v : vertexes)
1684 {
1685 if (v instanceof Template)
1686 {
1687 graphs.add(((Template)v).getInnerGraph());
1688 }
1689 }
1690 System.out.println("WARNING: Reading graphs from "
1691 + FileFormat.VRTXSDF + " file can only read the "
1692 + "templates' inner graphs. Importing "
1693 + graphs.size() + " graphs "
1694 + "from " + vertexes.size() + " vertexes.");
1695 return graphs;
1696
1697 default:
1698 throw new Exception("Format '" + format + "' could not be used "
1699 + "to read graphs from file '" + inFile + "'.");
1700 }
1701 }
1702
1703//------------------------------------------------------------------------------
1704
1712 public static ArrayList<DGraph> readDENOPTIMGraphsFromSDFile(
1713 String fileName) throws DENOPTIMException
1714 {
1715 ArrayList<DGraph> lstGraphs = new ArrayList<DGraph>();
1716 ArrayList<IAtomContainer> mols = DenoptimIO.readSDFFile(fileName);
1717 int i = 0;
1718 for (IAtomContainer mol : mols)
1719 {
1720 i++;
1721 DGraph g = readGraphFromSDFileIAC(mol,i,fileName);
1722 lstGraphs.add(g);
1723 }
1724 return lstGraphs;
1725 }
1726
1727//------------------------------------------------------------------------------
1728
1738 public static DGraph readGraphFromSDFileIAC(IAtomContainer mol)
1739 throws DENOPTIMException
1740 {
1741 return readGraphFromSDFileIAC(mol, -1, "");
1742 }
1743
1744//------------------------------------------------------------------------------
1745
1755 public static DGraph readGraphFromSDFileIAC(IAtomContainer mol,
1756 int molId) throws DENOPTIMException
1757 {
1758 return readGraphFromSDFileIAC(mol, molId, "");
1759 }
1760
1761//------------------------------------------------------------------------------
1762
1776 public static DGraph readGraphFromSDFileIAC(IAtomContainer mol,
1777 int molId, String fileName) throws DENOPTIMException
1778 {
1779 // Something very similar is done also in Candidate
1780 DGraph g = null;
1781 Object json = mol.getProperty(DENOPTIMConstants.GRAPHJSONTAG);
1782 if (json == null) {
1783 Object graphEnc = mol.getProperty(DENOPTIMConstants.GRAPHTAG);
1784 if (graphEnc!=null)
1785 {
1786 throw new DENOPTIMException("Use of '"
1787 + DENOPTIMConstants.GRAPHTAG + "' is deprecated. SDF "
1788 + "files containing graphs must include the "
1789 + "tag '" + DENOPTIMConstants.GRAPHJSONTAG + "'.");
1790 }
1791 String msg = "Attempt to load graph form "
1792 + "SDF that has no '" + DENOPTIMConstants.GRAPHJSONTAG
1793 + "' tag.";
1794 if (molId>-1)
1795 {
1796 msg = msg + " Check molecule " + molId;
1797 if (!fileName.isEmpty())
1798 {
1799 msg = msg + " in the SDF file '" + fileName + "'";
1800 } else {
1801 msg = msg + ".";
1802 }
1803 }
1804 throw new DENOPTIMException(msg);
1805 } else {
1806 String js = json.toString();
1807 try
1808 {
1809 g = DGraph.fromJson(js);
1810 } catch (Exception e)
1811 {
1812 String msg = e.getMessage();
1813 if (molId>-1)
1814 {
1815 msg = msg + " Check molecule " + molId;
1816 if (!fileName.isEmpty())
1817 {
1818 msg = msg + " in the SDF file '" + fileName + "'";
1819 } else {
1820 msg = msg + ".";
1821 }
1822 }
1823 throw new DENOPTIMException(msg, e);
1824 }
1825 }
1826 return g;
1827 }
1828
1829//------------------------------------------------------------------------------
1830
1838 public static ArrayList<DGraph> readDENOPTIMGraphsFromTxtFile(
1839 String fileName, FragmentSpace fragSpace, Logger logger)
1840 throws DENOPTIMException
1841 {
1842 ArrayList<DGraph> lstGraphs = new ArrayList<DGraph>();
1843 BufferedReader br = null;
1844 String line = null;
1845 try {
1846 br = new BufferedReader(new FileReader(fileName));
1847 while ((line = br.readLine()) != null) {
1848 if (line.trim().length() == 0) {
1849 continue;
1850 }
1851
1852 if (line.startsWith(DENOPTIMConstants.APCMAPIGNORE)) {
1853 continue;
1854 }
1855
1856 DGraph g;
1857 try {
1858 g = GraphConversionTool.getGraphFromString(line.trim(),
1859 fragSpace);
1860 } catch (Throwable t) {
1861 String msg = "Cannot convert string to DENOPTIMGraph. "
1862 + "Check line '" + line.trim() + "'";
1863 logger.log(Level.SEVERE, msg);
1864 throw new DENOPTIMException(msg, t);
1865 }
1866 lstGraphs.add(g);
1867 }
1868 } catch (IOException ioe) {
1869 String msg = "Cannot read file " + fileName;
1870 logger.log(Level.SEVERE, msg);
1871 throw new DENOPTIMException(msg, ioe);
1872 } finally {
1873 try {
1874 if (br != null) {
1875 br.close();
1876 }
1877 } catch (IOException ioe) {
1878 throw new DENOPTIMException(ioe);
1879 }
1880 }
1881 return lstGraphs;
1882 }
1883
1884//------------------------------------------------------------------------------
1885
1886 //TODO-v3+ this method should be almost a copy of the one working on graphs.
1887 // It should be possible to have one method do both tasks.
1888
1895 public static ArrayList<Vertex> readDENOPTIMVertexesFromJSONFile(
1896 String fileName) throws DENOPTIMException
1897 {
1898 ArrayList<Vertex> result = new ArrayList<Vertex>();
1899 Gson reader = DENOPTIMgson.getReader();
1900
1901 BufferedReader br = null;
1902 try
1903 {
1904 br = new BufferedReader(new FileReader(fileName));
1905 result = reader.fromJson(br,
1906 new TypeToken<ArrayList<Vertex>>(){}.getType());
1907 }
1908 catch (FileNotFoundException fnfe)
1909 {
1910 throw new DENOPTIMException("File '" + fileName + "' not found.");
1911 }
1912 catch (JsonSyntaxException jse)
1913 {
1914 String msg = "Expected BEGIN_ARRAY but was BEGIN_OBJECT";
1915 if (jse.getMessage().contains(msg))
1916 {
1917 // The file contains a single object, not a list. We try to read
1918 // that single object as a DENOPTIMVertex
1919 try
1920 {
1921 br.close();
1922 br = new BufferedReader(new FileReader(fileName));
1923 }
1924 catch (FileNotFoundException fnfe)
1925 {
1926 //cannot happen
1927 } catch (IOException ioe)
1928 {
1929 throw new DENOPTIMException(ioe);
1930 }
1931 Vertex v = reader.fromJson(br,Vertex.class);
1932 result.add(v);
1933 } else {
1934 throw new DENOPTIMException("ERROR! Unable to read vertex from '"
1935 + fileName + "'.", jse);
1936 }
1937 }
1938 finally
1939 {
1940 try {
1941 if (br != null)
1942 {
1943 br.close();
1944 }
1945 } catch (IOException ioe) {
1946 throw new DENOPTIMException(ioe);
1947 }
1948 }
1949
1950 return result;
1951 }
1952
1953//------------------------------------------------------------------------------
1954
1961 public static ArrayList<DGraph> readDENOPTIMGraphsFromJSONFile(
1962 String fileName) throws DENOPTIMException
1963 {
1964 ArrayList<DGraph> list_of_graphs = new ArrayList<DGraph>();
1965 Gson reader = DENOPTIMgson.getReader();
1966
1967 BufferedReader br = null;
1968 try
1969 {
1970 br = new BufferedReader(new FileReader(fileName));
1971 list_of_graphs = reader.fromJson(br,
1972 new TypeToken<ArrayList<DGraph>>(){}.getType());
1973 }
1974 catch (FileNotFoundException fnfe)
1975 {
1976 throw new DENOPTIMException("File '" + fileName + "' not found.");
1977 }
1978 catch (JsonSyntaxException jse)
1979 {
1980 String msg = "Expected BEGIN_ARRAY but was BEGIN_OBJECT";
1981 if (jse.getMessage().contains(msg))
1982 {
1983 // The file contains a single object, not a list. We try to read
1984 // that single object as a DENOPTIMGraph
1985 try
1986 {
1987 br.close();
1988 br = new BufferedReader(new FileReader(fileName));
1989 }
1990 catch (FileNotFoundException fnfe)
1991 {
1992 //cannot happen
1993 } catch (IOException ioe)
1994 {
1995 throw new DENOPTIMException(ioe);
1996 }
1997 DGraph g = reader.fromJson(br,DGraph.class);
1998 list_of_graphs.add(g);
1999 } else {
2000 throw new DENOPTIMException("ERROR! Unable to read graph from "
2001 + "JSON '" + fileName + "'", jse);
2002 }
2003 }
2004 finally
2005 {
2006 try {
2007 if (br != null)
2008 {
2009 br.close();
2010 }
2011 } catch (IOException ioe) {
2012 throw new DENOPTIMException(ioe);
2013 }
2014 }
2015
2016 return list_of_graphs;
2017 }
2018
2019//------------------------------------------------------------------------------
2020
2029 public static File writeGraphToFile(File file, FileFormat format,
2030 DGraph graph) throws DENOPTIMException
2031 {
2032 return writeGraphToFile(file, format, graph, StaticLogger.appLogger,
2033 new Randomizer());
2034 }
2035
2036//------------------------------------------------------------------------------
2037
2046 public static File writeGraphToFile(File file, FileFormat format,
2047 DGraph graph, Logger logger, Randomizer randomizer)
2048 throws DENOPTIMException
2049 {
2050 if (FilenameUtils.getExtension(file.getName()).equals(""))
2051 {
2052 file = new File(file.getAbsoluteFile()+"."+format.getExtension());
2053 }
2054 switch (format)
2055 {
2056 case GRAPHJSON:
2057 writeGraphToJSON(file, graph);
2058 break;
2059
2060 case GRAPHSDF:
2061 writeGraphToSDF(file, graph, false, true, logger, randomizer);
2062 break;
2063
2064 default:
2065 throw new DENOPTIMException("Cannot write graph with format '"
2066 + format + "'.");
2067 }
2068 return file;
2069 }
2070
2071//------------------------------------------------------------------------------
2072
2082 public static File writeGraphsToFile(File file, FileFormat format,
2083 List<DGraph> modGraphs, Logger logger, Randomizer randomizer)
2084 throws DENOPTIMException
2085 {
2086 if (FilenameUtils.getExtension(file.getName()).equals(""))
2087 {
2088 file = new File(file.getAbsoluteFile()+"."+format.getExtension());
2089 }
2090 switch (format)
2091 {
2092 case GRAPHJSON:
2093 writeGraphsToJSON(file, modGraphs);
2094 break;
2095
2096 case GRAPHSDF:
2097 writeGraphsToSDF(file, modGraphs, false, true, logger, randomizer);
2098 break;
2099
2100 default:
2101 throw new DENOPTIMException("Cannot write graphs with format '"
2102 + format + "'.");
2103 }
2104 return file;
2105 }
2106
2107//------------------------------------------------------------------------------
2108
2116 public static void writeGraphsToSDF(File file,
2117 List<DGraph> graphs, Logger logger, Randomizer randomizer)
2118 throws DENOPTIMException
2119 {
2120 writeGraphsToSDF(file, graphs, false, logger, randomizer);
2121 }
2122
2123//------------------------------------------------------------------------------
2124
2134 public static void writeGraphToSDF(File file, DGraph graph,
2135 boolean append, boolean make3D, Logger logger, Randomizer randomizer)
2136 throws DENOPTIMException
2137 {
2138 List<DGraph> lst = new ArrayList<>(1);
2139 lst.add(graph);
2140 writeGraphsToSDF(file, lst, append, make3D, logger, randomizer);
2141 }
2142
2143//------------------------------------------------------------------------------
2144
2153 public static void writeGraphToSDF(File file, DGraph graph,
2154 boolean append, Logger logger, Randomizer randomizer)
2155 throws DENOPTIMException
2156 {
2157 ArrayList<DGraph> lst = new ArrayList<>(1);
2158 lst.add(graph);
2159 writeGraphsToSDF(file, lst, append, logger, randomizer);
2160 }
2161
2162//------------------------------------------------------------------------------
2163
2172 public static void writeGraphsToSDF(File file,
2173 List<DGraph> graphs, boolean append,
2174 Logger logger, Randomizer randomizer) throws DENOPTIMException
2175 {
2176 writeGraphsToSDF(file, graphs, append, false, logger, randomizer);
2177 }
2178
2179//------------------------------------------------------------------------------
2180
2191 public static void writeGraphsToSDF(File file,
2192 List<DGraph> modGraphs, boolean append, boolean make3D,
2193 Logger logger, Randomizer randomizer) throws DENOPTIMException
2194 {
2195 ArrayList<IAtomContainer> lst = new ArrayList<IAtomContainer>();
2196 for (DGraph g : modGraphs)
2197 {
2198 ThreeDimTreeBuilder tb = new ThreeDimTreeBuilder(logger, randomizer);
2199 IAtomContainer iac = builder.newAtomContainer();
2200 if (make3D)
2201 {
2202 try {
2203 iac = tb.convertGraphTo3DAtomContainer(g, true);
2204 } catch (Throwable t) {
2205 t.printStackTrace();
2206 logger.log(Level.WARNING,"Couldn't make 3D-tree "
2207 + "representation: " + t.getMessage());
2208 }
2209 } else {
2210 GraphUtils.writeSDFFields(iac, g);
2211 }
2212 lst.add(iac);
2213 }
2214 writeSDFFile(file.getAbsolutePath(), lst, append);
2215 }
2216
2217//------------------------------------------------------------------------------
2218
2226 public static void writeGraphToJSON(File file, DGraph graph)
2227 throws DENOPTIMException
2228 {
2229 ArrayList<DGraph> graphs = new ArrayList<DGraph>();
2230 graphs.add(graph);
2231 writeGraphsToJSON(file, graphs);
2232 }
2233
2234//------------------------------------------------------------------------------
2235
2243 public static void writeGraphsToJSON(File file,
2244 List<DGraph> graphs) throws DENOPTIMException
2245 {
2246 Gson writer = DENOPTIMgson.getWriter();
2247 writeData(file.getAbsolutePath(), writer.toJson(graphs), false);
2248 }
2249
2250//------------------------------------------------------------------------------
2251
2260 public static void writeGraphsToJSON(File file,
2261 List<DGraph> graphs, boolean append) throws DENOPTIMException
2262 {
2263 Gson writer = DENOPTIMgson.getWriter();
2264 writeData(file.getAbsolutePath(), writer.toJson(graphs), append);
2265 }
2266
2267//------------------------------------------------------------------------------
2268
2277 public static void writeGraphToFile(String fileName, DGraph graph,
2278 boolean append) throws DENOPTIMException
2279 {
2280 writeData(fileName, graph.toString(), append);
2281 }
2282
2283//------------------------------------------------------------------------------
2284
2292 public static Map<File, FileFormat> readRecentFilesMap()
2293 {
2294 Map<File, FileFormat> map = new LinkedHashMap<File, FileFormat>();
2295 if (!DENOPTIMConstants.RECENTFILESLIST.exists())
2296 {
2297 return map;
2298 }
2299 try
2300 {
2301 for (String line : DenoptimIO.readList(
2302 DENOPTIMConstants.RECENTFILESLIST.getAbsolutePath(), true))
2303 {
2304 line = line.trim();
2305 String[] parts = line.split("\\s+");
2306 String ffStr = parts[0];
2307 FileFormat ff = null;
2308 try
2309 {
2310 ff = FileFormat.valueOf(FileFormat.class, ffStr);
2311 } catch (Exception e)
2312 {
2313 throw new DENOPTIMException("Unable to convert '" + ffStr
2314 + "' to a known file format.");
2315 }
2316 String fileName = line.substring(ffStr.length()).trim();
2317 if (FileUtils.checkExists(fileName))
2318 {
2319 map.put(new File(fileName), ff);
2320 }
2321 }
2322 } catch (DENOPTIMException e)
2323 {
2324 StaticLogger.appLogger.log(Level.WARNING, "WARNING: unable to "
2325 + "fetch list of recent files.", e);
2326 map = new HashMap<File, FileFormat>();
2327 }
2328 return map;
2329 }
2330
2331//------------------------------------------------------------------------------
2332
2346 public static ArrayList<Vertex> readVertexes(File file,
2348 IOException, IllegalArgumentException, DENOPTIMException
2349 {
2350 ArrayList<Vertex> vertexes = new ArrayList<Vertex>();
2352 switch (ff)
2353 {
2354 case VRTXSDF:
2356 file.getAbsolutePath(),bbt);
2357 break;
2358
2359 case VRTXJSON:
2361 file.getAbsolutePath());
2362 break;
2363
2364 case GRAPHSDF:
2365 ArrayList<DGraph> lstGraphs =
2366 readDENOPTIMGraphsFromSDFile(file.getAbsolutePath());
2367 for (DGraph g : lstGraphs)
2368 {
2369 Template t = new Template(bbt);
2370 t.setInnerGraph(g);
2371 vertexes.add(t);
2372 }
2373 break;
2374
2375 case GRAPHJSON:
2376 ArrayList<DGraph> lstGraphs2 =
2377 readDENOPTIMGraphsFromJSONFile(file.getAbsolutePath());
2378 for (DGraph g : lstGraphs2)
2379 {
2380 Template t = new Template(bbt);
2381 t.setInnerGraph(g);
2382 vertexes.add(t);
2383 }
2384 break;
2385
2386 default:
2387 throw new DENOPTIMException("Format '" + ff
2388 + "' could not be used to "
2389 + "read in vertices from file '" + file + "'.");
2390 }
2391 return vertexes;
2392 }
2393
2394//------------------------------------------------------------------------------
2395
2403 public static ArrayList<Vertex> readDENOPTIMVertexesFromSDFile(
2404 String fileName, Vertex.BBType bbt) throws DENOPTIMException
2405 {
2406 ArrayList<Vertex> vertexes = new ArrayList<Vertex>();
2407 int i=0;
2408 Gson reader = DENOPTIMgson.getReader();
2409 for (IAtomContainer mol : readSDFFile(fileName))
2410 {
2411 i++;
2412 Vertex v = null;
2413 try
2414 {
2415 v = Vertex.parseVertexFromSDFFormat(mol, reader, bbt);
2416 } catch (DENOPTIMException e)
2417 {
2418 throw new DENOPTIMException("Unable to read vertex " + i
2419 + " in file " + fileName,e);
2420 }
2421 vertexes.add(v);
2422 }
2423 return vertexes;
2424 }
2425
2426//------------------------------------------------------------------------------
2427
2444 public static LinkedHashMap<String, String> readCSDFormulae(File file)
2445 throws DENOPTIMException
2446 {
2447 LinkedHashMap<String, String> allFormulae = new LinkedHashMap<String,String>();
2448 BufferedReader buffRead = null;
2449 try {
2450 //Read the file line by line
2451 buffRead = new BufferedReader(new FileReader(file));
2452 String lineAll = null;
2453 String refcode = "";
2454 String formula = "";
2455 while ((lineAll = buffRead.readLine()) != null)
2456 {
2457 String[] lineArgs = lineAll.split(":");
2458 //Get the name
2459 if (lineArgs[0].equals("REFCODE"))
2460 refcode = lineArgs[1].trim();
2461
2462 //Get the formula
2463 if (lineArgs[0].equals(" Formula"))
2464 {
2465 formula = lineArgs[1].trim();
2466 //Store formula
2467 allFormulae.put(refcode,formula);
2468 //Clean fields
2469 refcode = "";
2470 formula = "";
2471 }
2472 }
2473 } catch (FileNotFoundException fnf) {
2474 throw new DENOPTIMException("File Not Found: " + file, fnf);
2475 } catch (IOException ioex) {
2476 throw new DENOPTIMException("Error reading file: " + file, ioex);
2477 } finally {
2478 try {
2479 if (buffRead != null)
2480 buffRead.close();
2481 } catch (IOException e) {
2482 throw new DENOPTIMException("Error closing buffer to "+file, e);
2483 }
2484 }
2485
2486 return allFormulae;
2487 }
2488
2489//------------------------------------------------------------------------------
2490
2502 public static void readCuttingRules(BufferedReader reader,
2503 List<CuttingRule> cutRules, String source) throws DENOPTIMException
2504 {
2505 ArrayList<String> cutRulLines = new ArrayList<String>();
2506 try
2507 {
2508 String line = null;
2509 while ((line = reader.readLine()) != null)
2510 {
2511 if (line.trim().startsWith(DENOPTIMConstants.CUTRULKEYWORD))
2512 cutRulLines.add(line.trim());
2513 }
2514 } catch (IOException e)
2515 {
2516 throw new DENOPTIMException(e);
2517 } finally {
2518 if (reader != null)
2519 try
2520 {
2521 reader.close();
2522 } catch (IOException e)
2523 {
2524 throw new DENOPTIMException(e);
2525 }
2526 }
2527 readCuttingRules(cutRulLines, cutRules, source);
2528 }
2529
2530//------------------------------------------------------------------------------
2531
2540 public static void readCuttingRules(File file,
2541 List<CuttingRule> cutRules) throws DENOPTIMException
2542 {
2543 ArrayList<String> allLines = readList(file.getAbsolutePath());
2544
2545 //Now get the list of cutting rules
2546 ArrayList<String> cutRulLines = new ArrayList<String>();
2547 allLines.stream()
2548 .filter(line -> line.trim().startsWith(
2550 .forEach(line -> cutRulLines.add(line.trim()));
2551
2552 readCuttingRules(cutRulLines, cutRules, "file '"
2553 + file.getAbsolutePath()+ "'");
2554 }
2555
2556//------------------------------------------------------------------------------
2557
2571 public static void readCuttingRules(ArrayList<String> cutRulLines,
2572 List<CuttingRule> cutRules, String source) throws DENOPTIMException
2573 {
2574 Set<Integer> usedPriorities = new HashSet<Integer>();
2575 for (int i = 0; i<cutRulLines.size(); i++)
2576 {
2577 String[] words = cutRulLines.get(i).split("\\s+");
2578 String name = words[1]; //name of the rule
2579 if (words.length < 6)
2580 {
2581 throw new DENOPTIMException("ERROR in getting cutting rule."
2582 + " Found " + words.length + " parts inctead of 6."
2583 + "Check line '" + cutRulLines.get(i) + "'"
2584 + "in " + source + ".");
2585 }
2586
2587 // further details in map of options
2588 ArrayList<String> opts = new ArrayList<String>();
2589 if (words.length >= 7)
2590 {
2591 for (int wi=6; wi<words.length; wi++)
2592 {
2593 opts.add(words[wi]);
2594 }
2595 }
2596
2597 int priority = Integer.parseInt(words[2]);
2598 if (usedPriorities.contains(priority))
2599 {
2600 throw new DENOPTIMException("ERROR in getting cutting rule."
2601 + " Duplicate priority index " + priority + ". "
2602 + "Check line '" + cutRulLines.get(i) + "'"
2603 + "in " + source + ".");
2604 } else {
2605 usedPriorities.add(priority);
2606 }
2607
2608 CuttingRule rule = new CuttingRule(name,
2609 words[3], //atom1
2610 words[4], //atom2
2611 words[5], //bond between 1 and 2
2612 priority,
2613 opts);
2614
2615 cutRules.add(rule);
2616 }
2617
2618 Collections.sort(cutRules, new Comparator<CuttingRule>() {
2619
2620 @Override
2621 public int compare(CuttingRule r1, CuttingRule r2)
2622 {
2623 return Integer.compare(r1.getPriority(), r2.getPriority());
2624 }
2625
2626 });
2627 }
2628
2629//------------------------------------------------------------------------------
2630
2637 public static void writeCuttingRules(File file,
2638 List<CuttingRule> cutRules) throws DENOPTIMException
2639 {
2640 StringBuilder sb = new StringBuilder();
2641 for (CuttingRule r : cutRules)
2642 {
2643 sb.append(DENOPTIMConstants.CUTRULKEYWORD).append(" ");
2644 sb.append(r.getName()).append(" ");
2645 sb.append(r.getPriority()).append(" ");
2646 sb.append(r.getSMARTSAtom0()).append(" ");
2647 sb.append(r.getSMARTSAtom1()).append(" ");
2648 sb.append(r.getSMARTSBnd()).append(" ");
2649 if (r.getOptions()!=null)
2650 {
2651 for (String opt : r.getOptions())
2652 sb.append(opt).append(" ");
2653 }
2654 sb.append(NL);
2655 }
2656 writeData(file.getAbsolutePath(), sb.toString(), false);
2657 }
2658
2659//------------------------------------------------------------------------------
2660
2667 public static void appendTxtFiles(File f1, List<File> files) throws IOException
2668 {
2669 FileWriter fw;
2670 BufferedWriter bw;
2671 PrintWriter pw = null;
2672 try
2673 {
2674 fw = new FileWriter(f1, true);
2675 bw = new BufferedWriter(fw);
2676 pw = new PrintWriter(bw);
2677 for (File inFile : files)
2678 {
2679 FileReader fr;
2680 BufferedReader br = null;
2681 try
2682 {
2683 fr = new FileReader(inFile);
2684 br = new BufferedReader(fr);
2685 String line = null;
2686 while ((line = br.readLine()) != null)
2687 {
2688 pw.println(line);
2689 }
2690 } finally {
2691 if (br != null)
2692 br.close();
2693 }
2694 }
2695 } finally {
2696 if (pw!=null)
2697 pw.close();
2698 }
2699 }
2700
2701//------------------------------------------------------------------------------
2702
2711 public static List<BridgeHeadFindingRule> readBridgeHesFindingRules(
2712 String fileName) throws DENOPTIMException
2713 {
2714 List<BridgeHeadFindingRule> rules = null;
2715 BufferedReader br = null;
2716 try {
2717 br = new BufferedReader(new FileReader(fileName));
2718 rules = readBridgeHesFindingRules(br);
2719 }
2720 catch (FileNotFoundException fnfe)
2721 {
2722 throw new DENOPTIMException("File '" + fileName + "' not found.");
2723 } catch (IOException ioe)
2724 {
2725 throw new DENOPTIMException(ioe);
2726 }
2727 finally
2728 {
2729 try {
2730 if (br != null)
2731 {
2732 br.close();
2733 }
2734 } catch (IOException ioe) {
2735 throw new DENOPTIMException(ioe);
2736 }
2737 }
2738 return rules;
2739 }
2740
2741//------------------------------------------------------------------------------
2742
2752 public static List<BridgeHeadFindingRule> readBridgeHesFindingRules(
2753 BufferedReader br) throws IOException
2754 {
2755 List<BridgeHeadFindingRule> rules = new ArrayList<>();
2756 Gson reader = DENOPTIMgson.getReader();
2757 try
2758 {
2759 rules = reader.fromJson(br,
2760 new TypeToken<ArrayList<BridgeHeadFindingRule>>(){}.getType());
2761 }
2762 finally
2763 {
2764 if (br != null)
2765 {
2766 br.close();
2767 }
2768 }
2769 return rules;
2770 }
2771
2772
2773//------------------------------------------------------------------------------
2774
2780 public static void scanLoggingLevels(Logger logger)
2781 {
2782 logger.log(Level.ALL, "ALL");
2783 logger.log(Level.SEVERE, "SEVERE");
2784 logger.log(Level.WARNING, "WARN");
2785 logger.log(Level.INFO, "INFO");
2786 logger.log(Level.CONFIG, "CONGIF");
2787 logger.log(Level.FINE, "Fine");
2788 logger.log(Level.FINER, "FINER");
2789 logger.log(Level.FINEST, "FIENEST");
2790 }
2791
2792//------------------------------------------------------------------------------
2793
2794}
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 (multiple SD format))
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 String getChemDoodleString(IAtomContainer mol)
Generate the ChemDoodle representation of the molecule.
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