23import java.io.IOException;
24import java.text.DecimalFormat;
25import java.text.NumberFormat;
26import java.util.ArrayList;
27import java.util.Arrays;
28import java.util.Comparator;
29import java.util.HashMap;
30import java.util.HashSet;
31import java.util.Iterator;
33import java.util.Locale;
36import java.util.concurrent.atomic.AtomicInteger;
37import java.util.logging.Level;
38import java.util.logging.Logger;
40import org.apache.commons.io.FileUtils;
41import org.apache.commons.io.FilenameUtils;
42import org.openscience.cdk.graph.ShortestPaths;
43import org.openscience.cdk.interfaces.IAtom;
44import org.openscience.cdk.interfaces.IAtomContainer;
45import org.openscience.cdk.isomorphism.Mappings;
47import java.util.stream.IntStream;
49import denoptim.constants.DENOPTIMConstants;
50import denoptim.exception.DENOPTIMException;
51import denoptim.fitness.FitnessParameters;
52import denoptim.fragmenter.BridgeHeadFindingRule;
53import denoptim.fragmenter.FragmenterTools;
54import denoptim.fragmenter.ScaffoldingPolicy;
55import denoptim.fragspace.FragmentSpace;
56import denoptim.fragspace.FragmentSpaceParameters;
57import denoptim.graph.APClass;
58import denoptim.graph.AttachmentPoint;
59import denoptim.graph.Candidate;
60import denoptim.graph.DGraph;
61import denoptim.graph.Edge.BondType;
62import denoptim.graph.EmptyVertex;
63import denoptim.graph.Fragment;
64import denoptim.graph.GraphPattern;
65import denoptim.graph.RelatedAPPair;
66import denoptim.graph.Ring;
67import denoptim.graph.SymmetricAPs;
68import denoptim.graph.SymmetricSet;
69import denoptim.graph.SymmetricSetWithMode;
70import denoptim.graph.Template;
71import denoptim.graph.Template.ContractLevel;
72import denoptim.graph.Vertex;
73import denoptim.graph.Vertex.BBType;
74import denoptim.graph.rings.CyclicGraphHandler;
75import denoptim.graph.rings.RingClosureParameters;
76import denoptim.graph.rings.RingClosuresArchive;
77import denoptim.io.DenoptimIO;
78import denoptim.logging.CounterID;
79import denoptim.logging.Monitor;
80import denoptim.molecularmodeling.ThreeDimTreeBuilder;
81import denoptim.programs.RunTimeParameters.ParametersType;
82import denoptim.programs.denovo.GAParameters;
83import denoptim.programs.fragmenter.CuttingRule;
84import denoptim.programs.fragmenter.FragmenterParameters;
85import denoptim.utils.DummyAtomHandler;
86import denoptim.utils.GeneralUtils;
87import denoptim.utils.GraphUtils;
88import denoptim.utils.ManySMARTSQuery;
89import denoptim.utils.MoleculeUtils;
90import denoptim.utils.Randomizer;
91import denoptim.utils.RotationalSpaceUtils;
92import denoptim.utils.SizeControlledSet;
93import denoptim.utils.StatUtils;
116 DecimalFormat
df = (DecimalFormat) NumberFormat.getNumberInstance(
118 df.setGroupingUsed(
false);
132 private static final String
NL =System.getProperty(
"line.separator");
133 private static final String
FSEP = System.getProperty(
"file.separator");
146 denoptim.files.FileUtils.createDirectory(
164 HashSet<String> lstUID =
new HashSet<>(1024);
165 if (!settings.getUIDFileIn().equals(
""))
168 for (String uid : lstUID)
170 uniqueIDsSet.addNewUniqueEntry(uid);
172 settings.getLogger().log(Level.INFO,
"Read " + lstUID.size()
173 +
" known UIDs from " + settings.getUIDFileIn());
177 int numFromInitGraphs = 0;
178 String initPopFile = settings.getInitialPopulationFile();
179 if (initPopFile.length() > 0)
184 numFromInitGraphs = population.size();
185 settings.getLogger().log(Level.INFO,
"Imported " + numFromInitGraphs
186 +
" candidates (as graphs) from " + initPopFile);
223 for (
int i=0; i<multiSiteMutationProb.length; i++)
224 tot = tot + multiSiteMutationProb[i];
226 double scaledHit = hit * tot;
231 for (
int i=0; i<multiSiteMutationProb.length; i++)
233 max = max + multiSiteMutationProb[i];
234 if (min < scaledHit && scaledHit <= max)
239 min = Math.max(min,min+multiSiteMutationProb[i]);
259 double xoverWeight,
double mutWeight,
double newWeight,
263 * (xoverWeight + mutWeight + newWeight);
264 if (hit <= xoverWeight)
267 }
else if (xoverWeight < hit && hit <= (mutWeight+xoverWeight))
289 List<Candidate> eligibleParents,
Population population,
293 null, -1, -1, settings, settings.maxOffsprintFromXover());
309 List<Candidate> eligibleParents,
Population population,
313 null, -1, -1, settings);
343 List<Candidate> eligibleParents,
Population population,
344 Monitor mnt,
int[] choiceOfParents,
int choiceOfXOverSites,
350 choiceOfParents, choiceOfXOverSites, choiceOfOffstring,
388 List<Candidate> eligibleParents,
Population population,
389 Monitor mnt,
int[] choiceOfParents,
int choiceOfXOverSites,
409 boolean foundPars =
false;
410 while (numatt < settings.getMaxGeneticOpAttempts())
415 population, choiceOfParents, choiceOfXOverSites,
425 eligibleParents, 2, settings);
426 if (parents[0] ==
null || parents[1] ==
null)
433 List<Vertex> subGraphA =
new ArrayList<Vertex>();
435 gpA, settings.getRandomizer()),subGraphA);
438 List<Vertex> subGraphB =
new ArrayList<Vertex>();
440 gpB, settings.getRandomizer()),subGraphB);
451 return new ArrayList<Candidate>();
455 Vertex vA =
null, vB =
null;
456 vA = xos.
getA().get(0);
457 vB = xos.
getB().get(0);
460 DGraph gB = vB.getGraphOwner();
464 String candIdB = cB.getName();
470 DGraph gAClone = xosOnClones.
getA().get(0).getGraphOwner();
471 DGraph gBClone = xosOnClones.
getB().get(0).getGraphOwner();
476 settings.maxAPMappingCombinations))
480 return new ArrayList<Candidate>();
482 }
catch (Throwable t) {
483 if (!settings.xoverFailureTolerant)
486 ArrayList<DGraph> parents =
new ArrayList<DGraph>();
490 +
"_failed_xover.sdf"), parents,
true,
491 settings.getLogger(), settings.getRandomizer());
494 +
"XOverSite(C): " + xosOnClones.
toString() +
NL
495 +
" Please, report this to the authors ",t);
499 return new ArrayList<Candidate>();
505 lstIdVA = lstIdVA +
"_" + v.getVertexId();
508 lstIdVB = lstIdVB +
"_" + v.getVertexId();
509 String[] msgs =
new String[2];
512 +
"|" + gid1 +
"|" + lstIdVA
514 +
"Gen:" + cB.getGeneration() +
" Cand:" + candIdB
515 +
"|" + gid2 +
"|" + lstIdVB;
517 +
"Gen:" + cB.getGeneration() +
" Cand:" + candIdB
518 +
"|" + gid2 +
"|" + lstIdVB
521 +
"|" + gid1 +
"|" + lstIdVA;
524 graphsAffectedByXover[0] = gAClone;
525 graphsAffectedByXover[1] = gBClone;
527 List<Candidate> validOffspring =
new Population(settings);
528 for (
int ig=0; ig<graphsAffectedByXover.length; ig++)
530 DGraph g = graphsAffectedByXover[ig];
552 }
catch (NullPointerException|IllegalArgumentException e)
554 if (!settings.xoverGraphFailedEvalTolerant)
556 ArrayList<DGraph> parents =
new ArrayList<DGraph>();
559 parents.add(gAClone);
560 parents.add(gBClone);
562 +
"_failed_xover-ed_check.sdf"), parents,
true,
563 settings.getLogger(), settings.getRandomizer());
583 APClass apc = rcv.getEdgeToParent().getSrcAP().getAPClass();
601 offspring.
setUID(res[0].toString().trim());
602 offspring.
setSmiles(res[1].toString().trim());
605 validOffspring.add(offspring);
608 if (validOffspring.size() == 0)
611 return new ArrayList<Candidate>();
614 if (maxCandidatesToReturn==1)
617 if (choiceOfOffstring<0)
619 chosenOffspring = settings.getRandomizer().randomlyChooseOne(
625 chosenOffspring = validOffspring.get(choiceOfOffstring);
627 validOffspring.retainAll(Arrays.asList(chosenOffspring));
636 return validOffspring;
642 List<Candidate> eligibleParents,
Monitor mnt,
658 while (numatt < settings.getMaxGeneticOpAttempts())
678 String parentMolName = FilenameUtils.getBaseName(parent.
getSDFFile());
681 +
" Gen:" + parent.
getGeneration() +
" Cand:" + parentMolName
682 +
"|" + parentGraphId);
699 }
catch (NullPointerException|IllegalArgumentException e)
701 if (!settings.mutatedGraphFailedEvalTolerant)
703 settings.getLogger().log(Level.INFO,
"WRITING DEBUG FILE for "
706 parent.
getGraph(),
false, settings.getLogger(),
707 settings.getRandomizer());
709 graph,
false, settings.getLogger(),
710 settings.getRandomizer());
734 APClass apc = rcv.getEdgeToParent().getSrcAP().getAPClass();
752 offspring.
setUID(res[0].toString().trim());
753 offspring.
setSmiles(res[1].toString().trim());
771 ArrayList<DGraph> graphs;
775 }
catch (Exception e)
779 String msg =
"Could not read graphs from file " + srcFile
780 +
". No candidate generated!";
781 settings.getLogger().log(Level.SEVERE, msg);
784 if (graphs.size() == 0 || graphs.size() > 1)
787 String msg =
"Found " + graphs.size() +
" graphs in file " + srcFile
788 +
". I expect one and only one graph. "
789 +
"No candidate generated!";
790 settings.getLogger().log(Level.SEVERE, msg);
794 DGraph graph = graphs.get(0);
798 String msg =
"Null graph from file " + srcFile
799 +
". Expected one and only one graph. "
800 +
"No candidate generated!";
801 settings.getLogger().log(Level.SEVERE, msg);
821 candidate.
setUID(res[0].toString().trim());
822 candidate.
setSmiles(res[1].toString().trim());
829 String msg =
"Candidate " + candidate.
getName() +
" is imported from "
831 settings.getLogger().log(Level.INFO, msg);
886 if (rcv.getEdgeToParent() ==
null)
891 if (rcv.getEdgeToParent() ==
null)
896 APClass apc = rcv.getEdgeToParent().getSrcAP().getAPClass();
913 candidate.
setUID(res[0].toString().trim());
914 candidate.
setSmiles(res[1].toString().trim());
961 +
"fragmentation but no cutting rules provided. Please,"
962 +
"add FRG-CUTTINGRULESFILE=path/to/your/file to the "
984 String msg =
"Unable to convert molecule (" + mol.getAtomCount()
985 +
" atoms) to DENOPTIM graph. " + de.getMessage();
986 settings.getLogger().log(Level.WARNING, msg);
1005 candidate.
setUID(res[0].toString().trim());
1006 candidate.
setSmiles(res[1].toString().trim());
1030 List<CuttingRule> cuttingRules, Logger logger,
1056 List<CuttingRule> cuttingRules, Logger logger,
1080 List<CuttingRule> cuttingRules, Logger logger,
1085 scaffoldingPolicy, 190, fragSpace);
1108 List<CuttingRule> cuttingRules, Logger logger,
1114 scaffoldingPolicy, linearAngleLimit,
false,
null,
1142 List<CuttingRule> cuttingRules, Logger logger,
1144 boolean embedRingsInTemplates,
ContractLevel ringTmplContract,
1207 double linearAngleLimit = frgParams.getLinearAngleLimit();
1208 boolean embedRingsInTemplates = frgParams.embedRingsInTemplate();
1209 ContractLevel ringTmplContract = frgParams.getEmbeddedRingsContract();
1215 for (
Vertex v : fragments)
1225 if (fragments.size()==0)
1232 + mol.getAtomCount() +
" atoms produced 0 fragments.");
1237 switch (scaffoldingPolicy)
1241 for (
Vertex v : fragments)
1245 boolean setAsScaffold =
false;
1247 for (IAtom atm : iac.atoms())
1249 if (scaffoldingPolicy.
label.equals(
1252 setAsScaffold =
true;
1267 case LARGEST_FRAGMENT:
1270 scaffold = fragments.stream()
1271 .max(Comparator.comparing(
1274 }
catch (Exception e)
1281 +
"among " + fragments.size() +
" fragments.", e);
1293 +
"identified as the "
1302 AtomicInteger vId =
new AtomicInteger(1);
1303 for (
int i=1; i<fragments.size(); i++)
1313 if (fragSpace!=
null && fragSpace.getCappingMap()!=
null)
1317 if (v.getAttachmentPoints().size()!=1 || v.isRCV())
1320 APClass srcAPC = v.getAP(0).getLinkedAPThroughout().getAPClass();
1321 APClass capAPC = fragSpace.getAPClassOfCappingVertex(srcAPC);
1322 Vertex cap = fragSpace.getCappingVertexWithAPClass(capAPC);
1334 v.getAP(0).setAPClass(capAPC);
1339 if (embedRingsInTemplates)
1343 fragSpace, ringTmplContract);
1363 Vertex lastlyAdded =
null;
1364 for (
int i=-1; i>-4; i--)
1366 lastlyAdded = graph.getVertexList().get(
1367 graph.getVertexList().size()+i);
1368 if (!lastlyAdded.
isRCV())
1373 if (!apI.isAvailable())
1376 for (
int j=0; j<vertexes.size(); j++)
1378 Vertex fragJ = vertexes.get(j);
1380 boolean ringClosure =
false;
1381 if (graph.containsVertex(fragJ))
1390 if (!apI.isAvailable() || !apJ.isAvailable())
1393 if (apI.getCutId()==apJ.getCutId())
1402 graph.appendVertexOnAP(apI, rcvI.
getAP(0));
1408 graph.appendVertexOnAP(apJ, rcvJ.
getAP(0));
1409 graph.addRing(rcvI, rcvJ);
1413 graph.appendVertexOnAP(apI, apJ);
1439 String filename,
GAParameters settings,
boolean printpathNames)
1442 StringBuilder sb =
new StringBuilder(512);
1446 df.setMaximumFractionDigits(settings.getPrecisionLevel());
1447 df.setMinimumFractionDigits(settings.getPrecisionLevel());
1452 synchronized (population)
1454 List<Candidate> popMembers =
new ArrayList<Candidate>();
1455 for (
int i=0; i<settings.getPopulationSize(); i++)
1458 popMembers.add(mol);
1463 sb.append(String.format(
"%-20s", mname));
1465 sb.append(String.format(
"%-20s",
1467 sb.append(String.format(
"%-30s", mol.
getUID()));
1475 sb.append(System.getProperty(
"line.separator"));
1482 if (settings.savePopFile())
1484 File dest =
new File(filename.replaceAll(
"\\.txt$",
".sdf"));
1488 if (stats.trim().length() > 0)
1505 StringBuilder sb =
new StringBuilder(128);
1506 sb.append(
NL+
NL+
"#####POPULATION SUMMARY#####"+
NL);
1507 int n = popln.size();
1508 sb.append(String.format(
"%-30s",
"SIZE:"));
1509 sb.append(String.format(
"%12s", n));
1513 sb.append(String.format(
"%-30s",
"MAX:")).append(
df.format(f));
1516 sb.append(String.format(
"%-30s",
"MIN:")).append(
df.format(f));
1519 sb.append(String.format(
"%-30s",
"MEAN:")).append(
df.format(f));
1522 sb.append(String.format(
"%-30s",
"MEDIAN:")).append(
df.format(f));
1525 sb.append(String.format(
"%-30s",
"STDDEV:")).append(
df.format(f));
1530 sb.append(String.format(
"%-30s",
"SKEW:")).append(
df.format(f));
1533 sb.append(String.format(
"%-30s",
"SKEW:")).append(
" NaN (sdev too small)");
1537 res = sb.toString();
1555 List<Candidate> eligibleParents,
int number,
GAParameters settings)
1579 for (
int i=0; i < mates.length; i++)
1582 matesStr = matesStr + settings.
NL;
1583 matesStr = matesStr + mates[i].
getUID();
1592 e.printStackTrace();
1607 List<Vertex> candidates =
new ArrayList<Vertex>(
1609 candidates.removeIf(v ->
1611 || v.getBuildingBlockType() ==
BBType.
CAP);
1633 List<Candidate> eligibleParents,
Population population,
1634 int[] choiceOfParents,
int choiceOfXOverSites,
GAParameters settings)
1637 if (choiceOfParents==
null)
1640 parentA = eligibleParents.get(choiceOfParents[0]);
1642 if (parentA ==
null)
1653 parentA, eligibleParents, fragSpace);
1654 if (matesCompatibleWithFirst.size() == 0)
1658 if (choiceOfParents==
null)
1663 parentB = eligibleParents.get(choiceOfParents[1]);
1665 if (parentB ==
null)
1669 if (choiceOfXOverSites<0)
1675 choiceOfXOverSites);
1685 StringBuilder sb =
new StringBuilder(32);
1693 return sb.toString();
1701 StringBuilder sb =
new StringBuilder(32);
1713 return sb.toString();
1720 StringBuilder sb =
new StringBuilder(32);
1722 return sb.toString();
1730 StringBuilder sb =
new StringBuilder(32);
1732 .append(
FSEP).append(
"Final.txt");
1733 return sb.toString();
1752 denoptim.files.FileUtils.createDirectory(dirName);
1753 File fileDir =
new File(dirName);
1755 boolean intermediateCandidatesAreOnDisk =
1759 for (
int i=0; i<popln.size(); i++)
1766 if (intermediateCandidatesAreOnDisk && sdfile!=
null)
1768 FileUtils.copyFileToDirectory(
new File(sdfile), fileDir);
1770 File candFile =
new File(fileDir, c.
getName()
1775 }
catch (IOException ioe) {
1777 + sdfile +
"' to '" + fileDir +
"' for candidate "
1780 if (imgfile !=
null && intermediateCandidatesAreOnDisk)
1783 FileUtils.copyFileToDirectory(
new File(imgfile), fileDir);
1784 }
catch (IOException ioe) {
1786 + imgfile +
"' to '" + fileDir +
"' for candidate "
1812 new File(filename),
true);
1813 if (candidates.size() == 0)
1815 String msg =
"Found 0 candidates in file " + filename;
1816 settings.getLogger().log(Level.SEVERE, msg);
1822 if (uniqueIDsSet.addNewUniqueEntry(candidate.getUID()))
1828 candidate.setName(molName);
1829 candidate.getGraph().setGraphId(gctr);
1830 candidate.getGraph().setLocalMsg(
"INITIAL_POPULATION");
1831 String sdfPathName = genDir + System.getProperty(
"file.separator")
1833 candidate.setSDFFile(sdfPathName);
1834 candidate.setImageFile(
null);
1840 population.add(candidate);
1842 settings.getLogger().log(Level.WARNING,
"Candidate from intial "
1843 +
"population file '" + filename
1844 +
"' is rejected because its identifier is "
1845 +
"already listed among the previously visited "
1850 if (population.isEmpty())
1852 String msg =
"Population is still empty after having processes "
1853 + candidates.size() +
" candidates from file " + filename;
1854 settings.getLogger().log(Level.SEVERE, msg);
1863 protected static void writeUID(String outfile, HashSet<String> lstInchi,
1866 StringBuilder sb =
new StringBuilder(256);
1867 Iterator<String> iter = lstInchi.iterator();
1869 boolean first =
true;
1870 while(iter.hasNext())
1874 sb.append(iter.next());
1879 sb.append(
NL).append(iter.next());
1899 long val = Long.MIN_VALUE;
1902 DGraph g = popln1.getGraph();
1939 && !((
Template) scafVertex).getContractLevel().equals(
1943 mnt.name =
"IntraTemplateBuild";
1945 settings.getExcludedMutationTypes());
1946 for (
Vertex mutableSite : initialMutableSites)
1988 if (!(scafVertex instanceof
Template)
2038 settings.getRandomizer());
2043 String rotoSpaceFile =
"";
2050 true, settings.getLogger());
2057 boolean onlyRandomCombOfRings =
true;
2059 if (onlyRandomCombOfRings)
2063 if (combsOfRings.size() > 0)
2065 for (
Ring ring : combsOfRings)
2068 double shot = settings.getRandomizer().nextDouble();
2070 ring.getHeadVertex().getEdgeToParent().getSrcAP(),
2073 ring.getTailVertex().getEdgeToParent().getSrcAP(),
2080 if (shot < crowdProbH && shot < crowdProbT)
2082 molGraph.addRing(ring);
2089 ArrayList<List<Ring>> allCombsOfRings =
2095 ArrayList<List<Ring>> toRemove =
new ArrayList<>();
2096 for (List<Ring> setRings : allCombsOfRings)
2100 toRemove.add(setRings);
2104 allCombsOfRings.removeAll(toRemove);
2105 if (allCombsOfRings.isEmpty())
2107 String msg =
"Setup Rings: no combination of rings.";
2108 settings.getLogger().log(Level.INFO, msg);
2114 int sz = allCombsOfRings.size();
2117 List<Ring> selected =
new ArrayList<>();
2120 selected = allCombsOfRings.get(0);
2124 int selId = settings.getRandomizer().nextInt(sz);
2125 selected = allCombsOfRings.get(selId);
2129 for (
Ring ring : selected)
2131 molGraph.addRing(ring);
2147 settings.getLogger());
2148 if (molsmiles ==
null)
2150 String msg =
"Evaluation of graph: SMILES is null! "
2151 + molGraph.toString();
2152 settings.getLogger().log(Level.INFO, msg);
2153 molsmiles =
"FAIL: NO SMILES GENERATED";
2162 settings.getLogger());
2163 if (inchikey ==
null)
2165 String msg =
"Evaluation of graph: INCHI is null!";
2166 settings.getLogger().log(Level.INFO, msg);
2167 inchikey =
"UNDEFINED";
2191 if (mol.getUID().compareToIgnoreCase(molcode) == 0)
2209 int k = mols.size();
2210 double[] arr =
new double[k];
2212 for (
int i=0; i<k; i++)
2214 arr[i] = mols.get(i).getFitness();
2249 double lambda,
double sigmaOne,
double sigmaTwo)
2251 return getProbability(level, scheme, lambda, sigmaOne, sigmaTwo);
2295 int scheme,
double lambda,
double sigmaOne,
double sigmaTwo)
2298 sigmaOne, sigmaTwo);
2314 int scheme,
double lambda,
double sigmaOne,
double sigmaTwo)
2319 double f = Math.exp(-1.0 * value * lambda);
2320 prob = 1 - ((1-f)/(1+f));
2322 else if (scheme == 1)
2324 prob = 1.0 - Math.tanh(lambda * value);
2326 else if (scheme == 2)
2328 prob = 1.0-1.0/(1.0 + Math.exp(-sigmaOne * (value - sigmaTwo)));
2330 else if (scheme == 3)
2401 sigmaOne, sigmaTwo);
2430 boolean ignoreFreeRCVs)
2441 && !oap.isAvailableThroughout()
2442 && oap.getLinkedAP().getOwner()
2445 if (ignoreFreeRCVs && oap.getLinkedAP().getOwner().isRCV())
2448 crowdness = crowdness + 1;
2450 crowdness = crowdness + 1;
2473 double lambda,
double sigmaOne,
double sigmaTwo)
2482 sigmaOne, sigmaTwo);
2498 double lambda,
double sigmaOne,
double sigmaTwo)
2500 return getProbability(crowdedness, scheme, lambda, sigmaOne, sigmaTwo);
2519 for (
Vertex vtx : vertices)
2521 List<AttachmentPoint> daps = vtx.getAttachmentPoints();
2524 if (dp.isAvailable())
2526 APClass apClass = dp.getAPClass();
2527 if (classOfForbEnds.contains(apClass))
2529 String msg =
"Forbidden free AP for Vertex: "
2531 +
" MolId: " + (vtx.getBuildingBlockId() + 1)
2532 +
" Ftype: " + vtx.getBuildingBlockType()
2533 +
"\n"+ molGraph+
" \n "
2534 +
" AP class: " + apClass;
2535 fsParams.
getLogger().log(Level.WARNING, msg);
2546 protected static void readUID(String infile, HashSet<String> lstInchi)
2550 for (String str:lst)
2603 gaParams.getSymmetryProbability());
2606 Logger logger = gaParams.getLogger();
2608 projectOnSymmetricAPs, logger, rng);
2647 List<List<RelatedAPPair>> result =
new ArrayList<List<RelatedAPPair>>();
2656 Set<Long> originalVertexIDs =
new HashSet<Long>();
2657 tmpGraph.getVertexList().stream()
2658 .forEach(v -> originalVertexIDs.add(v.getVertexId()));
2669 tmpGraph.addCappingGroups(fragSpace);
2679 Map<String, String> smarts =
new HashMap<String, String>();
2682 smarts.put(rule.getName(), rule.getSMARTS());
2688 logger.warning(
"Could not apply bridgehead finding rules: "
2689 + msq.
getMessage() +
". Returning no match.");
2692 Map<SymmetricSetWithMode,List<RelatedAPPair>> symmRelatedBridgeHeadAPs =
2693 new HashMap<SymmetricSetWithMode,List<RelatedAPPair>>();
2694 List<RelatedAPPair> symBridgeHeadAPs =
new ArrayList<RelatedAPPair>();
2695 List<RelatedAPPair> asymBridgeHeadAPs =
new ArrayList<RelatedAPPair>();
2707 Set<String> doneIdPairs =
new HashSet<String>();
2708 for (
int[] idSubstructure : halfRingAtms)
2710 if (idSubstructure.length<2)
2712 throw new Error(
"SMARTS for matching half-ring pattern '"
2714 +
"' has identified " + idSubstructure.length
2716 +
"instead of at least 2. Modify rule to make it "
2717 +
"find 2 or more atoms.");
2721 int[] ids =
new int[] {
2722 idSubstructure[rule.getBridgeHeadPositions()[0]],
2723 idSubstructure[rule.getBridgeHeadPositions()[1]]};
2725 IAtom bhA = mol.getAtom(ids[0]);
2726 IAtom bhB = mol.getAtom(ids[1]);
2729 String idPairIdentifier =
"";
2731 idPairIdentifier = ids[0]+
"_"+ids[1];
2733 idPairIdentifier = ids[1]+
"_"+ids[0];
2734 if (doneIdPairs.contains(idPairIdentifier))
2736 doneIdPairs.add(idPairIdentifier);
2744 throw new IllegalStateException(
"Atoms in 3d molecular "
2745 +
"models of graph objects must have the "
2748 long vrtxIdA = (Long)
2750 long vrtxIdB = (Long)
2754 @SuppressWarnings(
"unchecked")
2755 List<AttachmentPoint> apsOnA = (List<AttachmentPoint>)
2757 @SuppressWarnings(
"unchecked")
2758 List<AttachmentPoint> apsOnB = (List<AttachmentPoint>)
2760 for (
int iAPA=0; iAPA<apsOnA.size(); iAPA++)
2776 for (
int iAPB=0; iAPB<apsOnB.size(); iAPB++)
2798 .getAPWithId(copyOfApA.
getID());
2800 .getAPWithId(copyOfApB.
getID());
2801 if (apA==
null || apB==
null)
2815 if (symInA.size()!=0 && symInB.size()!=0)
2820 symmRelatedBridgeHeadAPs);
2823 symmRelatedBridgeHeadAPs);
2825 symmRelatedBridgeHeadAPs);
2827 symBridgeHeadAPs.add(pair);
2829 asymBridgeHeadAPs.add(pair);
2835 if (asymBridgeHeadAPs.size()==0 && symBridgeHeadAPs.size()==0)
2842 List<List<RelatedAPPair>> candidateBridgeHeadAPPairs =
2843 new ArrayList<List<RelatedAPPair>>();
2844 if (symmRelatedBridgeHeadAPs.size()>0)
2848 List<RelatedAPPair> chosenSymSet =
2849 symmRelatedBridgeHeadAPs.get(key);
2851 @SuppressWarnings(
"unchecked")
2854 boolean apcImposedSymm = fragSpace.imposeSymmetryOnAPsOfClass(
2855 symmRelatedAPs.get(0).getAPClass());
2857 if (projectOnSymmetricAPs || apcImposedSymm)
2861 for (
int k=Math.min(chosenSymSet.size(), 6); k>0; k--)
2865 chosenSymSet, k, 50);
2872 for (List<RelatedAPPair> comb : combs)
2874 boolean isNew =
true;
2875 for (List<RelatedAPPair> knownComb :
2876 candidateBridgeHeadAPPairs)
2878 if (knownComb.containsAll(comb)
2879 && comb.containsAll(knownComb))
2887 candidateBridgeHeadAPPairs.add(comb);
2889 symBridgeHeadAPs.remove(pair);
2900 List<RelatedAPPair> single =
new ArrayList<RelatedAPPair>();
2902 candidateBridgeHeadAPPairs.add(single);
2907 List<RelatedAPPair> single =
new ArrayList<RelatedAPPair>();
2909 candidateBridgeHeadAPPairs.add(single);
2913 for (List<RelatedAPPair> combOnTmpGraph : candidateBridgeHeadAPPairs)
2915 List<RelatedAPPair> combOnOriginalGraph =
2916 new ArrayList<RelatedAPPair>();
2923 if (tmpGraph.getSymSetForVertex(
2924 pairOnTmpGraph.apA.getOwner()).contains(
2925 pairOnTmpGraph.apB.getOwner()))
2929 Vertex headVertexOnGraph = graph.getVertexAtPosition(
2930 tmpGraph.indexOf(pairOnTmpGraph.apA.getOwner()));
2931 int apHeadID = pairOnTmpGraph.apA.getIndexInOwner();
2932 List<Vertex> symHeadVrts = graph.getSymVerticesForVertex(
2934 if (symHeadVrts.size()==0)
2935 symHeadVrts.add(headVertexOnGraph);
2937 Vertex tailVertexOnGraph = graph.getVertexAtPosition(
2938 tmpGraph.indexOf(pairOnTmpGraph.apB.getOwner()));
2939 int apTailID = pairOnTmpGraph.apB.getIndexInOwner();
2940 List<Vertex> symTailVrts = graph.getSymVerticesForVertex(
2942 if (symTailVrts.size()==0)
2943 symTailVrts.add(tailVertexOnGraph);
2945 int numPairs = Math.min(symHeadVrts.size(), symTailVrts.size());
2946 for (
int iPair=0; iPair<numPairs; iPair++)
2957 pairOnTmpGraph.property,
2958 pairOnTmpGraph.propID);
2961 if (
shareAPs(pairOnOriginalGraph, combOnOriginalGraph))
2965 combOnOriginalGraph.add(pairOnOriginalGraph);
2968 if (combOnOriginalGraph.size() != 0
2971 result.add(combOnOriginalGraph);
2980 List<RelatedAPPair> pool,
int k,
int limit)
2982 List<RelatedAPPair> tmp =
new ArrayList<RelatedAPPair>();
2983 List<List<RelatedAPPair>> allCombs =
new ArrayList<List<RelatedAPPair>>();
2992 List<RelatedAPPair> tmp,
2993 List<List<RelatedAPPair>> allCombs,
int limit)
2997 if (allCombs.size()>=limit)
3005 List<RelatedAPPair> oneComb =
new ArrayList<RelatedAPPair>(tmp);
3006 allCombs.add(oneComb);
3011 for (
int i=left; i<pool.size(); ++i)
3020 tmp.remove(tmp.size() - 1);
3031 if (storage.containsKey(key))
3033 storage.get(key).add(pair);
3035 List<RelatedAPPair> lst =
new ArrayList<RelatedAPPair>();
3037 storage.put(key, lst);
3053 Set<AttachmentPoint> aps =
new HashSet<AttachmentPoint>();
3057 if (pair.apA == pair.apB
3058 ||aps.contains(pair.apA) || aps.contains(pair.apB))
3079 Iterable<RelatedAPPair> lstB)
3081 Set<AttachmentPoint> aps =
new HashSet<AttachmentPoint>();
3087 return aps.contains(pairA.
apA) || aps.contains(pairA.
apB);
3118 || !originalVertexIDs.contains(
3142 String elInIncomingFrag,
int[] allowedLengths,
3145 List<Vertex> usableBridgesOriginals =
3147 List<Vertex> usableBridges =
new ArrayList<Vertex>();
3148 final String rootAPC = elInIncomingFrag;
3149 for (
Vertex bridge : usableBridgesOriginals)
3151 IAtomContainer iacFrag = bridge.getIAtomContainer();
3152 List<Integer> atomIDs =
new ArrayList<Integer>();
3153 bridge.getAttachmentPoints()
3155 .filter(ap -> ap.getAPClass().getRule().startsWith(
3157 .forEach(ap -> atomIDs.add(ap.getAtomPositionNumber()));
3158 ShortestPaths sp =
new ShortestPaths(iacFrag, iacFrag.getAtom
3160 List<IAtom> path =
new ArrayList<IAtom>(Arrays.asList(
3161 sp.atomsTo(atomIDs.get(1))));
3162 if (IntStream.of(allowedLengths).anyMatch(x -> x == path.size()))
3167 usableBridges.add(clone);
3170 return usableBridges;
3188 List<Vertex> usableBridges =
new ArrayList<Vertex>();
3192 for (
APClass compatA : compatApClassesA)
3194 for (
APClass compatB : compatApClassesB)
3196 boolean sameAPC = compatA.equals(compatB);
3197 Map<APClass,Integer> apFingerprint =
3198 new HashMap<APClass,Integer>();
3201 apFingerprint.put(compatA,2);
3203 apFingerprint.put(compatA,1);
3204 apFingerprint.put(compatB,1);
3209 IAtomContainer iacFrag = bridge.getIAtomContainer();
3212 List<AttachmentPoint> apsForA =
new ArrayList<AttachmentPoint>();
3213 List<AttachmentPoint> apsForB =
new ArrayList<AttachmentPoint>();
3216 if (compatA.equals(apOnBridge.getAPClass()))
3217 apsForA.add(apOnBridge);
3218 if (compatB.equals(apOnBridge.getAPClass()))
3219 apsForB.add(apOnBridge);
3225 ShortestPaths sp =
new ShortestPaths(iacFrag,
3226 iacFrag.getAtom(apForA.getAtomPositionNumber()));
3229 if (apForA.equals(apForB))
3232 List<IAtom> path =
new ArrayList<IAtom>(
3233 Arrays.asList(sp.atomsTo(
3234 apForB.getAtomPositionNumber())));
3235 if (IntStream.of(allowedLengths).anyMatch(
3236 x -> x == path.size()))
3244 apForA.getIndexInOwner());
3247 apForB.getIndexInOwner());
3248 usableBridges.add(clone);
3255 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 DGraph makeGraphFromFragmentationOfMol(IAtomContainer mol, FragmenterParameters frgParams)
Converts a molecule into a DGraph by fragmentation and re-assembling of the fragments.
static DGraph makeGraphFromFragmentationOfMol(IAtomContainer mol, FragmenterParameters frgParams, FragmentSpace fragSpace, Monitor monitor)
Converts a molecule into a DGraph by fragmentation and re-assembling of the fragments.
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()
Returns the list of vertexes without entering Templates.
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.
void setEmbeddedRingsContract(ContractLevel embeddedRingsContract)
double getLinearAngleLimit()
void setCuttingRules(List< CuttingRule > cuttingRules)
Assigns the cutting rules loaded from the input.
ScaffoldingPolicy getScaffoldingPolicy()
void setLinearAngleLimit(double linearAngleLimit)
Sets the upper limit for an angle before it is treated as "flat" angle, i.e., close enough to 180 DEG...
List< CuttingRule > getCuttingRules()
ContractLevel getEmbeddedRingsContract()
void setEmbedRingsInTemplate(boolean embedRingsInTemplate)
void setScaffoldingPolicy(ScaffoldingPolicy sp)
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 (a.k.a.
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.
String label
Label defining additional details, such as which label to search for in case of elemental symbol-base...
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.