$darkmode
DENOPTIM
GeneOpsRunner.java
Go to the documentation of this file.
1/*
2 * DENOPTIM
3 * Copyright (C) 2019 Marco Foscato <marco.foscato@uib.no>
4 *
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU Affero General Public License as published
7 * by the Free Software Foundation, either version 3 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU Affero General Public License for more details.
14 *
15 * You should have received a copy of the GNU Affero General Public License
16 * along with this program. If not, see <http://www.gnu.org/licenses/>.
17 */
18
19package denoptim.programs.genetweeker;
20
21import java.io.File;
22import java.util.ArrayList;
23import java.util.HashSet;
24import java.util.List;
25import java.util.Set;
26import java.util.logging.Level;
27import java.util.logging.Logger;
28
29import org.openscience.cdk.interfaces.IAtomContainer;
30
31import denoptim.constants.DENOPTIMConstants;
32import denoptim.exception.DENOPTIMException;
33import denoptim.fragspace.FragmentSpace;
34import denoptim.fragspace.FragmentSpaceParameters;
35import denoptim.ga.GraphOperations;
36import denoptim.ga.XoverSite;
37import denoptim.graph.DGraph;
38import denoptim.graph.Template;
39import denoptim.graph.Vertex;
40import denoptim.graph.rings.RingClosureParameters;
41import denoptim.io.DenoptimIO;
42import denoptim.logging.Monitor;
43import denoptim.molecularmodeling.ThreeDimTreeBuilder;
44import denoptim.programs.RunTimeParameters.ParametersType;
45import denoptim.programs.denovo.GAParameters;
46import denoptim.task.ProgramTask;
47import denoptim.utils.CrossoverType;
48import denoptim.utils.MutationType;
49
57public class GeneOpsRunner extends ProgramTask
58{
59
64
69
74
78 private Logger logger = null;
79
80//------------------------------------------------------------------------------
81
87 public GeneOpsRunner(File configFile, File workDir)
88 {
89 super(configFile,workDir);
90 }
91
92//------------------------------------------------------------------------------
93
94 @Override
95 public void runProgram() throws Throwable
96 {
98 goParams.readParameterFile(configFilePathName.getAbsolutePath());
99 goParams.checkParameters();
100 goParams.processParameters();
101 goParams.startProgramSpecificLogger(loggerIdentifier, false); //to STDOUT
102 goParams.printParameters();
103
104 this.logger = goParams.getLogger();
105 this.settings = goParams;
108 {
111 }
112 this.fragSpace = fsParams.getFragmentSpace();
114 {
115 this.gaParams = (GAParameters) settings.getParameters(
117 } else {
118 this.gaParams = new GAParameters();
119 }
120
121 switch (goParams.operatorToTest)
122 {
123 case CROSSOVER:
124 runXOver();
125 break;
126 case XOVER:
127 runXOver();
128 break;
129 case MUTATION:
130 runMutation();
131 break;
132 }
133 }
134
135//------------------------------------------------------------------------------
136
137 private void runMutation() throws DENOPTIMException
138 {
139 DGraph graph = null;
140 try
141 {
143 new File(settings.inpFileM)).get(0);
144 } catch (Exception e)
145 {
146 e.printStackTrace();
147 }
148
149 logger.log(Level.INFO, "Initial graphs: " + NL + graph.toString() + NL);
151
152 //Just in case we used some keyword to set something that affects
153 //mutation operations
156 {
159 }
161 {
164 }
166 {
169 }
170
171 boolean done = false;
172 if (mt != null)
173 {
175 graph, "mutation " + mt);
176
177 if (v == null)
178 {
179 List<Vertex> mutable = graph.getSelectedMutableSites(mt);
180 if (mutable.size()==0)
181 {
182 logger.log(Level.INFO, "Graph has no mutable site of type '"
183 + mt + "'. Mutation aborted.");
184 return;
185 }
187 logger.log(Level.INFO, "Randomly choosed vertex as target "
188 + "for mutation '" + mt + "': " + v);
189 }
190
191 int apID = settings.idNewAP;
192 if (mt==MutationType.ADDLINK)
193 {
194 apID = settings.idTargetAP;
195 if (apID<0)
196 throw new DENOPTIMException("ID of target AP is negative. "
197 + "For mutation " + mt + " you should specify also "
198 + "the index of the AP on the mutation target as "
199 + "TESTGENOPS-APIDONTARGETVERTEX.");
200 }
201
203
204 // NB: last boolean asks to ignore the growth probability
205 done = GraphOperations.performMutation(v, mt, true,
206 settings.idNewVrt, apID, new Monitor(), gaParams);
207 } else {
208 logger.log(Level.INFO, "Attempting mutation a random mutation on a "
209 + "random vertex");
210 done = GraphOperations.performMutation(graph, new Monitor(), gaParams);
211 }
212
213 if (done)
214 {
215 logger.log(Level.INFO, "Result of mutation:" + NL + graph.toString()+NL);
216 }
220 IAtomContainer iac = t3d.convertGraphTo3DAtomContainer(graph, true);
222 }
223
224//------------------------------------------------------------------------------
225
226 private void runXOver() throws DENOPTIMException
227 {
228 DGraph male = null;
229 DGraph female = null;
230 try
231 {
233 new File(settings.inpFileM)).get(0);
235 new File(settings.inpFileF)).get(0);
236 } catch (Exception e)
237 {
238 e.printStackTrace();
239 return;
240 }
241
242 logger.log(Level.INFO, "Initial graphs: "+NL
243 +"MALE: "+male+NL
244 +"FEMALE: "+female);
245
246 // Identify the crossover operation to perform
247 XoverSite xos = null;
248 if (settings.xoverSrcMale!=null && settings.xoverSrcFemale!=null)
249 {
251 male, "crossover");
253 female, "crossover");
254
256 if (settings.xoverSubGraphEndMale.size()!=0)
257 xoverType = CrossoverType.SUBGRAPH;
258
259 List<Vertex> subGraphA = new ArrayList<Vertex>();
260 subGraphA.add(vm);
261 male.getChildTreeLimited(vm, subGraphA, getSubGraphEnds(male,
262 settings.xoverSubGraphEndMale, "crossover"));
263 List<Vertex> subGraphB = new ArrayList<Vertex>();
264 subGraphB.add(vf);
265 female.getChildTreeLimited(vf, subGraphB, getSubGraphEnds(female,
266 settings.xoverSubGraphEndFemale, "crossover"));
267
268 xos = new XoverSite(subGraphA, subGraphB, xoverType);
269
270 // Ensure uniqueness on vertexID
272 female.renumberGraphVertices();
273
274 logger.log(Level.INFO,NL+"Initial graphs now with unique vertexID: "
275 +NL+ "v: "+ vm.getVertexId() + " of MALE: " + male
276 +NL+ "v:" + vf.getVertexId() + " of FEMALE: " + female);
277 } else {
278 logger.log(Level.INFO, "Attempting crossover on a site detected "
279 + "on-the-fly");
280 List<XoverSite> sites = GraphOperations.locateCompatibleXOverPoints(
282 if (sites.isEmpty())
283 {
284 logger.log(Level.WARNING, "No crossover site detected.");
285 return;
286 } else {
287 logger.log(Level.INFO, "Randombly choosing among "
288 + sites.size() + " xover sites.");
289 }
291 }
292
294
295 logger.log(Level.INFO, NL + "Result of crossover:"
296 + NL + "MALE: " + male
297 + NL + "FEMALE: " + female);
298
302 IAtomContainer iacM = t3d.convertGraphTo3DAtomContainer(male, true);
303 IAtomContainer iacF = t3d.convertGraphTo3DAtomContainer(female, true);
306 }
307
308//------------------------------------------------------------------------------
309
310 private Set<Vertex> getSubGraphEnds(DGraph graph,
311 List<int[]> embeddingPaths, String operation)
312 {
313 Set<Vertex> result = new HashSet<Vertex>();
314 for (int[] embeddingPath : embeddingPaths)
315 {
316 result.add(getEmbeddedVertex(embeddingPath, graph, operation));
317 }
318 return result;
319 }
320
321//------------------------------------------------------------------------------
322
323 private Vertex getEmbeddedVertex(int[] embeddingPath,
324 DGraph graph, String operation)
325 {
326 String str = "";
327 if (embeddingPath != null && embeddingPath.length>1)
328 {
329 for (int i=(embeddingPath.length-1); i>-1; i--)
330 {
331 if (i==embeddingPath.length-1)
332 {
333 str = "[" + embeddingPath[i] + "]";
334 } else {
335 str = "[" + str + " " + embeddingPath[i] + "] ";
336 }
337 }
338 logger.log(Level.INFO, "Attempting '" + operation + "' on deep "
339 + "vertex " + str);
340 Vertex outerVertex = null;
341 DGraph innerGraph = graph;
342 for (int i=0; i<embeddingPath.length; i++)
343 {
344 if (outerVertex != null && outerVertex instanceof Template)
345 {
346 innerGraph = ((Template) outerVertex).getInnerGraph();
347 }
348 outerVertex = innerGraph.getVertexWithId(embeddingPath[i]);
349 if (outerVertex == null)
350 {
351 logger.log(Level.INFO, "VertexID '" + embeddingPath[i] +
352 "' not found in graph " + innerGraph);
353 return null;
354 }
355 }
356 return outerVertex;
357 } else {
358 if (embeddingPath==null)
359 {
360 logger.log(Level.INFO, "No mutation site specified.");
361 return null;
362 }
363 int vid = embeddingPath[0];
364 logger.log(Level.INFO, "Attempting '" + operation + "' on vertex "
365 + embeddingPath[0]);
366 Vertex v = graph.getVertexWithId(vid);
367 if (v == null)
368 {
369 logger.log(Level.INFO, "VertexID '" + vid + "' not found in "
370 + "graph " + graph);
371 return null;
372 }
373 return v;
374 }
375 }
376
377//------------------------------------------------------------------------------
378
379}
General set of constants used in DENOPTIM.
static final Object STOREDVID
Key of the property remembering vertex IDs.
Class defining a space of building blocks.
Parameters defining the fragment space.
Collection of operators meant to alter graphs and associated utilities.
static List< XoverSite > locateCompatibleXOverPoints(DGraph graphA, DGraph graphB, FragmentSpace fragSpace, int maxSizeXoverSubGraph)
Identify crossover sites, i.e., subgraphs that can be swapped between two graphs (i....
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.
This class collects the data identifying the subgraphs that would be swapped by a crossover event.
Definition: XoverSite.java:36
Container for the list of vertices and the edges that connect them.
Definition: DGraph.java:102
Vertex getVertexWithId(long vid)
Searches for a vertex with the given identifier.
Definition: DGraph.java:2811
void renumberGraphVertices()
Reassign vertex IDs to all vertices of this graph.
Definition: DGraph.java:5512
void getChildTreeLimited(Vertex vertex, List< Vertex > children, boolean stopBeforeRCVs)
Gets all the children of the current vertex recursively.
Definition: DGraph.java:3257
List< Vertex > getSelectedMutableSites(MutationType requestedType)
A list of mutation sites from within this graph.
Definition: DGraph.java:6902
A vertex is a data structure that has an identity and holds a list of AttachmentPoints.
Definition: Vertex.java:61
void setProperty(Object key, Object property)
Definition: Vertex.java:1235
Parameters and setting related to handling ring closures.
Utility methods for input/output.
static void writeSDFFile(String fileName, IAtomContainer mol)
Writes IAtomContainer to SDF file.
static ArrayList< DGraph > readDENOPTIMGraphsFromFile(File inFile)
Reads a list of DGraphs from file.
A collection of counters user to count actions taken by the evolutionary algorithm.
Definition: Monitor.java:37
Tool to build build three-dimensional (3D) tree-like molecular structures from DGraph.
IAtomContainer convertGraphTo3DAtomContainer(DGraph graph)
Created a three-dimensional molecular representation from a given DGraph.
Logger startProgramSpecificLogger(String loggerIdentifier)
Starts a logger with the given name.
boolean containsParameters(ParametersType type)
void setParameters(RunTimeParameters otherParams)
RunTimeParameters getParameters(ParametersType type)
void readParameterFile(String infile)
Read the parameter TXT file line by line and interpret its content.
Logger getLogger()
Get the name of the program specific logger.
void printParameters()
Print all parameters.
Randomizer getRandomizer()
Returns the current program-specific randomizer.
Parameters for genetic algorithm.
int maxXOverableSubGraphSize
Limit to the size of subgraphs that are exchanged during crossover.
Tool to run genetic operations in a stand-alone fashion, i.e., outside of a genetic algorithm run.
Set< Vertex > getSubGraphEnds(DGraph graph, List< int[]> embeddingPaths, String operation)
GeneOpsRunnerParameters settings
Settings from input parameters.
Vertex getEmbeddedVertex(int[] embeddingPath, DGraph graph, String operation)
FragmentSpace fragSpace
Fragment space in use.
GeneOpsRunner(File configFile, File workDir)
Creates and configures the program task.
GAParameters gaParams
Parameters for genetic algorithm.
Logger logger
Program-specific logger.
Parameters controlling execution of TestOperator.
List< int[]> xoverSubGraphEndFemale
Female VertedID (not index) that represent the end of the subgraph that is swapped by crossover.
List< int[]> xoverSubGraphEndMale
Male VertedID (not index) that represent the end of the subgraph that is swapped by crossover.
int[] xoverSrcFemale
Female VertexID (not index) on which perform xover.
int idTargetAP
Target attachment point ID for mutation (AP belonging already to the graph).
void checkParameters()
Evaluate consistency of input parameters.
void processParameters()
Processes all parameters and initialize related objects.
MutationType mutationType
Type of mutation to perform.
int[] xoverSrcMale
Male VertedID (not index) on which perform xover.
Task structure for any of the main programs in the denoptim project, such as genetic algorithm and co...
String loggerIdentifier
Identifier of this program's logger.
File configFilePathName
File containing configuration parameters for the program task.
File workDir
The file system location where we want to be placed when doing the work.
Definition: Task.java:78
final String NL
System-dependent line separator (newline)
Definition: Task.java:93
public< T > T randomlyChooseOne(Collection< T > c)
Chooses one member among the given collection.
FS_PARAMS
Parameters pertaining the definition of the fragment space.
GA_PARAMS
Parameters pertaining the genetic algorithm.
RC_PARAMS
Parameters pertaining to ring closures in graphs.
Types of crossover defined.
SUBGRAPH
Swaps a portion of a branch trying to retain cyclicity.
BRANCH
Swaps the entire branch starting from a given vertex.
Types of mutation defined in relation to what happens to the target vertex (i.e., the actual mutation...
ADDLINK
Adds a vertex between two previously connected vertexes.