19package denoptim.combinatorial;
22import java.util.ArrayList;
23import java.util.Collection;
24import java.util.Collections;
25import java.util.HashMap;
28import java.util.concurrent.ArrayBlockingQueue;
29import java.util.concurrent.Future;
30import java.util.concurrent.RejectedExecutionHandler;
31import java.util.concurrent.ThreadPoolExecutor;
32import java.util.concurrent.TimeUnit;
33import java.util.logging.Level;
35import org.apache.commons.io.FileUtils;
36import org.apache.commons.lang3.time.StopWatch;
38import denoptim.constants.DENOPTIMConstants;
39import denoptim.exception.DENOPTIMException;
40import denoptim.fragspace.FragmentSpaceParameters;
41import denoptim.fragspace.FragsCombination;
42import denoptim.fragspace.FragsCombinationIterator;
43import denoptim.fragspace.IdFragmentAndAP;
44import denoptim.graph.DGraph;
45import denoptim.graph.Vertex;
46import denoptim.graph.Vertex.BBType;
47import denoptim.io.DenoptimIO;
48import denoptim.programs.RunTimeParameters.ParametersType;
49import denoptim.programs.combinatorial.CEBLParameters;
50import denoptim.utils.GraphUtils;
77 final ThreadPoolExecutor
tpe;
141 submitted =
new ArrayList<GraphBuildingTask>();
146 TimeUnit.NANOSECONDS,
147 new ArrayBlockingQueue<Runnable>(1));
149 Runtime.getRuntime().addShutdownHook(
new Thread()
158 if (!
tpe.awaitTermination(30, TimeUnit.SECONDS))
163 if (!
tpe.awaitTermination(60, TimeUnit.SECONDS))
168 catch (InterruptedException ie)
174 Thread.currentThread().interrupt();
180 tpe.setRejectedExecutionHandler(
new RejectedExecutionHandler()
183 public void rejectedExecution(Runnable r,
184 ThreadPoolExecutor executor)
189 executor.getQueue().put(r);
191 catch (InterruptedException ex)
195 ex.printStackTrace();
196 String msg =
"EXCEPTION in rejectedExecution.";
226 boolean hasException =
false;
229 if (tsk.foundException())
249 boolean allDone =
true;
252 if (!tsk.isCompleted())
275 boolean storeChkPt =
false;
307 List<GraphBuildingTask> completed =
new ArrayList<GraphBuildingTask>();
310 if (tsk.isCompleted())
338 tot = tot + tsk.getNumberOfSubTasks();
352 StopWatch watch =
new StopWatch();
355 tpe.prestartAllCoreThreads();
367 msg =
"Restarting Combinatorial job from checkpoint file. "
368 + DENOPTIMConstants.EOL
369 +
"All graphs with ID higher than "
371 +
" are now being re-generated. Be aware that this "
372 +
"includes graphs managed either by "
373 +
"partially executed or completed tasks of the previous "
375 + DENOPTIMConstants.EOL
376 +
"To avoid duplicates, you should remove from the results "
377 +
"of the previos run all graphs with ID higher than "
379 +
". You can find them in the "
380 +
"index file ('" + DENOPTIMConstants.FSEIDXNAMEROOT + level
382 + DENOPTIMConstants.EOL
383 +
"Now reading '" + DENOPTIMConstants.SERGFILENAMEEXT +
"' "
388 if (!denoptim.files.FileUtils.checkExists(
391 msg =
"ERROR! Folder '"
393 +
"' does not exist! Use 'FSE-DBROOTFOLDER' to "
394 +
"provide the pathname to the existing folder where "
395 +
"the previously generated graphs are located.";
400 Collection<File> lst = FileUtils.listFiles(
402 new String[] {DENOPTIMConstants.SERGFILENAMEEXT},
false);
407 String fName = f.getName();
408 int serGrphID = Integer.parseInt(fName.substring(
414 msg =
"Removing non-safely completed graph '" + fName +
"'";
417 denoptim.files.FileUtils.deleteFile(
419 + File.separator + fName);
424 boolean interrupted =
false;
427 msg =
"Starting exploration of level " + level;
435 long startTime = System.currentTimeMillis();
438 long endTime = System.currentTimeMillis();
439 long millis = (endTime - startTime);
442 Collection<File> lst = FileUtils.listFiles(
449 if (outCount != totSubmSubTasks && level > -1)
451 msg =
"Mismatch between the number of submitted "
452 +
"tasks (" + totSubmSubTasks +
") and those "
455 +
"(" + outCount +
")";
466 msg =
"Exception in submitted task.";
473 msg =
"Waiting for completion of level " + level;
474 msg = msg + String.format(
" (elapsed %d min, %d sec)",
475 TimeUnit.MILLISECONDS.toMinutes(millis),
476 TimeUnit.MILLISECONDS.toSeconds(millis)
477 - TimeUnit.MINUTES.toSeconds(
478 TimeUnit.MILLISECONDS.toMinutes(millis)));
485 msg =
"Timeout reached: stopping all subtasks.";
512 msg =
"Exploration of level " + level +
" "
513 +
"completed" + DENOPTIMConstants.EOL
514 +
"----------------------------------------"
515 +
"----------------------------------------"
524 boolean noRoot =
false;
525 if (numSubTasks == 0)
530 Collection<File> lstRootsForNextLev = FileUtils.listFiles(
533 new String[] {DENOPTIMConstants.SERGFILENAMEEXT},
535 if (lstRootsForNextLev.size() == 0)
547 msg =
"Previous level did not return any extendable graph. "
548 +
"Terminating exploration." + DENOPTIMConstants.EOL
549 +
"----------------------------------------"
550 +
"----------------------------------------"
567 msg =
"Overall time: " + watch.toString() +
". "
568 + DENOPTIMConstants.EOL
590 ArrayList<DGraph> scafLevel =
new ArrayList<DGraph>();
596 String msg =
"User defined root graphs are treated as "
597 +
"if they were scaffolds. "
598 +
"That is, the 'level' of the available attachment "
599 +
"points is considered to be '-1' "
600 +
"no matter what is the actual level of such APs "
601 +
"in the root graph.";
609 rootGraph.changeSignOfVertexID();
611 rootGraph.renumberGraphVertices();
613 scafLevel.add(rootGraph);
620 .getScaffoldLibrary().size(); i++)
630 return scafLevel.size();
638 int itersFromChkPt = 0;
640 if (!denoptim.files.FileUtils.checkExists(prevLevDirName))
642 msg =
"Previous level folder '" + prevLevDirName +
"' not found!";
645 Collection<File> files = FileUtils.listFiles(
new File(prevLevDirName),
647 ArrayList<File> lstFiles =
new ArrayList<File>(files);
648 Collections.sort(lstFiles);
649 for (File file : lstFiles)
659 file.getAbsolutePath()).get(0);
675 StringBuilder sb =
new StringBuilder(512);
677 sb.append(
" - #Usable APs on root = ");
679 sb.append(
" - Size of candidates sets = ");
681 sb.append(
" - Total #Combinations = ");
685 sb.append(
" - Details for root APs:");
687 Map<IdFragmentAndAP, ArrayList<IdFragmentAndAP>> m =
696 sb.append(
" " + iTrgAP +
" -> "+trgAP);
712 msg =
"Exception in submitted task.";
720 rootGraph, fragsToAdd, level,
724 ArrayList<Integer> nextIds = fcf.
getNextIds();
745 System.out.println(
"Wait until "+level+
"=="+maxL+
" and "
750 System.out.println(
"Execution stopped: now waiting "
751 +
" for checkpoint file to mature");
754 ArrayList<Integer> oldIds =
new ArrayList<Integer>();
755 ArrayList<Integer> nowIds =
new ArrayList<Integer>();
764 System.out.println(
"NOT CONVERGED");
766 +
"checkpoint file did not "
773 System.out.println(oldIds +
" " + nowIds
774 +
" nEqualChecks:" + nEqual);
775 boolean converged =
true;
776 if (nowIds.size() != oldIds.size())
782 for (
int iId=0; iId<nowIds.size(); iId++)
784 if (nowIds.get(iId) != oldIds.get(iId))
795 oldIds.addAll(nowIds);
804 System.out.println(
"Stopped with converged "
805 +
"checkpoint IDs: " + nowIds);
807 +
"request of generating checkpoint data "
808 +
"for testing purposes");
828 +
"for level " + level +
" of graph " + cntRoot;
833 msg =
"Total number of combination of fragments generated "
834 +
"for level " + level +
" = " + total;
897 tpe.getQueue().clear();
Helper methods for the exploration of the fragment space.
static void storeAllGraphsOfLevel(CEBLParameters settings, ArrayList< DGraph > lstGraphs, int level)
Serialize all DENOPTIMGraphs to file.
static String getNameOfStorageDir(CEBLParameters settings, int level)
static void serializeCheckPoint(CEBLParameters settings)
Store the checkpoint in a text file with json format.
Object collecting information needed to restart a FragSpaceExplorer job.
void setNextIds(ArrayList< Integer > nextIds)
Set the indexes that identify the combination of fragments next to the latest one that has been prope...
void setUnqGraphId(int val)
Set the restart value for the unique graph ID.
void setSafelyCompletedGraphId(int val)
Set the graphId of the safely completed graph.
ArrayList< Integer > getNextIds()
boolean serFileAlreadyUsed(String filename)
int getLatestSafelyCompletedGraphId()
void setLevel(int level)
Set the current level.
void setUnqMolId(int val)
Set the restart value for the unique molecule ID.
void setRootId(int val)
Set the graph ID of the root graph used to build this task.
void setUnqVrtId(long l)
Set the restart value for the unique vertex ID.
Generates all combinators of fragments by means of asynchronous threads.
boolean firstAfterRestart
Flag identifying the first iteration after restart from checkpoint.
int serFromChkRestart
Number of serialized graphs recovered from previous run database upon restart from checkpoint file.
FragmentSpaceParameters fsSettings
Settings and definition of the fragment space.
final List< GraphBuildingTask > submitted
Sorted list of subtasks.
void makeCheckPoint()
Identify the task preceding the earliest non-completed task and use it to create a checkpoint file.
DGraph startNewGraphFromScaffold(int scafIdx)
int verbosity
Verbosity level.
void cleanup()
clean all reference to submitted tasks
final Map< GraphBuildingTask, Future< Object > > submittedAndFutures
Submitted subtasks and their futures.
boolean subtaskHasException()
Looks for exceptions in the subtasks and, if any, store its reference locally to allow reporting it b...
CombinatorialExplorerByLayer(CEBLParameters settings)
Constructor.
boolean allTasksCompleted()
Check for completion of all subtasks.
Throwable thrownByTask
If any, here we stores the exception returned by a subtask.
CEBLParameters settings
All settings controlling the tasks executed by this class.
int totSubmittedTasks
Number of tasks submitted directly of by subtasks.
void stopRun()
Stops all subtasks and shutdown executor.
boolean restartFromChkPt
Flag indicating to restart from checkpoint file.
int exploreCombinationsAtGivenLevel(int level)
Generate graphs by exploring all combination of fragments at a given level of a growing graph.
final ThreadPoolExecutor tpe
Asynchronous tasks manager.
void run()
Run the combinatorial exploration.
Task that builds a graph by appending a given combination of fragments onto a given list of attachmen...
ArrayList< Integer > getNextIds()
Returns the set of indeces that identify the position of the the (next) combination of fragment in th...
int getRootId()
Returns the graphID of the root graph.
void setNextIds(ArrayList< Integer > nextIds)
Set the set of indexes that identify the position of the the (next) combination of fragment in the sp...
int getGraphId()
Returns the graphID of the original graph or of the latest cyclic alternative.
General set of constants used in DENOPTIM.
static final String SERGFILENAMEEXT
Extension filenames of serialized graphs.
static final String EOL
new line character
static final String SERGFILENAMEROOT
Prefix filenames of serialized graphs.
Parameters defining the fragment space.
FragmentSpace getFragmentSpace()
Data structure identifying a combination of one or more pairs of attachment points located on specifi...
Factory of combination of fragments.
int getNumGeneratedCombs()
FragsCombination next()
Generate the next combination of fragments.
Map< IdFragmentAndAP, ArrayList< IdFragmentAndAP > > getCandidatesMap()
ArrayList< Integer > getNextIds()
Returns the list of indeces used to calculate the next iteration.
void setStartingPoint(ArrayList< Integer > nextIds)
Sets the starting point for the iterator.
ArrayList< Integer > getSizesOfCandidateSets()
Data structure containing information that identifies a single AP of a vertex/fragment.
Container for the list of vertices and the edges that connect them.
void addVertex(Vertex vertex)
Appends a vertex to this graph without creating any edge.
void setLocalMsg(String msg)
A vertex is a data structure that has an identity and holds a list of AttachmentPoints.
static Vertex newVertexFromLibrary(int bbId, Vertex.BBType bbt, FragmentSpace fragSpace)
Builds a new molecular fragment kind of vertex.
Utility methods for input/output.
static ArrayList< DGraph > readDENOPTIMGraphsFromJSONFile(String fileName)
Reads a list of DGraphs from a JSON file.
boolean containsParameters(ParametersType type)
String getWorkDirectory()
Gets the pathname to the working directory.
RunTimeParameters getParameters(ParametersType type)
Logger getLogger()
Get the name of the program specific logger.
int getVerbosity()
Returns the level of verbosity, i.e., the amount of log that we want to print.
Parameters controlling execution of the combinatorial algorithm for exploration of a fragment space b...
ArrayList< DGraph > getRootGraphs()
boolean useGivenRoots
Flag declaring that generation of graphs will use a given list of graphs as starting points for the e...
CheckPoint getCheckPoint()
boolean prepareFilesForTests()
boolean restartFromCheckPoint()
static synchronized void resetUniqueGraphCounter(int val)
Reset the unique graph counter to the given value.
static synchronized long getUniqueVertexIndex()
Unique counter for the number of graph vertices generated.
static synchronized void resetUniqueMoleculeCounter(int val)
Reset the unique mol counter to the given value.
static synchronized int getUniqueMoleculeIndex()
Unique counter for the number of molecules generated.
static synchronized void resetUniqueVertexCounter(long l)
Reset the unique vertex counter to the given value.
static synchronized int getUniqueGraphIndex()
Unique counter for the number of graphs generated.
The type of building block.
Identifier of the type of parameters.
FS_PARAMS
Parameters pertaining the definition of the fragment space.