$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.io.DenoptimIO;
41import denoptim.logging.Monitor;
42import denoptim.molecularmodeling.ThreeDimTreeBuilder;
43import denoptim.programs.RunTimeParameters.ParametersType;
44import denoptim.programs.denovo.GAParameters;
45import denoptim.task.ProgramTask;
46import denoptim.utils.CrossoverType;
47import denoptim.utils.MutationType;
48
56public class GeneOpsRunner extends ProgramTask
57{
58
63
68
73
77 private Logger logger = null;
78
79//------------------------------------------------------------------------------
80
86 public GeneOpsRunner(File configFile, File workDir)
87 {
88 super(configFile,workDir);
89 }
90
91//------------------------------------------------------------------------------
92
93 @Override
94 public void runProgram() throws Throwable
95 {
97 goParams.readParameterFile(configFilePathName.getAbsolutePath());
98 goParams.checkParameters();
99 goParams.processParameters();
100 goParams.startProgramSpecificLogger(loggerIdentifier, false); //to STDOUT
101 goParams.printParameters();
102
103 this.logger = goParams.getLogger();
104 this.settings = goParams;
107 {
110 }
111 this.fragSpace = fsParams.getFragmentSpace();
113 {
114 this.gaParams = (GAParameters) settings.getParameters(
116 } else {
117 this.gaParams = new GAParameters();
118 }
119
120 switch (goParams.operatorToTest)
121 {
122 case CROSSOVER:
123 runXOver();
124 break;
125 case XOVER:
126 runXOver();
127 break;
128 case MUTATION:
129 runMutation();
130 break;
131 }
132 }
133
134//------------------------------------------------------------------------------
135
136 private void runMutation() throws DENOPTIMException
137 {
138 DGraph graph = null;
139 try
140 {
142 new File(settings.inpFileM)).get(0);
143 } catch (Exception e)
144 {
145 e.printStackTrace();
146 }
147
148 logger.log(Level.INFO, "Initial graphs: " + NL + graph.toString() + NL);
150
151 //Just in case we used some keyword to set something that affects
152 //mutation operations
155 {
158 }
160 {
163 }
164
165 if (mt != null)
166 {
168 graph, "mutation " + mt);
169
170 if (v == null)
171 {
172 return;
173 }
174
175 int apID = settings.idNewAP;
176 if (mt==MutationType.ADDLINK)
177 {
178 apID = settings.idTargetAP;
179 if (apID<0)
180 throw new DENOPTIMException("ID of target AP is negative. "
181 + "For mutation " + mt + " you should specify also "
182 + "the index of the AP on the mutation target as "
183 + "TESTGENOPS-APIDONTARGETVERTEX.");
184 }
185
187
188 // NB: last boolean asks to ignore the growth probability
190 settings.idNewVrt, apID, new Monitor(), gaParams);
191 } else {
192 logger.log(Level.INFO, "Attempting mutation a random mutation on a "
193 + "random vertex");
195 }
196 logger.log(Level.INFO, "Result of mutation:" + NL + graph.toString()+NL);
197
201 IAtomContainer iac = t3d.convertGraphTo3DAtomContainer(graph, true);
203 }
204
205//------------------------------------------------------------------------------
206
207 private void runXOver() throws DENOPTIMException
208 {
209 DGraph male = null;
210 DGraph female = null;
211 try
212 {
214 new File(settings.inpFileM)).get(0);
216 new File(settings.inpFileF)).get(0);
217 } catch (Exception e)
218 {
219 e.printStackTrace();
220 return;
221 }
222
223 logger.log(Level.INFO, "Initial graphs: "+NL
224 +"MALE: "+male+NL
225 +"FEMALE: "+female);
226
227 // Identify the crossover operation to perform
228 XoverSite xos = null;
229 if (settings.xoverSrcMale!=null && settings.xoverSrcFemale!=null)
230 {
232 male, "crossover");
234 female, "crossover");
235
237 if (settings.xoverSubGraphEndMale.size()!=0)
238 xoverType = CrossoverType.SUBGRAPH;
239
240 List<Vertex> subGraphA = new ArrayList<Vertex>();
241 subGraphA.add(vm);
242 male.getChildTreeLimited(vm, subGraphA, getSubGraphEnds(male,
243 settings.xoverSubGraphEndMale, "crossover"));
244 List<Vertex> subGraphB = new ArrayList<Vertex>();
245 subGraphB.add(vf);
246 female.getChildTreeLimited(vf, subGraphB, getSubGraphEnds(female,
247 settings.xoverSubGraphEndFemale, "crossover"));
248
249 xos = new XoverSite(subGraphA, subGraphB, xoverType);
250
251 // Ensure uniqueness on vertexID
253 female.renumberGraphVertices();
254
255 logger.log(Level.INFO,NL+"Initial graphs now with unique vertexID: "
256 +NL+ "v: "+ vm.getVertexId() + " of MALE: " + male
257 +NL+ "v:" + vf.getVertexId() + " of FEMALE: " + female);
258 } else {
259 logger.log(Level.INFO, "Attempting crossover on a site detected "
260 + "on-the-fly");
261 List<XoverSite> sites = GraphOperations.locateCompatibleXOverPoints(
263 if (sites.isEmpty())
264 {
265 logger.log(Level.WARNING, "No crossover site detected.");
266 return;
267 } else {
268 logger.log(Level.INFO, "Randombly choosing among "
269 + sites.size() + " xover sites.");
270 }
272 }
273
275
276 logger.log(Level.INFO, NL + "Result of crossover:"
277 + NL + "MALE: " + male
278 + NL + "FEMALE: " + female);
279
283 IAtomContainer iacM = t3d.convertGraphTo3DAtomContainer(male, true);
284 IAtomContainer iacF = t3d.convertGraphTo3DAtomContainer(female, true);
287 }
288
289//------------------------------------------------------------------------------
290
291 private Set<Vertex> getSubGraphEnds(DGraph graph,
292 List<int[]> embeddingPaths, String operation)
293 {
294 Set<Vertex> result = new HashSet<Vertex>();
295 for (int[] embeddingPath : embeddingPaths)
296 {
297 result.add(getEmbeddedVertex(embeddingPath, graph, operation));
298 }
299 return result;
300 }
301
302//------------------------------------------------------------------------------
303
304 private Vertex getEmbeddedVertex(int[] embeddingPath,
305 DGraph graph, String operation)
306 {
307 String str = "";
308 if (embeddingPath != null && embeddingPath.length>1)
309 {
310 for (int i=(embeddingPath.length-1); i>-1; i--)
311 {
312 if (i==embeddingPath.length-1)
313 {
314 str = "[" + embeddingPath[i] + "]";
315 } else {
316 str = "[" + str + " " + embeddingPath[i] + "] ";
317 }
318 }
319 logger.log(Level.INFO, "Attempting '" + operation + "' on deep "
320 + "vertex " + str);
321 Vertex outerVertex = null;
322 DGraph innerGraph = graph;
323 for (int i=0; i<embeddingPath.length; i++)
324 {
325 if (outerVertex != null && outerVertex instanceof Template)
326 {
327 innerGraph = ((Template) outerVertex).getInnerGraph();
328 }
329 outerVertex = innerGraph.getVertexWithId(embeddingPath[i]);
330 if (outerVertex == null)
331 {
332 logger.log(Level.INFO, "VertexID '" + embeddingPath[i] +
333 "' not found in graph " + innerGraph);
334 return null;
335 }
336 }
337 return outerVertex;
338 } else {
339 int vid = embeddingPath[0];
340 logger.log(Level.INFO, "Attempting '" + operation + "' on vertex "
341 + embeddingPath[0]);
342 Vertex v = graph.getVertexWithId(vid);
343 if (v == null)
344 {
345 logger.log(Level.INFO, "VertexID '" + vid + "' not found in "
346 + "graph " + graph);
347 return null;
348 }
349 return v;
350 }
351 }
352
353//------------------------------------------------------------------------------
354
355}
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:2582
void renumberGraphVertices()
Reassign vertex IDs to all vertices of this graph.
Definition: DGraph.java:5283
void getChildTreeLimited(Vertex vertex, List< Vertex > children, boolean stopBeforeRCVs)
Gets all the children of the current vertex recursively.
Definition: DGraph.java:3028
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:1148
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.
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.