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();
479 return new ArrayList<Candidate>();
481 }
catch (Throwable t) {
482 if (!settings.xoverFailureTolerant)
485 ArrayList<DGraph> parents =
new ArrayList<DGraph>();
489 +
"_failed_xover.sdf"), parents,
true,
490 settings.getLogger(), settings.getRandomizer());
493 +
"XOverSite(C): " + xosOnClones.
toString() +
NL
494 +
" Please, report this to the authors ",t);
498 return new ArrayList<Candidate>();
504 lstIdVA = lstIdVA +
"_" + v.getVertexId();
507 lstIdVB = lstIdVB +
"_" + v.getVertexId();
508 String[] msgs =
new String[2];
511 +
"|" + gid1 +
"|" + lstIdVA
513 +
"Gen:" + cB.getGeneration() +
" Cand:" + candIdB
514 +
"|" + gid2 +
"|" + lstIdVB;
516 +
"Gen:" + cB.getGeneration() +
" Cand:" + candIdB
517 +
"|" + gid2 +
"|" + lstIdVB
520 +
"|" + gid1 +
"|" + lstIdVA;
523 graphsAffectedByXover[0] = gAClone;
524 graphsAffectedByXover[1] = gBClone;
526 List<Candidate> validOffspring =
new Population(settings);
527 for (
int ig=0; ig<graphsAffectedByXover.length; ig++)
529 DGraph g = graphsAffectedByXover[ig];
551 }
catch (NullPointerException|IllegalArgumentException e)
553 if (!settings.xoverGraphFailedEvalTolerant)
555 ArrayList<DGraph> parents =
new ArrayList<DGraph>();
558 parents.add(gAClone);
559 parents.add(gBClone);
561 +
"_failed_xover-ed_check.sdf"), parents,
true,
562 settings.getLogger(), settings.getRandomizer());
582 APClass apc = rcv.getEdgeToParent().getSrcAP().getAPClass();
600 offspring.
setUID(res[0].toString().trim());
601 offspring.
setSmiles(res[1].toString().trim());
604 validOffspring.add(offspring);
607 if (validOffspring.size() == 0)
610 return new ArrayList<Candidate>();
613 if (maxCandidatesToReturn==1)
616 if (choiceOfOffstring<0)
618 chosenOffspring = settings.getRandomizer().randomlyChooseOne(
624 chosenOffspring = validOffspring.get(choiceOfOffstring);
626 validOffspring.retainAll(Arrays.asList(chosenOffspring));
635 return validOffspring;
641 List<Candidate> eligibleParents,
Monitor mnt,
657 while (numatt < settings.getMaxGeneticOpAttempts())
677 String parentMolName = FilenameUtils.getBaseName(parent.
getSDFFile());
680 +
" Gen:" + parent.
getGeneration() +
" Cand:" + parentMolName
681 +
"|" + parentGraphId);
698 }
catch (NullPointerException|IllegalArgumentException e)
700 if (!settings.mutatedGraphFailedEvalTolerant)
702 settings.getLogger().log(Level.INFO,
"WRITING DEBUG FILE for "
705 parent.
getGraph(),
false, settings.getLogger(),
706 settings.getRandomizer());
708 graph,
false, settings.getLogger(),
709 settings.getRandomizer());
733 APClass apc = rcv.getEdgeToParent().getSrcAP().getAPClass();
751 offspring.
setUID(res[0].toString().trim());
752 offspring.
setSmiles(res[1].toString().trim());
770 ArrayList<DGraph> graphs;
774 }
catch (Exception e)
778 String msg =
"Could not read graphs from file " + srcFile
779 +
". No candidate generated!";
780 settings.getLogger().log(Level.SEVERE, msg);
783 if (graphs.size() == 0 || graphs.size() > 1)
786 String msg =
"Found " + graphs.size() +
" graphs in file " + srcFile
787 +
". I expect one and only one graph. "
788 +
"No candidate generated!";
789 settings.getLogger().log(Level.SEVERE, msg);
793 DGraph graph = graphs.get(0);
797 String msg =
"Null graph from file " + srcFile
798 +
". Expected one and only one graph. "
799 +
"No candidate generated!";
800 settings.getLogger().log(Level.SEVERE, msg);
820 candidate.
setUID(res[0].toString().trim());
821 candidate.
setSmiles(res[1].toString().trim());
828 String msg =
"Candidate " + candidate.
getName() +
" is imported from "
830 settings.getLogger().log(Level.INFO, msg);
885 if (rcv.getEdgeToParent() ==
null)
890 if (rcv.getEdgeToParent() ==
null)
895 APClass apc = rcv.getEdgeToParent().getSrcAP().getAPClass();
912 candidate.
setUID(res[0].toString().trim());
913 candidate.
setSmiles(res[1].toString().trim());
960 +
"fragmentation but no cutting rules provided. Please,"
961 +
"add FRG-CUTTINGRULESFILE=path/to/your/file to the "
983 String msg =
"Unable to convert molecule (" + mol.getAtomCount()
984 +
" atoms) to DENOPTIM graph. " + de.getMessage();
985 settings.getLogger().log(Level.WARNING, msg);
1004 candidate.
setUID(res[0].toString().trim());
1005 candidate.
setSmiles(res[1].toString().trim());
1029 List<CuttingRule> cuttingRules, Logger logger,
1055 List<CuttingRule> cuttingRules, Logger logger,
1079 List<CuttingRule> cuttingRules, Logger logger,
1084 scaffoldingPolicy, 190, fragSpace);
1107 List<CuttingRule> cuttingRules, Logger logger,
1113 scaffoldingPolicy, linearAngleLimit,
false,
null,
1141 List<CuttingRule> cuttingRules, Logger logger,
1143 boolean embedRingsInTemplates,
ContractLevel ringTmplContract,
1149 cuttingRules, logger);
1150 for (
Vertex v : fragments)
1160 if (fragments.size()==0)
1167 + mol.getAtomCount() +
" atoms produced 0 fragments.");
1172 switch (scaffoldingPolicy)
1176 for (
Vertex v : fragments)
1180 boolean setAsScaffold =
false;
1182 for (IAtom atm : iac.atoms())
1184 if (scaffoldingPolicy.label.equals(
1187 setAsScaffold =
true;
1202 case LARGEST_FRAGMENT:
1205 scaffold = fragments.stream()
1206 .max(Comparator.comparing(
1209 }
catch (Exception e)
1216 +
"among " + fragments.size() +
" fragments.", e);
1228 +
"identified as the "
1237 AtomicInteger vId =
new AtomicInteger(1);
1238 for (
int i=1; i<fragments.size(); i++)
1248 if (fragSpace!=
null && fragSpace.getCappingMap()!=
null)
1252 if (v.getAttachmentPoints().size()!=1 || v.isRCV())
1255 APClass srcAPC = v.getAP(0).getLinkedAPThroughout().getAPClass();
1256 APClass capAPC = fragSpace.getAPClassOfCappingVertex(srcAPC);
1257 Vertex cap = fragSpace.getCappingVertexWithAPClass(capAPC);
1269 v.getAP(0).setAPClass(capAPC);
1274 if (embedRingsInTemplates)
1278 fragSpace, ringTmplContract);
1298 Vertex lastlyAdded =
null;
1299 for (
int i=-1; i>-4; i--)
1301 lastlyAdded = graph.getVertexList().get(
1302 graph.getVertexList().size()+i);
1303 if (!lastlyAdded.
isRCV())
1308 if (!apI.isAvailable())
1311 for (
int j=0; j<vertexes.size(); j++)
1313 Vertex fragJ = vertexes.get(j);
1315 boolean ringClosure =
false;
1316 if (graph.containsVertex(fragJ))
1325 if (apI.getCutId()==apJ.getCutId())
1334 graph.appendVertexOnAP(apI, rcvI.
getAP(0));
1340 graph.appendVertexOnAP(apJ, rcvJ.
getAP(0));
1341 graph.addRing(rcvI, rcvJ);
1345 graph.appendVertexOnAP(apI, apJ);
1371 String filename,
GAParameters settings,
boolean printpathNames)
1374 StringBuilder sb =
new StringBuilder(512);
1378 df.setMaximumFractionDigits(settings.getPrecisionLevel());
1379 df.setMinimumFractionDigits(settings.getPrecisionLevel());
1384 synchronized (population)
1386 List<Candidate> popMembers =
new ArrayList<Candidate>();
1387 for (
int i=0; i<settings.getPopulationSize(); i++)
1390 popMembers.add(mol);
1395 sb.append(String.format(
"%-20s", mname));
1397 sb.append(String.format(
"%-20s",
1399 sb.append(String.format(
"%-30s", mol.
getUID()));
1407 sb.append(System.getProperty(
"line.separator"));
1414 if (settings.savePopFile())
1416 File dest =
new File(filename.replaceAll(
"\\.txt$",
".sdf"));
1420 if (stats.trim().length() > 0)
1437 StringBuilder sb =
new StringBuilder(128);
1438 sb.append(
NL+
NL+
"#####POPULATION SUMMARY#####"+
NL);
1439 int n = popln.size();
1440 sb.append(String.format(
"%-30s",
"SIZE:"));
1441 sb.append(String.format(
"%12s", n));
1445 sb.append(String.format(
"%-30s",
"MAX:")).append(
df.format(f));
1448 sb.append(String.format(
"%-30s",
"MIN:")).append(
df.format(f));
1451 sb.append(String.format(
"%-30s",
"MEAN:")).append(
df.format(f));
1454 sb.append(String.format(
"%-30s",
"MEDIAN:")).append(
df.format(f));
1457 sb.append(String.format(
"%-30s",
"STDDEV:")).append(
df.format(f));
1462 sb.append(String.format(
"%-30s",
"SKEW:")).append(
df.format(f));
1465 sb.append(String.format(
"%-30s",
"SKEW:")).append(
" NaN (sdev too small)");
1469 res = sb.toString();
1487 List<Candidate> eligibleParents,
int number,
GAParameters settings)
1511 for (
int i=0; i < mates.length; i++)
1514 matesStr = matesStr + settings.
NL;
1515 matesStr = matesStr + mates[i].
getUID();
1524 e.printStackTrace();
1539 List<Vertex> candidates =
new ArrayList<Vertex>(
1541 candidates.removeIf(v ->
1543 || v.getBuildingBlockType() ==
BBType.
CAP);
1565 List<Candidate> eligibleParents,
Population population,
1566 int[] choiceOfParents,
int choiceOfXOverSites,
GAParameters settings)
1569 if (choiceOfParents==
null)
1572 parentA = eligibleParents.get(choiceOfParents[0]);
1574 if (parentA ==
null)
1585 parentA, eligibleParents, fragSpace);
1586 if (matesCompatibleWithFirst.size() == 0)
1590 if (choiceOfParents==
null)
1595 parentB = eligibleParents.get(choiceOfParents[1]);
1597 if (parentB ==
null)
1601 if (choiceOfXOverSites<0)
1607 choiceOfXOverSites);
1617 StringBuilder sb =
new StringBuilder(32);
1625 return sb.toString();
1633 StringBuilder sb =
new StringBuilder(32);
1645 return sb.toString();
1652 StringBuilder sb =
new StringBuilder(32);
1654 return sb.toString();
1662 StringBuilder sb =
new StringBuilder(32);
1664 .append(
FSEP).append(
"Final.txt");
1665 return sb.toString();
1684 denoptim.files.FileUtils.createDirectory(dirName);
1685 File fileDir =
new File(dirName);
1687 boolean intermediateCandidatesAreOnDisk =
1691 for (
int i=0; i<popln.size(); i++)
1698 if (intermediateCandidatesAreOnDisk && sdfile!=
null)
1700 FileUtils.copyFileToDirectory(
new File(sdfile), fileDir);
1702 File candFile =
new File(fileDir, c.
getName()
1707 }
catch (IOException ioe) {
1709 + sdfile +
"' to '" + fileDir +
"' for candidate "
1712 if (imgfile !=
null && intermediateCandidatesAreOnDisk)
1715 FileUtils.copyFileToDirectory(
new File(imgfile), fileDir);
1716 }
catch (IOException ioe) {
1718 + imgfile +
"' to '" + fileDir +
"' for candidate "
1744 new File(filename),
true);
1745 if (candidates.size() == 0)
1747 String msg =
"Found 0 candidates in file " + filename;
1748 settings.getLogger().log(Level.SEVERE, msg);
1754 if (uniqueIDsSet.addNewUniqueEntry(candidate.getUID()))
1760 candidate.setName(molName);
1761 candidate.getGraph().setGraphId(gctr);
1762 candidate.getGraph().setLocalMsg(
"INITIAL_POPULATION");
1763 String sdfPathName = genDir + System.getProperty(
"file.separator")
1765 candidate.setSDFFile(sdfPathName);
1766 candidate.setImageFile(
null);
1772 population.add(candidate);
1774 settings.getLogger().log(Level.WARNING,
"Candidate from intial "
1775 +
"population file '" + filename
1776 +
"' is rejected because its identifier is "
1777 +
"already listed among the previously visited "
1782 if (population.isEmpty())
1784 String msg =
"Population is still empty after having processes "
1785 + candidates.size() +
" candidates from file " + filename;
1786 settings.getLogger().log(Level.SEVERE, msg);
1795 protected static void writeUID(String outfile, HashSet<String> lstInchi,
1798 StringBuilder sb =
new StringBuilder(256);
1799 Iterator<String> iter = lstInchi.iterator();
1801 boolean first =
true;
1802 while(iter.hasNext())
1806 sb.append(iter.next());
1811 sb.append(
NL).append(iter.next());
1831 long val = Long.MIN_VALUE;
1834 DGraph g = popln1.getGraph();
1871 && !((
Template) scafVertex).getContractLevel().equals(
1875 mnt.name =
"IntraTemplateBuild";
1877 settings.getExcludedMutationTypes());
1878 for (
Vertex mutableSite : initialMutableSites)
1920 if (!(scafVertex instanceof
Template)
1970 settings.getRandomizer());
1975 String rotoSpaceFile =
"";
1982 true, settings.getLogger());
1989 boolean onlyRandomCombOfRings =
true;
1991 if (onlyRandomCombOfRings)
1995 if (combsOfRings.size() > 0)
1997 for (
Ring ring : combsOfRings)
2000 double shot = settings.getRandomizer().nextDouble();
2002 ring.getHeadVertex().getEdgeToParent().getSrcAP(),
2005 ring.getTailVertex().getEdgeToParent().getSrcAP(),
2012 if (shot < crowdProbH && shot < crowdProbT)
2014 molGraph.addRing(ring);
2021 ArrayList<List<Ring>> allCombsOfRings =
2027 ArrayList<List<Ring>> toRemove =
new ArrayList<>();
2028 for (List<Ring> setRings : allCombsOfRings)
2032 toRemove.add(setRings);
2036 allCombsOfRings.removeAll(toRemove);
2037 if (allCombsOfRings.isEmpty())
2039 String msg =
"Setup Rings: no combination of rings.";
2040 settings.getLogger().log(Level.INFO, msg);
2046 int sz = allCombsOfRings.size();
2049 List<Ring> selected =
new ArrayList<>();
2052 selected = allCombsOfRings.get(0);
2056 int selId = settings.getRandomizer().nextInt(sz);
2057 selected = allCombsOfRings.get(selId);
2061 for (
Ring ring : selected)
2063 molGraph.addRing(ring);
2079 settings.getLogger());
2080 if (molsmiles ==
null)
2082 String msg =
"Evaluation of graph: SMILES is null! "
2083 + molGraph.toString();
2084 settings.getLogger().log(Level.INFO, msg);
2085 molsmiles =
"FAIL: NO SMILES GENERATED";
2094 settings.getLogger());
2095 if (inchikey ==
null)
2097 String msg =
"Evaluation of graph: INCHI is null!";
2098 settings.getLogger().log(Level.INFO, msg);
2099 inchikey =
"UNDEFINED";
2123 if (mol.getUID().compareToIgnoreCase(molcode) == 0)
2141 int k = mols.size();
2142 double[] arr =
new double[k];
2144 for (
int i=0; i<k; i++)
2146 arr[i] = mols.get(i).getFitness();
2181 double lambda,
double sigmaOne,
double sigmaTwo)
2183 return getProbability(level, scheme, lambda, sigmaOne, sigmaTwo);
2227 int scheme,
double lambda,
double sigmaOne,
double sigmaTwo)
2230 sigmaOne, sigmaTwo);
2246 int scheme,
double lambda,
double sigmaOne,
double sigmaTwo)
2251 double f = Math.exp(-1.0 * value * lambda);
2252 prob = 1 - ((1-f)/(1+f));
2254 else if (scheme == 1)
2256 prob = 1.0 - Math.tanh(lambda * value);
2258 else if (scheme == 2)
2260 prob = 1.0-1.0/(1.0 + Math.exp(-sigmaOne * (value - sigmaTwo)));
2262 else if (scheme == 3)
2333 sigmaOne, sigmaTwo);
2362 boolean ignoreFreeRCVs)
2373 && !oap.isAvailableThroughout()
2374 && oap.getLinkedAP().getOwner()
2377 if (ignoreFreeRCVs && oap.getLinkedAP().getOwner().isRCV())
2380 crowdness = crowdness + 1;
2382 crowdness = crowdness + 1;
2405 double lambda,
double sigmaOne,
double sigmaTwo)
2414 sigmaOne, sigmaTwo);
2430 double lambda,
double sigmaOne,
double sigmaTwo)
2432 return getProbability(crowdedness, scheme, lambda, sigmaOne, sigmaTwo);
2451 for (
Vertex vtx : vertices)
2453 List<AttachmentPoint> daps = vtx.getAttachmentPoints();
2456 if (dp.isAvailable())
2458 APClass apClass = dp.getAPClass();
2459 if (classOfForbEnds.contains(apClass))
2461 String msg =
"Forbidden free AP for Vertex: "
2463 +
" MolId: " + (vtx.getBuildingBlockId() + 1)
2464 +
" Ftype: " + vtx.getBuildingBlockType()
2465 +
"\n"+ molGraph+
" \n "
2466 +
" AP class: " + apClass;
2467 fsParams.
getLogger().log(Level.WARNING, msg);
2478 protected static void readUID(String infile, HashSet<String> lstInchi)
2482 for (String str:lst)
2535 gaParams.getSymmetryProbability());
2538 Logger logger = gaParams.getLogger();
2540 projectOnSymmetricAPs, logger, rng);
2579 List<List<RelatedAPPair>> result =
new ArrayList<List<RelatedAPPair>>();
2588 Set<Long> originalVertexIDs =
new HashSet<Long>();
2589 tmpGraph.getVertexList().stream()
2590 .forEach(v -> originalVertexIDs.add(v.getVertexId()));
2601 tmpGraph.addCappingGroups(fragSpace);
2611 Map<String, String> smarts =
new HashMap<String, String>();
2614 smarts.put(rule.getName(), rule.getSMARTS());
2622 Map<SymmetricSetWithMode,List<RelatedAPPair>> symmRelatedBridgeHeadAPs =
2623 new HashMap<SymmetricSetWithMode,List<RelatedAPPair>>();
2624 List<RelatedAPPair> symBridgeHeadAPs =
new ArrayList<RelatedAPPair>();
2625 List<RelatedAPPair> asymBridgeHeadAPs =
new ArrayList<RelatedAPPair>();
2637 Set<String> doneIdPairs =
new HashSet<String>();
2638 for (
int[] idSubstructure : halfRingAtms)
2640 if (idSubstructure.length<2)
2642 throw new Error(
"SMARTS for matching half-ring pattern '"
2644 +
"' has identified " + idSubstructure.length
2646 +
"instead of at least 2. Modify rule to make it "
2647 +
"find 2 or more atoms.");
2651 int[] ids =
new int[] {
2652 idSubstructure[rule.getBridgeHeadPositions()[0]],
2653 idSubstructure[rule.getBridgeHeadPositions()[1]]};
2655 IAtom bhA = mol.getAtom(ids[0]);
2656 IAtom bhB = mol.getAtom(ids[1]);
2659 String idPairIdentifier =
"";
2661 idPairIdentifier = ids[0]+
"_"+ids[1];
2663 idPairIdentifier = ids[1]+
"_"+ids[0];
2664 if (doneIdPairs.contains(idPairIdentifier))
2666 doneIdPairs.add(idPairIdentifier);
2674 throw new IllegalStateException(
"Atoms in 3d molecular "
2675 +
"models of graph objects must have the "
2678 long vrtxIdA = (Long)
2680 long vrtxIdB = (Long)
2684 @SuppressWarnings(
"unchecked")
2685 List<AttachmentPoint> apsOnA = (List<AttachmentPoint>)
2687 @SuppressWarnings(
"unchecked")
2688 List<AttachmentPoint> apsOnB = (List<AttachmentPoint>)
2690 for (
int iAPA=0; iAPA<apsOnA.size(); iAPA++)
2706 for (
int iAPB=0; iAPB<apsOnB.size(); iAPB++)
2728 .getAPWithId(copyOfApA.
getID());
2730 .getAPWithId(copyOfApB.
getID());
2731 if (apA==
null || apB==
null)
2741 if (symInA.size()!=0 && symInB.size()!=0)
2746 symmRelatedBridgeHeadAPs);
2749 symmRelatedBridgeHeadAPs);
2751 symmRelatedBridgeHeadAPs);
2753 symBridgeHeadAPs.add(pair);
2755 asymBridgeHeadAPs.add(pair);
2761 if (asymBridgeHeadAPs.size()==0 && symBridgeHeadAPs.size()==0)
2768 List<List<RelatedAPPair>> candidateBridgeHeadAPPairs =
2769 new ArrayList<List<RelatedAPPair>>();
2770 if (symmRelatedBridgeHeadAPs.size()>0)
2774 List<RelatedAPPair> chosenSymSet =
2775 symmRelatedBridgeHeadAPs.get(key);
2777 @SuppressWarnings(
"unchecked")
2780 boolean apcImposedSymm = fragSpace.imposeSymmetryOnAPsOfClass(
2781 symmRelatedAPs.get(0).getAPClass());
2783 if (projectOnSymmetricAPs || apcImposedSymm)
2787 for (
int k=Math.min(chosenSymSet.size(), 6); k>0; k--)
2791 chosenSymSet, k, 50);
2798 for (List<RelatedAPPair> comb : combs)
2800 boolean isNew =
true;
2801 for (List<RelatedAPPair> knownComb :
2802 candidateBridgeHeadAPPairs)
2804 if (knownComb.containsAll(comb)
2805 && comb.containsAll(knownComb))
2813 candidateBridgeHeadAPPairs.add(comb);
2815 symBridgeHeadAPs.remove(pair);
2826 List<RelatedAPPair> single =
new ArrayList<RelatedAPPair>();
2828 candidateBridgeHeadAPPairs.add(single);
2833 List<RelatedAPPair> single =
new ArrayList<RelatedAPPair>();
2835 candidateBridgeHeadAPPairs.add(single);
2839 for (List<RelatedAPPair> combOnTmpGraph : candidateBridgeHeadAPPairs)
2841 List<RelatedAPPair> combOnOriginalGraph =
2842 new ArrayList<RelatedAPPair>();
2845 Vertex headVertexOnGraph = graph.getVertexAtPosition(
2846 tmpGraph.indexOf(pairOnTmpGraph.apA.getOwner()));
2847 int apHeadID = pairOnTmpGraph.apA.getIndexInOwner();
2848 List<Vertex> symHeadVrts = graph.getSymVerticesForVertex(
2850 if (symHeadVrts.size()==0)
2851 symHeadVrts.add(headVertexOnGraph);
2853 Vertex tailVertexOnGraph = graph.getVertexAtPosition(
2854 tmpGraph.indexOf(pairOnTmpGraph.apB.getOwner()));
2855 int apTailID = pairOnTmpGraph.apB.getIndexInOwner();
2856 List<Vertex> symTailVrts = graph.getSymVerticesForVertex(
2858 if (symTailVrts.size()==0)
2859 symTailVrts.add(tailVertexOnGraph);
2861 int numPairs = Math.min(symHeadVrts.size(), symTailVrts.size());
2862 for (
int iPair=0; iPair<numPairs; iPair++)
2865 symHeadVrts.get(iPair).getAP(apHeadID),
2866 symTailVrts.get(iPair).getAP(apTailID),
2867 pairOnTmpGraph.property,
2868 pairOnTmpGraph.propID);
2869 combOnOriginalGraph.add(pairOnOriginalGraph);
2872 result.add(combOnOriginalGraph);
2880 List<RelatedAPPair> pool,
int k,
int limit)
2882 List<RelatedAPPair> tmp =
new ArrayList<RelatedAPPair>();
2883 List<List<RelatedAPPair>> allCombs =
new ArrayList<List<RelatedAPPair>>();
2892 List<RelatedAPPair> tmp,
2893 List<List<RelatedAPPair>> allCombs,
int limit)
2897 if (allCombs.size()>=limit)
2905 List<RelatedAPPair> oneComb =
new ArrayList<RelatedAPPair>(tmp);
2906 allCombs.add(oneComb);
2911 for (
int i=left; i<pool.size(); ++i)
2920 tmp.remove(tmp.size() - 1);
2931 if (storage.containsKey(key))
2933 storage.get(key).add(pair);
2935 List<RelatedAPPair> lst =
new ArrayList<RelatedAPPair>();
2937 storage.put(key, lst);
2953 Set<AttachmentPoint> aps =
new HashSet<AttachmentPoint>();
2957 if (aps.contains(pair.apA) || aps.contains(pair.apB))
2978 Iterable<RelatedAPPair> lstB)
2980 Set<AttachmentPoint> aps =
new HashSet<AttachmentPoint>();
2986 return aps.contains(pairA.
apA) || aps.contains(pairA.
apB);
3017 || !originalVertexIDs.contains(
3041 String elInIncomingFrag,
int[] allowedLengths,
3044 List<Vertex> usableBridgesOriginals =
3046 List<Vertex> usableBridges =
new ArrayList<Vertex>();
3047 final String rootAPC = elInIncomingFrag;
3048 for (
Vertex bridge : usableBridgesOriginals)
3050 IAtomContainer iacFrag = bridge.getIAtomContainer();
3051 List<Integer> atomIDs =
new ArrayList<Integer>();
3052 bridge.getAttachmentPoints()
3054 .filter(ap -> ap.getAPClass().getRule().startsWith(
3056 .forEach(ap -> atomIDs.add(ap.getAtomPositionNumber()));
3057 ShortestPaths sp =
new ShortestPaths(iacFrag, iacFrag.getAtom
3059 List<IAtom> path =
new ArrayList<IAtom>(Arrays.asList(
3060 sp.atomsTo(atomIDs.get(1))));
3061 if (IntStream.of(allowedLengths).anyMatch(x -> x == path.size()))
3066 usableBridges.add(clone);
3069 return usableBridges;
3087 List<Vertex> usableBridges =
new ArrayList<Vertex>();
3091 for (
APClass compatA : compatApClassesA)
3093 for (
APClass compatB : compatApClassesB)
3095 boolean sameAPC = compatA.equals(compatB);
3096 Map<APClass,Integer> apFingerprint =
3097 new HashMap<APClass,Integer>();
3100 apFingerprint.put(compatA,2);
3102 apFingerprint.put(compatA,1);
3103 apFingerprint.put(compatB,1);
3108 IAtomContainer iacFrag = bridge.getIAtomContainer();
3111 List<AttachmentPoint> apsForA =
new ArrayList<AttachmentPoint>();
3112 List<AttachmentPoint> apsForB =
new ArrayList<AttachmentPoint>();
3115 if (compatA.equals(apOnBridge.getAPClass()))
3116 apsForA.add(apOnBridge);
3117 if (compatB.equals(apOnBridge.getAPClass()))
3118 apsForB.add(apOnBridge);
3124 ShortestPaths sp =
new ShortestPaths(iacFrag,
3125 iacFrag.getAtom(apForA.getAtomPositionNumber()));
3128 if (apForA.equals(apForB))
3131 List<IAtom> path =
new ArrayList<IAtom>(
3132 Arrays.asList(sp.atomsTo(
3133 apForB.getAtomPositionNumber())));
3134 if (IntStream.of(allowedLengths).anyMatch(
3135 x -> x == path.size()))
3143 apForA.getIndexInOwner());
3146 apForB.getIndexInOwner());
3147 usableBridges.add(clone);
3154 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 (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.
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.