$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.FormatFactory;
65import org.openscience.cdk.io.ISimpleChemObjectReader;
66import org.openscience.cdk.io.MDLV2000Reader;
67import org.openscience.cdk.io.MDLV2000Writer;
68import org.openscience.cdk.io.Mol2Writer;
69import org.openscience.cdk.io.ReaderFactory;
70import org.openscience.cdk.io.SDFWriter;
71import org.openscience.cdk.io.XYZWriter;
72import org.openscience.cdk.io.formats.CIFFormat;
73import org.openscience.cdk.io.formats.IChemFormat;
74import org.openscience.cdk.silent.SilentChemObjectBuilder;
75import org.openscience.cdk.tools.manipulator.ChemFileManipulator;
76
77import com.google.gson.Gson;
78import com.google.gson.JsonSyntaxException;
79import com.google.gson.reflect.TypeToken;
80
81import denoptim.constants.DENOPTIMConstants;
82import denoptim.exception.DENOPTIMException;
83import denoptim.files.FileFormat;
84import denoptim.files.FileUtils;
85import denoptim.files.UndetectedFileFormatException;
86import denoptim.fragmenter.BridgeHeadFindingRule;
87import denoptim.fragspace.FragmentSpace;
88import denoptim.graph.APClass;
89import denoptim.graph.AttachmentPoint;
90import denoptim.graph.Candidate;
91import denoptim.graph.CandidateLW;
92import denoptim.graph.DGraph;
93import denoptim.graph.Template;
94import denoptim.graph.Vertex;
95import denoptim.graph.Vertex.BBType;
96import denoptim.json.DENOPTIMgson;
97import denoptim.logging.StaticLogger;
98import denoptim.molecularmodeling.ThreeDimTreeBuilder;
99import denoptim.programs.fragmenter.CuttingRule;
100import denoptim.utils.GraphConversionTool;
101import denoptim.utils.GraphEdit;
102import denoptim.utils.GraphUtils;
103import denoptim.utils.Randomizer;
104
105
113public class DenoptimIO
114{
115
119 public static final String FS = System.getProperty("file.separator");
120
124 public static final String NL = System.getProperty("line.separator");
125
126 private static final IChemObjectBuilder builder =
127 SilentChemObjectBuilder.getInstance();
128
129//------------------------------------------------------------------------------
130
140 public static Object readDENOPTIMData(String pathname)
141 throws Exception
142 {
143 Object data = null;
144 File file = new File(pathname);
146 format = FileUtils.detectFileFormat(file);
147 if (format == FileFormat.UNRECOGNIZED)
148 {
149 throw new UndetectedFileFormatException(file);
150 }
151 switch (format)
152 {
153 case VRTXSDF:
154 {
155 ArrayList<Vertex> vrtxs = readVertexes(file, BBType.FRAGMENT);
156 if (vrtxs.size()>1)
157 data = vrtxs;
158 else
159 data = vrtxs.get(0);
160 break;
161 }
162
163 case VRTXJSON:
164 {
165 ArrayList<Vertex> vrtxs = readVertexes(file, BBType.FRAGMENT);
166 if (vrtxs.size()>1)
167 data = vrtxs;
168 else
169 data = vrtxs.get(0);
170 break;
171 }
172
173 case CANDIDATESDF:
174 {
175 ArrayList<Candidate> cands = readCandidates(file, true);
176 if (cands.size()>1)
177 data = cands;
178 else
179 data = cands.get(0);
180 break;
181 }
182
183 case GRAPHSDF:
184 {
185 ArrayList<DGraph> graphs = readDENOPTIMGraphsFromFile(file,
186 format);
187 if (graphs.size()>1)
188 data = graphs;
189 else
190 data = graphs.get(0);
191 break;
192 }
193
194 case GRAPHJSON:
195 {
196 ArrayList<DGraph> graphs = readDENOPTIMGraphsFromFile(file,
197 format);
198 if (graphs.size()>1)
199 data = graphs;
200 else
201 data = graphs.get(0);
202 break;
203 }
204
205 case GENSUMMARY:
206 {
207 List<Candidate> cands = readGenerationFromSummary(file);
208 if (cands.size()>1)
209 data = cands;
210 else
211 data = cands.get(0);
212 break;
213 }
214
215 default:
216 throw new DENOPTIMException("Data from file of format '"
217 + format + "' cannot be loaded yet. Please, contact"
218 + "the development team.");
219 }
220 return data;
221 }
222
223//------------------------------------------------------------------------------
224
238 public static List<Candidate> readGenerationFromSummary(File file)
239 throws DENOPTIMException
240 {
241 ArrayList<Candidate> cands = new ArrayList<Candidate>();
242 List<String> pathnames = readPopulationMemberPathnames(file);
243 String genSummaryParentDir = file.getParent(); // GenXXX folder
244 for (String candPathname : pathnames)
245 {
246 File candFile = new File(candPathname);
247 if (candFile.exists())
248 {
249 cands.add(readCandidates(candFile).get(0));
250 } else if (genSummaryParentDir!=null) {
251 // Extract the possibly non-existing pathname where the
252 // candidates files were originally generated
253 String runFolderPathname =
254 candFile.getParentFile() // GenXXX
255 .getParent(); // RUN###
256 if (runFolderPathname==null)
257 throw new DENOPTIMException("Unable to find parent "
258 + "folder for '"+ genSummaryParentDir +"'");
259
260 String genAndMolPath = candFile.getAbsolutePath()
261 .substring(runFolderPathname.length());
262
263 cands.add(readCandidates(new File(
264 genSummaryParentDir+genAndMolPath)).get(0));
265 }
266 }
267 return cands;
268 }
269
270//------------------------------------------------------------------------------
271
283 public static List<IAtomContainer> readAllAtomContainers(File file)
284 throws IOException, CDKException
285 {
286 List<IAtomContainer> results = null;
287
288 FileReader formatReader = new FileReader(file);
289 IChemFormat chemFormat = new FormatFactory().guessFormat(
290 new BufferedReader(formatReader));
291 formatReader.close();
292
293 if (chemFormat instanceof CIFFormat)
294 {
296 // WARNING
298 //
299 // * CDK's CIFReader is broken (skips lines _audit, AND ignores
300 // connectivity)
301 // * BioJava's fails on CIF files that do not complain to mmCIF
302 // format. Try this:
303 // CifStructureConverter.fromPath(f.toPath());
304 //
305 // The workaround unit CDK's implementation is fixed, is to use Jmol
306 // to read the CIF and make an SDF that can then be read normally.
307 // In fact, Jmol's reader is more robust than CDK's and more
308 // versatile than BioJava's.
309 // Moreover it reads also the bonds defined in the CIF
310 // (which OpenBabel does not read).
311 // Yet, Jmol's methods are not visible and require spinning a
312 // a viewer.
313
314 Map<String, Object> info = new Hashtable<String, Object>();
315 info.put("adapter", new SmarterJmolAdapter());
316 info.put("isApp", false);
317 info.put("silent", "");
318 Viewer v = new Viewer(info);
319 v.loadModelFromFile(null, file.getAbsolutePath(), null, null,
320 false, null, null, null, 0, " ");
321 String tmp = FileUtils.getTempFolder() + FS + "convertedCIF.sdf";
322 v.scriptWait("write " + tmp + " as sdf");
323 v.dispose();
324
325 results = readAllAtomContainers(new File(tmp));
326 } else {
327 FileReader fileReader = new FileReader(file);
328 ReaderFactory readerFact = new ReaderFactory();
329 ISimpleChemObjectReader reader = readerFact.createReader(fileReader);
330 IChemFile chemFile = (IChemFile) reader.read(
331 (IChemObject) new ChemFile());
332 results = ChemFileManipulator.getAllAtomContainers(chemFile);
333 fileReader.close();
334 }
335
336 return results;
337 }
338
339//------------------------------------------------------------------------------
340
348 public static ArrayList<IAtomContainer> readSDFFile(String fileName)
349 throws DENOPTIMException {
350 MDLV2000Reader mdlreader = null;
351 ArrayList<IAtomContainer> lstContainers = new ArrayList<>();
352
353 try {
354 mdlreader = new MDLV2000Reader(new FileReader(new File(fileName)));
355 ChemFile chemFile = (ChemFile) mdlreader.read((ChemObject) new ChemFile());
356 lstContainers.addAll(
357 ChemFileManipulator.getAllAtomContainers(chemFile));
358 } catch (CDKException | IOException cdke) {
359 throw new DENOPTIMException(cdke);
360 } finally {
361 try {
362 if (mdlreader != null) {
363 mdlreader.close();
364 }
365 } catch (IOException ioe) {
366 throw new DENOPTIMException(ioe);
367 }
368 }
369
370 if (lstContainers.isEmpty()) {
371 throw new DENOPTIMException("No data found in " + fileName);
372 }
373
374 return lstContainers;
375 }
376
377//------------------------------------------------------------------------------
378
387 public static File writeVertexesToFile(File file, FileFormat format,
388 List<Vertex> vertexes) throws DENOPTIMException
389 {
390 return writeVertexesToFile(file, format, vertexes, false);
391 }
392
393//------------------------------------------------------------------------------
394
403 public static File writeVertexToFile(File file, FileFormat format,
404 Vertex vertex, boolean append) throws DENOPTIMException
405 {
406 ArrayList<Vertex> lst = new ArrayList<Vertex>();
407 lst.add(vertex);
408 return writeVertexesToFile(file, format, lst, append);
409 }
410
411//------------------------------------------------------------------------------
412
421 public static File writeVertexesToFile(File file, FileFormat format,
422 List<Vertex> vertexes, boolean append) throws DENOPTIMException
423 {
424 if (FilenameUtils.getExtension(file.getName()).equals(""))
425 {
426 file = new File(file.getAbsoluteFile()+"."+format.getExtension());
427 }
428 switch (format)
429 {
430 case VRTXJSON:
431 writeVertexesToJSON(file, vertexes, append);
432 break;
433
434 case VRTXSDF:
435 writeVertexesToSDF(file, vertexes, append);
436 break;
437
438 default:
439 throw new DENOPTIMException("Cannot write vertexes with format '"
440 + format + "'.");
441 }
442 return file;
443 }
444
445//------------------------------------------------------------------------------
446
454 public static void writeVertexesToJSON(File file,
455 List<Vertex> vertexes) throws DENOPTIMException
456 {
457 writeVertexesToJSON(file, vertexes, false);
458 }
459
460//------------------------------------------------------------------------------
461
471 public static void writeVertexesToJSON(File file,
472 List<Vertex> vertexes, boolean append) throws DENOPTIMException
473 {
474 Gson writer = DENOPTIMgson.getWriter();
475 if (append)
476 {
477 ArrayList<Vertex> allVertexes = readDENOPTIMVertexesFromJSONFile(
478 file.getAbsolutePath());
479 allVertexes.addAll(vertexes);
480 writeData(file.getAbsolutePath(), writer.toJson(allVertexes), false);
481 } else {
482 writeData(file.getAbsolutePath(), writer.toJson(vertexes), false);
483 }
484 }
485
486//------------------------------------------------------------------------------
487
496 public static void writeVertexToSDF(String pathName, Vertex vertex)
497 throws DENOPTIMException
498 {
499 List<Vertex> lst = new ArrayList<Vertex>();
500 lst.add(vertex);
501 writeVertexesToSDF(new File(pathName), lst, false);
502 }
503
504//------------------------------------------------------------------------------
505
514 public static void writeVertexesToSDF(File file,
515 List<Vertex> vertexes, boolean append)
516 throws DENOPTIMException
517 {
518 List<IAtomContainer> lst = new ArrayList<IAtomContainer>();
519 for (Vertex v : vertexes)
520 {
521 lst.add(v.getIAtomContainer());
522 }
523 writeSDFFile(file.getAbsolutePath(), lst, append);
524 }
525
526//------------------------------------------------------------------------------
527
535 public static void writeSDFFile(String fileName, IAtomContainer mol)
536 throws DENOPTIMException {
537 List<IAtomContainer> mols = new ArrayList<IAtomContainer>();
538 mols.add(mol);
539 writeSDFFile(fileName, mols, false);
540 }
541
542//------------------------------------------------------------------------------
543
551 public static void writeSDFFile(String fileName, List<IAtomContainer> mols)
552 throws DENOPTIMException {
553 writeSDFFile(fileName,mols, false);
554 }
555
556//------------------------------------------------------------------------------
557
566 public static void writeSDFFile(String fileName, List<IAtomContainer> mols,
567 boolean append) throws DENOPTIMException
568 {
569 SDFWriter sdfWriter = null;
570 try {
571 IAtomContainerSet molSet = new AtomContainerSet();
572 for (int idx = 0; idx < mols.size(); idx++) {
573 molSet.addAtomContainer(mols.get(idx));
574 }
575 sdfWriter = new SDFWriter(new FileWriter(new File(fileName),append));
576 sdfWriter.write(molSet);
577 } catch (CDKException | IOException cdke) {
578 throw new DENOPTIMException(cdke);
579 } finally {
580 try {
581 if (sdfWriter != null) {
582 sdfWriter.close();
583 }
584 } catch (IOException ioe) {
585 throw new DENOPTIMException(ioe);
586 }
587 }
588 }
589
590//------------------------------------------------------------------------------
591
600 public static void writeSDFFile(String fileName, IAtomContainer mol,
601 boolean append) throws DENOPTIMException {
602 SDFWriter sdfWriter = null;
603 try {
604 sdfWriter = new SDFWriter(new FileWriter(new File(fileName), append));
605 sdfWriter.write(mol);
606 } catch (CDKException | IOException cdke) {
607 throw new DENOPTIMException(cdke);
608 } finally {
609 try {
610 if (sdfWriter != null) {
611 sdfWriter.close();
612 }
613 } catch (IOException ioe) {
614 throw new DENOPTIMException(ioe);
615 }
616 }
617 }
618
619//------------------------------------------------------------------------------
620
621 public static void writeMol2File(String fileName, IAtomContainer mol,
622 boolean append) throws DENOPTIMException {
623 Mol2Writer mol2Writer = null;
624 try {
625 mol2Writer = new Mol2Writer(new FileWriter(new File(fileName), append));
626 mol2Writer.write(mol);
627 } catch (CDKException cdke) {
628 throw new DENOPTIMException(cdke);
629 } catch (IOException ioe) {
630 throw new DENOPTIMException(ioe);
631 } finally {
632 try {
633 if (mol2Writer != null) {
634 mol2Writer.close();
635 }
636 } catch (IOException ioe) {
637 throw new DENOPTIMException(ioe);
638 }
639 }
640 }
641
642//------------------------------------------------------------------------------
643
644 public static void writeXYZFile(String fileName, IAtomContainer mol,
645 boolean append) throws DENOPTIMException {
646 XYZWriter xyzWriter = null;
647 try {
648 xyzWriter = new XYZWriter(new FileWriter(new File(fileName), append));
649 xyzWriter.write(mol);
650 } catch (CDKException cdke) {
651 throw new DENOPTIMException(cdke);
652 } catch (IOException ioe) {
653 throw new DENOPTIMException(ioe);
654 } finally {
655 try {
656 if (xyzWriter != null) {
657 xyzWriter.close();
658 }
659 } catch (IOException ioe) {
660 throw new DENOPTIMException(ioe);
661 }
662 }
663 }
664
665//------------------------------------------------------------------------------
666
676 public static void writeSmilesSet(String fileName, String[] smiles,
677 boolean append) throws DENOPTIMException {
678 FileWriter fw = null;
679 try {
680 fw = new FileWriter(new File(fileName), append);
681 for (int i = 0; i < smiles.length; i++) {
682 fw.write(smiles[i] + NL);
683 fw.flush();
684 }
685 } catch (IOException ioe) {
686 throw new DENOPTIMException(ioe);
687 } finally {
688 try {
689 if (fw != null) {
690 fw.close();
691 }
692 } catch (IOException ioe) {
693 throw new DENOPTIMException(ioe);
694 }
695 }
696 }
697
698//------------------------------------------------------------------------------
699
709 public static void writeSmiles(String fileName, String smiles,
710 boolean append) throws DENOPTIMException {
711 FileWriter fw = null;
712 try {
713 fw = new FileWriter(new File(fileName), append);
714 fw.write(smiles + NL);
715 fw.flush();
716 } catch (IOException ioe) {
717 throw new DENOPTIMException(ioe);
718 } finally {
719 try {
720 if (fw != null) {
721 fw.close();
722 }
723 } catch (IOException ioe) {
724 throw new DENOPTIMException(ioe);
725 }
726 }
727 }
728
729//------------------------------------------------------------------------------
730
739 public static void writeData(String fileName, String data, boolean append)
740 throws DENOPTIMException {
741 FileWriter fw = null;
742 try {
743 fw = new FileWriter(new File(fileName), append);
744 fw.write(data + NL);
745 fw.flush();
746 } catch (IOException ioe) {
747 throw new DENOPTIMException(ioe);
748 } finally {
749 try {
750 if (fw != null) {
751 fw.close();
752 }
753 } catch (IOException ioe) {
754 throw new DENOPTIMException(ioe);
755 }
756 }
757 }
758
759//------------------------------------------------------------------------------
760
770 public static List<CandidateLW> readLightWeightCandidate(File file)
771 throws DENOPTIMException
772 {
773 List<String> propNames = new ArrayList<String>(Arrays.asList(
775 CDKConstants.TITLE
776 ));
777 List<String> optionalPropNames = new ArrayList<String>(Arrays.asList(
782 ));
783 propNames.addAll(optionalPropNames);
784 List<Map<String, Object>> propsPerItem = readSDFProperties(
785 file.getAbsolutePath(), propNames);
786
787 List<CandidateLW> items = new ArrayList<CandidateLW>();
788 for (Map<String, Object> props : propsPerItem)
789 {
790 Object uidObj = props.get(DENOPTIMConstants.UNIQUEIDTAG);
791 if (uidObj==null )
792 {
793 throw new DENOPTIMException("Cannot create item if SDF tag "
794 + DENOPTIMConstants.UNIQUEIDTAG + " is null!");
795 }
796 Object nameObj = props.get(CDKConstants.TITLE);
797 if (nameObj==null)
798 {
799 throw new DENOPTIMException("Cannot create item is SDF tag "
800 + CDKConstants.TITLE + " is null!");
801 }
802 CandidateLW item = new CandidateLW(uidObj.toString(),
803 nameObj.toString(),file.getAbsolutePath());
804
805 for (String propName : optionalPropNames)
806 {
807 Object obj = props.get(propName);
808 if (obj != null)
809 {
810 switch (propName)
811 {
813 item.setFitness(Double.parseDouble(obj.toString()));
814 break;
815
817 item.setError(obj.toString());
818 break;
819
821 item.setGeneratingSource(obj.toString());
822 break;
823
825 item.setLevel(Integer.parseInt(obj.toString()));
826 break;
827 }
828 }
829 }
830 items.add(item);
831 }
832 return items;
833 }
834
835//------------------------------------------------------------------------------
836
845 public static double[] readPopulationProps(File file)
846 throws DENOPTIMException {
847 double[] vals = new double[4];
848 ArrayList<String> txt = readList(file.getAbsolutePath());
849 for (String line : txt) {
850 if (line.trim().length() < 8) {
851 continue;
852 }
853
854 String key = line.toUpperCase().trim().substring(0, 8);
855 switch (key) {
856 case ("MIN: "):
857 vals[0] = Double.parseDouble(line.split("\\s+")[1]);
858 break;
859
860 case ("MAX: "):
861 vals[1] = Double.parseDouble(line.split("\\s+")[1]);
862 break;
863
864 case ("MEAN: "):
865 vals[2] = Double.parseDouble(line.split("\\s+")[1]);
866 break;
867
868 case ("MEDIAN: "):
869 vals[3] = Double.parseDouble(line.split("\\s+")[1]);
870 break;
871 }
872 }
873 return vals;
874 }
875
876//------------------------------------------------------------------------------
877
886 public static List<String> readPopulationMemberPathnames(File file)
887 throws DENOPTIMException
888 {
889 List<String> vals = new ArrayList<String>();
890 ArrayList<String> txt = readList(file.getAbsolutePath());
891 for (String line : txt)
892 {
893 if (!line.contains(FS))
894 continue;
895
896 String[] words = line.trim().split("\\s+");
897 if (words.length < 5)
898 continue;
899
900 // NB: there is no keyword for population members!
901 vals.add(words[4]);
902 }
903 return vals;
904 }
905
906//------------------------------------------------------------------------------
907
919 public static List<CandidateLW> readPopulationMembersTraces(File file)
920 throws DENOPTIMException
921 {
922 List<CandidateLW> members = new ArrayList<CandidateLW>();
923 List<String> txt = readList(file.getAbsolutePath());
924
925 // Skip the header, i.e., the first line
926 for (int i=1; i<txt.size(); i++)
927 {
928 String line = txt.get(i);
929
930 // WARNING: here we set strong expectation on the format of the
931 // gensummary files!
932
933 if (line.startsWith("#"))
934 break;
935
936 if (line.isBlank())
937 continue;
938
939 String[] words = line.trim().split("\\s+");
940 String pathname = "nofile";
941 if (words.length >= 5)
942 {
943 pathname = words[4];
944 }
945 CandidateLW member = new CandidateLW(words[2], words[0], pathname);
946 member.setFitness(Double.parseDouble(words[3]));
947 members.add(member);
948 }
949 return members;
950 }
951
952//------------------------------------------------------------------------------
953
961 public static ArrayList<String> readList(String fileName)
962 throws DENOPTIMException {
963 return readList(fileName, false);
964 }
965
966//------------------------------------------------------------------------------
967
977 public static ArrayList<String> readList(String fileName,
978 boolean allowEmpty) throws DENOPTIMException {
979 ArrayList<String> lst = new ArrayList<>();
980 BufferedReader br = null;
981 String line = null;
982 try {
983 br = new BufferedReader(new FileReader(fileName));
984 while ((line = br.readLine()) != null) {
985 if (line.trim().length() == 0) {
986 continue;
987 }
988 lst.add(line.trim());
989 }
990 } catch (IOException ioe) {
991 throw new DENOPTIMException(ioe);
992 } finally {
993 try {
994 if (br != null) {
995 br.close();
996 }
997 } catch (IOException ioe) {
998 throw new DENOPTIMException(ioe);
999 }
1000 }
1001
1002 if (lst.isEmpty() && !allowEmpty) {
1003 throw new DENOPTIMException("No data found in file: " + fileName);
1004 }
1005
1006 return lst;
1007 }
1008
1009//------------------------------------------------------------------------------
1010
1018 public static String readText(String fileName) throws DENOPTIMException {
1019 StringBuilder sb = new StringBuilder();
1020 BufferedReader br = null;
1021 String line = null;
1022 try {
1023 br = new BufferedReader(new FileReader(fileName));
1024 while ((line = br.readLine()) != null) {
1025 sb.append(line).append(NL);
1026 }
1027 } catch (IOException ioe) {
1028 throw new DENOPTIMException(ioe);
1029 } finally {
1030 try {
1031 if (br != null) {
1032 br.close();
1033 }
1034 } catch (IOException ioe) {
1035 throw new DENOPTIMException(ioe);
1036 }
1037 }
1038
1039 return sb.toString();
1040 }
1041
1042//------------------------------------------------------------------------------
1043
1052 public static List<Map<String, Object>> readSDFProperties(String pathName,
1053 List<String> propNames) throws DENOPTIMException
1054 {
1055 List<Map<String,Object>> results = new ArrayList<Map<String,Object>>();
1056 ArrayList<IAtomContainer> iacs = DenoptimIO.readSDFFile(pathName);
1057 for (IAtomContainer iac : iacs)
1058 {
1059 Map<String,Object> properties = new HashMap<String,Object>();
1060 for (String propName : propNames)
1061 {
1062 properties.put(propName, iac.getProperty(propName));
1063 }
1064 results.add(properties);
1065 }
1066 return results;
1067 }
1068
1069//------------------------------------------------------------------------------
1070
1078 public static String getChemDoodleString(IAtomContainer mol)
1079 throws DENOPTIMException {
1080 StringWriter stringWriter = new StringWriter();
1081 MDLV2000Writer mw = null;
1082 try {
1083 mw = new MDLV2000Writer(stringWriter);
1084 mw.write(mol);
1085 } catch (CDKException cdke) {
1086 throw new DENOPTIMException(cdke);
1087 } finally {
1088 try {
1089 if (mw != null) {
1090 mw.close();
1091 }
1092 } catch (IOException ioe) {
1093 throw new DENOPTIMException(ioe);
1094 }
1095 }
1096
1097 String MoleculeString = stringWriter.toString();
1098
1099 //System.out.print(stringWriter.toString());
1100 //now split MoleculeString into multiple lines to enable explicit printout of \n
1101 String Moleculelines[] = MoleculeString.split("\\r?\\n");
1102
1103 StringBuilder sb = new StringBuilder(1024);
1104 sb.append("var molFile = '");
1105 for (int i = 0; i < Moleculelines.length; i++) {
1106 sb.append(Moleculelines[i]);
1107 sb.append("\\n");
1108 }
1109 sb.append("';");
1110 return sb.toString();
1111 }
1112
1113//------------------------------------------------------------------------------
1114
1115 public static Set<APClass> readAllAPClasses(File fragLib) {
1116 Set<APClass> allCLasses = new HashSet<APClass>();
1117 try {
1118 for (Vertex v : DenoptimIO.readVertexes(fragLib, BBType.UNDEFINED))
1119 {
1120 for (AttachmentPoint ap : v.getAttachmentPoints()) {
1121 allCLasses.add(ap.getAPClass());
1122 }
1123 }
1124 } catch (DENOPTIMException | IllegalArgumentException
1125 | UndetectedFileFormatException | IOException e) {
1126 System.out.println("Could not read data from '" + fragLib + "'. "
1127 + "Cause: " + e.getMessage());
1128 }
1129
1130 return allCLasses;
1131 }
1132
1133//------------------------------------------------------------------------------
1134
1143 public static void writeCompatibilityMatrix(String fileName,
1144 HashMap<APClass, ArrayList<APClass>> cpMap,
1145 HashMap<APClass, APClass> capMap,
1146 HashSet<APClass> ends) throws DENOPTIMException {
1147 DateFormat dateFormat = new SimpleDateFormat("dd/MM/yy HH:mm:ss");
1148 Date date = new Date();
1149 String dateStr = dateFormat.format(date);
1150
1151 StringBuilder sb = new StringBuilder();
1153 sb.append(" Compatibility matrix data").append(NL);
1155 sb.append(" Written by DENOPTIM-GUI on ").append(dateStr).append(NL);
1157 sb.append(" APCLass Compatibility rules").append(NL);
1158 SortedSet<APClass> keysCPMap = new TreeSet<APClass>();
1159 keysCPMap.addAll(cpMap.keySet());
1160 for (APClass srcAPC : keysCPMap) {
1161 sb.append(DENOPTIMConstants.APCMAPCOMPRULE).append(" ");
1162 sb.append(srcAPC).append(" ");
1163 for (int i = 0; i < cpMap.get(srcAPC).size(); i++) {
1164 APClass trgAPC = cpMap.get(srcAPC).get(i);
1165 sb.append(trgAPC);
1166 if (i != (cpMap.get(srcAPC).size() - 1)) {
1167 sb.append(",");
1168 } else {
1169 sb.append(NL);
1170 }
1171 }
1172 }
1173
1175 sb.append(" Capping rules").append(NL);
1176 SortedSet<APClass> keysCap = new TreeSet<APClass>();
1177 keysCap.addAll(capMap.keySet());
1178 for (APClass apc : keysCap) {
1179 sb.append(DENOPTIMConstants.APCMAPCAPPING).append(" ");
1180 sb.append(apc).append(" ").append(capMap.get(apc)).append(NL);
1181 }
1182
1184 sb.append(" Forbidden ends").append(NL);
1185 SortedSet<APClass> sortedFE = new TreeSet<APClass>();
1186 sortedFE.addAll(ends);
1187 for (APClass apc : sortedFE) {
1188 sb.append(DENOPTIMConstants.APCMAPFORBIDDENEND).append(" ");
1189 sb.append(apc).append(" ").append(NL);
1190 }
1191
1192 DenoptimIO.writeData(fileName, sb.toString(), false);
1193 }
1194
1195//------------------------------------------------------------------------------
1196
1206 public static void readCompatibilityMatrix(String fileName,HashMap<APClass,
1207 ArrayList<APClass>> compatMap,
1208 HashMap<APClass, APClass> cappingMap, Set<APClass> forbiddenEndList)
1209 throws DENOPTIMException {
1210
1211 BufferedReader br = null;
1212 String line = null;
1213 try {
1214 br = new BufferedReader(new FileReader(fileName));
1215 while ((line = br.readLine()) != null) {
1216 if (line.trim().length() == 0) {
1217 continue;
1218 }
1219
1220 if (line.startsWith(DENOPTIMConstants.APCMAPIGNORE)) {
1221 continue;
1222 }
1223
1224 if (line.startsWith(DENOPTIMConstants.APCMAPCOMPRULE)) {
1225 String str[] = line.split("\\s+");
1226 if (str.length < 3) {
1227 String err = "Incomplete APClass compatibility line '"
1228 + line + "'.";
1229 throw new DENOPTIMException(err + " " + fileName);
1230 }
1231
1232 APClass srcAPC = APClass.make(str[1]);
1233 ArrayList<APClass> trgAPCs = new ArrayList<APClass>();
1234 for (String s : str[2].split(","))
1235 {
1236 trgAPCs.add(APClass.make(s.trim()));
1237 }
1238 compatMap.put(srcAPC, trgAPCs);
1239 } else {
1240 if (line.startsWith(DENOPTIMConstants.APCMAPCAPPING)) {
1241 String str[] = line.split("\\s+");
1242 if (str.length != 3) {
1243 String err = "Incomplete capping line '"
1244 + line +"'.";
1245 throw new DENOPTIMException(err + " "+fileName);
1246 }
1247 APClass srcAPC = APClass.make(str[1]);
1248 APClass trgAPC = APClass.make(str[2]);
1249 cappingMap.put(srcAPC, trgAPC);
1250 } else {
1251 if (line.startsWith(
1253 String str[] = line.split("\\s+");
1254 if (str.length != 2) {
1255 for (int is = 1; is < str.length; is++) {
1256 forbiddenEndList.add(
1257 APClass.make(str[is]));
1258 }
1259 } else {
1260 forbiddenEndList.add(APClass.make(str[1]));
1261 }
1262 }
1263 }
1264 }
1265 }
1266 } catch (NumberFormatException | IOException nfe) {
1267 throw new DENOPTIMException(nfe);
1268 } finally {
1269 try {
1270 if (br != null) {
1271 br.close();
1272 }
1273 } catch (IOException ioe) {
1274 throw new DENOPTIMException(ioe);
1275 }
1276 }
1277
1278 if (compatMap.isEmpty()) {
1279 String err = "No reaction compatibility data found in file: ";
1280 throw new DENOPTIMException(err + " " + fileName);
1281 }
1282 }
1283
1284//------------------------------------------------------------------------------
1285
1300 public static void readRCCompatibilityMatrix(String fileName,
1301 HashMap<APClass, ArrayList<APClass>> rcCompatMap)
1302 throws DENOPTIMException {
1303 BufferedReader br = null;
1304 String line = null;
1305 try {
1306 br = new BufferedReader(new FileReader(fileName));
1307 while ((line = br.readLine()) != null) {
1308 if (line.trim().length() == 0) {
1309 continue;
1310 }
1311
1312 if (line.startsWith(DENOPTIMConstants.APCMAPIGNORE)) {
1313 continue;
1314 }
1315
1316 if (line.startsWith(DENOPTIMConstants.APCMAPCOMPRULE)) {
1317 String str[] = line.split("\\s+");
1318 if (str.length < 3) {
1319 String err = "Incomplete reaction compatibility data.";
1320 throw new DENOPTIMException(err + " " + fileName);
1321 }
1322
1323 APClass srcAPC = APClass.make(str[1]);
1324
1325 String strRcn[] = str[2].split(",");
1326 for (int i = 0; i < strRcn.length; i++) {
1327 strRcn[i] = strRcn[i].trim();
1328
1329 APClass trgAPC = APClass.make(strRcn[i]);
1330 if (rcCompatMap.containsKey(srcAPC)) {
1331 rcCompatMap.get(srcAPC).add(trgAPC);
1332 } else {
1333 ArrayList<APClass> list = new ArrayList<APClass>();
1334 list.add(trgAPC);
1335 rcCompatMap.put(srcAPC, list);
1336 }
1337
1338 if (rcCompatMap.containsKey(trgAPC)) {
1339 rcCompatMap.get(trgAPC).add(srcAPC);
1340 } else {
1341 ArrayList<APClass> list = new ArrayList<APClass>();
1342 list.add(srcAPC);
1343 rcCompatMap.put(trgAPC, list);
1344 }
1345 }
1346 }
1347 }
1348 } catch (NumberFormatException | IOException nfe) {
1349 throw new DENOPTIMException(nfe);
1350 } finally {
1351 try {
1352 if (br != null) {
1353 br.close();
1354 }
1355 } catch (IOException ioe) {
1356 throw new DENOPTIMException(ioe);
1357 }
1358 }
1359
1360 if (rcCompatMap.isEmpty()) {
1361 String err = "No reaction compatibility data found in file: ";
1362 throw new DENOPTIMException(err + " " + fileName);
1363 }
1364 }
1365
1366//------------------------------------------------------------------------------
1367
1379 public static ArrayList<Candidate> readCandidates(File file)
1380 throws DENOPTIMException {
1381 return readCandidates(file,false);
1382 }
1383
1384//------------------------------------------------------------------------------
1385
1398 public static ArrayList<Candidate> readCandidates(File file,
1399 boolean allowNoUID) throws DENOPTIMException {
1400 String filename = file.getAbsolutePath();
1401 ArrayList<Candidate> candidates = new ArrayList<>();
1402 ArrayList<IAtomContainer> iacs = readSDFFile(file.getAbsolutePath());
1403
1404 // Try to identify the generation at which this candidate was generated
1405 int genID = -1;
1406 if (file.getParentFile()!=null
1407 && file.getParentFile().getName().startsWith(
1409 {
1410 String genFolderName = file.getParentFile().getName();
1411 genID = Integer.valueOf(genFolderName.substring(
1413 }
1414
1415 for (IAtomContainer iac : iacs) {
1416 Candidate cand = new Candidate(iac, false, allowNoUID);
1417 cand.setSDFFile(filename);
1418 if (genID!=-1)
1419 cand.setGeneration(genID);
1420 candidates.add(cand);
1421 }
1422 return candidates;
1423 }
1424
1425//------------------------------------------------------------------------------
1426
1434 public static void writeCandidatesToFile(File file,
1435 List<Candidate> popMembers, boolean append)
1436 throws DENOPTIMException
1437 {
1438 if (FilenameUtils.getExtension(file.getName()).equals(""))
1439 {
1440 file = new File(file.getAbsoluteFile() + "."
1441 + FileFormat.CANDIDATESDF.getExtension());
1442 }
1443 ArrayList<IAtomContainer> lst = new ArrayList<IAtomContainer>();
1444 for (Candidate g : popMembers)
1445 {
1446 lst.add(g.getFitnessProviderOutputRepresentation());
1447 }
1448 writeSDFFile(file.getAbsolutePath(), lst, append);
1449 }
1450
1451//------------------------------------------------------------------------------
1452
1460 public static void writeCandidateToFile(File file, Candidate candidate,
1461 boolean append)
1462 throws DENOPTIMException
1463 {
1464 if (FilenameUtils.getExtension(file.getName()).equals(""))
1465 {
1466 file = new File(file.getAbsoluteFile() + "."
1467 + FileFormat.CANDIDATESDF.getExtension());
1468 }
1469 writeSDFFile(file.getAbsolutePath(),
1470 candidate.getFitnessProviderOutputRepresentation(), append);
1471 }
1472
1473//------------------------------------------------------------------------------
1474
1482 public static ArrayList<GraphEdit> readDENOPTIMGraphEditFromFile(
1483 String fileName) throws DENOPTIMException
1484 {
1485 ArrayList<GraphEdit> graphEditTasks = new ArrayList<>();
1486 Gson reader = DENOPTIMgson.getReader();
1487
1488 BufferedReader br = null;
1489 try
1490 {
1491 br = new BufferedReader(new FileReader(fileName));
1492 graphEditTasks = reader.fromJson(br,
1493 new TypeToken<ArrayList<GraphEdit>>(){}.getType());
1494 }
1495 catch (FileNotFoundException fnfe)
1496 {
1497 throw new DENOPTIMException("File '" + fileName + "' not found.");
1498 }
1499 catch (JsonSyntaxException jse)
1500 {
1501 String msg = "Expected BEGIN_ARRAY but was BEGIN_OBJECT";
1502 if (jse.getMessage().contains(msg))
1503 {
1504 // The file contains a single object, not a list. We try to read
1505 // that single object as a DENOPTIMGraph
1506 try
1507 {
1508 br.close();
1509 br = new BufferedReader(new FileReader(fileName));
1510 }
1511 catch (FileNotFoundException fnfe)
1512 {
1513 //cannot happen
1514 } catch (IOException ioe)
1515 {
1516 throw new DENOPTIMException(ioe);
1517 }
1518 GraphEdit graphEditTask = reader.fromJson(br,
1519 GraphEdit.class);
1520 graphEditTasks.add(graphEditTask);
1521 } else {
1522 jse.printStackTrace();
1523 throw new DENOPTIMException("ERROR! Unable to read JSON file "
1524 + "that defines a graph enditing task.",jse);
1525 }
1526 }
1527 finally
1528 {
1529 try {
1530 if (br != null)
1531 {
1532 br.close();
1533 }
1534 } catch (IOException ioe) {
1535 throw new DENOPTIMException(ioe);
1536 }
1537 }
1538
1539 return graphEditTasks;
1540 }
1541
1542//------------------------------------------------------------------------------
1543
1552 public static ArrayList<DGraph> readDENOPTIMGraphsFromFile(File inFile)
1553 throws Exception
1554 {
1556 return readDENOPTIMGraphsFromFile(inFile, ff);
1557 }
1558
1559//------------------------------------------------------------------------------
1560
1572 public static ArrayList<DGraph> readDENOPTIMGraphsFromFile(File inFile,
1573 FileFormat format) throws Exception
1574 {
1575 switch (format)
1576 {
1577 case GRAPHJSON:
1579 inFile.getAbsolutePath());
1580
1581 case GRAPHSDF:
1583 inFile.getAbsolutePath());
1584
1585 case GRAPHTXT:
1586 throw new DENOPTIMException("Use of string representation '"
1587 + DENOPTIMConstants.GRAPHTAG + "' is deprecated. Use "
1588 + "JSON format instead.");
1589
1590 case CANDIDATESDF:
1592 inFile.getAbsolutePath());
1593
1594 case VRTXSDF:
1595 ArrayList<DGraph> graphs = new ArrayList<DGraph>();
1596 ArrayList<Vertex> vertexes = readVertexes(inFile,
1598 for (Vertex v : vertexes)
1599 {
1600 if (v instanceof Template)
1601 {
1602 graphs.add(((Template)v).getInnerGraph());
1603 }
1604 }
1605 System.out.println("WARNING: Reading graphs from "
1606 + FileFormat.VRTXSDF + " file can only read the "
1607 + "templates' inner graphs. Importing "
1608 + graphs.size() + " graphs "
1609 + "from " + vertexes.size() + " vertexes.");
1610 return graphs;
1611
1612 default:
1613 throw new Exception("Format '" + format + "' could not be used "
1614 + "to read graphs from file '" + inFile + "'.");
1615 }
1616 }
1617
1618//------------------------------------------------------------------------------
1619
1627 public static ArrayList<DGraph> readDENOPTIMGraphsFromSDFile(
1628 String fileName) throws DENOPTIMException
1629 {
1630 ArrayList<DGraph> lstGraphs = new ArrayList<DGraph>();
1631 ArrayList<IAtomContainer> mols = DenoptimIO.readSDFFile(fileName);
1632 int i = 0;
1633 for (IAtomContainer mol : mols)
1634 {
1635 i++;
1636 DGraph g = readGraphFromSDFileIAC(mol,i,fileName);
1637 lstGraphs.add(g);
1638 }
1639 return lstGraphs;
1640 }
1641
1642//------------------------------------------------------------------------------
1643
1653 public static DGraph readGraphFromSDFileIAC(IAtomContainer mol)
1654 throws DENOPTIMException
1655 {
1656 return readGraphFromSDFileIAC(mol, -1, "");
1657 }
1658
1659//------------------------------------------------------------------------------
1660
1670 public static DGraph readGraphFromSDFileIAC(IAtomContainer mol,
1671 int molId) throws DENOPTIMException
1672 {
1673 return readGraphFromSDFileIAC(mol, molId, "");
1674 }
1675
1676//------------------------------------------------------------------------------
1677
1691 public static DGraph readGraphFromSDFileIAC(IAtomContainer mol,
1692 int molId, String fileName) throws DENOPTIMException
1693 {
1694 // Something very similar is done also in Candidate
1695 DGraph g = null;
1696 Object json = mol.getProperty(DENOPTIMConstants.GRAPHJSONTAG);
1697 if (json == null) {
1698 Object graphEnc = mol.getProperty(DENOPTIMConstants.GRAPHTAG);
1699 if (graphEnc!=null)
1700 {
1701 throw new DENOPTIMException("Use of '"
1702 + DENOPTIMConstants.GRAPHTAG + "' is deprecated. SDF "
1703 + "files containing graphs must include the "
1704 + "tag '" + DENOPTIMConstants.GRAPHJSONTAG + "'.");
1705 }
1706 String msg = "Attempt to load graph form "
1707 + "SDF that has no '" + DENOPTIMConstants.GRAPHJSONTAG
1708 + "' tag.";
1709 if (molId>-1)
1710 {
1711 msg = msg + " Check molecule " + molId;
1712 if (!fileName.isEmpty())
1713 {
1714 msg = msg + " in the SDF file '" + fileName + "'";
1715 } else {
1716 msg = msg + ".";
1717 }
1718 }
1719 throw new DENOPTIMException(msg);
1720 } else {
1721 String js = json.toString();
1722 try
1723 {
1724 g = DGraph.fromJson(js);
1725 } catch (Exception e)
1726 {
1727 String msg = e.getMessage();
1728 if (molId>-1)
1729 {
1730 msg = msg + " Check molecule " + molId;
1731 if (!fileName.isEmpty())
1732 {
1733 msg = msg + " in the SDF file '" + fileName + "'";
1734 } else {
1735 msg = msg + ".";
1736 }
1737 }
1738 throw new DENOPTIMException(msg, e);
1739 }
1740 }
1741 return g;
1742 }
1743
1744//------------------------------------------------------------------------------
1745
1753 public static ArrayList<DGraph> readDENOPTIMGraphsFromTxtFile(
1754 String fileName, FragmentSpace fragSpace, Logger logger)
1755 throws DENOPTIMException
1756 {
1757 ArrayList<DGraph> lstGraphs = new ArrayList<DGraph>();
1758 BufferedReader br = null;
1759 String line = null;
1760 try {
1761 br = new BufferedReader(new FileReader(fileName));
1762 while ((line = br.readLine()) != null) {
1763 if (line.trim().length() == 0) {
1764 continue;
1765 }
1766
1767 if (line.startsWith(DENOPTIMConstants.APCMAPIGNORE)) {
1768 continue;
1769 }
1770
1771 DGraph g;
1772 try {
1773 g = GraphConversionTool.getGraphFromString(line.trim(),
1774 fragSpace);
1775 } catch (Throwable t) {
1776 String msg = "Cannot convert string to DENOPTIMGraph. "
1777 + "Check line '" + line.trim() + "'";
1778 logger.log(Level.SEVERE, msg);
1779 throw new DENOPTIMException(msg, t);
1780 }
1781 lstGraphs.add(g);
1782 }
1783 } catch (IOException ioe) {
1784 String msg = "Cannot read file " + fileName;
1785 logger.log(Level.SEVERE, msg);
1786 throw new DENOPTIMException(msg, ioe);
1787 } finally {
1788 try {
1789 if (br != null) {
1790 br.close();
1791 }
1792 } catch (IOException ioe) {
1793 throw new DENOPTIMException(ioe);
1794 }
1795 }
1796 return lstGraphs;
1797 }
1798
1799//------------------------------------------------------------------------------
1800
1801 //TODO-v3+ this method should be almost a copy of the one working on graphs.
1802 // It should be possible to have one method do both tasks.
1803
1810 public static ArrayList<Vertex> readDENOPTIMVertexesFromJSONFile(
1811 String fileName) throws DENOPTIMException
1812 {
1813 ArrayList<Vertex> result = new ArrayList<Vertex>();
1814 Gson reader = DENOPTIMgson.getReader();
1815
1816 BufferedReader br = null;
1817 try
1818 {
1819 br = new BufferedReader(new FileReader(fileName));
1820 result = reader.fromJson(br,
1821 new TypeToken<ArrayList<Vertex>>(){}.getType());
1822 }
1823 catch (FileNotFoundException fnfe)
1824 {
1825 throw new DENOPTIMException("File '" + fileName + "' not found.");
1826 }
1827 catch (JsonSyntaxException jse)
1828 {
1829 String msg = "Expected BEGIN_ARRAY but was BEGIN_OBJECT";
1830 if (jse.getMessage().contains(msg))
1831 {
1832 // The file contains a single object, not a list. We try to read
1833 // that single object as a DENOPTIMVertex
1834 try
1835 {
1836 br.close();
1837 br = new BufferedReader(new FileReader(fileName));
1838 }
1839 catch (FileNotFoundException fnfe)
1840 {
1841 //cannot happen
1842 } catch (IOException ioe)
1843 {
1844 throw new DENOPTIMException(ioe);
1845 }
1846 Vertex v = reader.fromJson(br,Vertex.class);
1847 result.add(v);
1848 } else {
1849 throw new DENOPTIMException("ERROR! Unable to read vertex from '"
1850 + fileName + "'.", jse);
1851 }
1852 }
1853 finally
1854 {
1855 try {
1856 if (br != null)
1857 {
1858 br.close();
1859 }
1860 } catch (IOException ioe) {
1861 throw new DENOPTIMException(ioe);
1862 }
1863 }
1864
1865 return result;
1866 }
1867
1868//------------------------------------------------------------------------------
1869
1876 public static ArrayList<DGraph> readDENOPTIMGraphsFromJSONFile(
1877 String fileName) throws DENOPTIMException
1878 {
1879 ArrayList<DGraph> list_of_graphs = new ArrayList<DGraph>();
1880 Gson reader = DENOPTIMgson.getReader();
1881
1882 BufferedReader br = null;
1883 try
1884 {
1885 br = new BufferedReader(new FileReader(fileName));
1886 list_of_graphs = reader.fromJson(br,
1887 new TypeToken<ArrayList<DGraph>>(){}.getType());
1888 }
1889 catch (FileNotFoundException fnfe)
1890 {
1891 throw new DENOPTIMException("File '" + fileName + "' not found.");
1892 }
1893 catch (JsonSyntaxException jse)
1894 {
1895 String msg = "Expected BEGIN_ARRAY but was BEGIN_OBJECT";
1896 if (jse.getMessage().contains(msg))
1897 {
1898 // The file contains a single object, not a list. We try to read
1899 // that single object as a DENOPTIMGraph
1900 try
1901 {
1902 br.close();
1903 br = new BufferedReader(new FileReader(fileName));
1904 }
1905 catch (FileNotFoundException fnfe)
1906 {
1907 //cannot happen
1908 } catch (IOException ioe)
1909 {
1910 throw new DENOPTIMException(ioe);
1911 }
1912 DGraph g = reader.fromJson(br,DGraph.class);
1913 list_of_graphs.add(g);
1914 } else {
1915 throw new DENOPTIMException("ERROR! Unable to read graph from "
1916 + "JSON '" + fileName + "'", jse);
1917 }
1918 }
1919 finally
1920 {
1921 try {
1922 if (br != null)
1923 {
1924 br.close();
1925 }
1926 } catch (IOException ioe) {
1927 throw new DENOPTIMException(ioe);
1928 }
1929 }
1930
1931 return list_of_graphs;
1932 }
1933
1934//------------------------------------------------------------------------------
1935
1944 public static File writeGraphToFile(File file, FileFormat format,
1945 DGraph graph, Logger logger, Randomizer randomizer)
1946 throws DENOPTIMException
1947 {
1948 if (FilenameUtils.getExtension(file.getName()).equals(""))
1949 {
1950 file = new File(file.getAbsoluteFile()+"."+format.getExtension());
1951 }
1952 switch (format)
1953 {
1954 case GRAPHJSON:
1955 writeGraphToJSON(file, graph);
1956 break;
1957
1958 case GRAPHSDF:
1959 writeGraphToSDF(file, graph, false, true, logger, randomizer);
1960 break;
1961
1962 default:
1963 throw new DENOPTIMException("Cannot write graph with format '"
1964 + format + "'.");
1965 }
1966 return file;
1967 }
1968
1969//------------------------------------------------------------------------------
1970
1980 public static File writeGraphsToFile(File file, FileFormat format,
1981 List<DGraph> modGraphs, Logger logger, Randomizer randomizer)
1982 throws DENOPTIMException
1983 {
1984 if (FilenameUtils.getExtension(file.getName()).equals(""))
1985 {
1986 file = new File(file.getAbsoluteFile()+"."+format.getExtension());
1987 }
1988 switch (format)
1989 {
1990 case GRAPHJSON:
1991 writeGraphsToJSON(file, modGraphs);
1992 break;
1993
1994 case GRAPHSDF:
1995 writeGraphsToSDF(file, modGraphs, false, true, logger, randomizer);
1996 break;
1997
1998 default:
1999 throw new DENOPTIMException("Cannot write graphs with format '"
2000 + format + "'.");
2001 }
2002 return file;
2003 }
2004
2005//------------------------------------------------------------------------------
2006
2014 public static void writeGraphsToSDF(File file,
2015 List<DGraph> graphs, Logger logger, Randomizer randomizer)
2016 throws DENOPTIMException
2017 {
2018 writeGraphsToSDF(file, graphs, false, logger, randomizer);
2019 }
2020
2021//------------------------------------------------------------------------------
2022
2032 public static void writeGraphToSDF(File file, DGraph graph,
2033 boolean append, boolean make3D, Logger logger, Randomizer randomizer)
2034 throws DENOPTIMException
2035 {
2036 List<DGraph> lst = new ArrayList<>(1);
2037 lst.add(graph);
2038 writeGraphsToSDF(file, lst, append, make3D, logger, randomizer);
2039 }
2040
2041//------------------------------------------------------------------------------
2042
2051 public static void writeGraphToSDF(File file, DGraph graph,
2052 boolean append, Logger logger, Randomizer randomizer)
2053 throws DENOPTIMException
2054 {
2055 ArrayList<DGraph> lst = new ArrayList<>(1);
2056 lst.add(graph);
2057 writeGraphsToSDF(file, lst, append, logger, randomizer);
2058 }
2059
2060//------------------------------------------------------------------------------
2061
2070 public static void writeGraphsToSDF(File file,
2071 List<DGraph> graphs, boolean append,
2072 Logger logger, Randomizer randomizer) throws DENOPTIMException
2073 {
2074 writeGraphsToSDF(file, graphs, append, false, logger, randomizer);
2075 }
2076
2077//------------------------------------------------------------------------------
2078
2089 public static void writeGraphsToSDF(File file,
2090 List<DGraph> modGraphs, boolean append, boolean make3D,
2091 Logger logger, Randomizer randomizer) throws DENOPTIMException
2092 {
2093 ArrayList<IAtomContainer> lst = new ArrayList<IAtomContainer>();
2094 for (DGraph g : modGraphs)
2095 {
2096 ThreeDimTreeBuilder tb = new ThreeDimTreeBuilder(logger, randomizer);
2097 IAtomContainer iac = builder.newAtomContainer();
2098 if (make3D)
2099 {
2100 try {
2101 iac = tb.convertGraphTo3DAtomContainer(g, true);
2102 } catch (Throwable t) {
2103 t.printStackTrace();
2104 logger.log(Level.WARNING,"Couldn't make 3D-tree "
2105 + "representation: " + t.getMessage());
2106 }
2107 } else {
2108 GraphUtils.writeSDFFields(iac, g);
2109 }
2110 lst.add(iac);
2111 }
2112 writeSDFFile(file.getAbsolutePath(), lst, append);
2113 }
2114
2115//------------------------------------------------------------------------------
2116
2124 public static void writeGraphToJSON(File file, DGraph graph)
2125 throws DENOPTIMException
2126 {
2127 ArrayList<DGraph> graphs = new ArrayList<DGraph>();
2128 graphs.add(graph);
2129 writeGraphsToJSON(file, graphs);
2130 }
2131
2132//------------------------------------------------------------------------------
2133
2141 public static void writeGraphsToJSON(File file,
2142 List<DGraph> graphs) throws DENOPTIMException
2143 {
2144 Gson writer = DENOPTIMgson.getWriter();
2145 writeData(file.getAbsolutePath(), writer.toJson(graphs), false);
2146 }
2147
2148//------------------------------------------------------------------------------
2149
2158 public static void writeGraphsToJSON(File file,
2159 List<DGraph> graphs, boolean append) throws DENOPTIMException
2160 {
2161 Gson writer = DENOPTIMgson.getWriter();
2162 writeData(file.getAbsolutePath(), writer.toJson(graphs), append);
2163 }
2164
2165//------------------------------------------------------------------------------
2166
2175 public static void writeGraphToFile(String fileName, DGraph graph,
2176 boolean append) throws DENOPTIMException
2177 {
2178 writeData(fileName, graph.toString(), append);
2179 }
2180
2181//------------------------------------------------------------------------------
2182
2190 public static Map<File, FileFormat> readRecentFilesMap()
2191 {
2192 Map<File, FileFormat> map = new LinkedHashMap<File, FileFormat>();
2193 if (!DENOPTIMConstants.RECENTFILESLIST.exists())
2194 {
2195 return map;
2196 }
2197 try
2198 {
2199 for (String line : DenoptimIO.readList(
2200 DENOPTIMConstants.RECENTFILESLIST.getAbsolutePath(), true))
2201 {
2202 line = line.trim();
2203 String[] parts = line.split("\\s+");
2204 String ffStr = parts[0];
2205 FileFormat ff = null;
2206 try
2207 {
2208 ff = FileFormat.valueOf(FileFormat.class, ffStr);
2209 } catch (Exception e)
2210 {
2211 throw new DENOPTIMException("Unable to convert '" + ffStr
2212 + "' to a known file format.");
2213 }
2214 String fileName = line.substring(ffStr.length()).trim();
2215 if (FileUtils.checkExists(fileName))
2216 {
2217 map.put(new File(fileName), ff);
2218 }
2219 }
2220 } catch (DENOPTIMException e)
2221 {
2222 StaticLogger.appLogger.log(Level.WARNING, "WARNING: unable to "
2223 + "fetch list of recent files.", e);
2224 map = new HashMap<File, FileFormat>();
2225 }
2226 return map;
2227 }
2228
2229//------------------------------------------------------------------------------
2230
2244 public static ArrayList<Vertex> readVertexes(File file,
2246 IOException, IllegalArgumentException, DENOPTIMException
2247 {
2248 ArrayList<Vertex> vertexes = new ArrayList<Vertex>();
2250 switch (ff)
2251 {
2252 case VRTXSDF:
2254 file.getAbsolutePath(),bbt);
2255 break;
2256
2257 case VRTXJSON:
2259 file.getAbsolutePath());
2260 break;
2261
2262 case GRAPHSDF:
2263 ArrayList<DGraph> lstGraphs =
2264 readDENOPTIMGraphsFromSDFile(file.getAbsolutePath());
2265 for (DGraph g : lstGraphs)
2266 {
2267 Template t = new Template(bbt);
2268 t.setInnerGraph(g);
2269 vertexes.add(t);
2270 }
2271 break;
2272
2273 case GRAPHJSON:
2274 ArrayList<DGraph> lstGraphs2 =
2275 readDENOPTIMGraphsFromJSONFile(file.getAbsolutePath());
2276 for (DGraph g : lstGraphs2)
2277 {
2278 Template t = new Template(bbt);
2279 t.setInnerGraph(g);
2280 vertexes.add(t);
2281 }
2282 break;
2283
2284 default:
2285 throw new DENOPTIMException("Format '" + ff
2286 + "' could not be used to "
2287 + "read in vertices from file '" + file + "'.");
2288 }
2289 return vertexes;
2290 }
2291
2292//------------------------------------------------------------------------------
2293
2301 public static ArrayList<Vertex> readDENOPTIMVertexesFromSDFile(
2302 String fileName, Vertex.BBType bbt) throws DENOPTIMException
2303 {
2304 ArrayList<Vertex> vertexes = new ArrayList<Vertex>();
2305 int i=0;
2306 Gson reader = DENOPTIMgson.getReader();
2307 for (IAtomContainer mol : readSDFFile(fileName))
2308 {
2309 i++;
2310 Vertex v = null;
2311 try
2312 {
2313 v = Vertex.parseVertexFromSDFFormat(mol, reader, bbt);
2314 } catch (DENOPTIMException e)
2315 {
2316 throw new DENOPTIMException("Unable to read vertex " + i
2317 + " in file " + fileName,e);
2318 }
2319 vertexes.add(v);
2320 }
2321 return vertexes;
2322 }
2323
2324//------------------------------------------------------------------------------
2325
2342 public static LinkedHashMap<String, String> readCSDFormulae(File file)
2343 throws DENOPTIMException
2344 {
2345 LinkedHashMap<String, String> allFormulae = new LinkedHashMap<String,String>();
2346 BufferedReader buffRead = null;
2347 try {
2348 //Read the file line by line
2349 buffRead = new BufferedReader(new FileReader(file));
2350 String lineAll = null;
2351 String refcode = "";
2352 String formula = "";
2353 while ((lineAll = buffRead.readLine()) != null)
2354 {
2355 String[] lineArgs = lineAll.split(":");
2356 //Get the name
2357 if (lineArgs[0].equals("REFCODE"))
2358 refcode = lineArgs[1].trim();
2359
2360 //Get the formula
2361 if (lineArgs[0].equals(" Formula"))
2362 {
2363 formula = lineArgs[1].trim();
2364 //Store formula
2365 allFormulae.put(refcode,formula);
2366 //Clean fields
2367 refcode = "";
2368 formula = "";
2369 }
2370 }
2371 } catch (FileNotFoundException fnf) {
2372 throw new DENOPTIMException("File Not Found: " + file, fnf);
2373 } catch (IOException ioex) {
2374 throw new DENOPTIMException("Error reading file: " + file, ioex);
2375 } finally {
2376 try {
2377 if (buffRead != null)
2378 buffRead.close();
2379 } catch (IOException e) {
2380 throw new DENOPTIMException("Error closing buffer to "+file, e);
2381 }
2382 }
2383
2384 return allFormulae;
2385 }
2386
2387//------------------------------------------------------------------------------
2388
2400 public static void readCuttingRules(BufferedReader reader,
2401 List<CuttingRule> cutRules, String source) throws DENOPTIMException
2402 {
2403 ArrayList<String> cutRulLines = new ArrayList<String>();
2404 try
2405 {
2406 String line = null;
2407 while ((line = reader.readLine()) != null)
2408 {
2409 if (line.trim().startsWith(DENOPTIMConstants.CUTRULKEYWORD))
2410 cutRulLines.add(line.trim());
2411 }
2412 } catch (IOException e)
2413 {
2414 throw new DENOPTIMException(e);
2415 } finally {
2416 if (reader != null)
2417 try
2418 {
2419 reader.close();
2420 } catch (IOException e)
2421 {
2422 throw new DENOPTIMException(e);
2423 }
2424 }
2425 readCuttingRules(cutRulLines, cutRules, source);
2426 }
2427
2428//------------------------------------------------------------------------------
2429
2438 public static void readCuttingRules(File file,
2439 List<CuttingRule> cutRules) throws DENOPTIMException
2440 {
2441 ArrayList<String> allLines = readList(file.getAbsolutePath());
2442
2443 //Now get the list of cutting rules
2444 ArrayList<String> cutRulLines = new ArrayList<String>();
2445 allLines.stream()
2446 .filter(line -> line.trim().startsWith(
2448 .forEach(line -> cutRulLines.add(line.trim()));
2449
2450 readCuttingRules(cutRulLines, cutRules, "file '"
2451 + file.getAbsolutePath()+ "'");
2452 }
2453
2454//------------------------------------------------------------------------------
2455
2469 public static void readCuttingRules(ArrayList<String> cutRulLines,
2470 List<CuttingRule> cutRules, String source) throws DENOPTIMException
2471 {
2472 Set<Integer> usedPriorities = new HashSet<Integer>();
2473 for (int i = 0; i<cutRulLines.size(); i++)
2474 {
2475 String[] words = cutRulLines.get(i).split("\\s+");
2476 String name = words[1]; //name of the rule
2477 if (words.length < 6)
2478 {
2479 throw new DENOPTIMException("ERROR in getting cutting rule."
2480 + " Found " + words.length + " parts inctead of 6."
2481 + "Check line '" + cutRulLines.get(i) + "'"
2482 + "in " + source + ".");
2483 }
2484
2485 // further details in map of options
2486 ArrayList<String> opts = new ArrayList<String>();
2487 if (words.length >= 7)
2488 {
2489 for (int wi=6; wi<words.length; wi++)
2490 {
2491 opts.add(words[wi]);
2492 }
2493 }
2494
2495 int priority = Integer.parseInt(words[2]);
2496 if (usedPriorities.contains(priority))
2497 {
2498 throw new DENOPTIMException("ERROR in getting cutting rule."
2499 + " Duplicate priority index " + priority + ". "
2500 + "Check line '" + cutRulLines.get(i) + "'"
2501 + "in " + source + ".");
2502 } else {
2503 usedPriorities.add(priority);
2504 }
2505
2506 CuttingRule rule = new CuttingRule(name,
2507 words[3], //atom1
2508 words[4], //atom2
2509 words[5], //bond between 1 and 2
2510 priority,
2511 opts);
2512
2513 cutRules.add(rule);
2514 }
2515
2516 Collections.sort(cutRules, new Comparator<CuttingRule>() {
2517
2518 @Override
2519 public int compare(CuttingRule r1, CuttingRule r2)
2520 {
2521 return Integer.compare(r1.getPriority(), r2.getPriority());
2522 }
2523
2524 });
2525 }
2526
2527//------------------------------------------------------------------------------
2528
2535 public static void writeCuttingRules(File file,
2536 List<CuttingRule> cutRules) throws DENOPTIMException
2537 {
2538 StringBuilder sb = new StringBuilder();
2539 for (CuttingRule r : cutRules)
2540 {
2541 sb.append(DENOPTIMConstants.CUTRULKEYWORD).append(" ");
2542 sb.append(r.getName()).append(" ");
2543 sb.append(r.getPriority()).append(" ");
2544 sb.append(r.getSMARTSAtom0()).append(" ");
2545 sb.append(r.getSMARTSAtom1()).append(" ");
2546 sb.append(r.getSMARTSBnd()).append(" ");
2547 if (r.getOptions()!=null)
2548 {
2549 for (String opt : r.getOptions())
2550 sb.append(opt).append(" ");
2551 }
2552 sb.append(NL);
2553 }
2554 writeData(file.getAbsolutePath(), sb.toString(), false);
2555 }
2556
2557//------------------------------------------------------------------------------
2558
2565 public static void appendTxtFiles(File f1, List<File> files) throws IOException
2566 {
2567 FileWriter fw;
2568 BufferedWriter bw;
2569 PrintWriter pw = null;
2570 try
2571 {
2572 fw = new FileWriter(f1, true);
2573 bw = new BufferedWriter(fw);
2574 pw = new PrintWriter(bw);
2575 for (File inFile : files)
2576 {
2577 FileReader fr;
2578 BufferedReader br = null;
2579 try
2580 {
2581 fr = new FileReader(inFile);
2582 br = new BufferedReader(fr);
2583 String line = null;
2584 while ((line = br.readLine()) != null)
2585 {
2586 pw.println(line);
2587 }
2588 } finally {
2589 if (br != null)
2590 br.close();
2591 }
2592 }
2593 } finally {
2594 if (pw!=null)
2595 pw.close();
2596 }
2597 }
2598
2599//------------------------------------------------------------------------------
2600
2609 public static List<BridgeHeadFindingRule> readBridgeHesFindingRules(
2610 String fileName) throws DENOPTIMException
2611 {
2612 List<BridgeHeadFindingRule> rules = null;
2613 BufferedReader br = null;
2614 try {
2615 br = new BufferedReader(new FileReader(fileName));
2616 rules = readBridgeHesFindingRules(br);
2617 }
2618 catch (FileNotFoundException fnfe)
2619 {
2620 throw new DENOPTIMException("File '" + fileName + "' not found.");
2621 } catch (IOException ioe)
2622 {
2623 throw new DENOPTIMException(ioe);
2624 }
2625 finally
2626 {
2627 try {
2628 if (br != null)
2629 {
2630 br.close();
2631 }
2632 } catch (IOException ioe) {
2633 throw new DENOPTIMException(ioe);
2634 }
2635 }
2636 return rules;
2637 }
2638
2639//------------------------------------------------------------------------------
2640
2650 public static List<BridgeHeadFindingRule> readBridgeHesFindingRules(
2651 BufferedReader br) throws IOException
2652 {
2653 List<BridgeHeadFindingRule> rules = new ArrayList<>();
2654 Gson reader = DENOPTIMgson.getReader();
2655 try
2656 {
2657 rules = reader.fromJson(br,
2658 new TypeToken<ArrayList<BridgeHeadFindingRule>>(){}.getType());
2659 }
2660 finally
2661 {
2662 if (br != null)
2663 {
2664 br.close();
2665 }
2666 }
2667 return rules;
2668 }
2669
2670//------------------------------------------------------------------------------
2671
2672}
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:102
static DGraph fromJson(String json)
Reads a JSON string and returns an instance of this class.
Definition: DGraph.java:6951
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:62
static Vertex parseVertexFromSDFFormat(IAtomContainer mol, Gson reader, BBType bbt)
Created a Vertex from the SDF representation, i.e., from an IAtomContainer.
Definition: Vertex.java:1454
static Vertex fromJson(String json)
Definition: Vertex.java:1290
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 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 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:38
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:87