23import java.io.IOException;
24import java.nio.file.Path;
25import java.text.DecimalFormat;
26import java.text.NumberFormat;
27import java.util.ArrayList;
28import java.util.Arrays;
29import java.util.Comparator;
30import java.util.HashMap;
31import java.util.HashSet;
32import java.util.Iterator;
34import java.util.Locale;
37import java.util.concurrent.atomic.AtomicInteger;
38import java.util.logging.Level;
39import java.util.logging.Logger;
40import java.util.stream.Collectors;
41import java.util.stream.IntStream;
43import org.apache.commons.io.FileUtils;
44import org.apache.commons.io.FilenameUtils;
45import org.openscience.cdk.graph.ShortestPaths;
46import org.openscience.cdk.interfaces.IAtom;
47import org.openscience.cdk.interfaces.IAtomContainer;
48import org.openscience.cdk.isomorphism.Mappings;
49import org.paukov.combinatorics3.Generator;
51import com.google.gson.Gson;
53import denoptim.constants.DENOPTIMConstants;
54import denoptim.exception.DENOPTIMException;
55import denoptim.fitness.FitnessParameters;
56import denoptim.fragmenter.BridgeHeadFindingRule;
57import denoptim.fragmenter.FragmenterTools;
58import denoptim.fragmenter.ScaffoldingPolicy;
59import denoptim.fragspace.FragmentSpace;
60import denoptim.fragspace.FragmentSpaceParameters;
61import denoptim.graph.APClass;
62import denoptim.graph.AttachmentPoint;
63import denoptim.graph.Candidate;
64import denoptim.graph.DGraph;
65import denoptim.graph.Edge.BondType;
66import denoptim.graph.EmptyVertex;
67import denoptim.graph.Fragment;
68import denoptim.graph.GraphPattern;
69import denoptim.graph.RelatedAPPair;
70import denoptim.graph.Ring;
71import denoptim.graph.SymmetricAPs;
72import denoptim.graph.SymmetricSet;
73import denoptim.graph.SymmetricSetWithMode;
74import denoptim.graph.Template;
75import denoptim.graph.Template.ContractLevel;
76import denoptim.graph.Vertex;
77import denoptim.graph.Vertex.BBType;
78import denoptim.graph.rings.CyclicGraphHandler;
79import denoptim.graph.rings.RingClosureParameters;
80import denoptim.graph.rings.RingClosuresArchive;
81import denoptim.io.DenoptimIO;
82import denoptim.json.DENOPTIMgson;
83import denoptim.logging.CounterID;
84import denoptim.logging.Monitor;
85import denoptim.molecularmodeling.ThreeDimTreeBuilder;
86import denoptim.programs.RunTimeParameters.ParametersType;
87import denoptim.programs.denovo.GAParameters;
88import denoptim.programs.fragmenter.CuttingRule;
89import denoptim.programs.fragmenter.FragmenterParameters;
90import denoptim.utils.DummyAtomHandler;
91import denoptim.utils.GeneralUtils;
92import denoptim.utils.GraphUtils;
93import denoptim.utils.ManySMARTSQuery;
94import denoptim.utils.MoleculeUtils;
95import denoptim.utils.Randomizer;
96import denoptim.utils.RotationalSpaceUtils;
97import denoptim.utils.SizeControlledSet;
98import denoptim.utils.StatUtils;
121 DecimalFormat
df = (DecimalFormat) NumberFormat.getNumberInstance(
123 df.setGroupingUsed(
false);
137 private static final String
NL =System.getProperty(
"line.separator");
138 private static final String
FSEP = System.getProperty(
"file.separator");
151 denoptim.files.FileUtils.createDirectory(
169 HashSet<String> lstUID =
new HashSet<>(1024);
170 if (!settings.getUIDFileIn().equals(
""))
173 for (String uid : lstUID)
175 uniqueIDsSet.addNewUniqueEntry(uid);
177 settings.getLogger().log(Level.INFO,
"Read " + lstUID.size()
178 +
" known UIDs from " + settings.getUIDFileIn());
182 int numFromInitGraphs = 0;
183 String initPopFile = settings.getInitialPopulationFile();
184 if (initPopFile.length() > 0)
189 numFromInitGraphs = population.size();
190 settings.getLogger().log(Level.INFO,
"Imported " + numFromInitGraphs
191 +
" candidates (as graphs) from " + initPopFile);
228 for (
int i=0; i<multiSiteMutationProb.length; i++)
229 tot = tot + multiSiteMutationProb[i];
231 double scaledHit = hit * tot;
236 for (
int i=0; i<multiSiteMutationProb.length; i++)
238 max = max + multiSiteMutationProb[i];
239 if (min < scaledHit && scaledHit <= max)
244 min = Math.max(min,min+multiSiteMutationProb[i]);
264 double xoverWeight,
double mutWeight,
double newWeight,
268 * (xoverWeight + mutWeight + newWeight);
269 if (hit <= xoverWeight)
272 }
else if (xoverWeight < hit && hit <= (mutWeight+xoverWeight))
294 List<Candidate> eligibleParents,
Population population,
298 null, -1, -1, settings, settings.maxOffsprintFromXover());
314 List<Candidate> eligibleParents,
Population population,
318 null, -1, -1, settings);
348 List<Candidate> eligibleParents,
Population population,
349 Monitor mnt,
int[] choiceOfParents,
int choiceOfXOverSites,
355 choiceOfParents, choiceOfXOverSites, choiceOfOffstring,
393 List<Candidate> eligibleParents,
Population population,
394 Monitor mnt,
int[] choiceOfParents,
int choiceOfXOverSites,
414 boolean foundPars =
false;
415 while (numatt < settings.getMaxGeneticOpAttempts())
420 population, choiceOfParents, choiceOfXOverSites,
430 eligibleParents, 2, settings);
431 if (parents[0] ==
null || parents[1] ==
null)
438 List<Vertex> subGraphA =
new ArrayList<Vertex>();
440 gpA, settings.getRandomizer()),subGraphA);
443 List<Vertex> subGraphB =
new ArrayList<Vertex>();
445 gpB, settings.getRandomizer()),subGraphB);
456 return new ArrayList<Candidate>();
460 Vertex vA =
null, vB =
null;
461 vA = xos.
getA().get(0);
462 vB = xos.
getB().get(0);
465 DGraph gB = vB.getGraphOwner();
469 String candIdB = cB.getName();
475 DGraph gAClone = xosOnClones.
getA().get(0).getGraphOwner();
476 DGraph gBClone = xosOnClones.
getB().get(0).getGraphOwner();
484 return new ArrayList<Candidate>();
486 }
catch (Throwable t) {
487 if (!settings.xoverFailureTolerant)
490 ArrayList<DGraph> parents =
new ArrayList<DGraph>();
494 +
"_failed_xover.sdf"), parents,
true,
495 settings.getLogger(), settings.getRandomizer());
498 +
"XOverSite(C): " + xosOnClones.
toString() +
NL
499 +
" Please, report this to the authors ",t);
503 return new ArrayList<Candidate>();
509 lstIdVA = lstIdVA +
"_" + v.getVertexId();
512 lstIdVB = lstIdVB +
"_" + v.getVertexId();
513 String[] msgs =
new String[2];
516 +
"|" + gid1 +
"|" + lstIdVA
518 +
"Gen:" + cB.getGeneration() +
" Cand:" + candIdB
519 +
"|" + gid2 +
"|" + lstIdVB;
521 +
"Gen:" + cB.getGeneration() +
" Cand:" + candIdB
522 +
"|" + gid2 +
"|" + lstIdVB
525 +
"|" + gid1 +
"|" + lstIdVA;
528 graphsAffectedByXover[0] = gAClone;
529 graphsAffectedByXover[1] = gBClone;
531 List<Candidate> validOffspring =
new Population(settings);
532 for (
int ig=0; ig<graphsAffectedByXover.length; ig++)
534 DGraph g = graphsAffectedByXover[ig];
556 }
catch (NullPointerException|IllegalArgumentException e)
558 if (!settings.xoverGraphFailedEvalTolerant)
560 ArrayList<DGraph> parents =
new ArrayList<DGraph>();
563 parents.add(gAClone);
564 parents.add(gBClone);
566 +
"_failed_xover-ed_check.sdf"), parents,
true,
567 settings.getLogger(), settings.getRandomizer());
587 APClass apc = rcv.getEdgeToParent().getSrcAP().getAPClass();
605 offspring.
setUID(res[0].toString().trim());
606 offspring.
setSmiles(res[1].toString().trim());
609 validOffspring.add(offspring);
612 if (validOffspring.size() == 0)
615 return new ArrayList<Candidate>();
618 if (maxCandidatesToReturn==1)
621 if (choiceOfOffstring<0)
623 chosenOffspring = settings.getRandomizer().randomlyChooseOne(
629 chosenOffspring = validOffspring.get(choiceOfOffstring);
631 validOffspring.retainAll(Arrays.asList(chosenOffspring));
640 return validOffspring;
646 List<Candidate> eligibleParents,
Monitor mnt,
662 while (numatt < settings.getMaxGeneticOpAttempts())
682 String parentMolName = FilenameUtils.getBaseName(parent.
getSDFFile());
685 +
" Gen:" + parent.
getGeneration() +
" Cand:" + parentMolName
686 +
"|" + parentGraphId);
703 }
catch (NullPointerException|IllegalArgumentException e)
705 if (!settings.mutatedGraphFailedEvalTolerant)
707 settings.getLogger().log(Level.INFO,
"WRITING DEBUG FILE for "
710 parent.
getGraph(),
false, settings.getLogger(),
711 settings.getRandomizer());
713 graph,
false, settings.getLogger(),
714 settings.getRandomizer());
738 APClass apc = rcv.getEdgeToParent().getSrcAP().getAPClass();
756 offspring.
setUID(res[0].toString().trim());
757 offspring.
setSmiles(res[1].toString().trim());
775 ArrayList<DGraph> graphs;
779 }
catch (Exception e)
783 String msg =
"Could not read graphs from file " + srcFile
784 +
". No candidate generated!";
785 settings.getLogger().log(Level.SEVERE, msg);
788 if (graphs.size() == 0 || graphs.size() > 1)
791 String msg =
"Found " + graphs.size() +
" graphs in file " + srcFile
792 +
". I expect one and only one graph. "
793 +
"No candidate generated!";
794 settings.getLogger().log(Level.SEVERE, msg);
798 DGraph graph = graphs.get(0);
802 String msg =
"Null graph from file " + srcFile
803 +
". Expected one and only one graph. "
804 +
"No candidate generated!";
805 settings.getLogger().log(Level.SEVERE, msg);
825 candidate.
setUID(res[0].toString().trim());
826 candidate.
setSmiles(res[1].toString().trim());
833 String msg =
"Candidate " + candidate.
getName() +
" is imported from "
835 settings.getLogger().log(Level.INFO, msg);
890 if (rcv.getEdgeToParent() ==
null)
895 if (rcv.getEdgeToParent() ==
null)
900 APClass apc = rcv.getEdgeToParent().getSrcAP().getAPClass();
917 candidate.
setUID(res[0].toString().trim());
918 candidate.
setSmiles(res[1].toString().trim());
965 +
"fragmentation but no cutting rules provided. Please,"
966 +
"add FRG-CUTTINGRULESFILE=path/to/your/file to the "
988 String msg =
"Unable to convert molecule (" + mol.getAtomCount()
989 +
" atoms) to DENOPTIM graph. " + de.getMessage();
990 settings.getLogger().log(Level.WARNING, msg);
1009 candidate.
setUID(res[0].toString().trim());
1010 candidate.
setSmiles(res[1].toString().trim());
1034 List<CuttingRule> cuttingRules, Logger logger,
1060 List<CuttingRule> cuttingRules, Logger logger,
1084 List<CuttingRule> cuttingRules, Logger logger,
1089 scaffoldingPolicy, 190, fragSpace);
1112 List<CuttingRule> cuttingRules, Logger logger,
1118 scaffoldingPolicy, linearAngleLimit,
false,
null,
1146 List<CuttingRule> cuttingRules, Logger logger,
1148 boolean embedRingsInTemplates,
ContractLevel ringTmplContract,
1154 cuttingRules, logger);
1155 for (
Vertex v : fragments)
1165 if (fragments.size()==0)
1172 + mol.getAtomCount() +
" atoms produced 0 fragments.");
1177 switch (scaffoldingPolicy)
1181 for (
Vertex v : fragments)
1185 boolean setAsScaffold =
false;
1187 for (IAtom atm : iac.atoms())
1189 if (scaffoldingPolicy.label.equals(
1192 setAsScaffold =
true;
1207 case LARGEST_FRAGMENT:
1210 scaffold = fragments.stream()
1211 .max(Comparator.comparing(
1214 }
catch (Exception e)
1221 +
"among " + fragments.size() +
" fragments.", e);
1233 +
"identified as the "
1242 AtomicInteger vId =
new AtomicInteger(1);
1243 for (
int i=1; i<fragments.size(); i++)
1253 if (fragSpace!=
null && fragSpace.getCappingMap()!=
null)
1257 if (v.getAttachmentPoints().size()!=1 || v.isRCV())
1260 APClass srcAPC = v.getAP(0).getLinkedAPThroughout().getAPClass();
1261 APClass capAPC = fragSpace.getAPClassOfCappingVertex(srcAPC);
1262 Vertex cap = fragSpace.getCappingVertexWithAPClass(capAPC);
1274 v.getAP(0).setAPClass(capAPC);
1279 if (embedRingsInTemplates)
1283 fragSpace, ringTmplContract);
1303 Vertex lastlyAdded =
null;
1304 for (
int i=-1; i>-4; i--)
1306 lastlyAdded = graph.getVertexList().get(
1307 graph.getVertexList().size()+i);
1308 if (!lastlyAdded.
isRCV())
1313 if (!apI.isAvailable())
1316 for (
int j=0; j<vertexes.size(); j++)
1318 Vertex fragJ = vertexes.get(j);
1320 boolean ringClosure =
false;
1321 if (graph.containsVertex(fragJ))
1330 if (apI.getCutId()==apJ.getCutId())
1339 graph.appendVertexOnAP(apI, rcvI.
getAP(0));
1345 graph.appendVertexOnAP(apJ, rcvJ.
getAP(0));
1346 graph.addRing(rcvI, rcvJ);
1350 graph.appendVertexOnAP(apI, apJ);
1376 String filename,
GAParameters settings,
boolean printpathNames)
1379 StringBuilder sb =
new StringBuilder(512);
1383 df.setMaximumFractionDigits(settings.getPrecisionLevel());
1384 df.setMinimumFractionDigits(settings.getPrecisionLevel());
1389 synchronized (population)
1391 List<Candidate> popMembers =
new ArrayList<Candidate>();
1392 for (
int i=0; i<settings.getPopulationSize(); i++)
1395 popMembers.add(mol);
1400 sb.append(String.format(
"%-20s", mname));
1402 sb.append(String.format(
"%-20s",
1404 sb.append(String.format(
"%-30s", mol.
getUID()));
1412 sb.append(System.getProperty(
"line.separator"));
1419 if (settings.savePopFile())
1421 File dest =
new File(filename.replaceAll(
"\\.txt$",
".sdf"));
1425 if (stats.trim().length() > 0)
1442 StringBuilder sb =
new StringBuilder(128);
1443 sb.append(
NL+
NL+
"#####POPULATION SUMMARY#####"+
NL);
1444 int n = popln.size();
1445 sb.append(String.format(
"%-30s",
"SIZE:"));
1446 sb.append(String.format(
"%12s", n));
1450 sb.append(String.format(
"%-30s",
"MAX:")).append(
df.format(f));
1453 sb.append(String.format(
"%-30s",
"MIN:")).append(
df.format(f));
1456 sb.append(String.format(
"%-30s",
"MEAN:")).append(
df.format(f));
1459 sb.append(String.format(
"%-30s",
"MEDIAN:")).append(
df.format(f));
1462 sb.append(String.format(
"%-30s",
"STDDEV:")).append(
df.format(f));
1467 sb.append(String.format(
"%-30s",
"SKEW:")).append(
df.format(f));
1470 sb.append(String.format(
"%-30s",
"SKEW:")).append(
" NaN (sdev too small)");
1474 res = sb.toString();
1492 List<Candidate> eligibleParents,
int number,
GAParameters settings)
1516 for (
int i=0; i < mates.length; i++)
1519 matesStr = matesStr + settings.
NL;
1520 matesStr = matesStr + mates[i].
getUID();
1529 e.printStackTrace();
1544 List<Vertex> candidates =
new ArrayList<Vertex>(
1546 candidates.removeIf(v ->
1548 || v.getBuildingBlockType() ==
BBType.
CAP);
1570 List<Candidate> eligibleParents,
Population population,
1571 int[] choiceOfParents,
int choiceOfXOverSites,
GAParameters settings)
1574 if (choiceOfParents==
null)
1577 parentA = eligibleParents.get(choiceOfParents[0]);
1579 if (parentA ==
null)
1590 parentA, eligibleParents, fragSpace);
1591 if (matesCompatibleWithFirst.size() == 0)
1595 if (choiceOfParents==
null)
1600 parentB = eligibleParents.get(choiceOfParents[1]);
1602 if (parentB ==
null)
1606 if (choiceOfXOverSites<0)
1612 choiceOfXOverSites);
1622 StringBuilder sb =
new StringBuilder(32);
1630 return sb.toString();
1638 StringBuilder sb =
new StringBuilder(32);
1650 return sb.toString();
1657 StringBuilder sb =
new StringBuilder(32);
1659 return sb.toString();
1667 StringBuilder sb =
new StringBuilder(32);
1669 .append(
FSEP).append(
"Final.txt");
1670 return sb.toString();
1689 denoptim.files.FileUtils.createDirectory(dirName);
1690 File fileDir =
new File(dirName);
1692 boolean intermediateCandidatesAreOnDisk =
1696 for (
int i=0; i<popln.size(); i++)
1703 if (intermediateCandidatesAreOnDisk && sdfile!=
null)
1705 FileUtils.copyFileToDirectory(
new File(sdfile), fileDir);
1707 File candFile =
new File(fileDir, c.
getName()
1712 }
catch (IOException ioe) {
1714 + sdfile +
"' to '" + fileDir +
"' for candidate "
1717 if (imgfile !=
null && intermediateCandidatesAreOnDisk)
1720 FileUtils.copyFileToDirectory(
new File(imgfile), fileDir);
1721 }
catch (IOException ioe) {
1723 + imgfile +
"' to '" + fileDir +
"' for candidate "
1749 new File(filename),
true);
1750 if (candidates.size() == 0)
1752 String msg =
"Found 0 candidates in file " + filename;
1753 settings.getLogger().log(Level.SEVERE, msg);
1759 if (uniqueIDsSet.addNewUniqueEntry(candidate.getUID()))
1765 candidate.setName(molName);
1766 candidate.getGraph().setGraphId(gctr);
1767 candidate.getGraph().setLocalMsg(
"INITIAL_POPULATION");
1768 String sdfPathName = genDir + System.getProperty(
"file.separator")
1770 candidate.setSDFFile(sdfPathName);
1771 candidate.setImageFile(
null);
1777 population.add(candidate);
1779 settings.getLogger().log(Level.WARNING,
"Candidate from intial "
1780 +
"population file '" + filename
1781 +
"' is rejected because its identifier is "
1782 +
"already listed among the previously visited "
1787 if (population.isEmpty())
1789 String msg =
"Population is still empty after having processes "
1790 + candidates.size() +
" candidates from file " + filename;
1791 settings.getLogger().log(Level.SEVERE, msg);
1800 protected static void writeUID(String outfile, HashSet<String> lstInchi,
1803 StringBuilder sb =
new StringBuilder(256);
1804 Iterator<String> iter = lstInchi.iterator();
1806 boolean first =
true;
1807 while(iter.hasNext())
1811 sb.append(iter.next());
1816 sb.append(
NL).append(iter.next());
1836 long val = Long.MIN_VALUE;
1839 DGraph g = popln1.getGraph();
1876 && !((
Template) scafVertex).getContractLevel().equals(
1880 mnt.name =
"IntraTemplateBuild";
1882 settings.getExcludedMutationTypes());
1883 for (
Vertex mutableSite : initialMutableSites)
1925 if (!(scafVertex instanceof
Template)
1975 settings.getRandomizer());
1980 String rotoSpaceFile =
"";
1987 true, settings.getLogger());
1994 boolean onlyRandomCombOfRings =
true;
1996 if (onlyRandomCombOfRings)
2000 if (combsOfRings.size() > 0)
2002 for (
Ring ring : combsOfRings)
2005 double shot = settings.getRandomizer().nextDouble();
2007 ring.getHeadVertex().getEdgeToParent().getSrcAP(),
2010 ring.getTailVertex().getEdgeToParent().getSrcAP(),
2017 if (shot < crowdProbH && shot < crowdProbT)
2019 molGraph.addRing(ring);
2026 ArrayList<List<Ring>> allCombsOfRings =
2032 ArrayList<List<Ring>> toRemove =
new ArrayList<>();
2033 for (List<Ring> setRings : allCombsOfRings)
2037 toRemove.add(setRings);
2041 allCombsOfRings.removeAll(toRemove);
2042 if (allCombsOfRings.isEmpty())
2044 String msg =
"Setup Rings: no combination of rings.";
2045 settings.getLogger().log(Level.INFO, msg);
2051 int sz = allCombsOfRings.size();
2054 List<Ring> selected =
new ArrayList<>();
2057 selected = allCombsOfRings.get(0);
2061 int selId = settings.getRandomizer().nextInt(sz);
2062 selected = allCombsOfRings.get(selId);
2066 for (
Ring ring : selected)
2068 molGraph.addRing(ring);
2084 settings.getLogger());
2085 if (molsmiles ==
null)
2087 String msg =
"Evaluation of graph: SMILES is null! "
2088 + molGraph.toString();
2089 settings.getLogger().log(Level.INFO, msg);
2090 molsmiles =
"FAIL: NO SMILES GENERATED";
2099 settings.getLogger());
2100 if (inchikey ==
null)
2102 String msg =
"Evaluation of graph: INCHI is null!";
2103 settings.getLogger().log(Level.INFO, msg);
2104 inchikey =
"UNDEFINED";
2128 if (mol.getUID().compareToIgnoreCase(molcode) == 0)
2146 int k = mols.size();
2147 double[] arr =
new double[k];
2149 for (
int i=0; i<k; i++)
2151 arr[i] = mols.get(i).getFitness();
2186 double lambda,
double sigmaOne,
double sigmaTwo)
2188 return getProbability(level, scheme, lambda, sigmaOne, sigmaTwo);
2232 int scheme,
double lambda,
double sigmaOne,
double sigmaTwo)
2235 sigmaOne, sigmaTwo);
2251 int scheme,
double lambda,
double sigmaOne,
double sigmaTwo)
2256 double f = Math.exp(-1.0 * value * lambda);
2257 prob = 1 - ((1-f)/(1+f));
2259 else if (scheme == 1)
2261 prob = 1.0 - Math.tanh(lambda * value);
2263 else if (scheme == 2)
2265 prob = 1.0-1.0/(1.0 + Math.exp(-sigmaOne * (value - sigmaTwo)));
2267 else if (scheme == 3)
2338 sigmaOne, sigmaTwo);
2367 boolean ignoreFreeRCVs)
2378 && !oap.isAvailableThroughout()
2379 && oap.getLinkedAP().getOwner()
2382 if (ignoreFreeRCVs && oap.getLinkedAP().getOwner().isRCV())
2385 crowdness = crowdness + 1;
2387 crowdness = crowdness + 1;
2410 double lambda,
double sigmaOne,
double sigmaTwo)
2419 sigmaOne, sigmaTwo);
2435 double lambda,
double sigmaOne,
double sigmaTwo)
2437 return getProbability(crowdedness, scheme, lambda, sigmaOne, sigmaTwo);
2456 for (
Vertex vtx : vertices)
2458 List<AttachmentPoint> daps = vtx.getAttachmentPoints();
2461 if (dp.isAvailable())
2463 APClass apClass = dp.getAPClass();
2464 if (classOfForbEnds.contains(apClass))
2466 String msg =
"Forbidden free AP for Vertex: "
2468 +
" MolId: " + (vtx.getBuildingBlockId() + 1)
2469 +
" Ftype: " + vtx.getBuildingBlockType()
2470 +
"\n"+ molGraph+
" \n "
2471 +
" AP class: " + apClass;
2472 fsParams.
getLogger().log(Level.WARNING, msg);
2483 protected static void readUID(String infile, HashSet<String> lstInchi)
2487 for (String str:lst)
2540 gaParams.getSymmetryProbability());
2543 Logger logger = gaParams.getLogger();
2545 projectOnSymmetricAPs, logger, rng);
2584 List<List<RelatedAPPair>> result =
new ArrayList<List<RelatedAPPair>>();
2593 Set<Long> originalVertexIDs =
new HashSet<Long>();
2594 tmpGraph.getVertexList().stream()
2595 .forEach(v -> originalVertexIDs.add(v.getVertexId()));
2606 tmpGraph.addCappingGroups(fragSpace);
2616 Map<String, String> smarts =
new HashMap<String, String>();
2619 smarts.put(rule.getName(), rule.getSMARTS());
2627 Map<SymmetricSetWithMode,List<RelatedAPPair>> symmRelatedBridgeHeadAPs =
2628 new HashMap<SymmetricSetWithMode,List<RelatedAPPair>>();
2629 List<RelatedAPPair> symBridgeHeadAPs =
new ArrayList<RelatedAPPair>();
2630 List<RelatedAPPair> asymBridgeHeadAPs =
new ArrayList<RelatedAPPair>();
2642 Set<String> doneIdPairs =
new HashSet<String>();
2643 for (
int[] idSubstructure : halfRingAtms)
2645 if (idSubstructure.length<2)
2647 throw new Error(
"SMARTS for matching half-ring pattern '"
2649 +
"' has identified " + idSubstructure.length
2651 +
"instead of at least 2. Modify rule to make it "
2652 +
"find 2 or more atoms.");
2656 int[] ids =
new int[] {
2657 idSubstructure[rule.getBridgeHeadPositions()[0]],
2658 idSubstructure[rule.getBridgeHeadPositions()[1]]};
2660 IAtom bhA = mol.getAtom(ids[0]);
2661 IAtom bhB = mol.getAtom(ids[1]);
2664 String idPairIdentifier =
"";
2666 idPairIdentifier = ids[0]+
"_"+ids[1];
2668 idPairIdentifier = ids[1]+
"_"+ids[0];
2669 if (doneIdPairs.contains(idPairIdentifier))
2671 doneIdPairs.add(idPairIdentifier);
2679 throw new IllegalStateException(
"Atoms in 3d molecular "
2680 +
"models of graph objects must have the "
2683 long vrtxIdA = (Long)
2685 long vrtxIdB = (Long)
2689 @SuppressWarnings(
"unchecked")
2690 List<AttachmentPoint> apsOnA = (List<AttachmentPoint>)
2692 @SuppressWarnings(
"unchecked")
2693 List<AttachmentPoint> apsOnB = (List<AttachmentPoint>)
2695 for (
int iAPA=0; iAPA<apsOnA.size(); iAPA++)
2711 for (
int iAPB=0; iAPB<apsOnB.size(); iAPB++)
2733 .getAPWithId(copyOfApA.
getID());
2735 .getAPWithId(copyOfApB.
getID());
2736 if (apA==
null || apB==
null)
2746 if (symInA.size()!=0 && symInB.size()!=0)
2751 symmRelatedBridgeHeadAPs);
2754 symmRelatedBridgeHeadAPs);
2756 symmRelatedBridgeHeadAPs);
2758 symBridgeHeadAPs.add(pair);
2760 asymBridgeHeadAPs.add(pair);
2766 if (asymBridgeHeadAPs.size()==0 && symBridgeHeadAPs.size()==0)
2773 List<List<RelatedAPPair>> candidateBridgeHeadAPPairs =
2774 new ArrayList<List<RelatedAPPair>>();
2775 if (symmRelatedBridgeHeadAPs.size()>0)
2779 List<RelatedAPPair> chosenSymSet =
2780 symmRelatedBridgeHeadAPs.get(key);
2782 @SuppressWarnings(
"unchecked")
2785 boolean apcImposedSymm = fragSpace.imposeSymmetryOnAPsOfClass(
2786 symmRelatedAPs.get(0).getAPClass());
2788 if (projectOnSymmetricAPs || apcImposedSymm)
2792 for (
int k=Math.min(chosenSymSet.size(), 6); k>0; k--)
2796 chosenSymSet, k, 50);
2803 for (List<RelatedAPPair> comb : combs)
2805 boolean isNew =
true;
2806 for (List<RelatedAPPair> knownComb :
2807 candidateBridgeHeadAPPairs)
2809 if (knownComb.containsAll(comb)
2810 && comb.containsAll(knownComb))
2818 candidateBridgeHeadAPPairs.add(comb);
2820 symBridgeHeadAPs.remove(pair);
2831 List<RelatedAPPair> single =
new ArrayList<RelatedAPPair>();
2833 candidateBridgeHeadAPPairs.add(single);
2838 List<RelatedAPPair> single =
new ArrayList<RelatedAPPair>();
2840 candidateBridgeHeadAPPairs.add(single);
2844 for (List<RelatedAPPair> combOnTmpGraph : candidateBridgeHeadAPPairs)
2846 List<RelatedAPPair> combOnOriginalGraph =
2847 new ArrayList<RelatedAPPair>();
2850 Vertex headVertexOnGraph = graph.getVertexAtPosition(
2851 tmpGraph.indexOf(pairOnTmpGraph.apA.getOwner()));
2852 int apHeadID = pairOnTmpGraph.apA.getIndexInOwner();
2853 List<Vertex> symHeadVrts = graph.getSymVerticesForVertex(
2855 if (symHeadVrts.size()==0)
2856 symHeadVrts.add(headVertexOnGraph);
2858 Vertex tailVertexOnGraph = graph.getVertexAtPosition(
2859 tmpGraph.indexOf(pairOnTmpGraph.apB.getOwner()));
2860 int apTailID = pairOnTmpGraph.apB.getIndexInOwner();
2861 List<Vertex> symTailVrts = graph.getSymVerticesForVertex(
2863 if (symTailVrts.size()==0)
2864 symTailVrts.add(tailVertexOnGraph);
2866 int numPairs = Math.min(symHeadVrts.size(), symTailVrts.size());
2867 for (
int iPair=0; iPair<numPairs; iPair++)
2870 symHeadVrts.get(iPair).getAP(apHeadID),
2871 symTailVrts.get(iPair).getAP(apTailID),
2872 pairOnTmpGraph.property,
2873 pairOnTmpGraph.propID);
2874 combOnOriginalGraph.add(pairOnOriginalGraph);
2877 result.add(combOnOriginalGraph);
2885 List<RelatedAPPair> pool,
int k,
int limit)
2887 List<RelatedAPPair> tmp =
new ArrayList<RelatedAPPair>();
2888 List<List<RelatedAPPair>> allCombs =
new ArrayList<List<RelatedAPPair>>();
2897 List<RelatedAPPair> tmp,
2898 List<List<RelatedAPPair>> allCombs,
int limit)
2902 if (allCombs.size()>=limit)
2910 List<RelatedAPPair> oneComb =
new ArrayList<RelatedAPPair>(tmp);
2911 allCombs.add(oneComb);
2916 for (
int i=left; i<pool.size(); ++i)
2925 tmp.remove(tmp.size() - 1);
2936 if (storage.containsKey(key))
2938 storage.get(key).add(pair);
2940 List<RelatedAPPair> lst =
new ArrayList<RelatedAPPair>();
2942 storage.put(key, lst);
2958 Set<AttachmentPoint> aps =
new HashSet<AttachmentPoint>();
2962 if (aps.contains(pair.apA) || aps.contains(pair.apB))
2983 Iterable<RelatedAPPair> lstB)
2985 Set<AttachmentPoint> aps =
new HashSet<AttachmentPoint>();
2991 return aps.contains(pairA.
apA) || aps.contains(pairA.
apB);
3022 || !originalVertexIDs.contains(
3046 String elInIncomingFrag,
int[] allowedLengths,
3049 List<Vertex> usableBridgesOriginals =
3051 List<Vertex> usableBridges =
new ArrayList<Vertex>();
3052 final String rootAPC = elInIncomingFrag;
3053 for (
Vertex bridge : usableBridgesOriginals)
3055 IAtomContainer iacFrag = bridge.getIAtomContainer();
3056 List<Integer> atomIDs =
new ArrayList<Integer>();
3057 bridge.getAttachmentPoints()
3059 .filter(ap -> ap.getAPClass().getRule().startsWith(
3061 .forEach(ap -> atomIDs.add(ap.getAtomPositionNumber()));
3062 ShortestPaths sp =
new ShortestPaths(iacFrag, iacFrag.getAtom
3064 List<IAtom> path =
new ArrayList<IAtom>(Arrays.asList(
3065 sp.atomsTo(atomIDs.get(1))));
3066 if (IntStream.of(allowedLengths).anyMatch(x -> x == path.size()))
3071 usableBridges.add(clone);
3074 return usableBridges;
3092 List<Vertex> usableBridges =
new ArrayList<Vertex>();
3096 for (
APClass compatA : compatApClassesA)
3098 for (
APClass compatB : compatApClassesB)
3100 boolean sameAPC = compatA.equals(compatB);
3101 Map<APClass,Integer> apFingerprint =
3102 new HashMap<APClass,Integer>();
3105 apFingerprint.put(compatA,2);
3107 apFingerprint.put(compatA,1);
3108 apFingerprint.put(compatB,1);
3113 IAtomContainer iacFrag = bridge.getIAtomContainer();
3116 List<AttachmentPoint> apsForA =
new ArrayList<AttachmentPoint>();
3117 List<AttachmentPoint> apsForB =
new ArrayList<AttachmentPoint>();
3120 if (compatA.equals(apOnBridge.getAPClass()))
3121 apsForA.add(apOnBridge);
3122 if (compatB.equals(apOnBridge.getAPClass()))
3123 apsForB.add(apOnBridge);
3129 ShortestPaths sp =
new ShortestPaths(iacFrag,
3130 iacFrag.getAtom(apForA.getAtomPositionNumber()));
3133 if (apForA.equals(apForB))
3136 List<IAtom> path =
new ArrayList<IAtom>(
3137 Arrays.asList(sp.atomsTo(
3138 apForB.getAtomPositionNumber())));
3139 if (IntStream.of(allowedLengths).anyMatch(
3140 x -> x == path.size()))
3148 apForA.getIndexInOwner());
3151 apForB.getIndexInOwner());
3152 usableBridges.add(clone);
3159 return usableBridges;
General set of constants used in DENOPTIM.
static final String VRTPROPBRIDGELENGTH
Name of Vertex property used to record how long a ring-closing bridge is.
static final int MOLDIGITS
static final String ATMPROPAPS
String tag of Atom property used to store attachment points.
static final String VRTPROPBRIDGEEND_B
Name of Vertex property used to record which AP is selected for bridge formation on side 'B'.
static final String ATMPROPVERTEXID
String tag of Atom property used to store the unique ID of the Vertex corresponding to the molecular ...
static final String GAGENSUMMARYHEADER
Header of text files collection generation details.
static final String GAGENDIRNAMEROOT
Prefix for generation folders.
static final String FITFILENAMEEXTOUT
Ending and extension of output file of external fitness provider.
static final String VRTPROPBRIDGEEND_A
Name of Vertex property used to record which AP is selected for bridge formation on side 'A'.
Settings defining the calculation of fitness.
SMARTS-based rules to identify potential bridge head atoms for ring fusion operations.
Class defining a space of building blocks.
boolean useAPclassBasedApproach()
Check usage of APClass-based approach, i.e., uses attachment points with annotated data (i....
Set< APClass > getForbiddenEndList()
List< Vertex > getVerticesWithAPClassStartingWith(String root)
Extracts vertexes from the collection of vertexes defined by this FragmentSpace.
HashMap< APClass, ArrayList< APClass > > getRCCompatibilityMatrix()
Returns the compatibility matrix for ring closing fragment-fragment connections or null if not provid...
Vertex makeRandomScaffold()
Randomly select a scaffold and return a fully configured clone of it.
HashMap< APClass, APClass > getCappingMap()
ArrayList< APClass > getCompatibleAPClasses(APClass apc)
Returns a list of APClasses compatible with the given APClass.
List< Vertex > getVerticesWithAPFingerprint(Map< APClass, Integer > apcCounts)
Returns the list of vertexes that have the specified number of AttachmentPoints with the given APClas...
Parameters defining the fragment space.
FragmentSpace getFragmentSpace()
Helper methods for the genetic algorithm.
static Boolean shareAPs(RelatedAPPair pairA, Iterable< RelatedAPPair > lstB)
Evaluates if a RelatedAPPair involves the same AttachmentPoint present in a collection.
static void outputFinalResults(Population popln, GAParameters settings)
Saves the final results to disk.
static List< Candidate > buildCandidatesByXOver(List< Candidate > eligibleParents, Population population, Monitor mnt, int[] choiceOfParents, int choiceOfXOverSites, int choiceOfOffstring, GAParameters settings, int maxCandidatesToReturn)
Generates up to a pair of new offspring by performing a crossover operation.
static CandidateSource pickNewCandidateGenerationMode(double xoverWeight, double mutWeight, double newWeight, Randomizer randomizer)
Takes a decision on which CandidateSource method to use for generating a new Candidate.
static double getGrowthByLevelProbability(int level, GAParameters settings)
Calculates the probability of adding a fragment to the given level.
static double getCrowdingProbability(int crowdedness, GAParameters settings)
Calculated the probability of using and attachment point rooted on an atom that is holding other atta...
static int chooseNumberOfSitesToMutate(double[] multiSiteMutationProb, double hit)
Takes a decision on how many sites to mutate on a candidate.
static void appendVertexesToGraphFollowingEdges(DGraph graph, AtomicInteger vId, List< Vertex > vertexes)
static Candidate readCandidateFromFile(File srcFile, Monitor mnt, GAParameters settings)
static Candidate[] selectBasedOnFitness(List< Candidate > eligibleParents, int number, GAParameters settings)
Selects a number of members from the given population.
static DGraph makeGraphFromFragmentationOfMol(IAtomContainer mol, List< CuttingRule > cuttingRules, Logger logger, ScaffoldingPolicy scaffoldingPolicy, double linearAngleLimit)
Converts a molecule into a DGraph by fragmentation and re-assembling of the fragments.
static boolean setupRings(Object[] res, DGraph molGraph, GAParameters settings)
Evaluates the possibility of closing rings in a given graph and if any ring can be closed,...
static Candidate buildCandidateByXOver(List< Candidate > eligibleParents, Population population, Monitor mnt, GAParameters settings)
Generates a new offspring by performing a crossover operation.
static List< Candidate > buildCandidatesByXOver(List< Candidate > eligibleParents, Population population, Monitor mnt, GAParameters settings)
Generates a pair of new offspring by performing a crossover operation.
static boolean canBeUsedForRingFusion(AttachmentPoint ap, Set< Long > originalVertexIDs, FragmentSpace fs)
Decides if an AttachmentPoint can be considered for making a ring fusion operation,...
static void getPopulationFromFile(String filename, Population population, SizeControlledSet uniqueIDsSet, String genDir, GAParameters settings)
Reconstruct the molecular population from the file.
static void writeUID(String outfile, HashSet< String > lstInchi, boolean append)
static HashMap< Integer, ArrayList< String > > lstFragmentClass
static double getGrowthProbabilityAtLevel(int level, int scheme, double lambda, double sigmaOne, double sigmaTwo)
Calculates the probability of adding a fragment to the given level.
static DGraph makeGraphFromFragmentationOfMol(IAtomContainer mol, List< CuttingRule > cuttingRules, Logger logger, ScaffoldingPolicy scaffoldingPolicy)
Converts a molecule into a DGraph by fragmentation and re-assembling of the fragments.
static double getProbability(double value, int scheme, double lambda, double sigmaOne, double sigmaTwo)
Calculated a probability given parameters defining the shape of the probability function and a single...
static List< Vertex > getUsableAliphaticBridges(APClass apcA, APClass apcB, int[] allowedLengths, FragmentSpace fragSpace)
Finds all vertexes that can be used as aliphatic bridge.
static XoverSite performFBCC(List< Candidate > eligibleParents, Population population, int[] choiceOfParents, int choiceOfXOverSites, GAParameters settings)
Perform fitness-based, class-compatible selection of parents that can do crossover operations.
static String getPathNameToFinalPopulationFolder(GAParameters settings)
static DGraph makeGraphFromFragmentationOfMol(IAtomContainer mol, List< CuttingRule > cuttingRules, Logger logger, ScaffoldingPolicy scaffoldingPolicy, double linearAngleLimit, FragmentSpace fragSpace)
Converts a molecule into a DGraph by fragmentation and re-assembling of the fragments.
static CandidateSource chooseGenerationMethod(GAParameters settings)
Choose one of the methods to make new Candidates.
static Locale enUsLocale
Locale used to write reports.
static double getCrowdingProbability(AttachmentPoint ap, GAParameters settings)
Calculated the probability of using and attachment point rooted on an atom that is holding other atta...
static DGraph makeGraphFromFragmentationOfMol(IAtomContainer mol, List< CuttingRule > cuttingRules, Logger logger, ScaffoldingPolicy scaffoldingPolicy, double linearAngleLimit, boolean embedRingsInTemplates, ContractLevel ringTmplContract, FragmentSpace fragSpace, Monitor monitor)
Converts a molecule into a DGraph by fragmentation and re-assembling of the fragments.
static boolean foundForbiddenEnd(DGraph molGraph, FragmentSpaceParameters fsParams)
Check if there are forbidden ends: free attachment points that are not suitable for capping and not a...
static List< List< RelatedAPPair > > searchRingFusionSites(DGraph graph, GAParameters gaParams)
static void setVertexCounterValue(Population population)
Set the Vertex counter value according to the largest value found in the given population.
static Candidate buildCandidateByMutation(List< Candidate > eligibleParents, Monitor mnt, GAParameters settings)
static Candidate buildCandidateByFragmentingMolecule(IAtomContainer mol, Monitor mnt, GAParameters settings, int index)
Generates a candidate by fragmenting a molecule and generating the graph that reconnects all fragment...
static DGraph buildGraph(GAParameters settings)
Graph construction starts with selecting a random core/scaffold.
static Candidate buildCandidateByXOver(List< Candidate > eligibleParents, Population population, Monitor mnt, int[] choiceOfParents, int choiceOfXOverSites, int choiceOfOffstring, GAParameters settings)
Generates a new offspring by performing a crossover operation.
static double[] getFitnesses(Population mols)
Get the fitness values for the list of molecules.
static String getSummaryStatistics(Population popln, GAParameters settings)
static void createFolderForGeneration(int genId, GAParameters settings)
Creates a folder meant to hold all the data generated during a generation.
static double getMolSizeProbability(DGraph graph, int scheme, double lambda, double sigmaOne, double sigmaTwo)
Calculated the probability of extending a graph based on the current size of the molecular representa...
static DecimalFormat initialiseFormatter()
static int getCrowdedness(AttachmentPoint ap)
Calculate the current crowdedness of the given attachment point.
static int getCrowdedness(AttachmentPoint ap, boolean ignoreFreeRCVs)
Calculate the current crowdedness of the given attachment point.
static HashMap< Integer, ArrayList< Integer > > fragmentPool
static List< List< RelatedAPPair > > combineRelatedAPPair(List< RelatedAPPair > pool, int k, int limit)
static void combineRelatedAPPairUtil(List< RelatedAPPair > pool, int left, int k, List< RelatedAPPair > tmp, List< List< RelatedAPPair > > allCombs, int limit)
static void outputPopulationDetails(Population population, String filename, GAParameters settings, boolean printpathNames)
Write out summary for the current GA population.
static List< Vertex > getUsableAromaticBridges(String elInIncomingFrag, int[] allowedLengths, FragmentSpace fragSpace)
Finds all vertexes that can be used as aromatic bridge, i.e., can be used to create an aromatic ring ...
static Vertex selectNonScaffoldNonCapVertex(DGraph g, Randomizer randomizer)
Chose randomly a vertex that is neither scaffold or capping group.
static double getCrowdingProbabilityForCrowdedness(int crowdedness, int scheme, double lambda, double sigmaOne, double sigmaTwo)
Calculated the crowding probability for a given level of crowdedness.
static String getPathNameToGenerationFolder(int genID, GAParameters settings)
static double getPopulationSD(Population molPopulation)
Check if fitness values have significant standard deviation.
static String getPathNameToFinalPopulationDetailsFile(GAParameters settings)
static Candidate buildCandidateFromScratch(Monitor mnt, GAParameters settings)
static double getCrowdingProbability(AttachmentPoint ap, int scheme, double lambda, double sigmaOne, double sigmaTwo)
Calculated the probability of using and attachment point rooted on an atom that is holding other atta...
static boolean containsMolecule(Population mols, String molcode)
Check if the population contains the specified InChi code.
static DecimalFormat df
Format for decimal fitness numbers that overwrites Locale to en_US.
static DGraph makeGraphFromFragmentationOfMol(IAtomContainer mol, List< CuttingRule > cuttingRules, Logger logger, ScaffoldingPolicy scaffoldingPolicy, FragmentSpace fragSpace)
Converts a molecule into a DGraph by fragmentation and re-assembling of the fragments.
static List< List< RelatedAPPair > > searchRingFusionSites(DGraph graph, FragmentSpace fragSpace, RingClosureParameters rcParams, boolean projectOnSymmetricAPs, Logger logger, Randomizer rng)
static void storePairsSymmetricRelations(RelatedAPPair pair, SymmetricAPs symAPs, Map< SymmetricSetWithMode, List< RelatedAPPair > > storage)
static void readUID(String infile, HashSet< String > lstInchi)
static String getPathNameToGenerationDetailsFile(int genID, GAParameters settings)
static double getMolSizeProbability(DGraph graph, GAParameters settings)
Calculated the probability of extending a graph based on the current size of the molecular representa...
static Population importInitialPopulation(SizeControlledSet uniqueIDsSet, GAParameters settings)
Reads unique identifiers and initial population file according to the GAParameters.
static Boolean apPairsAreOverlapping(Iterable< RelatedAPPair > pairs)
Evaluates if any pair of AttachmentPoint pairs involve the same AttachmentPoint, i....
Collection of operators meant to alter graphs and associated utilities.
static boolean extendGraph(Vertex curVertex, boolean extend, boolean symmetryOnAps, GAParameters settings)
function that will keep extending the graph according to the growth/substitution probability.
static boolean performMutation(DGraph graph, Monitor mnt, GAParameters settings)
Tries to do mutate the given graph.
static boolean performCrossover(XoverSite site, FragmentSpace fragSpace)
Performs the crossover that swaps the two subgraphs defining the given XoverSite.
A collection of candidates.
List< XoverSite > getXoverSites(Candidate parentA, Candidate parentB)
Returns a list of crossover sites between the two given parents.
List< Candidate > getXoverPartners(Candidate memberA, List< Candidate > eligibleParents, FragmentSpace fragSpace)
Returns a list of population members that can do crossover with the specified member.
Class that offers methods to performs fitness-driven selection of candidates.
static Candidate[] performRandomSelection(List< Candidate > population, int sz, RunTimeParameters settings)
Randomly select k individuals from the population.
static Candidate[] performRWS(List< Candidate > population, int sz, RunTimeParameters settings)
Roulette wheel selection is implemented as follows:
static Candidate[] performSUS(List< Candidate > population, int sz, RunTimeParameters settings)
Stochastic Uniform Sampling Note: this implementation is based on the WATCHMAKER framework http://wat...
static Candidate[] performTournamentSelection(List< Candidate > eligibleParents, int sz, GAParameters settings)
Select a number individuals at random (i.e., tournamentSize).
This class collects the data identifying the subgraphs that would be swapped by a crossover event.
XoverSite projectToClonedGraphs()
Creates a new instance of this class that contains the list of vertexes that correspond to those cont...
String toString()
Produced a string for showing what this object is.
List< Vertex > getA()
Returns the collection of vertexes belonging to the first subgraph.
List< Vertex > getB()
Returns the collection of vertexes belonging to the second subgraph.
static final APClass RCACLASSMINUS
Conventional class of attachment points on ring-closing vertexes.
static final String ATPLUS
String defining a conventional APClass.
static APClass make(String ruleAndSubclass)
Creates an APClass if it does not exist already, or returns the reference to the existing instance.
An attachment point (AP) is a possibility to attach a Vertex onto the vertex holding the AP (i....
APClass getAPClass()
Returns the Attachment Point class.
int getID()
Returns a unique integer that is used to sort list of attachment points.
int getAtomPositionNumber()
The index of the source atom in the atom list of the fragment.
boolean isAvailableThroughout()
Check availability of this attachment point throughout the graph level, i.e., check also across the i...
AttachmentPoint getLinkedAPThroughout()
Gets the attachment point (AP) that is connected to this AP via the edge user or in any edge user tha...
A candidate is the combination of a denoptim graph with molecular representation and may include also...
void setSDFFile(String molFile)
void setSmiles(String smiles)
int getGeneration()
The generation this candidate belong to is that in which it was generated.
void setName(String name)
void setChemicalRepresentation(IAtomContainer iac)
Just place the argument in the IAtomContainer field of this object.
Container for the list of vertices and the edges that connect them.
void setCandidateClosableChains(ArrayList< ClosableChain > closableChains)
void addVertex(Vertex vertex)
Appends a vertex to this graph without creating any edge.
DGraph embedPatternsInTemplates(GraphPattern pattern, FragmentSpace fragSpace)
Searches for the given pattern type and generated a new graph where each set of (clones of) vertexes ...
void getChildrenTree(Vertex vertex, List< Vertex > children)
Gets all the children of the current vertex recursively.
ArrayList< Vertex > getFreeRCVertices()
Search for unused ring closing vertices: vertices that contain only a RingClosingAttractor and are no...
Object[] checkConsistency(RunTimeParameters settings)
Peeks into this graph to derive a preliminary chemical representation with SMILES and InChIKey.
List< Vertex > getVertexList()
DGraph clone()
Returns almost "deep-copy" of this graph.
void renumberGraphVertices()
Reassign vertex IDs to all vertices of this graph.
boolean containsOrEmbedsVertex(Vertex v)
Check if the specified vertex is contained in this graph as a node or in any inner graphs that may be...
DGraph getOutermostGraphOwner()
void addCappingGroups(FragmentSpace fragSpace)
Add a capping groups on free unused attachment points.
void cleanup()
Wipes the data in this graph.
Candidate getCandidateOwner()
Returns the reference of the candidate item that is defined by this graph.
ArrayList< Vertex > getUsedRCVertices()
Search for used ring closing vertices: vertices that contain only a RingClosingAttractor and are part...
int getHeavyAtomsCount()
Calculate the number of atoms from the graph representation.
List< Vertex > getMutableSites()
A list of mutation sites from within this graph.
void setLocalMsg(String msg)
boolean detectSymVertexSets()
Detects and groups symmetric sets of Vertexes in the graph based on unique identification and path en...
An empty vertex has the behaviors of a vertex, but has no molecular structure.
Class representing a continuously connected portion of chemical object holding attachment points.
boolean isIsomorphicTo(Vertex other)
Checks for isomorphism of the graph representation of this and another fragment.
void updateAPs()
Changes the properties of each APs as to reflect the current atom list.
This class represents the closure of a ring in a spanning tree.
A collection of AttachmentPoints that are related by a relation that we call "symmetry",...
Class representing a list of references pointing to instances that are related by some conventional c...
Class coupling a reference to a SymmetricSet with a string that we call "mode" and can is used to sto...
A vertex is a data structure that has an identity and holds a list of AttachmentPoints.
abstract Vertex clone()
Returns a deep-copy of this vertex.
int getBuildingBlockId()
Returns the index of the building block that should correspond to the position of the building block ...
void setVertexId(long vertexId2)
DGraph getGraphOwner()
Returns the graph this vertex belongs to or null.
abstract List< AttachmentPoint > getAttachmentPoints()
SymmetricAPs getSymmetricAPs(AttachmentPoint ap)
For the given attachment point index locate the symmetric partners i.e.
abstract int getHeavyAtomsCount()
void setBuildingBlockType(Vertex.BBType buildingBlockType)
abstract IAtomContainer getIAtomContainer()
void setProperty(Object key, Object property)
AttachmentPoint getAP(int i)
Get attachment point i on this vertex.
This is a tool to identify and manage vertices' connections not included in the DGraph,...
List< Ring > getRandomCombinationOfRings(IAtomContainer inMol, DGraph molGraph, int maxRingClosures)
Identifies a random combination of ring closing paths and returns it as list of DENOPTIMRings ready t...
boolean checkChelatesGraph(DGraph molGraph, List< Ring > ringsSet)
Evaluates the combination of a DENOPTIMGraph and a set of DENOPTIMRings and decides whether it's a pr...
ArrayList< List< Ring > > getPossibleCombinationOfRings(IAtomContainer mol, DGraph molGraph)
Identifies all possible ring closing paths and returns them as list of DENOPTIMRings ready to be appe...
Parameters and setting related to handling ring closures.
RingClosuresArchive getRingClosuresArchive()
boolean buildChelatesMode
Flag activating procedures favoring formation of chelates.
void allowRingClosures(boolean value)
Data structure to store and handle information about sub-structures (i.e., chains of fragments) and r...
ArrayList< ClosableChain > getCCFromTurningPointId(int tpId)
Returns the library of closable chains having the given turning point (i.e., the fragments involved i...
Utility methods for input/output.
static ArrayList< Candidate > readCandidates(File file)
Reads SDF files that represent one or more tested candidates.
static void writeGraphsToSDF(File file, List< DGraph > graphs, Logger logger, Randomizer randomizer)
Writes the graphs to SDF file.
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 ArrayList< DGraph > readDENOPTIMGraphsFromFile(File inFile)
Reads a list of DGraphs from file.
static ArrayList< String > readList(String fileName)
Read list of data as text.
static void writeData(String fileName, String data, boolean append)
Write text-like data file.
static void writeCandidatesToFile(File file, List< Candidate > popMembers, boolean append)
Writes candidate items to file.
A collection of counters user to count actions taken by the evolutionary algorithm.
void increase(CounterID cid)
Tool to build build three-dimensional (3D) tree-like molecular structures from DGraph.
void setAlignBBsIn3D(boolean align)
Sets the flag that controls whether building blocks have to be aligned according to the AP vectors or...
IAtomContainer convertGraphTo3DAtomContainer(DGraph graph)
Created a three-dimensional molecular representation from a given DGraph.
boolean containsParameters(ParametersType type)
RunTimeParameters getParameters(ParametersType type)
Logger getLogger()
Get the name of the program specific logger.
final String NL
New line character.
Randomizer getRandomizer()
Returns the current program-specific randomizer.
Parameters for genetic algorithm.
double getConstructionWeight()
double getMutationWeight()
boolean useMolSizeBasedProb
Flag recording the intention to use molecular size-controlled graph extension probability.
boolean recordMateSelection
Flag defining whether we record which mates are selected or not.
int getMolGrowthProbabilityScheme()
int getCrowdingProbabilityScheme()
String getDataDirectory()
double getGrowthFactorMiddleSigma()
double getMolGrowthFactorMiddleSigma()
boolean useLevelBasedProb
Flag recording the intention to use level-controlled graph extension probability.
int getNumberOfGenerations()
double getMolGrowthFactorSteepSigma()
double getGrowthFactorSteepSigma()
double getMolGrowthMultiplier()
double getCrowdingFactorSteepSigma()
double getCrowdingFactorMiddleSigma()
int getGrowthProbabilityScheme()
double getGrowthMultiplier()
int getSelectionStrategyType()
double getCrowdingMultiplier()
double getCrossoverWeight()
Parameters controlling execution of the fragmenter.
double getLinearAngleLimit()
ScaffoldingPolicy getScaffoldingPolicy()
List< CuttingRule > getCuttingRules()
ContractLevel getEmbeddedRingsContract()
boolean embedRingsInTemplate
Flag that enables the embedding of rings in templates upon conversion of molecules into DGraph.
Toll to add/remove dummy atoms from linearities or multi-hapto sites.
static void addDummiesOnLinearities(Fragment frag, double angLim)
Append dummy atoms on otherwise linear arrangements of atoms.
static String getPaddedString(int count, int number)
returns the padded string with zeroes placed to the left of 'number' up to reach the desired number o...
static synchronized void ensureVertexIDConsistency(long l)
Method used to ensure consistency between internal atomic integer and vertex id from imported graphs.
static synchronized int getUniqueMoleculeIndex()
Unique counter for the number of molecules generated.
static synchronized int getUniqueGraphIndex()
Unique counter for the number of graphs generated.
Container of lists of atoms matching a list of SMARTS.
Mappings getMatchesOfSMARTS(String ref)
int getNumMatchesOfQuery(String query)
Utilities for molecule conversion.
static String getInChIKeyForMolecule(IAtomContainer mol, Logger logger)
Generates the InChI key for the given atom container.
static String getSMILESForMolecule(IAtomContainer mol, Logger logger)
Returns the SMILES representation of the molecule.
static String getSymbolOrLabel(IAtom atm)
Gets either the elemental symbol (for standard atoms) of the label (for pseudo-atoms).
Tool to generate random numbers and random decisions.
boolean nextBoolean()
Returns the next pseudo-random, uniformly distributed boolean value from this random number generator...
public< T > T randomlyChooseOne(Collection< T > c)
Chooses one member among the given collection.
double nextDouble()
Returns the next pseudo-random, uniformly distributed double value between 0.0 and 1....
Tool box for definition and management of the rotational space, which is given by the list of rotatab...
static ArrayList< ObjectPair > defineRotatableBonds(IAtomContainer mol, String defRotBndsFile, boolean addIterfragBonds, boolean excludeRings, Logger logger)
Define the rotational space (also torsional space) for a given molecule.
Class meant to collect unique strings without leading to memory overflow.
Utilities for calculating basic statistics.
static double mean(double[] numbers)
Returns the mean number in the numbers list.
static double stddev(double[] numbers, boolean biasCorrected)
Returns the standard deviation of the numbers.
static double skewness(double[] m, boolean biasCorrected)
Computes the skewness of the available values.
static double median(double[] m)
Calculates median value of a sorted list.
static double min(double[] numbers)
Returns the minimum value among the numbers .
static double max(double[] numbers)
Returns the maximum value among the numbers .
Defines how to define the scaffold vertex of a graph.
A chosen method for generation of new Candidates.
Possible chemical bond types an edge can represent.
Enum specifying to what extent the template's inner graph can be changed.
FIXED
Inner graphs are effectively equivalent to the Fragment class, as no change in the inner structure is...
The type of building block.
FAILEDBUILDATTEMPTS_SETUPRINGS
FAILEDMANUALADDATTEMPTS_EVAL
FAILEDCONVERTBYFRAGATTEMPTS
FAILEDMUTATTEMTS_FORBENDS
FAILEDXOVERATTEMPTS_SETUPRINGS
FAILEDXOVERATTEMPTS_FORBENDS
FAILEDBUILDATTEMPTS_FORBIDENDS
FAILEDXOVERATTEMPTS_FINDPARENTS
FAILEDCONVERTBYFRAGATTEMPTS_TMPLEMBEDDING
FAILEDXOVERATTEMPTS_PERFORM
FAILEDCONVERTBYFRAGATTEMPTS_EVAL
FAILEDCONVERTBYFRAGATTEMPTS_FRAGMENTATION
FAILEDBUILDATTEMPTS_GRAPHBUILD
FAILEDMUTATTEMTS_SETUPRINGS
Identifier of the type of parameters.
FS_PARAMS
Parameters pertaining the definition of the fragment space.
FRG_PARAMS
Parameters controlling the fragmenter.
FIT_PARAMS
Parameters pertaining the calculation of fitness (i.e., the fitness provider).
RC_PARAMS
Parameters pertaining to ring closures in graphs.