repo
stringlengths
1
191
file
stringlengths
23
351
code
stringlengths
0
5.32M
file_length
int64
0
5.32M
avg_line_length
float64
0
2.9k
max_line_length
int64
0
288k
extension_type
stringclasses
1 value
Janus
Janus-master/src/minerful/MinerFulMinerStarter.java
package minerful; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Set; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import org.apache.commons.cli.Option; import org.apache.commons.cli.Options; import minerful.concept.ProcessModel; import minerful.concept.TaskChar; import minerful.concept.TaskCharArchive; import minerful.concept.constraint.ConstraintsBag; import minerful.io.params.OutputModelParameters; import minerful.logparser.LogParser; import minerful.miner.core.MinerFulKBCore; import minerful.miner.core.MinerFulPruningCore; import minerful.miner.core.MinerFulQueryingCore; import minerful.miner.params.MinerFulCmdParameters; import minerful.miner.stats.GlobalStatsTable; import minerful.params.InputLogCmdParameters; import minerful.params.SystemCmdParameters; import minerful.params.ViewCmdParameters; import minerful.postprocessing.params.PostProcessingCmdParameters; import minerful.utils.MessagePrinter; public class MinerFulMinerStarter extends AbstractMinerFulStarter { protected static final String PROCESS_MODEL_NAME_PATTERN = "Process model discovered from %s"; protected static final String DEFAULT_ANONYMOUS_MODEL_NAME = "Discovered process model"; private static MessagePrinter logger = MessagePrinter.getInstance(MinerFulMinerStarter.class); @Override public Options setupOptions() { Options cmdLineOptions = new Options(); Options minerfulOptions = MinerFulCmdParameters.parseableOptions(), inputOptions = InputLogCmdParameters.parseableOptions(), systemOptions = SystemCmdParameters.parseableOptions(), viewOptions = ViewCmdParameters.parseableOptions(), outputOptions = OutputModelParameters.parseableOptions(), postProptions = PostProcessingCmdParameters.parseableOptions(); for (Object opt: postProptions.getOptions()) { cmdLineOptions.addOption((Option)opt); } for (Object opt: minerfulOptions.getOptions()) { cmdLineOptions.addOption((Option)opt); } for (Object opt: inputOptions.getOptions()) { cmdLineOptions.addOption((Option)opt); } for (Object opt: viewOptions.getOptions()) { cmdLineOptions.addOption((Option)opt); } for (Object opt: outputOptions.getOptions()) { cmdLineOptions.addOption((Option)opt); } for (Object opt: systemOptions.getOptions()) { cmdLineOptions.addOption((Option)opt); } return cmdLineOptions; } /** * @param args * the command line arguments: [regular expression] [number of * strings] [minimum number of characters per string] [maximum * number of characters per string] [alphabet]... */ public static void main(String[] args) { MinerFulMinerStarter minerMinaStarter = new MinerFulMinerStarter(); Options cmdLineOptions = minerMinaStarter.setupOptions(); InputLogCmdParameters inputParams = new InputLogCmdParameters( cmdLineOptions, args); MinerFulCmdParameters minerFulParams = new MinerFulCmdParameters( cmdLineOptions, args); ViewCmdParameters viewParams = new ViewCmdParameters( cmdLineOptions, args); OutputModelParameters outParams = new OutputModelParameters( cmdLineOptions, args); SystemCmdParameters systemParams = new SystemCmdParameters( cmdLineOptions, args); PostProcessingCmdParameters postParams = new PostProcessingCmdParameters( cmdLineOptions, args); if (systemParams.help) { systemParams.printHelp(cmdLineOptions); System.exit(0); } if (!isEventLogGiven(cmdLineOptions, inputParams, systemParams)) { System.exit(1); } MessagePrinter.configureLogging(systemParams.debugLevel); logger.info("Loading log..."); LogParser logParser = MinerFulMinerLauncher.deriveLogParserFromLogFile( inputParams, minerFulParams); TaskCharArchive taskCharArchive = logParser.getTaskCharArchive(); ProcessModel processModel = minerMinaStarter.mine(logParser, inputParams, minerFulParams, postParams, taskCharArchive); new MinerFulOutputManagementLauncher().manageOutput(processModel, viewParams, outParams, systemParams, logParser); } public static boolean isEventLogGiven(Options cmdLineOptions, InputLogCmdParameters inputParams, SystemCmdParameters systemParams) { if (inputParams.inputLogFile == null) { systemParams.printHelpForWrongUsage("Input log file missing! Please use the " + InputLogCmdParameters.INPUT_LOGFILE_PATH_PARAM_NAME + " option.", cmdLineOptions); return false; } return true; } public ProcessModel mine(LogParser logParser, MinerFulCmdParameters minerFulParams, PostProcessingCmdParameters postParams, Character[] alphabet) { return this.mine(logParser, null, minerFulParams, postParams, alphabet); } public ProcessModel mine(LogParser logParser, InputLogCmdParameters inputParams, MinerFulCmdParameters minerFulParams, PostProcessingCmdParameters postParams, Character[] alphabet) { TaskCharArchive taskCharArchive = new TaskCharArchive(alphabet); return this.mine(logParser, inputParams, minerFulParams, postParams, taskCharArchive); } public ProcessModel mine(LogParser logParser, MinerFulCmdParameters minerFulParams, PostProcessingCmdParameters postParams, TaskCharArchive taskCharArchive) { return this.mine(logParser, null, minerFulParams, postParams, taskCharArchive); } public ProcessModel mine(LogParser logParser, InputLogCmdParameters inputParams, MinerFulCmdParameters minerFulParams, PostProcessingCmdParameters postParams, TaskCharArchive taskCharArchive) { GlobalStatsTable globalStatsTable = new GlobalStatsTable(taskCharArchive, minerFulParams.branchingLimit); globalStatsTable = computeKB(logParser, minerFulParams, taskCharArchive, globalStatsTable); System.gc(); ProcessModel proMod = ProcessModel.generateNonEvaluatedBinaryModel(taskCharArchive); proMod.setName(makeDiscoveredProcessName(inputParams)); proMod.bag = queryForConstraints(logParser, minerFulParams, postParams, taskCharArchive, globalStatsTable, proMod.bag); System.gc(); pruneConstraints(proMod, minerFulParams, postParams); return proMod; } public static String makeDiscoveredProcessName(InputLogCmdParameters inputParams) { return (inputParams != null && inputParams.inputLogFile != null ) ? String.format(MinerFulMinerStarter.PROCESS_MODEL_NAME_PATTERN, inputParams.inputLogFile.getName()) : DEFAULT_ANONYMOUS_MODEL_NAME; } protected GlobalStatsTable computeKB(LogParser logParser, MinerFulCmdParameters minerFulParams, TaskCharArchive taskCharArchive, GlobalStatsTable globalStatsTable) { int coreNum = 0; long before = 0, after = 0; if (minerFulParams.isParallelKbComputationRequired()) { // Slice the log List<LogParser> listOfLogParsers = logParser .split(minerFulParams.kbParallelProcessingThreads); List<MinerFulKBCore> listOfMinerFulCores = new ArrayList<MinerFulKBCore>( minerFulParams.kbParallelProcessingThreads); // Associate a dedicated KB-computing core to each log slice for (LogParser slicedLogParser : listOfLogParsers) { listOfMinerFulCores.add(new MinerFulKBCore( coreNum++, slicedLogParser, minerFulParams, taskCharArchive)); } ExecutorService executor = Executors .newFixedThreadPool(minerFulParams.kbParallelProcessingThreads); // ForkJoinPool executor = new ForkJoinPool(minerFulParams.kbParallelProcessingThreads); try { before = System.currentTimeMillis(); for (Future<GlobalStatsTable> statsTab : executor .invokeAll(listOfMinerFulCores)) { globalStatsTable.mergeAdditively(statsTab.get()); } after = System.currentTimeMillis(); } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); System.exit(1); } executor.shutdown(); } else { MinerFulKBCore minerFulKbCore = new MinerFulKBCore( coreNum++, logParser, minerFulParams, taskCharArchive); before = System.currentTimeMillis(); globalStatsTable = minerFulKbCore.discover(); after = System.currentTimeMillis(); } logger.info("Total KB construction time: " + (after - before)); return globalStatsTable; } protected ConstraintsBag queryForConstraints( LogParser logParser, MinerFulCmdParameters minerFulParams, PostProcessingCmdParameters postPrarams, TaskCharArchive taskCharArchive, GlobalStatsTable globalStatsTable, ConstraintsBag bag) { int coreNum = 0; long before = 0, after = 0; if (minerFulParams.isParallelQueryProcessingRequired() && minerFulParams.isBranchingRequired()) { logger.warn("Parallel querying of branched constraints not yet implemented. Proceeding with the single-core operations..."); } if (minerFulParams.isParallelQueryProcessingRequired() && !minerFulParams.isBranchingRequired()) { Collection<Set<TaskChar>> taskCharSubSets = taskCharArchive.splitTaskCharsIntoSubsets( minerFulParams.queryParallelProcessingThreads); List<MinerFulQueryingCore> listOfMinerFulCores = new ArrayList<MinerFulQueryingCore>( minerFulParams.queryParallelProcessingThreads); ConstraintsBag subBag = null; // Associate a dedicated query-computing core to each taskChar-subset for (Set<TaskChar> taskCharSubset : taskCharSubSets) { subBag = bag.slice(taskCharSubset); listOfMinerFulCores.add( new MinerFulQueryingCore(coreNum++, logParser, minerFulParams, postPrarams, taskCharArchive, globalStatsTable, taskCharSubset, subBag)); } ExecutorService executor = Executors .newFixedThreadPool(minerFulParams.queryParallelProcessingThreads); // .newCachedThreadPool(); // ForkJoinPool executor = new ForkJoinPool(minerFulParams.queryParallelProcessingThreads); try { before = System.currentTimeMillis(); for (Callable<ConstraintsBag> core : listOfMinerFulCores) { bag.shallowMerge(executor.submit(core).get()); } // for (Future<ConstraintsBag> processedSubBag : executor // .invokeAll(listOfMinerFulCores)) { // bag.shallowMerge(processedSubBag.get()); // } after = System.currentTimeMillis(); } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); System.exit(1); } executor.shutdown(); } else { MinerFulQueryingCore minerFulQueryingCore = new MinerFulQueryingCore(coreNum++, logParser, minerFulParams, postPrarams, taskCharArchive, globalStatsTable, bag); before = System.currentTimeMillis(); minerFulQueryingCore.discover(); after = System.currentTimeMillis(); } logger.info("Total KB querying time: " + (after - before)); return bag; } protected ProcessModel pruneConstraints( ProcessModel processModel, MinerFulCmdParameters minerFulParams, PostProcessingCmdParameters postPrarams) { // int coreNum = 0; // if (minerFulParams.queryParallelProcessingThreads > MinerFulCmdParameters.MINIMUM_PARALLEL_EXECUTION_THREADS) { // // TODO // } else { MinerFulPruningCore pruniCore = new MinerFulPruningCore(processModel, processModel.bag.getTaskChars(), postPrarams); processModel.bag = pruniCore.massageConstraints(); // } return processModel; } }
11,396
35.883495
150
java
Janus
Janus-master/src/minerful/MinerFulOutputManagementLauncher.java
package minerful; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.PrintWriter; import java.io.StringReader; import java.util.Map; import java.util.NavigableMap; import javax.xml.bind.JAXBException; import javax.xml.bind.PropertyException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.stream.StreamSource; import org.w3c.dom.Document; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import javassist.convert.Transformer; import minerful.concept.ProcessModel; import minerful.concept.constraint.Constraint; import minerful.concept.constraint.ConstraintsBag; import minerful.index.LinearConstraintsIndexFactory; import minerful.io.ConstraintsPrinter; import minerful.io.encdec.ProcessModelEncoderDecoder; import minerful.io.params.OutputModelParameters; import minerful.logparser.LogParser; import minerful.params.SystemCmdParameters; import minerful.params.ViewCmdParameters; import minerful.utils.MessagePrinter; public class MinerFulOutputManagementLauncher { public static MessagePrinter logger = MessagePrinter.getInstance(MinerFulOutputManagementLauncher.class); private String additionalFileSuffix = null; public String getAdditionalFileSuffix() { return additionalFileSuffix; } public void setAdditionalFileSuffix(String additionalFileSuffix) { if (additionalFileSuffix != null) { this.additionalFileSuffix = additionalFileSuffix.trim().replaceAll("\\W", "-"); } } protected File retrieveFile(File originalFile) { return ( this.additionalFileSuffix == null ? originalFile : new File(originalFile.getAbsolutePath().concat(additionalFileSuffix)) ); } protected File retrieveFile(String originalFilePath) { return ( this.additionalFileSuffix == null ? new File(originalFilePath) : new File(originalFilePath.concat(additionalFileSuffix)) ); } public void manageOutput(ProcessModel processModel, NavigableMap<Constraint, String> additionalCnsIndexedInfo, OutputModelParameters outParams, ViewCmdParameters viewParams, SystemCmdParameters systemParams, LogParser logParser) { ConstraintsPrinter printer = new ConstraintsPrinter(processModel, additionalCnsIndexedInfo); PrintWriter outWriter = null; File outputFile = null; if (viewParams.machineReadableResults) { logger.info(printer.printBagAsMachineReadable( (systemParams.debugLevel.compareTo( SystemCmdParameters.DebugLevel.debug) >= 0), true, true ) ); } if (outParams.fileToSaveConstraintsAsCSV != null) { outputFile = this.retrieveFile(outParams.fileToSaveConstraintsAsCSV); logger.info("Saving discovered constraints in CSV format as " + outputFile + "..."); try { outWriter = new PrintWriter(outputFile); outWriter.print(printer.printBagCsv(outParams.csvColumnsToPrint)); outWriter.flush(); outWriter.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if (outParams.fileToSaveAsConDec != null) { outputFile = this.retrieveFile(outParams.fileToSaveAsConDec); logger.info("Saving discovered process model in ConDec/Declare-map XML format as " + outputFile + "..."); try { printer.saveAsConDecModel(outputFile); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } ConstraintsBag bagClone = null; switch (viewParams.constraintsSorting) { case support: bagClone = LinearConstraintsIndexFactory.createConstraintsBagCloneIndexedByTaskCharAndSupport(processModel.bag); break; case interest: bagClone = LinearConstraintsIndexFactory.createConstraintsBagCloneIndexedByTaskCharAndInterest(processModel.bag); case type: default: break; } if (! viewParams.suppressScreenPrintOut ) { if (viewParams.noFoldingRequired) { switch (viewParams.constraintsSorting) { case interest: MessagePrinter.printlnOut(printer.printUnfoldedBagOrderedByInterest()); case support: MessagePrinter.printlnOut(printer.printUnfoldedBagOrderedBySupport()); break; case type: default: MessagePrinter.printlnOut(printer.printUnfoldedBag()); break; } } else { MessagePrinter.printlnOut(printer.printBag()); } } if (outParams.fileToSaveDotFileForAutomaton != null) { outputFile = this.retrieveFile(outParams.fileToSaveDotFileForAutomaton); try { outWriter = new PrintWriter(outputFile); outWriter.print(printer.printDotAutomaton()); outWriter.flush(); outWriter.close(); MessagePrinter.printlnOut("Discovered process automaton written in DOT format on " + outputFile); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /* TODO To be completed, one day if (outParams.fileToSaveDotFileForCondensedAutomaton != null) { outputFile = this.retrieveFile(outParams.fileToSaveDotFileForCondensedAutomaton); try { StringBuffer xmlBuff = // <create-XML-automaton-here> DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document document = builder.parse(new InputSource(new StringReader(xmlBuff.toString()))); TransformerFactory tFactory = TransformerFactory.newInstance(); StreamSource stylesource = // <load the stylesheet here> Transformer transformer = tFactory.newTransformer(stylesource); } catch (PropertyException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (JAXBException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SAXException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ParserConfigurationException e) { // TODO Auto-generated catch block e.printStackTrace(); } } */ if (outParams.fileToSaveTsmlFileForAutomaton != null) { outputFile = this.retrieveFile(outParams.fileToSaveTsmlFileForAutomaton); try { outWriter = new PrintWriter(new File(outputFile.getAbsolutePath())); outWriter.print(printer.printTSMLAutomaton()); outWriter.flush(); outWriter.close(); MessagePrinter.printlnOut("Discovered process automaton written in TSML format on " + outputFile); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if (logParser != null) { if (outParams.fileToSaveXmlFileForAutomaton != null) { outputFile = this.retrieveFile(outParams.fileToSaveXmlFileForAutomaton); try { outWriter = new PrintWriter(new File(outputFile.getAbsolutePath())); outWriter.print(printer.printWeightedXmlAutomaton(logParser, false)); outWriter.flush(); outWriter.close(); MessagePrinter.printlnOut("Discovered weighted process automaton written in XML format on " + outputFile); } catch (FileNotFoundException | JAXBException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if (outParams.fileToSaveSkimmedXmlFileForAutomaton != null) { outputFile = this.retrieveFile(outParams.fileToSaveSkimmedXmlFileForAutomaton); try { outWriter = new PrintWriter(new File(outputFile.getAbsolutePath())); outWriter.print(printer.printWeightedXmlAutomaton(logParser, true)); outWriter.flush(); outWriter.close(); MessagePrinter.printlnOut("Discovered skimmed weighted process automaton written in XML format on " + outputFile); } catch (FileNotFoundException | JAXBException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if (outParams.folderToSaveXmlFilesForPartialAutomata != null) { try { NavigableMap<String, String> partialAutoMap = printer.printWeightedXmlSubAutomata(logParser); StringBuilder subAutomataPathsBuilder = new StringBuilder(); String subAutomatonPath = null; for (Map.Entry<String, String> partialAutomaton : partialAutoMap.entrySet()) { try { subAutomatonPath = outParams.folderToSaveXmlFilesForPartialAutomata + "/" + partialAutomaton.getKey().replaceAll("\\W", "_") + ".automaton.xml"; outputFile = retrieveFile(subAutomatonPath); outWriter = new PrintWriter( outputFile ); outWriter.print(partialAutomaton.getValue()); outWriter.flush(); outWriter.close(); subAutomataPathsBuilder.append("Sub-automaton for activity \""); subAutomataPathsBuilder.append(partialAutomaton.getKey()); subAutomataPathsBuilder.append("\" written in XML format on "); subAutomataPathsBuilder.append(outputFile); subAutomataPathsBuilder.append('\n'); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } MessagePrinter.printlnOut(subAutomataPathsBuilder.toString()); } catch (JAXBException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } else if (outParams.folderToSaveXmlFilesForPartialAutomata != null || outParams.fileToSaveXmlFileForAutomaton != null) { throw new IllegalArgumentException("A log parser must be provided to create the weighted XML automaton corresponding to the process model"); } if (outParams.folderToSaveDotFilesForPartialAutomata != null) { NavigableMap<String, String> partialAutoMap = printer.printDotPartialAutomata(); StringBuilder subAutomataPathsBuilder = new StringBuilder(); String subAutomatonPath = null; logger.info("Saving activation-related automata DOT files in folder " + outParams.folderToSaveDotFilesForPartialAutomata + "..."); for (Map.Entry<String, String> partialAutomaton : partialAutoMap.entrySet()) { try { subAutomatonPath = outParams.folderToSaveDotFilesForPartialAutomata + "/" + partialAutomaton.getKey().replaceAll("\\W", "_") + ".automaton.dot"; outputFile = retrieveFile(subAutomatonPath); outWriter = new PrintWriter( outputFile ); outWriter.print(partialAutomaton.getValue()); outWriter.flush(); outWriter.close(); subAutomataPathsBuilder.append("Sub-automaton for activity \""); subAutomataPathsBuilder.append(partialAutomaton.getKey()); subAutomataPathsBuilder.append("\" written in DOT format on "); subAutomataPathsBuilder.append(outputFile); subAutomataPathsBuilder.append('\n'); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } MessagePrinter.printlnOut(subAutomataPathsBuilder.toString()); } if (outParams.fileToSaveAsXML != null) { outputFile = retrieveFile(outParams.fileToSaveAsXML); logger.info("Saving the discovered process as XML in " + outputFile + "..."); try { new ProcessModelEncoderDecoder().marshalProcessModel(processModel, outputFile); } catch (PropertyException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (JAXBException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if (outParams.fileToSaveAsJSON != null) { outputFile = retrieveFile(outParams.fileToSaveAsJSON); logger.info("Saving the discovered process as JSON in " + outputFile + "..."); try { new ProcessModelEncoderDecoder().writeToJsonFile(processModel, outputFile); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } public void manageOutput(ProcessModel processModel, ViewCmdParameters viewParams, OutputModelParameters outParams, SystemCmdParameters systemParams, LogParser logParser) { this.manageOutput(processModel, null, outParams, viewParams, systemParams, logParser); } public void manageOutput(ProcessModel processModel, ViewCmdParameters viewParams, OutputModelParameters outParams, SystemCmdParameters systemParams) { this.manageOutput(processModel, null, outParams, viewParams, systemParams, null); } public void manageOutput(ProcessModel processModel, OutputModelParameters outParams) { this.manageOutput(processModel, null, outParams, new ViewCmdParameters(), new SystemCmdParameters(), null); } public void manageOutput(ProcessModel processModel, OutputModelParameters outParams, LogParser logParser) { this.manageOutput(processModel, null, outParams, new ViewCmdParameters(), new SystemCmdParameters(), logParser); } }
13,574
37.239437
231
java
Janus
Janus-master/src/minerful/MinerFulSimplificationLauncher.java
package minerful; import org.processmining.plugins.declareminer.visualizing.AssignmentModel; import minerful.concept.ProcessModel; import minerful.io.ProcessModelLoader; import minerful.io.params.InputModelParameters; import minerful.miner.core.MinerFulPruningCore; import minerful.params.SystemCmdParameters; import minerful.postprocessing.params.PostProcessingCmdParameters; import minerful.utils.MessagePrinter; public class MinerFulSimplificationLauncher { public static MessagePrinter logger = MessagePrinter.getInstance(MinerFulSimplificationLauncher.class); private ProcessModel inputProcess; private ProcessModel fixpointModel; // subset of InputModel: if given in input, the constraints of this model are kept form the simplification private PostProcessingCmdParameters postParams; private MinerFulSimplificationLauncher(PostProcessingCmdParameters postParams) { this.postParams = postParams; } public MinerFulSimplificationLauncher(AssignmentModel declareMapModel, PostProcessingCmdParameters postParams) { this(postParams); this.inputProcess = new ProcessModelLoader().loadProcessModel(declareMapModel); } public MinerFulSimplificationLauncher(ProcessModel minerFulProcessModel, PostProcessingCmdParameters postParams) { this(postParams); this.inputProcess = minerFulProcessModel; } public MinerFulSimplificationLauncher(ProcessModel minerFulProcessModel, PostProcessingCmdParameters postParams, ProcessModel fixPointProcess) { this(postParams); this.inputProcess = minerFulProcessModel; this.fixpointModel = fixPointProcess; } public MinerFulSimplificationLauncher(InputModelParameters inputParams, PostProcessingCmdParameters postParams, SystemCmdParameters systemParams) { this(postParams); this.inputProcess = new ProcessModelLoader().loadProcessModel(inputParams.inputLanguage, inputParams.inputFile); if (inputParams.inputFile == null) { systemParams.printHelpForWrongUsage("Input process model file missing!"); System.exit(1); } if(postParams.fixpointModel != null){ this.fixpointModel =new ProcessModelLoader().loadProcessModel(inputParams.inputLanguage, postParams.fixpointModel); } MessagePrinter.configureLogging(systemParams.debugLevel); } public ProcessModel simplify() { MinerFulPruningCore miFuPruNi; if (fixpointModel !=null){ miFuPruNi = new MinerFulPruningCore(inputProcess, postParams, fixpointModel); }else { miFuPruNi = new MinerFulPruningCore(inputProcess, postParams); } miFuPruNi.massageConstraints(); ProcessModel outputProcess = miFuPruNi.getProcessModel(); return outputProcess; } }
2,881
38.479452
148
java
Janus
Janus-master/src/minerful/MinerFulSimplificationStarter.java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package minerful; import minerful.concept.ProcessModel; import minerful.io.params.InputModelParameters; import minerful.io.params.OutputModelParameters; import minerful.params.SystemCmdParameters; import minerful.params.ViewCmdParameters; import minerful.postprocessing.params.PostProcessingCmdParameters; import minerful.utils.MessagePrinter; import org.apache.commons.cli.Option; import org.apache.commons.cli.Options; public class MinerFulSimplificationStarter extends MinerFulMinerStarter { public static MessagePrinter logger = MessagePrinter.getInstance(MinerFulSimplificationStarter.class); @Override public Options setupOptions() { Options cmdLineOptions = new Options(); Options systemOptions = SystemCmdParameters.parseableOptions(), postProptions = PostProcessingCmdParameters.parseableOptions(), viewOptions = ViewCmdParameters.parseableOptions(), outputOptions = OutputModelParameters.parseableOptions(), inputOptions = InputModelParameters.parseableOptions(); for (Object opt: postProptions.getOptions()) { cmdLineOptions.addOption((Option)opt); } for (Object opt: systemOptions.getOptions()) { cmdLineOptions.addOption((Option)opt); } for (Object opt: viewOptions.getOptions()) { cmdLineOptions.addOption((Option)opt); } for (Object opt: outputOptions.getOptions()) { cmdLineOptions.addOption((Option)opt); } for (Object opt: inputOptions.getOptions()) { cmdLineOptions.addOption((Option)opt); } return cmdLineOptions; } public static void main(String[] args) { MinerFulSimplificationStarter prunerStarter = new MinerFulSimplificationStarter(); Options cmdLineOptions = prunerStarter.setupOptions(); SystemCmdParameters systemParams = new SystemCmdParameters( cmdLineOptions, args); PostProcessingCmdParameters postParams = new PostProcessingCmdParameters( cmdLineOptions, args); OutputModelParameters outParams = new OutputModelParameters( cmdLineOptions, args); InputModelParameters inputParams = new InputModelParameters( cmdLineOptions, args); ViewCmdParameters viewParams = new ViewCmdParameters( cmdLineOptions, args); if (systemParams.help) { systemParams.printHelp(cmdLineOptions); System.exit(0); } if (inputParams.inputFile == null) { systemParams.printHelpForWrongUsage("Input process model file missing!"); System.exit(1); } MessagePrinter.configureLogging(systemParams.debugLevel); MinerFulSimplificationLauncher miFuSimpLa = new MinerFulSimplificationLauncher(inputParams, postParams, systemParams); ProcessModel outputProcess = miFuSimpLa.simplify(); new MinerFulOutputManagementLauncher().manageOutput(outputProcess, viewParams, outParams, systemParams); } }
3,066
31.978495
126
java
Janus
Janus-master/src/minerful/MinerFulSimuStarter.java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package minerful; import org.apache.commons.cli.Option; import org.apache.commons.cli.Options; import minerful.concept.ProcessModel; import minerful.concept.TaskCharArchive; import minerful.io.params.OutputModelParameters; import minerful.logparser.LogEventClassifier.ClassificationType; import minerful.logparser.LogParser; import minerful.logparser.StringLogParser; import minerful.miner.params.MinerFulCmdParameters; import minerful.params.SystemCmdParameters; import minerful.params.ViewCmdParameters; import minerful.postprocessing.params.PostProcessingCmdParameters; import minerful.stringsmaker.MinerFulStringTracesMaker; import minerful.stringsmaker.params.StringTracesMakerCmdParameters; import minerful.utils.MessagePrinter; public class MinerFulSimuStarter extends MinerFulMinerStarter { public static MessagePrinter logger = MessagePrinter.getInstance(MinerFulSimuStarter.class); @Override public Options setupOptions() { Options cmdLineOptions = new Options(); Options minerfulOptions = MinerFulCmdParameters.parseableOptions(), tracesMakerOptions = StringTracesMakerCmdParameters.parseableOptions(), systemOptions = SystemCmdParameters.parseableOptions(), viewOptions = ViewCmdParameters.parseableOptions(), outputOptions = OutputModelParameters.parseableOptions(), postProptions = PostProcessingCmdParameters.parseableOptions(); for (Object opt: postProptions.getOptions()) { cmdLineOptions.addOption((Option)opt); } for (Object opt: minerfulOptions.getOptions()) { cmdLineOptions.addOption((Option)opt); } for (Object opt: tracesMakerOptions.getOptions()) { cmdLineOptions.addOption((Option)opt); } for (Object opt: viewOptions.getOptions()) { cmdLineOptions.addOption((Option)opt); } for (Object opt: outputOptions.getOptions()) { cmdLineOptions.addOption((Option)opt); } for (Object opt: systemOptions.getOptions()) { cmdLineOptions.addOption((Option)opt); } return cmdLineOptions; } /** * @param args the command line arguments: * [regular expression] * [number of strings] * [minimum number of characters per string] * [maximum number of characters per string] * [alphabet]... */ public static void main(String[] args) { MinerFulSimuStarter minerSimuStarter = new MinerFulSimuStarter(); Options cmdLineOptions = minerSimuStarter.setupOptions(); ViewCmdParameters viewParams = new ViewCmdParameters( cmdLineOptions, args); StringTracesMakerCmdParameters tracesMakParams = new StringTracesMakerCmdParameters( cmdLineOptions, args); MinerFulCmdParameters minerFulParams = new MinerFulCmdParameters( cmdLineOptions, args); OutputModelParameters outParams = new OutputModelParameters( cmdLineOptions, args); SystemCmdParameters systemParams = new SystemCmdParameters( cmdLineOptions, args); PostProcessingCmdParameters postParams = new PostProcessingCmdParameters( cmdLineOptions, args); if (systemParams.help) { systemParams.printHelp(cmdLineOptions); System.exit(0); } MessagePrinter.configureLogging(systemParams.debugLevel); String[] testBedArray = new String[0]; testBedArray = new MinerFulStringTracesMaker().makeTraces(tracesMakParams); try { LogParser stringLogParser = new StringLogParser(testBedArray, ClassificationType.NAME); TaskCharArchive taskCharArchive = new TaskCharArchive(stringLogParser.getEventEncoderDecoder().getTranslationMap()); // minerSimuStarter.mine(testBedArray, minerFulParams, tracesMakParams, systemParams); ProcessModel processModel = minerSimuStarter.mine(stringLogParser, minerFulParams, postParams, taskCharArchive); MinerFulOutputManagementLauncher proViewStarter = new MinerFulOutputManagementLauncher(); proViewStarter.manageOutput(processModel, viewParams, outParams, systemParams, stringLogParser); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); System.exit(1); } } }
4,412
34.878049
119
java
Janus
Janus-master/src/minerful/MinerFulTracesMakerStarter.java
package minerful; import minerful.params.SystemCmdParameters; import minerful.stringsmaker.MinerFulStringTracesMaker; import minerful.stringsmaker.params.StringTracesMakerCmdParameters; import minerful.utils.MessagePrinter; import org.apache.commons.cli.Option; import org.apache.commons.cli.Options; public class MinerFulTracesMakerStarter extends AbstractMinerFulStarter { public static MessagePrinter logger = MessagePrinter.getInstance(MinerFulTracesMakerStarter.class); @Override public Options setupOptions() { Options cmdLineOptions = new Options(); Options systemOptions = SystemCmdParameters.parseableOptions(), tracesMakOptions = StringTracesMakerCmdParameters.parseableOptions(); for (Object opt: systemOptions.getOptions()) { cmdLineOptions.addOption((Option)opt); } for (Object opt: tracesMakOptions.getOptions()) { cmdLineOptions.addOption((Option)opt); } return cmdLineOptions; } public static void main(String[] args) { MinerFulTracesMakerStarter traMakeStarter = new MinerFulTracesMakerStarter(); Options cmdLineOptions = traMakeStarter.setupOptions(); StringTracesMakerCmdParameters tracesMakParams = new StringTracesMakerCmdParameters( cmdLineOptions, args); SystemCmdParameters systemParams = new SystemCmdParameters( cmdLineOptions, args); if (systemParams.help) { systemParams.printHelp(cmdLineOptions); System.exit(0); } MessagePrinter.configureLogging(systemParams.debugLevel); MinerFulStringTracesMaker traMaker = new MinerFulStringTracesMaker(); String[] traces = traMaker.makeTraces(tracesMakParams); traMaker.store(tracesMakParams, traces); } }
1,830
31.696429
100
java
Janus
Janus-master/src/minerful/MinerFulVacuityChecker.java
package minerful; import java.io.File; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Iterator; import minerful.checking.ConstraintsFitnessEvaluator; import minerful.checking.ProcessSpecificationFitnessEvaluator; import minerful.checking.relevance.dao.ConstraintsFitnessEvaluationsMap; import minerful.checking.relevance.dao.ModelFitnessEvaluation; import minerful.concept.ProcessModel; import minerful.concept.TaskChar; import minerful.concept.TaskCharFactory; import minerful.concept.constraint.Constraint; import minerful.concept.constraint.ConstraintsBag; import minerful.concept.constraint.existence.AtMostOne; import minerful.concept.constraint.existence.End; import minerful.concept.constraint.existence.Init; import minerful.concept.constraint.existence.Participation; import minerful.concept.constraint.relation.AlternatePrecedence; import minerful.concept.constraint.relation.AlternateResponse; import minerful.concept.constraint.relation.AlternateSuccession; import minerful.concept.constraint.relation.ChainPrecedence; import minerful.concept.constraint.relation.ChainResponse; import minerful.concept.constraint.relation.ChainSuccession; import minerful.concept.constraint.relation.CoExistence; import minerful.concept.constraint.relation.NotChainSuccession; import minerful.concept.constraint.relation.NotCoExistence; import minerful.concept.constraint.relation.NotSuccession; import minerful.concept.constraint.relation.Precedence; import minerful.concept.constraint.relation.RespondedExistence; import minerful.concept.constraint.relation.Response; import minerful.concept.constraint.relation.Succession; import minerful.io.ConstraintsPrinter; import minerful.io.encdec.declaremap.DeclareMapEncoderDecoder; import minerful.io.encdec.declaremap.DeclareMapReaderWriter; import minerful.io.params.OutputModelParameters; import minerful.logparser.LogEventClassifier.ClassificationType; import minerful.logparser.LogParser; import minerful.logparser.LogTraceParser; import minerful.logparser.StringLogParser; import minerful.logparser.XesLogParser; import minerful.params.SystemCmdParameters.DebugLevel; import minerful.relevance.test.constraint.SequenceResponse21; import minerful.relevance.test.constraint.SequenceResponse22; import minerful.relevance.test.constraint.SequenceResponse32; import minerful.utils.MessagePrinter; public class MinerFulVacuityChecker { public static MessagePrinter logger = MessagePrinter.getInstance(MinerFulVacuityChecker.class); /** * Task place-holders to be used as parameters for the constraint templates to check. */ public static TaskChar a = new TaskChar('A'), b = new TaskChar('B'), c = new TaskChar('C'), x = new TaskChar('X'), y = new TaskChar('Y'); /** * Constraint templates to be checked. */ // Toggle the comment to add/remove the template from the set of checked ones. public static Constraint[] parametricConstraints = new Constraint[] { new SequenceResponse21(a,b,x), // new SequenceResponse22(a,b,x,y), // new SequenceResponse32(a,b,c,x,y), new Participation(a), // a.k.a. Existence(1, a) // new AtMostOne(a), // a.k.a. Absence(2, a) new Init(a), new End(a), // new RespondedExistence(a,b), // new Response(a, b), // new AlternateResponse(a,b), // new ChainResponse(a,b), // new Precedence(a,b), // new AlternatePrecedence(a,b), // new ChainPrecedence(a,b), // new CoExistence(a,b), // new Succession(a,b), // new AlternateSuccession(a, b), // new ChainSuccession(a, b), // new NotChainSuccession(a, b), // new NotSuccession(a, b), // new NotCoExistence(a, b), }; public static void main(String[] args) throws Exception { System.err.println( "#### WARNING" + "\n" + "This class is not yet part of the MINERful framework. It is meant to be the proof-of-concept software for the paper entitled " + "\"On the Relevance of a Business Constraint to an Event Log\", authored by C. Di Ciccio, F.M. Maggi, M. Montali, and J. Mendling (DOI: https://doi.org/10.1016/j.is.2018.01.011). " + "Please use it for testing purposes only." + "\n\n" + "#### USAGE" + "\n" + "Usage: java " + MinerFulVacuityChecker.class.getCanonicalName() + " <XES-log-file-path> [threshold] [Declare-map-output-file-path]." + "\n" + "Param: <XES-log-file-path>: the path to a XES event log file (mandatory)" + "\n" + "Param: [threshold]: the ratio of traces in which the constraints have to be non-vacuously satisfied, from 0.0 to 1.0 (default: " + ConstraintsFitnessEvaluator.DEFAULT_FITNESS_THRESHOLD + ") (optional)" + "\n" + "Param: [Declare-map-output-file-path]: the path of the file in which the returned constraints are stored as a Declare Map XML file (by default, no Declare Map XML file is saved) (optional)" + "\n\n" + "#### OUTPUT" + "\n" + "To customise the constraint templates to be checked, please change the code of this class (" + MinerFulVacuityChecker.class.getCanonicalName() + ") in the specified point and recompile." + "\n" + "The printed output is a CSV-encoding of constraints that are non-vacuously satisfied in the given log. The output can be also saved as a Declare Map XML file by specifying the third optional command parameter (for standard Declare constraints only) -- see above: [Declare-map-output-file-path]." + "\n\n" + "Press any key to continue..." ); System.in.read(); MessagePrinter.configureLogging(DebugLevel.all); LogParser loPar = null; try { loPar = new XesLogParser(new File(args[0]), ClassificationType.LOG_SPECIFIED); } catch (Exception e) { MessagePrinter.printlnOut(args[0] + " is not an XES file"); loPar = new StringLogParser(new File(args[0]), ClassificationType.NAME); } ConstraintsFitnessEvaluator evalor = new ConstraintsFitnessEvaluator( loPar.getEventEncoderDecoder(), loPar.getTaskCharArchive(), Arrays.asList(parametricConstraints)); ConstraintsFitnessEvaluationsMap evalon = null; if (args.length > 1) { evalon = evalor.runOnLog(loPar, Double.valueOf(args[1])); } else { evalon = evalor.runOnLog(loPar); } MessagePrinter.printlnOut(evalon.printCSV()); /*Alessio save output model as CSV, not just print it*/ try { PrintWriter outWriter = new PrintWriter(args[3]); outWriter.print(evalon.printCSV()); outWriter.flush(); outWriter.close(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } /**/ if (args.length > 2) { logger.debug("Storing fully-supported default-Declare constraints as a Declare map on " + args[2]); Collection<Constraint> nuStandardConstraints = new ArrayList<Constraint>(); Double fitnessThreshold = Double.valueOf(args[1]); for (Constraint con : evalor.getCheckedConstraints()) { if (con.getFamily() != null && con.getFitness() >= fitnessThreshold) { nuStandardConstraints.add(con); } } ConstraintsBag coBag = new ConstraintsBag(loPar.getTaskCharArchive().getTaskChars(), nuStandardConstraints); ProcessModel model = new ProcessModel(loPar.getTaskCharArchive(), coBag); DeclareMapReaderWriter.marshal(args[2], new DeclareMapEncoderDecoder(model).createDeclareMap()); logger.debug("Done."); } } }
7,373
39.295082
300
java
Janus
Janus-master/src/minerful/automaton/AutomatonFactory.java
package minerful.automaton; import java.util.AbstractMap; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import java.util.NavigableMap; import java.util.SortedSet; import java.util.TreeSet; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import minerful.automaton.utils.AutomatonUtils; import minerful.concept.constraint.Constraint; import minerful.concept.constraint.ConstraintsBag; import minerful.concept.constraint.relation.NotChainSuccession; import minerful.index.LinearConstraintsIndexFactory; import minerful.index.ModularConstraintsSorter; import minerful.index.comparator.modular.ConstraintSortingPolicy; import minerful.io.encdec.TaskCharEncoderDecoder; import org.apache.commons.lang3.StringUtils; import org.apache.log4j.LogMF; import org.apache.log4j.Logger; import dk.brics.automaton.Automaton; import dk.brics.automaton.RegExp; public class AutomatonFactory { public static final int NO_LIMITS_IN_ACTIONS_FOR_SUBAUTOMATA = 0; public static final int NO_TRACE_LENGTH_CONSTRAINT = 0; private static Logger logger = Logger.getLogger(AutomatonFactory.class .getCanonicalName()); public static final int THREAD_MAX = 8; public static final Character WILD_CARD = TaskCharEncoderDecoder.WILDCARD_CHAR; public static Collection<SubAutomaton> subAutomataFromRegularExpressionsInMultiThreading( NavigableMap<Character, Collection<String>> regExpsMap, Collection<Character> alphabet) { return subAutomataFromRegularExpressionsInMultiThreading(regExpsMap, alphabet, NO_LIMITS_IN_ACTIONS_FOR_SUBAUTOMATA); } public static Collection<SubAutomaton> subAutomataFromRegularExpressionsInMultiThreading( NavigableMap<Character, Collection<String>> regExpsMap, Collection<Character> alphabet, int maxActions) { Collection<String> regExps = null; Collection<DimensionalityHeuristicBasedCallableSubAutomataMaker> autoMakers = new ArrayList<DimensionalityHeuristicBasedCallableSubAutomataMaker>( regExpsMap.size()); Collection<SubAutomaton> partialAutomata = new ArrayList<SubAutomaton>( alphabet.size()); ExecutorService executor = Executors.newFixedThreadPool(THREAD_MAX); for (Character tIdChr : regExpsMap.keySet()) { regExps = new ArrayList<String>(); regExps.addAll(regExpsMap.get(tIdChr)); if (maxActions <= AutomatonFactory.NO_LIMITS_IN_ACTIONS_FOR_SUBAUTOMATA) { autoMakers .add(new DimensionalityHeuristicBasedCallableSubAutomataMaker( tIdChr, regExps)); } else { autoMakers .add(new DimensionalityHeuristicBasedCallableBriefSubAutomataMaker( tIdChr, regExps, maxActions)); } } try { for (Future<SubAutomaton> resultWithNewAutomaton : executor .invokeAll(autoMakers)) { partialAutomata.add(resultWithNewAutomaton.get()); } } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ExecutionException e) { // TODO Auto-generated catch block e.printStackTrace(); } executor.shutdown(); return partialAutomata; } public static Automaton fromRegularExpressionsByDimensionalityHeuristicInMultiThreading( AbstractMap<Character, Collection<String>> regExpsMap, Collection<Character> alphabet) { SortedSet<Automaton> partialAutomata = new TreeSet<Automaton>( new DimensionalityHeuristicBasedAutomataIntersector.AutomataAscendingDimensionComparator()); Automaton processAutomaton = null; for (Automaton otherProcessAutomaton : partialAutomata) { if (processAutomaton == null) { processAutomaton = otherProcessAutomaton; } else { logger.trace("Intersecting automaton..."); processAutomaton = processAutomaton .intersection(otherProcessAutomaton); processAutomaton.minimize(); logger.trace("Automaton states: " + processAutomaton.getNumberOfStates() + "; automaton transitions: " + processAutomaton.getNumberOfTransitions()); } } return processAutomaton; } public static Automaton fromRegularExpressions(Collection<String> regExps, Collection<Character> basicAlphabet, boolean withWildCard, int minLen, int maxLen) { boolean traceLengthLimitSet = (minLen != NO_TRACE_LENGTH_CONSTRAINT || maxLen != NO_TRACE_LENGTH_CONSTRAINT); Collection<String> regularExpressions = new ArrayList<String>( regExps.size() + (traceLengthLimitSet ? 2 : 1) ); // limit the alphabet regularExpressions.add(AutomatonUtils.createRegExpLimitingTheAlphabet(basicAlphabet, withWildCard)); regularExpressions.addAll(regExps); // limit the minimum and maximum length of runs, if needed if (traceLengthLimitSet) { regularExpressions.add(AutomatonUtils.createRegExpLimitingRunLength(minLen, maxLen)); } return new CallableAutomataMaker(regularExpressions).makeAutomaton(); } public static Automaton fromRegularExpressions(Collection<String> regExps, Collection<Character> basicAlphabet, int minLen, int maxLen) { return fromRegularExpressions(regExps, basicAlphabet, false, NO_TRACE_LENGTH_CONSTRAINT, NO_TRACE_LENGTH_CONSTRAINT); } public static Automaton fromRegularExpressions(Collection<String> regExps, Collection<Character> basicAlphabet) { return fromRegularExpressions(regExps, basicAlphabet, NO_TRACE_LENGTH_CONSTRAINT, NO_TRACE_LENGTH_CONSTRAINT); } public static Automaton fromRegularExpressions(Collection<String> regExps, Collection<Character> basicAlphabet, boolean withWildCard) { return fromRegularExpressions(regExps, basicAlphabet, withWildCard, NO_TRACE_LENGTH_CONSTRAINT, NO_TRACE_LENGTH_CONSTRAINT); } @Deprecated public static Automaton fromRegularExpressionsDeprecated( Collection<String> regExps, Collection<Character> alphabet) { // Turn strings into Regular Expressions and attach them Automaton processAutomaton = null, nuConstraintAutomaton = null; String nuRegExp = null; logger.trace("Preparing the automaton..."); if (regExps.size() > 0) { Iterator<String> regExpsIterator = regExps.iterator(); if (regExpsIterator.hasNext()) { processAutomaton = new RegExp( AutomatonUtils.createRegExpLimitingTheAlphabet(alphabet)) .toAutomaton(); // DEBUGGING! // processAutomaton = processAutomaton.intersection(new // RegExp(".{1," + alphabet.size() * 2 + "}").toAutomaton()); // processAutomaton = processAutomaton.intersection(new // RegExp(".{1," + ((int)(alphabet.size() * 1.25)) + // "}").toAutomaton()); // processAutomaton = processAutomaton.intersection(new // RegExp(".{1,24}").toAutomaton()); // E.O. DEBUGGING while (regExpsIterator.hasNext()) { nuRegExp = regExpsIterator.next(); logger.trace("Intersecting the automaton with the accepting for: " + nuRegExp); nuConstraintAutomaton = new RegExp(nuRegExp).toAutomaton(); processAutomaton = processAutomaton .intersection(nuConstraintAutomaton); processAutomaton.minimize(); logger.trace("Automaton states: " + processAutomaton.getNumberOfStates() + "; automaton transitions: " + processAutomaton.getNumberOfTransitions()); } } // DEBUGGING! // processAutomaton = processAutomaton.intersection(new // RegExp("[^a]?[^a]a[^a][^a]?").toAutomaton()); // E.O. DEBUGGING } return processAutomaton; } public static Automaton buildAutomaton(ConstraintsBag bag, Collection<Character> basicAlphabet) { return buildAutomaton(bag, basicAlphabet, NO_TRACE_LENGTH_CONSTRAINT, NO_TRACE_LENGTH_CONSTRAINT, new Constraint[0]); } public static Automaton buildAutomaton(ConstraintsBag bag, Collection<Character> basicAlphabet, Constraint... excludedConstraints) { return buildAutomaton(bag, basicAlphabet, NO_TRACE_LENGTH_CONSTRAINT, NO_TRACE_LENGTH_CONSTRAINT, excludedConstraints); } public static Automaton buildAutomaton(ConstraintsBag bag, Collection<Character> basicAlphabet, int minLen, int maxLen) { return buildAutomaton(bag, basicAlphabet, minLen, maxLen, new Constraint[0]); } public static Automaton buildAutomaton(ConstraintsBag bag, Collection<Character> basicAlphabet, int minLen, int maxLen, Constraint... excludedConstraints) { Collection<String> regularExpressions = null; Collection<Constraint> constraints = bag.getAllConstraints(); for (Constraint excluCon : excludedConstraints) { constraints.remove(excluCon); } constraints = new ModularConstraintsSorter(constraints).sort(ConstraintSortingPolicy.ACTIVATIONTARGETBONDS,ConstraintSortingPolicy.FAMILYHIERARCHY); // HashSet<Constraint> excludedConstraintsSet = null; // if (excludedConstraints.length > 0) // excludedConstraintsSet = new HashSet<Constraint>(excludedConstraints.length, (float)1.0); // for (Constraint excludedConstraint : excludedConstraints) { // excludedConstraintsSet.add(excludedConstraint); // } regularExpressions = new ArrayList<String>(constraints.size()); for (Constraint con : constraints) { // if (excludedConstraintsSet != null && !excludedConstraintsSet.contains(con)) { regularExpressions.add(con.getRegularExpression()); // } } if (minLen != NO_TRACE_LENGTH_CONSTRAINT || maxLen != NO_TRACE_LENGTH_CONSTRAINT) { return AutomatonFactory.fromRegularExpressions(regularExpressions, basicAlphabet, minLen, maxLen); } return AutomatonFactory.fromRegularExpressions(regularExpressions, basicAlphabet); } public static Automaton buildAutomatonWithWildcard(Constraint constraint) { return fromRegularExpressions(Arrays.asList(constraint.getRegularExpression()),constraint.getInvolvedTaskCharIdentifiers(),true); } }
9,734
38.897541
150
java
Janus
Janus-master/src/minerful/automaton/AutomatonRandomWalker.java
package minerful.automaton; import java.util.ArrayList; import java.util.Collection; import minerful.automaton.utils.AutomatonUtils; import dk.brics.automaton.Automaton; import dk.brics.automaton.State; public class AutomatonRandomWalker { private Automaton automaton; private State currentState; private ArrayList<Character> enabledTransitions = new ArrayList<Character>(); public AutomatonRandomWalker(Automaton automaton) { this.automaton = automaton; this.goToStart(); } public void goToStart() { this.goToState(this.automaton.getInitialState()); } private void goToState(State state) { this.currentState = state; this.enabledTransitions = AutomatonUtils.getAllPossibleSteps(this.currentState); } public Character walkOn() { Character pickedTransitionChar = null; int pickedTransitionNumber = -1; if (!this.currentState.isAccept() || decideToContinueTheWalk()) { if (this.enabledTransitions.size() > 0) { pickedTransitionNumber = pickTransitionToWalkThrough(this.enabledTransitions); pickedTransitionChar = this.enabledTransitions.get(pickedTransitionNumber); this.goToState(this.currentState.step(pickedTransitionChar)); } } return pickedTransitionChar; } private int pickTransitionToWalkThrough(Collection<Character> enabledTransitions) { return (int) (Math.floor(Math.random() * enabledTransitions.size())); } private boolean decideToContinueTheWalk() { return Math.random() > 0.5; } }
1,465
27.745098
84
java
Janus
Janus-master/src/minerful/automaton/CallableAutomataMaker.java
package minerful.automaton; import java.util.Collection; import java.util.Iterator; import java.util.concurrent.Callable; import org.apache.log4j.Logger; import dk.brics.automaton.Automaton; import dk.brics.automaton.RegExp; public class CallableAutomataMaker implements Callable<Automaton> { private static Logger logger = Logger.getLogger(CallableAutomataMaker.class.getCanonicalName()); public Collection<String> regularExpressions; public CallableAutomataMaker(Collection<String> regularExpressions) { this.regularExpressions = regularExpressions; } @Override public Automaton call() throws Exception { return makeAutomaton(); } public Automaton makeAutomaton() { Automaton processAutomaton = null, nuConstraintAutomaton = null; String nuRegExp = null; // logger.trace("Preparing the automaton..."); if (regularExpressions.size() > 0) { Iterator<String> regExpsIterator = regularExpressions.iterator(); // int i = 1; while (regExpsIterator.hasNext()) { nuRegExp = regExpsIterator.next(); // logger.trace("Intersecting the automaton with the accepting for: " // + nuRegExp + " (" + i + " / " + this.regularExpressions.size() + ")"); // i++; nuConstraintAutomaton = new RegExp(nuRegExp).toAutomaton(); if (processAutomaton != null) { processAutomaton = processAutomaton .intersection(nuConstraintAutomaton); } else { processAutomaton = nuConstraintAutomaton; } processAutomaton.minimize(); // logger.trace("Automaton states: " // + processAutomaton.getNumberOfStates() // + "; automaton transitions: " // + processAutomaton.getNumberOfTransitions()); } } return processAutomaton; } }
1,703
28.37931
97
java
Janus
Janus-master/src/minerful/automaton/DimensionalityHeuristicBasedAutomataIntersector.java
package minerful.automaton; import java.util.Collection; import java.util.Comparator; import java.util.NavigableSet; import java.util.TreeSet; import org.apache.log4j.Logger; import dk.brics.automaton.Automaton; public class DimensionalityHeuristicBasedAutomataIntersector { private static Logger logger = Logger.getLogger(DimensionalityHeuristicBasedAutomataIntersector.class.getCanonicalName()); public static class AutomataAscendingDimensionComparator implements Comparator<Automaton> { @Override public int compare(Automaton o1, Automaton o2) { return Integer.valueOf(o1.getNumberOfTransitions()) .compareTo( Integer.valueOf(o2.getNumberOfTransitions()) ); } } public static class AutomataDescendingDimensionComparator implements Comparator<Automaton> { @Override public int compare(Automaton o1, Automaton o2) { return Integer.valueOf(o1.getNumberOfTransitions()) .compareTo( Integer.valueOf(o2.getNumberOfTransitions()) ) * (-1); } } public Automaton intersect(Collection<Automaton> automata) { TreeSet<Automaton> orderedAutomata = new TreeSet<Automaton>(new AutomataAscendingDimensionComparator()); orderedAutomata.addAll(automata); return intersectInRecursion(orderedAutomata).pollFirst(); } private NavigableSet<Automaton> intersectInRecursion(NavigableSet<Automaton> orderedAutomata) { if (orderedAutomata.size() < 2) { return orderedAutomata; } TreeSet<Automaton> automataForNextRound = new TreeSet<Automaton>(new AutomataAscendingDimensionComparator()); Automaton intersectedAutomaton = null; int sizeOfAutomataSet = orderedAutomata.size(); for (int i = 0; i < sizeOfAutomataSet / 2; i++) { logger.trace("Intersecting automaton..."); intersectedAutomaton = orderedAutomata.pollFirst().intersection(orderedAutomata.pollLast()); // Only for the last loop, and only if the number of automata were odd if (orderedAutomata.size() == 1) { // Intersect with the spurious automaton automataForNextRound.add(intersectedAutomaton.intersection(orderedAutomata.pollFirst())); } else { automataForNextRound.add(intersectedAutomaton); } logger.trace("Automaton states: " + intersectedAutomaton.getNumberOfStates() + "; automaton transitions: " + intersectedAutomaton.getNumberOfTransitions()); } return intersectInRecursion(automataForNextRound); } }
2,423
31.756757
162
java
Janus
Janus-master/src/minerful/automaton/DimensionalityHeuristicBasedCallableAutomataMaker.java
package minerful.automaton; import java.util.Collection; import java.util.Iterator; import java.util.SortedSet; import java.util.TreeSet; import java.util.concurrent.Callable; import org.apache.log4j.Logger; import dk.brics.automaton.Automaton; import dk.brics.automaton.RegExp; public class DimensionalityHeuristicBasedCallableAutomataMaker implements Callable<Automaton> { private static Logger logger = Logger.getLogger(DimensionalityHeuristicBasedCallableAutomataMaker.class.getCanonicalName()); public Collection<String> regularExpressions; public DimensionalityHeuristicBasedCallableAutomataMaker(Collection<String> regularExpressions) { this.regularExpressions = regularExpressions; } @Override public Automaton call() throws Exception { // Turn strings into Regular Expressions and attach them Automaton automaton = null; SortedSet<Automaton> regExpAutomata = new TreeSet<Automaton>( new DimensionalityHeuristicBasedAutomataIntersector.AutomataAscendingDimensionComparator()); String nuRegExp = null; logger.trace("Preparing the automaton..."); if (regularExpressions.size() > 0) { Iterator<String> regExpsIterator = regularExpressions.iterator(); if (regExpsIterator.hasNext()) { // DEBUGGING! // processAutomaton = processAutomaton.intersection(new RegExp(".{1," + alphabet.size() * 2 + "}").toAutomaton()); // processAutomaton = processAutomaton.intersection(new RegExp(".{1," + ((int)(alphabet.size() * 1.25)) + "}").toAutomaton()); // processAutomaton = processAutomaton.intersection(new RegExp(".{1,24}").toAutomaton()); // E.O. DEBUGGING while (regExpsIterator.hasNext()) { nuRegExp = regExpsIterator.next(); // logger.trace("Intersecting the automaton with the accepting for: " + nuRegExp); regExpAutomata.add(new RegExp(nuRegExp).toAutomaton()); } automaton = new DimensionalityHeuristicBasedAutomataIntersector().intersect(regExpAutomata); logger.trace("Automaton states: " + automaton.getNumberOfStates() + "; automaton transitions: " + automaton.getNumberOfTransitions()); } // DEBUGGING! // processAutomaton = processAutomaton.intersection(new RegExp("[^a]?[^a]a[^a][^a]?").toAutomaton()); // E.O. DEBUGGING } return automaton; } }
2,455
37.984127
144
java
Janus
Janus-master/src/minerful/automaton/DimensionalityHeuristicBasedCallableBriefSubAutomataMaker.java
package minerful.automaton; import java.util.Collection; import java.util.Iterator; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; import org.apache.log4j.Logger; import dk.brics.automaton.Automaton; import dk.brics.automaton.RegExp; import dk.brics.automaton.State; import dk.brics.automaton.Transition; public class DimensionalityHeuristicBasedCallableBriefSubAutomataMaker extends DimensionalityHeuristicBasedCallableSubAutomataMaker { private static Logger logger = Logger.getLogger(DimensionalityHeuristicBasedCallableBriefSubAutomataMaker.class.getCanonicalName()); public static final String LIMITING_ACTIONS_REG_EXP_TEMPLATE = "[^%1$s]{0,%2$d}%1$s[^%1$s]{0,%2$d}"; public final int maxActions; public DimensionalityHeuristicBasedCallableBriefSubAutomataMaker(Character basingCharacter, Collection<String> regularExpressions, int maxActions) { super(basingCharacter, regularExpressions); this.maxActions = maxActions; } @Override public SubAutomaton call() throws Exception { // Turn strings into Regular Expressions and attach them Automaton automaton = null; SortedSet<Automaton> regExpAutomata = new TreeSet<Automaton>( new DimensionalityHeuristicBasedAutomataIntersector.AutomataAscendingDimensionComparator()); String nuRegExp = null, limitingRegExp = buildActivitiesLimitingRegExp(); logger.trace("Preparing the automaton..."); regExpAutomata.add(new RegExp(limitingRegExp).toAutomaton()); if (regularExpressions.size() > 0) { Iterator<String> regExpsIterator = regularExpressions.iterator(); if (regExpsIterator.hasNext()) { // DEBUGGING! // processAutomaton = processAutomaton.intersection(new RegExp(".{1," + alphabet.size() * 2 + "}").toAutomaton()); // processAutomaton = processAutomaton.intersection(new RegExp(".{1," + ((int)(alphabet.size() * 1.25)) + "}").toAutomaton()); // processAutomaton = processAutomaton.intersection(new RegExp(".{1,24}").toAutomaton()); // E.O. DEBUGGING while (regExpsIterator.hasNext()) { nuRegExp = regExpsIterator.next(); // logger.trace("Intersecting the automaton with the accepting for: " + nuRegExp); regExpAutomata.add(new RegExp(nuRegExp).toAutomaton()); } automaton = new DimensionalityHeuristicBasedAutomataIntersector().intersect(regExpAutomata); automaton.minimize(); logger.trace("Automaton states: " + automaton.getNumberOfStates() + "; automaton transitions: " + automaton.getNumberOfTransitions()); automaton = this.refineAutomaton(automaton); } } return new SubAutomaton(basingCharacter, automaton); } private Automaton refineAutomaton(Automaton automaton) { State initialState = automaton.getInitialState(); this.pruneOutRedundantTransitions(initialState); automaton.minimize(); return automaton; } private void pruneOutRedundantTransitions(State initialState) { boolean redundantTransitions = false; State nextState = initialState.step(basingCharacter.charValue()); // Heuristic 1: if the automaton contains an action with the basingCharacter, the other are optional: we can exclude them! if (nextState != null) redundantTransitions = true; if (redundantTransitions) { Iterator<Transition> transIterator = initialState.getTransitions().iterator(); while (transIterator.hasNext()) { transIterator.next(); transIterator.remove(); } initialState.addTransition(new Transition(basingCharacter, nextState)); } else { Set<Transition> transitions = initialState.getTransitions(); if (transitions.size() == 0) { return; } else { for (Transition transition : transitions) { this.pruneOutRedundantTransitions(transition.getDest()); } } } } protected String buildActivitiesLimitingRegExp() { return String.format(LIMITING_ACTIONS_REG_EXP_TEMPLATE, this.basingCharacter, this.maxActions); } }
4,109
37.411215
149
java
Janus
Janus-master/src/minerful/automaton/DimensionalityHeuristicBasedCallableSubAutomataMaker.java
package minerful.automaton; import java.util.Collection; import java.util.Iterator; import java.util.SortedSet; import java.util.TreeSet; import java.util.concurrent.Callable; import org.apache.log4j.Logger; import dk.brics.automaton.Automaton; import dk.brics.automaton.RegExp; public class DimensionalityHeuristicBasedCallableSubAutomataMaker implements Callable<SubAutomaton> { private static Logger logger = Logger.getLogger(DimensionalityHeuristicBasedCallableSubAutomataMaker.class.getCanonicalName()); public final Character basingCharacter; public final Collection<String> regularExpressions; public DimensionalityHeuristicBasedCallableSubAutomataMaker(Character basingCharacter, Collection<String> regularExpressions) { this.regularExpressions = regularExpressions; this.basingCharacter = basingCharacter; } @Override public SubAutomaton call() throws Exception { // Turn strings into Regular Expressions and attach them Automaton automaton = null; SortedSet<Automaton> regExpAutomata = new TreeSet<Automaton>( new DimensionalityHeuristicBasedAutomataIntersector.AutomataAscendingDimensionComparator()); String nuRegExp = null; logger.trace("Preparing the automaton..."); if (regularExpressions.size() > 0) { Iterator<String> regExpsIterator = regularExpressions.iterator(); if (regExpsIterator.hasNext()) { // DEBUGGING! // processAutomaton = processAutomaton.intersection(new RegExp(".{1," + alphabet.size() * 2 + "}").toAutomaton()); // processAutomaton = processAutomaton.intersection(new RegExp(".{1," + ((int)(alphabet.size() * 1.25)) + "}").toAutomaton()); // processAutomaton = processAutomaton.intersection(new RegExp(".{1,24}").toAutomaton()); // E.O. DEBUGGING while (regExpsIterator.hasNext()) { nuRegExp = regExpsIterator.next(); // logger.trace("Intersecting the automaton with the accepting for: " + nuRegExp); regExpAutomata.add(new RegExp(nuRegExp).toAutomaton()); } automaton = new DimensionalityHeuristicBasedAutomataIntersector().intersect(regExpAutomata); logger.trace("Automaton states: " + automaton.getNumberOfStates() + "; automaton transitions: " + automaton.getNumberOfTransitions()); } // DEBUGGING! // processAutomaton = processAutomaton.intersection(new RegExp("[^a]?[^a]a[^a][^a]?").toAutomaton()); // E.O. DEBUGGING } automaton.minimize(); return new SubAutomaton(basingCharacter, automaton); } }
2,651
39.181818
144
java
Janus
Janus-master/src/minerful/automaton/RunnableAutoJoiner.java
package minerful.automaton; import org.apache.log4j.Logger; import dk.brics.automaton.Automaton; public class RunnableAutoJoiner implements Runnable { private static Logger logger = Logger.getLogger(AutomatonFactory.class.getCanonicalName()); public Automaton automaton; public Automaton secondAutomaton; public RunnableAutoJoiner(Automaton firstAutomaton, Automaton secondAutomaton) { this.automaton = firstAutomaton; this.secondAutomaton = secondAutomaton; } @Override public void run() { this.automaton = this.automaton.intersection(secondAutomaton); logger.trace("Automaton states: " + this.automaton.getNumberOfStates() + "; automaton transitions: " + this.automaton.getNumberOfTransitions()); } }
724
30.521739
146
java
Janus
Janus-master/src/minerful/automaton/RunnableAutoMaker.java
package minerful.automaton; import java.util.Collection; import java.util.Iterator; import org.apache.log4j.Logger; import dk.brics.automaton.Automaton; import dk.brics.automaton.RegExp; public class RunnableAutoMaker implements Runnable { public Automaton automaton; private static Logger logger = Logger.getLogger(AutomatonFactory.class.getCanonicalName()); public Collection<String> regularExpressions; public RunnableAutoMaker(Collection<String> regularExpressions) { this.automaton = null; this.regularExpressions = regularExpressions; } @Override public void run() { // Turn strings into Regular Expressions and attach them Automaton nuConstraintAutomaton = null; String nuRegExp = null; logger.trace("Preparing the automaton..."); if (regularExpressions.size() > 0) { Iterator<String> regExpsIterator = regularExpressions.iterator(); if (regExpsIterator.hasNext()) { // DEBUGGING! // processAutomaton = processAutomaton.intersection(new RegExp(".{1," + alphabet.size() * 2 + "}").toAutomaton()); // processAutomaton = processAutomaton.intersection(new RegExp(".{1," + ((int)(alphabet.size() * 1.25)) + "}").toAutomaton()); // processAutomaton = processAutomaton.intersection(new RegExp(".{1,24}").toAutomaton()); // E.O. DEBUGGING while (regExpsIterator.hasNext()) { nuRegExp = regExpsIterator.next(); // logger.trace("Intersecting the automaton with the accepting for: " + nuRegExp); nuConstraintAutomaton = new RegExp(nuRegExp).toAutomaton(); if (this.automaton == null) { this.automaton = nuConstraintAutomaton; } else { this.automaton = this.automaton.intersection(nuConstraintAutomaton); this.automaton.minimize(); } } logger.trace("Automaton states: " + this.automaton.getNumberOfStates() + "; automaton transitions: " + this.automaton.getNumberOfTransitions()); } // DEBUGGING! // processAutomaton = processAutomaton.intersection(new RegExp("[^a]?[^a]a[^a][^a]?").toAutomaton()); // E.O. DEBUGGING } } }
2,253
34.21875
154
java
Janus
Janus-master/src/minerful/automaton/SubAutomaton.java
package minerful.automaton; import dk.brics.automaton.Automaton; public class SubAutomaton { public final Character basingCharacter; public final Automaton automaton; public SubAutomaton(Character character, Automaton automaton) { this.basingCharacter = character; this.automaton = automaton; } }
307
22.692308
64
java
Janus
Janus-master/src/minerful/automaton/concept/relevance/ActivationStatusAwareState.java
package minerful.automaton.concept.relevance; import java.util.NavigableMap; import java.util.Set; import java.util.SortedSet; import java.util.TreeMap; import java.util.TreeSet; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlElementWrapper; import minerful.utils.RandomCharGenerator; import dk.brics.automaton.State; import dk.brics.automaton.Transition; @XmlAccessorType(XmlAccessType.NONE) public class ActivationStatusAwareState extends State { private static final long serialVersionUID = 169203888647636487L; protected StateActivationStatus status = StateActivationStatus.SAT_TEMP; protected String stateUUID = "s" + RandomCharGenerator.generateChar(6); protected NavigableMap<Character, Transition> transitionMap = new TreeMap<Character, Transition>(); @Override @XmlElementWrapper(name="transitions") @XmlElement(name="transition") public Set<Transition> getTransitions() { return super.getTransitions(); } @XmlAttribute(name="id") public String getStateUUID() { return stateUUID; } public void setStateUUID(String stateUUID) { this.stateUUID = stateUUID; } public Set<Character> getAllowedTransitionChars() { return this.transitionMap.keySet(); } @Override public void setAccept(boolean accept) { super.setAccept(accept); } @Override @XmlAttribute public boolean isAccept() { return super.isAccept(); } @Override public void addTransition(Transition transition) { for (char fire = transition.getMin(); fire <= transition.getMax(); fire++) this.transitionMap.put(fire, transition); super.addTransition(transition); } public boolean allowsTheSameTransitionsAs(ActivationStatusAwareState state) { return this.transitionMap.keySet().equals(state.transitionMap.keySet()); } public StateActivationStatus getStatus() { return status; } public void setStatus(StateActivationStatus status) { this.status = status; } public RelevanceAwareTransition getTransition(Character arg0) { if (this.transitionMap.containsKey(arg0)) return (RelevanceAwareTransition) this.transitionMap.get(arg0); return null; } @Override public String toString() { StringBuilder sBuil = new StringBuilder(); sBuil.append("State"); sBuil.append(" ID: "); sBuil.append(this.getStateUUID()); sBuil.append(" Status: "); sBuil.append(this.getStatus()); sBuil.append(" Accept: "); sBuil.append(this.isAccept()); sBuil.append(" "); sBuil.append("\n Transitions:\n"); for (Transition trans : this.getTransitions()) { sBuil.append(" Transition "); sBuil.append(trans.getMin() + " - " + trans.getMax()); sBuil.append(" to "); sBuil.append(((ActivationStatusAwareState)trans.getDest()).getStateUUID()); sBuil.append(" "); sBuil.append(" Relevant: "); sBuil.append(((RelevanceAwareTransition) trans).getRelevance()); sBuil.append("\n"); } return sBuil.toString(); } }
3,058
26.809091
100
java
Janus
Janus-master/src/minerful/automaton/concept/relevance/ActivationStatusWildcardAwareState.java
package minerful.automaton.concept.relevance; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import dk.brics.automaton.State; @XmlAccessorType(XmlAccessType.NONE) public class ActivationStatusWildcardAwareState extends ActivationStatusAwareState { private static final long serialVersionUID = 7185379079900528036L; public State stepWild() { return super.step(VacuityAwareWildcardAutomaton.getWildCardChar()); } public RelevanceAwareTransition getWildTransition() { if (this.transitionMap.containsKey(VacuityAwareWildcardAutomaton.getWildCardChar())) return (RelevanceAwareTransition) this.transitionMap.get(VacuityAwareWildcardAutomaton.getWildCardChar()); return null; } }
743
34.428571
109
java
Janus
Janus-master/src/minerful/automaton/concept/relevance/RelevanceAwareTransition.java
package minerful.automaton.concept.relevance; import javax.xml.bind.annotation.XmlAttribute; import minerful.utils.RandomCharGenerator; import dk.brics.automaton.State; import dk.brics.automaton.Transition; public class RelevanceAwareTransition extends Transition { private static final long serialVersionUID = 4844924976055163637L; private TransitionRelevance relevance = TransitionRelevance.RELEVANT; private String name = ""; private String taskName = null; // private String transitionUUID = UUID.randomUUID().toString(); //ID String would be too long private String transitionUUID = "t" + RandomCharGenerator.generateChar(6); @XmlAttribute(name="id") public String getTransitionUUID() { return transitionUUID; } public void setTransitionUUID(String transitionUUID) { this.transitionUUID = transitionUUID; } public RelevanceAwareTransition(char event, State to, String taskName) { super(event, to); this.taskName = taskName; } @XmlAttribute(name="to") public String getDestinationStateUUID(){ return ((ActivationStatusAwareState) getDest()).getStateUUID(); } @Override public char getMin() { return super.getMin(); } @Override public char getMax() { return super.getMax(); } @Override public State getDest() { return super.getDest(); } public TransitionRelevance getRelevance() { return relevance; } public void setRelevance(TransitionRelevance relevance) { this.relevance = relevance; } @XmlAttribute public String getName() { name = getMin() == getMax() ? "" + getMin() : "" + getMin() + getMax(); //Character of the transition (should not be more than one character) return name; } public void setName(String name) { this.name = name; } @XmlAttribute public String getTaskName() { return taskName; } public void setTaskName(String taskName) { this.taskName = taskName; } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("RelevanceAwareTransition [relevance="); builder.append(relevance); builder.append(", name="); builder.append(name); builder.append(", taskName="); builder.append(taskName); builder.append("]"); return builder.toString(); } }
2,212
22.795699
143
java
Janus
Janus-master/src/minerful/automaton/concept/relevance/StateActivationStatus.java
package minerful.automaton.concept.relevance; public enum StateActivationStatus { SAT_PERM, SAT_TEMP, VIO_PERM, VIO_TEMP }
127
15
45
java
Janus
Janus-master/src/minerful/automaton/concept/relevance/TransitionRelevance.java
package minerful.automaton.concept.relevance; public enum TransitionRelevance { RELEVANT, IRRELEVANT }
105
16.666667
45
java
Janus
Janus-master/src/minerful/automaton/concept/relevance/VacuityAwareAutomaton.java
package minerful.automaton.concept.relevance; import java.util.Iterator; import java.util.Map; import java.util.NavigableMap; import java.util.NavigableSet; import java.util.Set; import java.util.TreeMap; import java.util.TreeSet; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlElementWrapper; import javax.xml.bind.annotation.XmlRootElement; import dk.brics.automaton.Automaton; import dk.brics.automaton.State; import dk.brics.automaton.Transition; import minerful.concept.AbstractTaskClass; import minerful.utils.MessagePrinter; @XmlRootElement @XmlAccessorType(XmlAccessType.PUBLIC_MEMBER) public class VacuityAwareAutomaton extends Automaton { public static MessagePrinter logger = MessagePrinter.getInstance(VacuityAwareAutomaton.class); private static final long serialVersionUID = 7002546525205169853L; private String name; protected Set<Character> alphabet; protected Map<Character, AbstractTaskClass> translationMap; protected VacuityAwareAutomaton() { super(); this.translationMap = new TreeMap<Character, AbstractTaskClass>(); } protected VacuityAwareAutomaton(Map<Character, AbstractTaskClass> translationMap) { super(); this.translationMap = translationMap; } public VacuityAwareAutomaton(String name, Automaton automaton, Map<Character, AbstractTaskClass> translationMap) { this(translationMap); this.name = name; this.postConstructionInit(automaton); } protected void postConstructionInit(Automaton automaton) { // logger.debug(String.format("Building %s", this.name)); this.alphabet = new TreeSet<Character>(); automaton.minimize(); NavigableMap<State, ActivationStatusAwareState> statesTranslationMap = new TreeMap<State, ActivationStatusAwareState>(); NavigableSet<State> visitedStates = new TreeSet<State>(); ActivationStatusAwareState initWState = makeNewState(); State initState = automaton.getInitialState(); this.setInitialState(initWState); statesTranslationMap.put(initState, initWState); visitTransitions(statesTranslationMap, visitedStates, initState); } @Override @XmlElementWrapper(name = "states") @XmlElement(name = "state") public Set<State> getStates() { return super.getStates(); } public void visitTransitions(NavigableMap<State, ActivationStatusAwareState> statesTranslationMap, NavigableSet<State> visitedStates, State currentState) { if (visitedStates.contains(currentState)) return; ActivationStatusAwareState currentStAwaState = statesTranslationMap.get(currentState), destStAwaState = null; State destinationState = null; this.decideActivationStatus(currentState, currentStAwaState); for (Transition trans : currentState.getTransitions()) { // logger.debug(String.format("Visiting %s", trans.toString())); destinationState = trans.getDest(); if (!statesTranslationMap.containsKey(destinationState)) { destStAwaState = makeNewState(); statesTranslationMap.put(destinationState, destStAwaState); } else { destStAwaState = statesTranslationMap.get(destinationState); } for (char evt = trans.getMin(); evt <= trans.getMax(); evt++) { currentStAwaState.addTransition(new RelevanceAwareTransition(evt, destStAwaState, translationMap.get(evt).toString())); this.alphabet.add(evt); } visitedStates.add(currentState); // Recursive call: after this call, the reachable states have all been visited and assigned an activation status visitTransitions(statesTranslationMap, visitedStates, destinationState); } this.decideRelevanceOfTransitions(currentStAwaState); return; } protected ActivationStatusAwareState makeNewState() { return new ActivationStatusAwareState(); } private void decideRelevanceOfTransitions( ActivationStatusAwareState currentStAwaState) { ActivationStatusAwareState destStAwaState; RelevanceAwareTransition relAwaTrans; for (Transition trans : currentStAwaState.getTransitions()) { relAwaTrans = (RelevanceAwareTransition) trans; destStAwaState = (ActivationStatusAwareState) relAwaTrans.getDest(); // A transition is of relevance iff... if ( // 1. the activation status of the destination state changes (no matter how), or !currentStAwaState.getStatus().equals(destStAwaState.getStatus()) // 2. the possible actions that are allowed from this state are different than the ones in the destination state || !currentStAwaState.allowsTheSameTransitionsAs(destStAwaState) ) { relAwaTrans.setRelevance(TransitionRelevance.RELEVANT); } else { relAwaTrans.setRelevance(TransitionRelevance.IRRELEVANT); } } } private void decideActivationStatus(State currentState, ActivationStatusAwareState currentStAwaState) { boolean loop = true; int outgoingAllowedTransitions = 0; // A permanent satisfaction is possible in trimmed MINIMISED automata iff // 1. the state is accepting... if (currentState.isAccept()) { currentStAwaState.setAccept(true); Iterator<Transition> transIt = currentState.getTransitions().iterator(); Transition nextTrans = null; // 2. the state is looping... while (loop & transIt.hasNext()) { nextTrans = transIt.next(); loop = loop && nextTrans.getDest().equals(currentState); outgoingAllowedTransitions += nextTrans.getMax() - nextTrans.getMin() + 1; } // 3. all transitions are loops if (loop && outgoingAllowedTransitions == this.translationMap.size()) { currentStAwaState.setStatus(StateActivationStatus.SAT_PERM); } else { // In the worst case, an accepting state is at least a temp-satisfied one currentStAwaState.setStatus(StateActivationStatus.SAT_TEMP); } } else { // A state is of permanent violation when it is a not accepting sink // Watch out: empty automata are clearly composed only of a permanently violating state if (currentState.getTransitions().size() == 0) { currentStAwaState.setStatus(StateActivationStatus.VIO_PERM); // An intermediate non-accepting state is a temporary violation } else { currentStAwaState.setStatus(StateActivationStatus.VIO_TEMP); } } // logger.debug(String.format("Current state is %2$s (%1$s)", currentState.toString(), currentStAwaState.getStatus())); } @Override public State getInitialState() { return super.getInitialState(); } @Override public void setInitialState(State s) { super.setInitialState(s); } @Override @XmlAttribute public boolean isDeterministic() { return super.isDeterministic(); } @Override public void setDeterministic(boolean deterministic) { super.setDeterministic(deterministic); } public Set<Character> getAlphabet() { return alphabet; } }
6,823
32.782178
156
java
Janus
Janus-master/src/minerful/automaton/concept/relevance/VacuityAwareWildcardAutomaton.java
package minerful.automaton.concept.relevance; import java.util.Arrays; import java.util.Map; import java.util.SortedSet; import java.util.TreeSet; import minerful.automaton.AutomatonFactory; import minerful.concept.AbstractTaskClass; import minerful.logparser.StringTaskClass; import dk.brics.automaton.Automaton; public class VacuityAwareWildcardAutomaton extends VacuityAwareAutomaton { private static final long serialVersionUID = 2481171406279235021L; protected SortedSet<Character> alphabetWithoutWildcard; private String name; protected VacuityAwareWildcardAutomaton() { super(); } protected VacuityAwareWildcardAutomaton( String regExp, Map<Character, AbstractTaskClass> translationMap) { super(translationMap); this.alphabetWithoutWildcard = new TreeSet<Character>(translationMap.keySet()); this.translationMap.put(getWildCardChar(), getWildCardClass()); Automaton automaton = AutomatonFactory.fromRegularExpressions( Arrays.asList(regExp), translationMap.keySet(), true ); super.postConstructionInit(automaton); } public VacuityAwareWildcardAutomaton(String name, String regularExpression, Map<Character, AbstractTaskClass> translationMap) { this(regularExpression, translationMap); this.name = name; } public SortedSet<Character> getAlphabetWithoutWildcard() { return alphabetWithoutWildcard; } @Override protected ActivationStatusAwareState makeNewState() { return new ActivationStatusWildcardAwareState(); } public static final Character getWildCardChar() { return AutomatonFactory.WILD_CARD; } public static final StringTaskClass getWildCardClass() { return StringTaskClass.WILD_CARD; } public ActivationStatusWildcardAwareState getInitialWildState() { return (ActivationStatusWildcardAwareState) super.getInitialState(); } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("VacuityAwareWildcardAutomaton [name="); builder.append(name); builder.append(", automaton="); builder.append(super.toDot().trim() + " // Open this with XDot or similar GraphViz tools"); builder.append("]"); return builder.toString(); } }
2,281
26.493976
93
java
Janus
Janus-master/src/minerful/automaton/concept/weight/AutomatonElementButter.java
package minerful.automaton.concept.weight; public interface AutomatonElementButter { public static final int SINGLE_WEIGHT_INCREASE = 1; public abstract int increaseWeight(); public abstract int addWeight(int weight); public abstract int getWeight(); public abstract void setWeight(int weight); }
306
22.615385
52
java
Janus
Janus-master/src/minerful/automaton/concept/weight/AutomatonElementQuantileButter.java
package minerful.automaton.concept.weight; public interface AutomatonElementQuantileButter extends AutomatonElementButter { public static final int UNASSIGNED_QUANTILE = -1; public abstract int getWeightQuantile(); public abstract void setWeightQuantile(int weightQuantile); }
281
34.25
80
java
Janus
Janus-master/src/minerful/automaton/concept/weight/AutomatonNonConformityElementButter.java
package minerful.automaton.concept.weight; public interface AutomatonNonConformityElementButter { public abstract boolean isIllegal(); public abstract void setIllegal(boolean illegal); public abstract int increaseNonConformityWeight(); public abstract int addNonConformityWeight(int weight); public abstract int getNonConformityWeight(); public abstract void setNonConformityWeight(int weight); public abstract int getNonConformityWeightQuantile(); public abstract void setNonConformityWeightQuantile(int weightQuantile); }
541
26.1
73
java
Janus
Janus-master/src/minerful/automaton/concept/weight/WeightedAutomaton.java
package minerful.automaton.concept.weight; import java.util.NavigableMap; import java.util.NavigableSet; import java.util.Set; import java.util.TreeMap; import java.util.TreeSet; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlElementWrapper; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; import minerful.concept.AbstractTaskClass; import dk.brics.automaton.Automaton; import dk.brics.automaton.State; import dk.brics.automaton.Transition; @XmlRootElement @XmlAccessorType(XmlAccessType.PUBLIC_MEMBER) //@XmlJavaTypeAdapter(WeightedAutomatonXmlAdapter.class) public class WeightedAutomaton extends Automaton { private static final long serialVersionUID = 7002546525205169853L; private NavigableMap<Character, AbstractTaskClass> translationMap; @SuppressWarnings("unused") private WeightedAutomaton() { super(); } public WeightedAutomaton(Automaton automaton) { this(automaton, null); } public WeightedAutomaton(Automaton automaton, NavigableMap<Character, AbstractTaskClass> translationMap) { this.translationMap = translationMap; NavigableMap<State, WeightedState> statesTranslationMap = new TreeMap<State, WeightedState>(); NavigableSet<State> visitedStates = new TreeSet<State>(); WeightedState initWState = new WeightedState(); State initState = automaton.getInitialState(); this.setInitialState(initWState); statesTranslationMap.put(initState, initWState); unfoldTransitions(statesTranslationMap, visitedStates, initState); } @Override @XmlElementWrapper(name = "states") @XmlElement(name = "state") @XmlJavaTypeAdapter(WeightedStateXmlAdapter.class) public Set<State> getStates() { return super.getStates(); } public void unfoldTransitions( NavigableMap<State, WeightedState> statesTranslationMap, NavigableSet<State> visitedStates, State currentState) { if (visitedStates.contains(currentState)) return; WeightedState currentWState = statesTranslationMap.get(currentState), destinationWState = null; State destinationState = null; if (currentState.isAccept()) currentWState.setAccept(true); for (Transition trans : currentState.getTransitions()) { destinationState = trans.getDest(); if (!statesTranslationMap.containsKey(destinationState)) { destinationWState = new WeightedState(); statesTranslationMap.put(destinationState, destinationWState); } else { destinationWState = statesTranslationMap.get(destinationState); } for (char evt = trans.getMin(); evt <= trans.getMax(); evt++) { currentWState.addTransition(new WeightedTransition(evt, destinationWState, translationMap.get(evt).toString())); } visitedStates.add(currentState); unfoldTransitions(statesTranslationMap, visitedStates, destinationState); } } @Override public State getInitialState() { return super.getInitialState(); } @Override public void setInitialState(State s) { super.setInitialState(s); } @Override @XmlAttribute public boolean isDeterministic() { // TODO Auto-generated method stub return super.isDeterministic(); } @Override public void setDeterministic(boolean deterministic) { // TODO Auto-generated method stub super.setDeterministic(deterministic); } }
3,451
28.758621
116
java
Janus
Janus-master/src/minerful/automaton/concept/weight/WeightedAutomatonStats.java
package minerful.automaton.concept.weight; import java.util.ArrayList; import java.util.Set; import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics; import dk.brics.automaton.State; import dk.brics.automaton.Transition; public class WeightedAutomatonStats { public static int AMOUNT_OF_QUANTILES = 4; public static int MAX_PERCENTAGE = 100; private WeightedAutomaton automaton; private DescriptiveStatistics stateStats, transiStats, stateIllegalityStats, transIllegalityStats; private double stateQuantileBoundaries[] = new double[AMOUNT_OF_QUANTILES - 1], transQuantileBoundaries[] = new double[AMOUNT_OF_QUANTILES - 1], stateIllegalityQuantileBoundaries[] = new double[AMOUNT_OF_QUANTILES - 1], transIllegalityQuantileBoundaries[] = new double[AMOUNT_OF_QUANTILES - 1]; public WeightedAutomatonStats(WeightedAutomaton automaton) { this.automaton = automaton; this.buildStats(); this.buildIllegalityStats(); } public void augmentWeightedAutomatonWithQuantiles(boolean doRemoveNeverTraversedTransitions) { WeightedState auxWState = null; WeightedTransition auxWTrans = null; ArrayList<Transition> neverTraversedTransitions = null; for (State state : this.automaton.getStates()) { if (doRemoveNeverTraversedTransitions) { neverTraversedTransitions = new ArrayList<Transition>(); } auxWState = (WeightedState) state; auxWState.setWeightQuantile(this.calculateStateQuantile(auxWState.getWeight())); for (Transition trans : auxWState.getTransitions()) { auxWTrans = (WeightedTransition) trans; if (doRemoveNeverTraversedTransitions && auxWTrans.getWeight() == 0) { neverTraversedTransitions.add(auxWTrans); } else { auxWTrans.setWeightQuantile(this.calculateTransQuantile(auxWTrans.getWeight())); } } if (doRemoveNeverTraversedTransitions) { for (Transition inuTran : neverTraversedTransitions) { auxWState.getTransitions().remove(inuTran); } } } } public void augmentWeightedAutomatonWithIllegalityQuantiles() { WeightedState auxWState = null; WeightedTransition auxWTrans = null; for (State state : this.automaton.getStates()) { auxWState = (WeightedState) state; auxWState.setNonConformityWeightQuantile(this.calculateStateIllegalityQuantile(auxWState.getNonConformityWeight())); for (Transition trans : auxWState.getTransitions()) { auxWTrans = (WeightedTransition) trans; auxWTrans.setNonConformityWeightQuantile(this.calculateTransIllegalityQuantile(auxWTrans.getNonConformityWeight())); } } } public int calculateStateQuantile(int value) { return this.calculateXtile(value, stateQuantileBoundaries); } public int calculateTransQuantile(int value) { return this.calculateXtile(value, transQuantileBoundaries); } public int calculateStateIllegalityQuantile(int value) { return this.calculateXtile(value, stateIllegalityQuantileBoundaries); } public int calculateTransIllegalityQuantile(int value) { return this.calculateXtile(value, transIllegalityQuantileBoundaries); } public int calculateXtile(int value, double[] xTileBoundaries) { int trials = 1; int xBoundaryIndex = ( AMOUNT_OF_QUANTILES / (int) Math.pow(2, trials) ) - 1; double auxBoundary = xTileBoundaries[xBoundaryIndex]; boolean onTheLeft = false; while ( trials <= Math.log(AMOUNT_OF_QUANTILES)/Math.log(2) ) { if (value < auxBoundary) { xBoundaryIndex -= AMOUNT_OF_QUANTILES / (int) Math.pow(2, ++trials); onTheLeft = true; } else { xBoundaryIndex += AMOUNT_OF_QUANTILES / (int) Math.pow(2, ++trials); onTheLeft = false; } auxBoundary = xTileBoundaries[xBoundaryIndex]; } return xBoundaryIndex + (onTheLeft ? 0 : 1); } private void buildStats() { this.stateStats = new DescriptiveStatistics(); this.transiStats = new DescriptiveStatistics(); for (State state : this.automaton.getStates()) { this.stateStats.addValue(((WeightedState) state).getWeight()); for (Transition trans: state.getTransitions()) { /* * In BPI 2012, it happened that most of weights (vast majority, * amounting to more than 82.5%) were equal to 0. This entailed * the presence of 6 quantile-boundaries equal to 0.0 and only * one having a higher value. However, this made it impossible * to distinguish between, e.g., transitions which were * traversed 8100 times from transitions traversed twice. * Therefore, we decide to remove from the quantile-boundary-computation all those values that amount to 0. * Motivation is, we do not care about never-enacted behaviour! * This prevents the imbalance. */ if (((WeightedTransition) trans).getWeight() > 0) this.transiStats.addValue(((WeightedTransition) trans).getWeight()); } } for (int q = 0; q < AMOUNT_OF_QUANTILES - 1 ; q++) { // say we want quartiles. Then AMOUNT_OF_QUANTILES = 4. We want boundary values for 25, 50 and 75 => q values have to be 0, 1, 2 because the percentile is calculated as MAX_PERCENTAGE / AMOUNT_OF_QUANTILES * (q + 1) -- see the +1 there? Good! stateQuantileBoundaries[q] = stateStats.getPercentile((double) MAX_PERCENTAGE / AMOUNT_OF_QUANTILES * (q + 1) ); } for (int q = 0; q < AMOUNT_OF_QUANTILES - 1 ; q++) { // say we want quartiles. Then AMOUNT_OF_QUANTILES = 4. We want boundary values for 25, 50 and 75 => q values have to be 0, 1, 2 because the percentile is calculated as MAX_PERCENTAGE / AMOUNT_OF_QUANTILES * (q + 1) -- see the +1 there? Good! transQuantileBoundaries[q] = transiStats.getPercentile((double) MAX_PERCENTAGE / AMOUNT_OF_QUANTILES * (q + 1) ); } } private void buildIllegalityStats() { this.stateIllegalityStats = new DescriptiveStatistics(); this.transIllegalityStats = new DescriptiveStatistics(); for (State state : this.automaton.getStates()) { this.stateIllegalityStats.addValue(((WeightedState) state).getWeight()); for (Transition trans: state.getTransitions()) { if (((WeightedTransition) trans).getWeight() > 0) this.transIllegalityStats.addValue(((WeightedTransition) trans).getWeight()); } } for (int q = 0; q < AMOUNT_OF_QUANTILES - 1 ; q++) { // say we want quartiles. Then AMOUNT_OF_QUANTILES = 4. We want boundary values for 25, 50 and 75 => q values have to be 0, 1, 2 because the percentile is calculated as MAX_PERCENTAGE / AMOUNT_OF_QUANTILES * (q + 1) -- see the +1 there? Good! stateIllegalityQuantileBoundaries[q] = stateIllegalityStats.getPercentile((double) MAX_PERCENTAGE / AMOUNT_OF_QUANTILES * (q + 1) ); } for (int q = 0; q < AMOUNT_OF_QUANTILES - 1 ; q++) { // say we want quartiles. Then AMOUNT_OF_QUANTILES = 4. We want boundary values for 25, 50 and 75 => q values have to be 0, 1, 2 because the percentile is calculated as MAX_PERCENTAGE / AMOUNT_OF_QUANTILES * (q + 1) -- see the +1 there? Good! transIllegalityQuantileBoundaries[q] = transIllegalityStats.getPercentile((double) MAX_PERCENTAGE / AMOUNT_OF_QUANTILES * (q + 1) ); } } }
7,017
41.792683
298
java
Janus
Janus-master/src/minerful/automaton/concept/weight/WeightedAutomatonXmlAdapter.java
package minerful.automaton.concept.weight; import javax.xml.bind.annotation.adapters.XmlAdapter; import dk.brics.automaton.Automaton; public class WeightedAutomatonXmlAdapter extends XmlAdapter<WeightedAutomaton, Automaton> { @Override public Automaton unmarshal(WeightedAutomaton v) throws Exception { return v; } @Override public WeightedAutomaton marshal(Automaton v) throws Exception { return (WeightedAutomaton) v; } }
442
20.095238
67
java
Janus
Janus-master/src/minerful/automaton/concept/weight/WeightedState.java
package minerful.automaton.concept.weight; import java.util.NavigableMap; import java.util.Set; import java.util.TreeMap; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlElementWrapper; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; import dk.brics.automaton.State; import dk.brics.automaton.Transition; import minerful.utils.MessagePrinter; import minerful.utils.RandomCharGenerator; @XmlAccessorType(XmlAccessType.NONE) public class WeightedState extends State implements AutomatonElementQuantileButter, AutomatonNonConformityElementButter { private static final long serialVersionUID = -3665359375777248550L; public static MessagePrinter logger = MessagePrinter.getInstance(WeightedState.class); private int weight = 0; private int weightQuantile = UNASSIGNED_QUANTILE; private int nonConformityWeight = 0; private int nonConformityWeightQuantile = 0; private boolean illegal = false; // private String stateUUID = UUID.randomUUID().toString(); //ID String would be too long private String stateUUID = "s" + RandomCharGenerator.generateChar(6); private NavigableMap<Character, Transition> transitionMap = new TreeMap<Character, Transition>(); @Override @XmlElementWrapper(name="transitions") @XmlElement(name="transition") @XmlJavaTypeAdapter(WeightedTransitionXmlAdapter.class) public Set<Transition> getTransitions() { return super.getTransitions(); } @XmlAttribute(name="id") public String getStateUUID() { return stateUUID; } public void setStateUUID(String stateUUID) { this.stateUUID = stateUUID; } @Override public int increaseWeight() { return this.addWeight(SINGLE_WEIGHT_INCREASE); } @Override public int addWeight(int weight) { setWeight(this.weight + weight); return getWeight(); } @Override @XmlAttribute public int getWeight() { return weight; } @Override public void setWeight(int weight) { this.weight = weight; } @Override @XmlAttribute public int getWeightQuantile() { return weightQuantile; } @Override public void setWeightQuantile(int weightQuantile) { this.weightQuantile = weightQuantile; } @Override public int increaseNonConformityWeight() { return this.addNonConformityWeight(SINGLE_WEIGHT_INCREASE); } @Override public int addNonConformityWeight(int weight) { setNonConformityWeight(this.weight + weight); return getNonConformityWeight(); } @Override @XmlAttribute public int getNonConformityWeight() { return this.nonConformityWeight; } @Override public void setNonConformityWeight(int weight) { this.nonConformityWeight = weight; } @Override @XmlAttribute public int getNonConformityWeightQuantile() { return this.nonConformityWeightQuantile; } @Override public void setNonConformityWeightQuantile(int weightQuantile) { this.nonConformityWeightQuantile = weightQuantile; } @Override public void setAccept(boolean accept) { super.setAccept(accept); } @Override @XmlAttribute public boolean isAccept() { return super.isAccept(); } @Override @XmlAttribute public boolean isIllegal() { return this.illegal; } @Override public void setIllegal(boolean illegal) { this.illegal = illegal; } @Override public void addTransition(Transition transition) { for (char fire = transition.getMin(); fire <= transition.getMax(); fire++) this.transitionMap.put(fire, transition); super.addTransition(transition); } public WeightedState stepAndIncreaseTransitionWeight(char chr) { try { ((WeightedTransition) this.transitionMap.get(chr)).increaseWeight(); } catch (NullPointerException nPEx) { logger.error("Unallowed transition requested!"); // nPEx.printStackTrace(); logger.error("Transition map: " + this.transitionMap); logger.error("Searched chr: " + chr); logger.error("State: " + super.toString()); return null; } return (WeightedState) super.step(chr); } public WeightedState stepAndIncreaseTransitionsNonConformityWeight(char chr) { try { ((WeightedTransition) this.transitionMap.get(chr)).increaseNonConformityWeight(); } catch (NullPointerException nPEx) { // All right here: it happens! } return (WeightedState) super.step(chr); } @Override public String toString() { StringBuilder sBuildo = new StringBuilder(); sBuildo.append(super.toString()); sBuildo.append('\n'); sBuildo.append("weight="); sBuildo.append(this.weight); if (this.weightQuantile != UNASSIGNED_QUANTILE) { sBuildo.append(" ("); sBuildo.append(this.weightQuantile + 1); sBuildo.append(". quantile"); sBuildo.append(')'); } sBuildo.append('\n'); return sBuildo.toString(); } }
4,825
23.876289
121
java
Janus
Janus-master/src/minerful/automaton/concept/weight/WeightedStateXmlAdapter.java
package minerful.automaton.concept.weight; import javax.xml.bind.annotation.adapters.XmlAdapter; import dk.brics.automaton.State; public class WeightedStateXmlAdapter extends XmlAdapter<WeightedState, State> { @Override public State unmarshal(WeightedState v) throws Exception { return v; } @Override public WeightedState marshal(State v) throws Exception { return (WeightedState) v; } }
404
19.25
79
java
Janus
Janus-master/src/minerful/automaton/concept/weight/WeightedTransition.java
package minerful.automaton.concept.weight; import javax.xml.bind.annotation.XmlAttribute; import minerful.utils.RandomCharGenerator; import dk.brics.automaton.State; import dk.brics.automaton.Transition; public class WeightedTransition extends Transition implements AutomatonElementQuantileButter, AutomatonNonConformityElementButter { private static final long serialVersionUID = -135495105218792952L; private int weight = 0; private int nonConformityWeight = 0; private int weightQuantile = 0; private int nonConformityWeightQuantile = 0; private boolean illegal = false; private String name = ""; private String taskName = null; // private String transitionUUID = UUID.randomUUID().toString(); //ID String would be too long private String transitionUUID = "t" + RandomCharGenerator.generateChar(6); @XmlAttribute(name="id") public String getTransitionUUID() { return transitionUUID; } public void setTransitionUUID(String transitionUUID) { this.transitionUUID = transitionUUID; } public WeightedTransition(char event, State to, String taskName) { super(event, to); this.taskName = taskName; } @XmlAttribute(name="to") public String getDestinationStateUUID(){ return ((WeightedState) getDest()).getStateUUID(); } @Override public char getMin() { return super.getMin(); } @Override public char getMax() { return super.getMax(); } @Override public State getDest() { return super.getDest(); } @Override public int increaseWeight() { return this.addWeight(SINGLE_WEIGHT_INCREASE); } @Override public int addWeight(int weight) { setWeight(this.weight + weight); return getWeight(); } @Override @XmlAttribute public int getWeight() { return weight; } @Override public void setWeight(int weight) { this.weight = weight; } @Override @XmlAttribute public int getWeightQuantile() { return weightQuantile; } @Override public void setWeightQuantile(int weightQuantile) { this.weightQuantile = weightQuantile; } @XmlAttribute public String getName() { name = getMin() == getMax() ? "" + getMin() : "" + getMin() + getMax(); //Character of the transition (should not be more than one character) return name; } public void setName(String name) { this.name = name; } @XmlAttribute public String getTaskName() { return taskName; } public void setTaskName(String taskName) { this.taskName = taskName; } @Override public int increaseNonConformityWeight() { return this.addNonConformityWeight(SINGLE_WEIGHT_INCREASE); } @Override public int addNonConformityWeight(int weight) { setNonConformityWeight(this.weight + weight); return getNonConformityWeight(); } @Override @XmlAttribute public int getNonConformityWeight() { return this.nonConformityWeight; } @Override public void setNonConformityWeight(int weight) { this.nonConformityWeight = weight; } @Override @XmlAttribute public int getNonConformityWeightQuantile() { return this.nonConformityWeightQuantile; } @Override public void setNonConformityWeightQuantile(int weightQuantile) { this.nonConformityWeightQuantile = weightQuantile; } @Override @XmlAttribute public boolean isIllegal() { return this.illegal; } @Override public void setIllegal(boolean illegal) { this.illegal = illegal; } @Override public String toString() { StringBuilder sBuildo = new StringBuilder(); sBuildo.append(super.toString()); sBuildo.append("; "); sBuildo.append("weight="); sBuildo.append(this.weight); if (this.weightQuantile != UNASSIGNED_QUANTILE) { sBuildo.append(" ("); sBuildo.append(this.weightQuantile + 1); sBuildo.append(". quantile"); sBuildo.append(')'); } return sBuildo.toString(); } }
3,728
21.737805
143
java
Janus
Janus-master/src/minerful/automaton/concept/weight/WeightedTransitionXmlAdapter.java
package minerful.automaton.concept.weight; import javax.xml.bind.annotation.adapters.XmlAdapter; import dk.brics.automaton.Transition; public class WeightedTransitionXmlAdapter extends XmlAdapter<WeightedTransition, Transition> { @Override public Transition unmarshal(WeightedTransition v) throws Exception { return v; } @Override public WeightedTransition marshal(Transition v) throws Exception { return (WeightedTransition) v; } }
449
21.5
94
java
Janus
Janus-master/src/minerful/automaton/encdec/AbstractAutomatonDotPrinter.java
package minerful.automaton.encdec; import java.io.IOException; import java.util.Collection; import java.util.Map; import java.util.NavigableMap; import java.util.Properties; import java.util.Set; import java.util.TreeMap; import java.util.TreeSet; import minerful.utils.ResourceReader; import dk.brics.automaton.State; public abstract class AbstractAutomatonDotPrinter { protected static class EmphasizableLabelPojo { public final String label; public final boolean emphasized; public EmphasizableLabelPojo(String label, boolean emphasized) { this.label = label; this.emphasized = emphasized; } } protected static final String DOT_INIT = ResourceReader.readResource("minerful/automaton/encdec/init_for_dot.txt"); protected static final String DOT_END = ResourceReader.readResource("minerful/automaton/encdec/end_for_dot.txt"); protected static Properties DOT_TEMPLATES = null; protected NavigableMap<Character, String> transMap; public AbstractAutomatonDotPrinter(NavigableMap<Character, String> translationMap) { this.transMap = translationMap; if (DOT_TEMPLATES == null) { DOT_TEMPLATES = new Properties(); try { DOT_TEMPLATES.load(ResourceReader.loadResource("minerful/automaton/encdec/dot_templates.properties")); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } protected int getAlphabetSize() { return this.transMap.keySet().size(); } protected Map<State, String> defineStateNodesIds(Set<State> states) { Map<State, String> statesIdMap = new TreeMap<State, String>(); int i = 0; for (State state : states) { // Let us map states with unique identifiers statesIdMap.put(state, String.format(DOT_TEMPLATES.getProperty("stateNodeNameTemplate"), i++)); } return statesIdMap; } protected Collection<Character> makeItHowNotToGetThere(Collection<Character> list) { Collection<Character> notThere = new TreeSet<Character>(this.transMap.keySet()); notThere.removeAll(list); return notThere; } }
2,028
29.742424
116
java
Janus
Janus-master/src/minerful/automaton/encdec/AutomatonDotPrinter.java
package minerful.automaton.encdec; import java.io.BufferedReader; import java.io.IOException; import java.io.StringReader; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.Map; import java.util.NavigableMap; import java.util.Set; import java.util.TreeMap; import java.util.TreeSet; import java.util.regex.Matcher; import java.util.regex.Pattern; import minerful.io.encdec.TaskCharEncoderDecoder; import dk.brics.automaton.Automaton; import dk.brics.automaton.State; import dk.brics.automaton.Transition; public class AutomatonDotPrinter extends AbstractAutomatonDotPrinter { // TODO: this has to be changed into something read from a properties file! public static final boolean RAW_DOT = true; public AutomatonDotPrinter(NavigableMap<Character, String> translationMap) { super(translationMap); } public String printDot(Automaton automaton) { if (!RAW_DOT) return this.printDot(automaton, null); else return this.printRawDot(automaton); } public String printDot(Automaton automaton, Character emphasizedActivity) { if (RAW_DOT) return this.printRawDot(automaton, emphasizedActivity); StringBuilder sBuilder = new StringBuilder(); // Put the header of the file sBuilder.append(DOT_INIT); // Start from the init state Set<State> states = automaton.getStates(); State initState = automaton.getInitialState(); Map<State, String> statesIdMap = defineStateNodesIds(states); for (State state : states) { // If this is the init state, start the automaton with it if (state.isAccept()) { sBuilder.append(String.format(DOT_TEMPLATES.getProperty("acceptingStateNodeTemplate"), statesIdMap.get(state))); } if (state.equals(initState)) { sBuilder.append(String.format(DOT_TEMPLATES.getProperty("startTemplate"), statesIdMap.get(state))); } } for (State state : states) { sBuilder.append(printDot(state, statesIdMap, emphasizedActivity)); } sBuilder.append(DOT_END); return sBuilder.toString(); } private String printDot(State state, Map<State, String> statesIdMap, Character emphasizedActivity) { StringBuilder sBuilder = new StringBuilder(); boolean goForNot = false, goForNotRequiredNow = false; NavigableMap<State, Collection<Character>> howToGetThere = new TreeMap<State, Collection<Character>>(); String stateNodeName = statesIdMap.get(state); Collection<Character> outGoingWays = new TreeSet<Character>(), outGoingWaysToOneState = null, howNotToGetThere = null; EmphasizableLabelPojo eLaPo = null; // Get the output transitions, and labels. for (Transition trans : state.getTransitions()) { if (!howToGetThere.containsKey(trans.getDest())) howToGetThere.put(trans.getDest(), new ArrayList<Character>()); outGoingWaysToOneState = this.transMap.headMap(trans.getMax(),true).tailMap(trans.getMin(),true).keySet(); outGoingWays.addAll(outGoingWaysToOneState); howToGetThere.put(trans.getDest(), outGoingWaysToOneState); } Set<State> reachableStates = howToGetThere.keySet(); String actiNodeName = null, targetStateNodeName = null, blaurghStateName = null, compensatingStateName = null; int activityCounter = 0; for (State reachableState : reachableStates) { goForNotRequiredNow = false; targetStateNodeName = statesIdMap.get(reachableState); // Then, for each reached state, check numbers: how many are the outgoing connections? // If they are more than half of the alphabet size, start considering the "not" transitions if (howToGetThere.get(reachableState).size() > (this.getAlphabetSize() / 2)) { goForNotRequiredNow = true; } else { goForNotRequiredNow = false; } goForNot = goForNot || goForNotRequiredNow; // Add the new activity node if (goForNotRequiredNow) { } else { eLaPo = buildActivityLabel(howToGetThere.get(reachableState), emphasizedActivity); actiNodeName = String.format(DOT_TEMPLATES.getProperty("activityNodeNameTemplate"), stateNodeName, ++activityCounter); sBuilder.append(String.format(DOT_TEMPLATES.getProperty("activityNodeTemplate"), actiNodeName, eLaPo.label)); if (eLaPo.emphasized) { sBuilder.append(String.format(DOT_TEMPLATES.getProperty("emphasizedTransitionTemplate"), stateNodeName, actiNodeName, targetStateNodeName)); } else { sBuilder.append(String.format(DOT_TEMPLATES.getProperty("transitionTemplate"), stateNodeName, actiNodeName, targetStateNodeName)); } } } if (goForNot) { // good transitions (the remaining guys) are thus labelled with "*" actiNodeName = String.format(DOT_TEMPLATES.getProperty("activityNodeNameTemplate"), stateNodeName, ++activityCounter); compensatingStateName = String.format(DOT_TEMPLATES.getProperty("compensatingActivityWrapperStateNodeTemplate"), stateNodeName, actiNodeName); sBuilder.append(String.format(DOT_TEMPLATES.getProperty("compensationForNotTransitionTemplate"), stateNodeName, compensatingStateName, targetStateNodeName)); howNotToGetThere = this.makeItHowNotToGetThere(outGoingWays); if (howNotToGetThere.size() > 0) { eLaPo = buildActivityLabel(howNotToGetThere, emphasizedActivity); blaurghStateName = String.format(DOT_TEMPLATES.getProperty("blaurghStateNodeTemplate"), stateNodeName); // "not" transitions lead to blaurgh states actiNodeName = String.format(DOT_TEMPLATES.getProperty("activityNodeNameTemplate"), stateNodeName, ++activityCounter); sBuilder.append(String.format(DOT_TEMPLATES.getProperty("activityNodeTemplate"), actiNodeName, eLaPo.label)); if (eLaPo.emphasized) sBuilder.append(String.format(DOT_TEMPLATES.getProperty("emphasizedNotTransitionTemplate"), stateNodeName, actiNodeName, blaurghStateName)); else sBuilder.append(String.format(DOT_TEMPLATES.getProperty("notTransitionTemplate"), stateNodeName, actiNodeName, blaurghStateName)); } } return sBuilder.toString(); } private EmphasizableLabelPojo buildActivityLabel(Collection<Character> waysList, Character emphasizedActivity) { StringBuilder actiSBuilder = new StringBuilder(); Iterator<Character> howToIterator = waysList.iterator(); Character way = howToIterator.next(); actiSBuilder.append(String.format(DOT_TEMPLATES.getProperty("activityLabelTemplateStarter"), this.transMap.get(way))); boolean emphasizeIt = false; if (emphasizedActivity != null && way.equals(emphasizedActivity)) { emphasizeIt = true; } while (howToIterator.hasNext()) { way = howToIterator.next(); if (emphasizedActivity != null && !emphasizeIt && way.equals(emphasizedActivity)) { emphasizeIt = true; } actiSBuilder.append(String.format(DOT_TEMPLATES.getProperty("activityLabelTemplate"), this.transMap.get(way))); } return new EmphasizableLabelPojo(actiSBuilder.toString().trim(), emphasizeIt); } public String printRawDot(Automaton automaton) { return this.printRawDot(automaton, null); } public String printRawDot(Automaton automaton, Character emphasizedActivity) { String dotString = automaton.toDot(); return this.replaceIdentifiersWithActivityNamesInDotAutomaton(dotString, emphasizedActivity); } public String replaceIdentifiersWithActivityNamesInDotAutomaton(String automatonDotFormat, Character basingCharacter) { BufferedReader buRead = new BufferedReader(new StringReader(automatonDotFormat)); StringBuilder sBuil = new StringBuilder(); String line; Character activityId = null, activityIdForUpperBoundInRange = null; Pattern patternForSingleLabel = Pattern.compile("label=\"(.|\\\\[^\"-]+)\""); // Originarily, label="\"(.)\"", but it did not capture, e.g., label="\u00eb" Pattern patternForRangeLabel = Pattern.compile("label=\"(.|\\\\[^\"-]+)-(.|\\\\[^\"-]+)\""); // Originarily, label="\"(.)-(.)\"", but it did not capture, e.g., label="\u00eb-\u00ef" Matcher m = null; try { line = buRead.readLine(); while (line != null) { m = patternForSingleLabel.matcher(line); if (m.find()) { activityId = TaskCharEncoderDecoder.encodedCharFromString(m.group(1)); line = m.replaceFirst("label=\"" + ( (transMap.containsKey(activityId)) ? (transMap.get(activityId) + ( (basingCharacter != null && activityId.compareTo(basingCharacter) == 0) ? "\",color=firebrick,style=bold" : "\"" ) ) : (activityId + "\"") ) ); } else { m = patternForRangeLabel.matcher(line); if (m.find()) { activityId = TaskCharEncoderDecoder.encodedCharFromString(m.group(1)); activityIdForUpperBoundInRange = TaskCharEncoderDecoder.encodedCharFromString(m.group(2)); line = m.replaceFirst("label=\"" + replaceIdentifiersWithActivityNamesInDotAutomatonLabel(activityId, activityIdForUpperBoundInRange) + "\"" ); } } sBuil.append(line); sBuil.append("\n"); line = buRead.readLine(); } } catch (IOException e) { e.printStackTrace(); } return sBuil.toString(); } private String replaceIdentifiersWithActivityNamesInDotAutomatonLabel(Character from, Character to) { StringBuilder sBuil = new StringBuilder(); NavigableMap<Character, String> subMap = transMap.tailMap(from, true).headMap(to, true); if (subMap.size() > 0) { Iterator<String> actIterator = subMap.values().iterator(); while (actIterator.hasNext()) { sBuil.append(actIterator.next()); if (actIterator.hasNext()) { sBuil.append("\\\\n"); } } } return sBuil.toString().trim(); } }
9,619
36.142857
160
java
Janus
Janus-master/src/minerful/automaton/encdec/StateTransitionCounter.java
package minerful.automaton.encdec; import java.util.Map; import java.util.TreeMap; import dk.brics.automaton.State; public class StateTransitionCounter implements Comparable<StateTransitionCounter> { public static final int DEFAULT_INCREMENT = 1; public final State tailState; private Map<Character, Integer> transitionCounterMap; private int howManyCrossings = 0; public StateTransitionCounter(State tailState) { this.tailState = tailState; this.transitionCounterMap = new TreeMap<Character, Integer>(); } public void incrementTransitionsCounter(Character to) { this.incrementTransitionsCounter(to, DEFAULT_INCREMENT); } public void incrementTransitionsCounter(Character to, int by) { int howMuch = by; if (this.transitionCounterMap.containsKey(to)) { howMuch += this.transitionCounterMap.get(to); } this.transitionCounterMap.put(to, howMuch); } public void incrementCrossingsCounter() { this.incrementCrossingsCounter(DEFAULT_INCREMENT); } public void incrementCrossingsCounter(int by) { this.howManyCrossings += by; } public Map<Character, Integer> getTransitionCounterMap() { return transitionCounterMap; } public int getHowManyCrossings() { return howManyCrossings; } @Override public int compareTo(StateTransitionCounter o) { return this.tailState.compareTo(o.tailState); } }
1,341
26.387755
83
java
Janus
Janus-master/src/minerful/automaton/encdec/StateTransitionCountersMap.java
package minerful.automaton.encdec; import java.util.Map; import java.util.TreeMap; import dk.brics.automaton.State; public class StateTransitionCountersMap { private Map<State, StateTransitionCounter> stateTransCountMap = new TreeMap<State, StateTransitionCounter>(); public void incrementStateCrossingsCounter(State state) { this.addStateToMapIfNeeded(state); stateTransCountMap.get(state).incrementCrossingsCounter(); } public void incrementStateCrossingsCounter(State state, int by) { this.addStateToMapIfNeeded(state); stateTransCountMap.get(state).incrementCrossingsCounter(by); } public void incrementTransitionsCounter(State tailState, Character to, int by) { this.addStateToMapIfNeeded(tailState); stateTransCountMap.get(tailState).incrementTransitionsCounter(to, by); } public void incrementTransitionsCounter(State tailState, Character to) { this.addStateToMapIfNeeded(tailState); stateTransCountMap.get(tailState).incrementTransitionsCounter(to); } private void addStateToMapIfNeeded(State tailState) { if (!this.stateTransCountMap.containsKey(tailState)) { this.stateTransCountMap.put(tailState, new StateTransitionCounter(tailState)); } } public Map<State, StateTransitionCounter> getStateTransCountMap() { return stateTransCountMap; } }
1,297
33.157895
110
java
Janus
Janus-master/src/minerful/automaton/encdec/TsmlEncoder.java
package minerful.automaton.encdec; import java.util.HashMap; import java.util.NavigableMap; import java.util.Set; import dk.brics.automaton.Automaton; import dk.brics.automaton.State; import dk.brics.automaton.Transition; public class TsmlEncoder { public final static String DEFAULT_WEIGHT = "1"; protected NavigableMap<Character, String> transMap; public TsmlEncoder(NavigableMap<Character, String> transMap) { this.transMap = transMap; } /** * * Creates a TSML-document based on an instance of the class {@link Automaton}. * * @param a Automaton to be used. * @param automatonSource The Automaton used. * @return TSML document. */ public String automatonToTSML(Automaton a, String automatonSource) { Set<State> stateSet = a.getStates(); HashMap<State, Set<Transition>> transitionSet = new HashMap<State, Set<Transition>>(); StringBuilder tsmlBuilder = new StringBuilder(); tsmlBuilder.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); tsmlBuilder.append('\n'); tsmlBuilder.append("<tsml label=\"Converted from " + automatonSource + "\" layout=\"false\">"); tsmlBuilder.append('\n'); State initialState = a.getInitialState(); for (State state : stateSet) { tsmlBuilder.append("<state weight=\""); tsmlBuilder.append(DEFAULT_WEIGHT); // TODO: WEIGHT of a transition! tsmlBuilder.append("\" "); tsmlBuilder.append("id=\"state" + state.hashCode() + "\" "); if (initialState.equals(state)) tsmlBuilder.append(" start=\"true\""); if (state.isAccept()) tsmlBuilder.append(" accept=\"true\""); tsmlBuilder.append(">\n<name><text>" + state.hashCode()); tsmlBuilder.append("</text></name>"); tsmlBuilder.append("</state>"); tsmlBuilder.append('\n'); transitionSet.put(state, state.getTransitions()); } for (State source : transitionSet.keySet()) { for (Transition t : transitionSet.get(source)) { for (Character c = t.getMin(); c <= t.getMax(); c++) { tsmlBuilder.append("<transition weight=\""); tsmlBuilder.append(DEFAULT_WEIGHT); // TODO: WEIGHT of a transition! tsmlBuilder.append("\" "); // tsmlBuilder.append("id=\"transition_" + source.hashCode() + "_" + c.hashCode() + "_" + t.getDest().hashCode() + "\" "); tsmlBuilder.append("id=\"" + this.transMap.get(c) + "\" "); tsmlBuilder.append("source=\"state" + source.hashCode() + "\" "); tsmlBuilder.append("target=\"state" + t.getDest().hashCode() + "\" >"); tsmlBuilder.append("<name><text>"); tsmlBuilder.append(this.transMap.get(c)); tsmlBuilder.append("</text></name>"); tsmlBuilder.append("</transition>"); tsmlBuilder.append('\n'); } } } tsmlBuilder.append("</tsml>"); return tsmlBuilder.toString(); } }
2,743
34.179487
126
java
Janus
Janus-master/src/minerful/automaton/encdec/WeightedAutomatonFactory.java
package minerful.automaton.encdec; import java.util.Iterator; import java.util.NavigableMap; import dk.brics.automaton.Automaton; import minerful.automaton.concept.weight.WeightedAutomaton; import minerful.automaton.concept.weight.WeightedAutomatonStats; import minerful.automaton.concept.weight.WeightedState; import minerful.automaton.concept.weight.WeightedTransition; import minerful.automaton.utils.AutomatonUtils; import minerful.concept.AbstractTaskClass; import minerful.logparser.LogParser; import minerful.logparser.LogTraceParser; import minerful.utils.MessagePrinter; public class WeightedAutomatonFactory { private static MessagePrinter logger = MessagePrinter.getInstance(WeightedAutomatonFactory.class); private NavigableMap<Character, AbstractTaskClass> translationMap; public static class IllegalTransitionException extends IllegalStateException { private static final long serialVersionUID = -562295596335012451L; // public static final String MESSAGE_TEMPLATE = new String("%1$s is not allowed after %2$s"); public final String history; public final Character illegalEvent; public IllegalTransitionException(String history, Character illegalEvent) { this.history = history; this.illegalEvent = illegalEvent; } } public WeightedAutomatonFactory(NavigableMap<Character, AbstractTaskClass> navigableMap) { this.translationMap = navigableMap; } public WeightedAutomaton augmentByReplay(Automaton automaton, LogParser logParser, boolean skimIt) { return this.augmentByReplay(automaton, logParser, skimIt, true); } public WeightedAutomaton augmentByReplay(Automaton automaton, LogParser logParser, boolean skimIt, boolean ignoreIfNotCompliant) { if (automaton == null || automaton.isEmpty()) return null; WeightedAutomaton weightedAutomaton = new WeightedAutomaton(automaton, translationMap); WeightedState initState = (WeightedState) weightedAutomaton.getInitialState(), currentState = null, nextState = null; WeightedState faultPitState = new WeightedState(); faultPitState.setIllegal(true); StringBuilder soFar = new StringBuilder(); String trace = null; boolean illegalEventReached = false; int i = 0; Character auxEvtIdentifier = null; LogTraceParser auXTraPar = null; Iterator<LogTraceParser> traceParsersIterator = logParser.traceIterator(); while (traceParsersIterator.hasNext()) { auXTraPar = traceParsersIterator.next(); auXTraPar.init(); trace = auXTraPar.encodeTrace(); if (AutomatonUtils.accepts(automaton, trace)) { nextState = initState; nextState.increaseWeight(); // This is the initial state: at every start of a trace, a +1 is added to the visit counter logger.trace("Replaying legal trace #{0}/{1}: {2}", i++, logParser.length(), trace); boolean illegalTransitionRequested = false; while(!auXTraPar.isParsingOver() && !illegalTransitionRequested) { auxEvtIdentifier = auXTraPar.parseSubsequentAndEncode(); currentState = nextState; nextState = currentState.stepAndIncreaseTransitionWeight(auxEvtIdentifier); if (nextState == null) { illegalTransitionRequested = true; } else { nextState.increaseWeight(); } } if (illegalTransitionRequested) { logger.error("Last read: " + auxEvtIdentifier + " (" + translationMap.get(auxEvtIdentifier) + ")"); logger.error("Full trace: " + trace); } } else if (!ignoreIfNotCompliant) { soFar = new StringBuilder(); illegalEventReached = false; nextState = initState; nextState.increaseNonConformityWeight(); // This is the initial state: at every start of a trace, a +1 is added to the visit counter logger.trace("Replaying trace #" + (i++) + "/" + logParser.length()); while(!auXTraPar.isParsingOver() && !illegalEventReached) { auxEvtIdentifier = auXTraPar.parseSubsequentAndEncode(); currentState = nextState; nextState = currentState.stepAndIncreaseTransitionsNonConformityWeight(auxEvtIdentifier); if (nextState != null) { nextState.increaseNonConformityWeight(); } else { illegalEventReached = true; // New illegal transition WeightedTransition illegalTransition = new WeightedTransition(auxEvtIdentifier, faultPitState, this.translationMap.get(auxEvtIdentifier).getName()); illegalTransition.setIllegal(true); // Connect the transition to the current state currentState.addTransition(illegalTransition); // Increase the non-conformity weight faultPitState.increaseNonConformityWeight(); illegalTransition.increaseNonConformityWeight(); } // TODO Record somewhere and somewhat the illegal trace + the state where it took place the last legal action! soFar.append(this.translationMap.get(auxEvtIdentifier)); soFar.append(", "); } logger.trace("Legal trunk of replayed trace: " + soFar.substring(0, soFar.length() - 2)); } } WeightedAutomatonStats wAutSta = new WeightedAutomatonStats(weightedAutomaton); wAutSta.augmentWeightedAutomatonWithQuantiles(skimIt); if (!ignoreIfNotCompliant) { wAutSta.augmentWeightedAutomatonWithIllegalityQuantiles(); } return weightedAutomaton; } }
5,240
37.822222
154
java
Janus
Janus-master/src/minerful/automaton/utils/AutomatonUtils.java
package minerful.automaton.utils; import java.util.ArrayList; import java.util.Collection; import minerful.io.encdec.TaskCharEncoderDecoder; import dk.brics.automaton.Automaton; import dk.brics.automaton.RegExp; import dk.brics.automaton.State; import dk.brics.automaton.Transition; public class AutomatonUtils { public static final boolean accepts(Automaton automaton, String string) { State state = automaton.getInitialState(); for (char step : string.toCharArray()) { state = state.step(step); if (state == null) return false; } return state.isAccept(); } public static String createRegExpLimitingRunLength (int minLen, int maxLen) { assert minLen >= 0; assert maxLen >= minLen; StringBuilder sBuil = new StringBuilder(); if (minLen > 0 || maxLen > 0) { sBuil.append(".{"); sBuil.append(minLen > 0 ? minLen : 0); sBuil.append(","); sBuil.append(maxLen > 0 ? maxLen : ""); sBuil.append("}"); } return sBuil.toString(); } public static String createRegExpLimitingTheAlphabet( Collection<Character> alphabet) { return createRegExpLimitingTheAlphabet(alphabet, false); } public static String createRegExpLimitingTheAlphabet( Collection<Character> alphabet, boolean withWildcard) { if (alphabet.size() < 1) return ""; // limiting the alphabet String regexpLimitingTheAlphabet = ""; for (Character c : alphabet) { regexpLimitingTheAlphabet += c; } if (withWildcard) regexpLimitingTheAlphabet += TaskCharEncoderDecoder.WILDCARD_CHAR; return "[" + regexpLimitingTheAlphabet + "]*"; } public static Automaton limitRunLength(Automaton automaton, int minLen, int maxLen) { RegExp regExpLimitingRunLength = new RegExp(createRegExpLimitingRunLength(minLen, maxLen)); return automaton.intersection(regExpLimitingRunLength.toAutomaton()); } public static ArrayList<Character> getAllPossibleSteps(State state) { Collection<Transition> transitions = state.getTransitions(); ArrayList<Character> enabledTransitions = new ArrayList<Character>(); for (Transition transition : transitions) { for (char c = transition.getMin(); c <= transition.getMax(); c++) { enabledTransitions.add(c); } } return enabledTransitions; } }
2,267
29.648649
93
java
Janus
Janus-master/src/minerful/checking/ConstraintsFitnessEvaluator.java
package minerful.checking; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.TreeMap; import java.util.TreeSet; import minerful.automaton.concept.relevance.VacuityAwareWildcardAutomaton; import minerful.checking.relevance.dao.ConstraintFitnessEvaluation; import minerful.checking.relevance.dao.ConstraintsFitnessEvaluationsMap; import minerful.checking.relevance.dao.TraceEvaluation; import minerful.checking.relevance.walkers.RelevanceAutomatonMultiWalker; import minerful.checking.relevance.walkers.RelevanceAutomatonWalker; import minerful.concept.TaskChar; import minerful.concept.TaskCharArchive; import minerful.concept.TaskCharSet; import minerful.concept.constraint.Constraint; import minerful.index.comparator.allinone.TemplateAndParametersBasedComparator; import minerful.index.comparator.allinone.TemplateBasedComparator; import minerful.io.encdec.TaskCharEncoderDecoder; import minerful.logparser.LogParser; import minerful.logparser.LogTraceParser; import minerful.params.SystemCmdParameters.DebugLevel; import minerful.utils.MessagePrinter; /** * Return the relevant constraints out of the log. * @author Claudio Di Ciccio */ public class ConstraintsFitnessEvaluator { private static MessagePrinter logger = MessagePrinter.getInstance(ConstraintsFitnessEvaluator.class); public static final Double DEFAULT_FITNESS_THRESHOLD = (Double)0.5; public static final Double NO_FITNESS_THRESHOLD = (Double)0.0; protected RelevanceAutomatonMultiWalker[] texasMultiRangers; protected TaskCharEncoderDecoder taChaEncoDeco; protected TaskCharArchive tChArchive; protected Map<Constraint, VacuityAwareWildcardAutomaton> vacuAwAutos; protected List<Constraint> checkedConstraints; /** * Constructor of this class. Notice that the * {@link TaskChar TaskChar} * elements in the given process model are re-encoded according to the encoding of the event log. * Notice that it does so as a side effect on the original constraints passed in input and on the * {@link TaskChar TaskChar} elements themselves. * @param taChaEncoDeco An encoder/decoder for tasks of constraints * @param constraints Constraints to be evaluated */ public ConstraintsFitnessEvaluator(TaskCharEncoderDecoder taChaEncoDeco, Constraint... constraints) { this.init(taChaEncoDeco, constraints); } /** * Constructor of this class. * @param constraints Constraints to be evaluated */ public ConstraintsFitnessEvaluator(Constraint... constraints) { this.init(new TaskCharEncoderDecoder(), constraints); } protected void init(TaskCharEncoderDecoder taChaEncoDeco, Constraint... constraints) { Arrays.sort(constraints, new TemplateAndParametersBasedComparator()); this.checkedConstraints = new ArrayList<Constraint>(Arrays.asList(constraints)); this.taChaEncoDeco = taChaEncoDeco; this.taChaEncoDeco.mergeWithConstraintsAndUpdateTheirParameters(constraints); Collection<Constraint> templates = identifyTemplates(this.checkedConstraints); this.initStructures(taChaEncoDeco, null, templates); this.setupAutomataWalkers(templates, constraints); } /** * Constructor of this class. * @param taChaEncoDeco An encoder/decoder for tasks of constraints. * @param tCharArchive An archive of all tasks to be checked against the given templates. * @param parametricConstraints Constraints for which permutations of tasks from <code>tCharArchive</code> will be used as actual parameters for the templates in <code>parametricConstraints</code>. */ public ConstraintsFitnessEvaluator(TaskCharEncoderDecoder taChaEncoDeco, TaskCharArchive tCharArchive, Collection<Constraint> parametricConstraints) { MessagePrinter.configureLogging(DebugLevel.all); this.checkedConstraints = new ArrayList<Constraint>(); Collection<Constraint> templates = identifyTemplates(parametricConstraints); long from = 0, to = 0; logger.debug("Preparing the data structures..."); from = System.currentTimeMillis(); initStructures(taChaEncoDeco, tCharArchive, templates); int numOfGeneratedConstraints = setupAutomataWalkersByTaskPermutations(templates); to = System.currentTimeMillis(); logger.debug( String.format("Automata walkers prepared (for %d constraints). Time in msec: %d.", numOfGeneratedConstraints, (to - from))); } protected Collection<Constraint> identifyTemplates(Collection<Constraint> parametricConstraints) { // In case we have, e.g., Response(a,b) and Response(c,d), they are instances of the same template, so we do not want duplicates Collection<Constraint> templates = null; if (parametricConstraints.size() > 1) { templates = new TreeSet<Constraint>(new TemplateBasedComparator()); templates.addAll(parametricConstraints); } else { templates = parametricConstraints; } return templates; } protected void initStructures(TaskCharEncoderDecoder taChaEncoDeco, TaskCharArchive tCharArchive, Collection<Constraint> templates) { this.taChaEncoDeco = taChaEncoDeco; this.tChArchive = tCharArchive; this.vacuAwAutos = new TreeMap<Constraint,VacuityAwareWildcardAutomaton>(new TemplateBasedComparator()); int numOfGeneratedAutomata = setupCheckAutomata(templates); logger.debug(String.format("Automata prepared (%d).)", numOfGeneratedAutomata)); this.texasMultiRangers = new RelevanceAutomatonMultiWalker[templates.size()]; } protected void setupAutomataWalkers(Collection<Constraint> templates, Constraint[] constraints) { Map<Constraint, List<List<Character>>> parametersPerTemplate = new TreeMap<Constraint, List<List<Character>>>(new TemplateBasedComparator()); List<Character> charParameters = null; for (Constraint constraint : constraints) { if (constraint.isBranched()) { // FIXME Relevance check to be added for branched Declare throw new UnsupportedOperationException("Branched Declare not yet considered"); } charParameters = new ArrayList<Character>(); for (TaskCharSet param : constraint.getParameters()) { charParameters.addAll(param.getListOfIdentifiers()); } if (!parametersPerTemplate.containsKey(constraint)) { parametersPerTemplate.put(constraint, new ArrayList<List<Character>>()); } parametersPerTemplate.get(constraint).add(charParameters); } int templateIndex = 0; //System.out.println("MERDACCIA taChaEncoDeco.getTranslationMap() + " + taChaEncoDeco.getTranslationMap()); for (Constraint template : templates) { //System.out.println("MERDACCIA parametersPerTemplate.get(template) " + parametersPerTemplate.get(template)); //System.out.println("MERDACCIA template " + template); texasMultiRangers[templateIndex++] = new RelevanceAutomatonMultiWalker( template.type, vacuAwAutos.get(template), taChaEncoDeco.getTranslationMap(), parametersPerTemplate.get(template)); } } protected int setupAutomataWalkersByTaskPermutations(Collection<Constraint> templates) { int numOfGeneratedConstraints = 0, templateIndex = 0, paramsIndex = 0; List<TaskChar> constraintParams = null; TaskChar[] nuConstraintParams = null; Constraint nuConstraint = null; for (Constraint template : templates) { constraintParams = new ArrayList<TaskChar>(); for(TaskCharSet tChSet : template.getParameters()) { // FIXME Relevance check to be added for branched Declare constraintParams.addAll(tChSet.getTaskCharsList()); } texasMultiRangers[templateIndex] = new RelevanceAutomatonMultiWalker( template.type,vacuAwAutos.get(template), taChaEncoDeco.getTranslationMap()); for (RelevanceAutomatonWalker walker : texasMultiRangers[templateIndex].getWalkers()) { paramsIndex = 0; nuConstraintParams = new TaskChar[constraintParams.size()]; for (TaskChar param : constraintParams){ nuConstraintParams[paramsIndex++] = tChArchive.getTaskChar(walker.decode(param.identifier)); } nuConstraint = template.copy(nuConstraintParams); numOfGeneratedConstraints++; this.checkedConstraints.add(nuConstraint); } templateIndex++; } logger.debug(numOfGeneratedConstraints + " automata walkers set up."); return numOfGeneratedConstraints; } protected int setupCheckAutomata(Collection<Constraint> templates) { int automatonIndex = 0; for (Constraint paraCon : templates) { if (paraCon.isBranched()) { // FIXME Relevance check to be added for branched Declare throw new UnsupportedOperationException("Branched Declare not yet considered"); } vacuAwAutos.put(paraCon, paraCon.getCheckAutomaton()); automatonIndex++; } return automatonIndex; } public ConstraintsFitnessEvaluationsMap runOnLog(LogParser loPar) { return runOnLog(loPar, null); } /** * Evaluates relevance of constraints on the event log passed to the constructor. * @param logParser Parser of the event log to replay */ public ConstraintsFitnessEvaluationsMap runOnLog(LogParser logParser, Double fitnessThreshold) { logger.debug("Running on the log"); long from = 0, to = 0; Iterator<LogTraceParser> logParIter = logParser.traceIterator(); int constraintIndex = 0; LogTraceParser loTraParse = null; Constraint constraintUnderAnalysis = null; ArrayList<RelevanceAutomatonWalker> walkersToRemove = new ArrayList<RelevanceAutomatonWalker>(); ConstraintFitnessEvaluation eval = null; ConstraintsFitnessEvaluationsMap logEvalsMap = new ConstraintsFitnessEvaluationsMap(checkedConstraints); int traceCount = 0, barCount = 0, traceNum = 0; boolean traceIsFitting = true; MessagePrinter.printOut("Parsing log: "); from = System.currentTimeMillis(); // For every trace while (logParIter.hasNext()) { constraintIndex = 0; traceNum++; loTraParse = logParIter.next(); // We assume the trace fits, by default traceIsFitting = true; // For parametric automata associated to constraint templates for (RelevanceAutomatonMultiWalker texasMultiRanger : texasMultiRangers) { loTraParse.init(); // Run the cursors on the parametric automata texasMultiRanger.run(loTraParse); // For every run for (RelevanceAutomatonWalker walker : texasMultiRanger.getWalkers()) { // Get the corresponding checked constraint constraintUnderAnalysis = this.checkedConstraints.get(constraintIndex); // Retrieve the results of the verification of the trace by replay eval = logEvalsMap.increment(constraintUnderAnalysis, walker.getTraceEvaluation()); // If the trace violates the corresponding constraint if (walker.getTraceEvaluation().equals(TraceEvaluation.VIOLATION)) { logger.trace("Trace " + loTraParse.printStringTrace() + " (num " + traceNum + ", " + loTraParse.getName() + ") violates " + constraintUnderAnalysis); traceIsFitting = traceIsFitting & false; } // This condition is activated only when fitness is used for mining -- to save memory by removing those constraints that for sure will not make it to have a sufficient fitness at this stage already if (fitnessThreshold != null && isFitnessInsufficient(fitnessThreshold, eval, logParser)) { this.checkedConstraints.remove(constraintIndex); walkersToRemove.add(walker); logEvalsMap.remove(constraintUnderAnalysis); } else { constraintIndex++; } } // This loop is run only when fitness is used for mining -- to save memory by removing those constraints that for sure will not make it to have a sufficient fitness at this stage already for (RelevanceAutomatonWalker walkerToRemove : walkersToRemove) { texasMultiRanger.remove(walkerToRemove); } walkersToRemove = new ArrayList<RelevanceAutomatonWalker>(); } barCount = displayAdvancementBars(logParser.length(), barCount); traceCount++; barCount++; if (traceIsFitting) { logEvalsMap.incrementFittingTracesCount(); } else { logEvalsMap.incrementNonFittingTracesCount(); } } this.updateConstraintsFitness(logEvalsMap, logParser); to = System.currentTimeMillis(); MessagePrinter.printlnOut("\nDone."); logger.debug(traceCount + " traces evaluated on the log."); logger.debug("Evaluation done. Time in msec: " + (to - from)); return logEvalsMap; } private static int displayAdvancementBars(int logParserLength, int barCount) { if (barCount > logParserLength / 80) { barCount = 0; MessagePrinter.printOut("|"); } return barCount; } public ConstraintsFitnessEvaluationsMap runOnTrace(LogTraceParser loTraParser) { ConstraintsFitnessEvaluationsMap logEvalsMap = new ConstraintsFitnessEvaluationsMap(checkedConstraints); Constraint constraintUnderAnalysis = null; int constraintIndex = 0; logger.debug(String.format("Checking %s (encoded as %s)...", loTraParser.printStringTrace(), loTraParser.encodeTrace())); for (RelevanceAutomatonMultiWalker texasMultiRanger : texasMultiRangers) { loTraParser.init(); texasMultiRanger.run(loTraParser); for (RelevanceAutomatonWalker walker : texasMultiRanger.getWalkers()) { constraintUnderAnalysis = this.checkedConstraints.get(constraintIndex++); logEvalsMap.increment(constraintUnderAnalysis, walker.getTraceEvaluation()); //System.out.println("MERDACCIA " + constraintUnderAnalysis + constraintUnderAnalysis.getRegularExpression() + " ha dato " + walker.getTraceEvaluation() + " su " + loTraParser.encodeTrace() + ": " + loTraParser.toString()); } } updateConstraintsFitness(logEvalsMap, loTraParser); return logEvalsMap; } private void updateConstraintsFitness(ConstraintsFitnessEvaluationsMap logEvalsMap, LogTraceParser loTraParser) { for (Constraint con : this.checkedConstraints) { con.setFitness(computeFitness(logEvalsMap.evaluationsOnLog.get(con), loTraParser)); } } public void updateConstraintsFitness(ConstraintsFitnessEvaluationsMap logEvalsMap, LogParser logParser) { for (Constraint con : this.checkedConstraints) { con.setFitness(computeFitness(logEvalsMap.evaluationsOnLog.get(con), logParser)); } } public List<Constraint> getCheckedConstraints() { return checkedConstraints; } public static double computeVacuousFitness(ConstraintFitnessEvaluation eval, LogParser logParser) { return (1.0 * eval.numberOfNonViolatingTraces() / logParser.length()); } public static boolean isFitnessInsufficient(Double fitnessThreshold, ConstraintFitnessEvaluation eval, LogParser logParser) { return eval.numberOfViolatingTraces > (logParser.length() - fitnessThreshold * logParser.length()); } public static double computeFitness(ConstraintFitnessEvaluation eval, LogParser logParser) { return (1.0 * eval.numberOfNonViolatingTraces() / logParser.length()); } public static double computeFitness(ConstraintFitnessEvaluation eval, LogTraceParser loTraParser) { return (1.0 * eval.numberOfNonViolatingTraces()); } }
14,992
38.875
223
java
Janus
Janus-master/src/minerful/checking/ProcessSpecificationFitnessEvaluator.java
package minerful.checking; import minerful.checking.relevance.dao.ModelFitnessEvaluation; import minerful.concept.ProcessModel; import minerful.concept.constraint.Constraint; import minerful.io.encdec.TaskCharEncoderDecoder; import minerful.logparser.LogParser; import minerful.logparser.LogTraceParser; import minerful.logparser.XesLogParser; public class ProcessSpecificationFitnessEvaluator extends ConstraintsFitnessEvaluator { private ProcessModel processSpecification; /** * Constructor of this class. * @param taskCharEncoderDecoder Encoder of tasks stemming from the event log * @param constraints Constraints to be evaluated */ public ProcessSpecificationFitnessEvaluator(TaskCharEncoderDecoder taskCharEncoderDecoder, ProcessModel specification) { super(taskCharEncoderDecoder, specification.getAllUnmarkedConstraints().toArray(new Constraint[0])); this.processSpecification = specification; } public ModelFitnessEvaluation evaluateOnLog(LogParser logParser) { return new ModelFitnessEvaluation(super.runOnLog(logParser), processSpecification.getName()); } public ModelFitnessEvaluation evaluateOnLog(XesLogParser logParser, Double fitnessThreshold) { return new ModelFitnessEvaluation(super.runOnLog(logParser, fitnessThreshold), processSpecification.getName()); } public ModelFitnessEvaluation evaluateOnTrace(LogTraceParser loTraParser) { return new ModelFitnessEvaluation(super.runOnTrace(loTraParser), processSpecification.getName()); } public ProcessModel getSpecification() { return this.processSpecification; } }
1,571
39.307692
121
java
Janus
Janus-master/src/minerful/checking/integration/prom/ModelFitnessEvaluatorOpenXesInterface.java
package minerful.checking.integration.prom; import org.deckfour.xes.model.XLog; import org.deckfour.xes.model.XTrace; import minerful.checking.ProcessSpecificationFitnessEvaluator; import minerful.checking.relevance.dao.ModelFitnessEvaluation; import minerful.concept.ProcessModel; import minerful.logparser.LogEventClassifier.ClassificationType; import minerful.logparser.XesLogParser; import minerful.logparser.XesTraceParser; public class ModelFitnessEvaluatorOpenXesInterface { public ProcessSpecificationFitnessEvaluator evaluator; private XesLogParser logParser; public ModelFitnessEvaluatorOpenXesInterface(XLog log, ClassificationType eventClassType, ProcessModel specification) { this.logParser = new XesLogParser(log, eventClassType); this.evaluator = new ProcessSpecificationFitnessEvaluator(logParser.getEventEncoderDecoder(), specification); } public ModelFitnessEvaluation evaluateOnLog() { return this.evaluator.evaluateOnLog(logParser); } public ModelFitnessEvaluation evaluateOnLog(Double fitnessThreshold) { return this.evaluator.evaluateOnLog(logParser, fitnessThreshold); } public ModelFitnessEvaluation evaluateOnTrace(XTrace trace) { XesTraceParser xesTraceParser = new XesTraceParser(trace, this.logParser); return this.evaluator.evaluateOnTrace(xesTraceParser); } }
1,320
37.852941
120
java
Janus
Janus-master/src/minerful/checking/integration/prom/package-info.java
/** * Integration package to interface this package of MINERful with ProM plug-ins. * @author Claudio Di Ciccio ([email protected]) */ package minerful.checking.integration.prom;
184
36
80
java
Janus
Janus-master/src/minerful/checking/params/CheckingCmdParameters.java
package minerful.checking.params; import java.io.File; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.Option; import org.apache.commons.cli.Options; import minerful.params.ParamsManager; public class CheckingCmdParameters extends ParamsManager { /** * Defines how constraints are meant to be considered as satisfied: * either including vacuous satisfactions ({@link #LOOSE LOOSE}) * or not (({@link #STRICT STRICT})). * The default is {@link #DEFAULT_STRICTNESS_POLICY DEFAULT_STRICTNESS_POLICY} * @author Claudio Di Ciccio ([email protected]) */ public static enum StrictnessPolicy { LOOSE, STRICT } public static final String STRICTNESS_POLICY_PARAM_NAME = "chkS"; public static final String SAVE_AS_CSV_PARAM_NAME = "chkOut"; public static final StrictnessPolicy DEFAULT_STRICTNESS_POLICY = StrictnessPolicy.LOOSE; /** Policy according to which constraints are considered as satisfied or not (see {@link StrictnessPolicy StrictnessPolicy}. The default value is {@link #DEFAULT_STRICTNESS_POLICY DEFAULT_STRICTNESS_POLICY}. */ public StrictnessPolicy strictnessPolicy; /** File in which the checking output is printed in a CSV format. Keep it equal to <code>null</code> for avoiding such print-out. */ public File fileToSaveResultsAsCSV; public CheckingCmdParameters() { super(); this.strictnessPolicy = DEFAULT_STRICTNESS_POLICY; this.fileToSaveResultsAsCSV = null; } public CheckingCmdParameters(Options options, String[] args) { this(); // parse the command line arguments this.parseAndSetup(options, args); } public CheckingCmdParameters(String[] args) { this(); // parse the command line arguments this.parseAndSetup(new Options(), args); } @Override protected void setup(CommandLine line) { this.strictnessPolicy = StrictnessPolicy.valueOf( line.getOptionValue( STRICTNESS_POLICY_PARAM_NAME, this.strictnessPolicy.toString() ) ); this.fileToSaveResultsAsCSV = openOutputFile(line, SAVE_AS_CSV_PARAM_NAME); } @Override public Options addParseableOptions(Options options) { Options myOptions = listParseableOptions(); for (Object myOpt: myOptions.getOptions()) options.addOption((Option)myOpt); return options; } @Override public Options listParseableOptions() { return parseableOptions(); } @SuppressWarnings("static-access") public static Options parseableOptions() { Options options = new Options(); options.addOption( Option.builder(STRICTNESS_POLICY_PARAM_NAME) .hasArg().argName("type") .longOpt("checking-strictness") .desc("level of strictness of the checking analysis over constraints. It can be one of the following: " + printValues(StrictnessPolicy.values()) + printDefault(fromEnumValueToString(DEFAULT_STRICTNESS_POLICY))) .type(String.class) .build() // .create(STRICTNESS_POLICY_PARAM_NAME) ); options.addOption( Option.builder(SAVE_AS_CSV_PARAM_NAME) .hasArg().argName("path") .longOpt("save-check-as-csv") .desc("print results in CSV format into the specified file") .type(String.class) .build() // .create(SAVE_AS_CSV_PARAM_NAME) ); return options; } }
3,374
32.75
211
java
Janus
Janus-master/src/minerful/checking/relevance/dao/ConstraintFitnessEvaluation.java
package minerful.checking.relevance.dao; public class ConstraintFitnessEvaluation { public static final String CSV_HEADER = "FullSatisfactions;VacuousSatisfactions;Violations"; public int numberOfFullySatisfyingTraces = 0; public int numberOfVacuouslySatisfyingTraces = 0; public int numberOfViolatingTraces = 0; public void increment(TraceEvaluation eval) { switch (eval) { case SATISFACTION: this.numberOfFullySatisfyingTraces++; break; case VACUOUS_SATISFACTION: case NONE: this.numberOfVacuouslySatisfyingTraces++; break; case VIOLATION: this.numberOfViolatingTraces++; break; default: break; } } public int numberOfViolatingOrVacuouslySatisfyingTraces() { return this.numberOfVacuouslySatisfyingTraces + this.numberOfViolatingTraces; } public int numberOfNonViolatingTraces() { return this.numberOfVacuouslySatisfyingTraces + this.numberOfFullySatisfyingTraces; } public double numberOfFullySatisfyingTraces() { return numberOfFullySatisfyingTraces; } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("LogEvaluation [numberOfFullySatisfyingTraces="); builder.append(numberOfFullySatisfyingTraces); builder.append(", numberOfVacuouslySatisfyingTraces="); builder.append(numberOfVacuouslySatisfyingTraces); builder.append(", numberOfViolatingTraces="); builder.append(numberOfViolatingTraces); builder.append("]"); return builder.toString(); } public String printCSV() { return numberOfFullySatisfyingTraces + ";" + numberOfVacuouslySatisfyingTraces + ";" + numberOfViolatingTraces; } }
1,626
29.12963
113
java
Janus
Janus-master/src/minerful/checking/relevance/dao/ConstraintsFitnessEvaluationsMap.java
package minerful.checking.relevance.dao; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.TreeSet; import minerful.concept.constraint.Constraint; public class ConstraintsFitnessEvaluationsMap { public static final String CSV_PRE_HEADER = "Template;Constraint;Fitness;"; public Map<Constraint, ConstraintFitnessEvaluation> evaluationsOnLog; private int fittingTracesCount = 0; private int nonFittingTracesCount = 0; public ConstraintsFitnessEvaluationsMap(List<Constraint> checkedConstraints) { this.evaluationsOnLog = new HashMap<Constraint, ConstraintFitnessEvaluation>(checkedConstraints.size(), (float)1.0); for (Constraint chkCns : checkedConstraints) { this.evaluationsOnLog.put(chkCns, new ConstraintFitnessEvaluation()); } } public int getFittingTracesCount() { return fittingTracesCount; } public int getNonFittingTracesCount() { return nonFittingTracesCount; } public ConstraintFitnessEvaluation increment(Constraint constraintUnderAnalysis, TraceEvaluation traceEvaluation) { ConstraintFitnessEvaluation eval = this.evaluationsOnLog.get(constraintUnderAnalysis); eval.increment(traceEvaluation); return eval; } public ConstraintFitnessEvaluation remove(Constraint constraintUnderAnalysis) { return this.evaluationsOnLog.remove(constraintUnderAnalysis); } public int incrementFittingTracesCount() { fittingTracesCount++; return this.getFittingTracesCount(); } public int incrementNonFittingTracesCount() { nonFittingTracesCount++; return this.getNonFittingTracesCount(); } public String printCSV() { StringBuilder sBuil = new StringBuilder(); sBuil.append(ConstraintsFitnessEvaluationsMap.CSV_PRE_HEADER); sBuil.append(ConstraintFitnessEvaluation.CSV_HEADER); sBuil.append("\n"); TreeSet<Constraint> constraints = new TreeSet<Constraint>(evaluationsOnLog.keySet()); for (Constraint con : constraints) { sBuil.append(con.getTemplateName()); sBuil.append(';'); sBuil.append(con); sBuil.append(';'); sBuil.append(con.getFitness()); sBuil.append(';'); sBuil.append(this.evaluationsOnLog.get(con).printCSV()); sBuil.append('\n'); } return sBuil.toString(); } }
2,223
28.263158
118
java
Janus
Janus-master/src/minerful/checking/relevance/dao/ModelFitnessEvaluation.java
package minerful.checking.relevance.dao; import minerful.concept.constraint.Constraint; import minerful.utils.MessagePrinter; public class ModelFitnessEvaluation { public static final String CSV_POST_HEADER = ";Avg-fitness;Trace-fit-ratio"; public final ConstraintsFitnessEvaluationsMap evaloMap; public final String name; public ModelFitnessEvaluation(ConstraintsFitnessEvaluationsMap evaloMap, String name) { this.evaloMap = evaloMap; this.name = name; } public Double avgFitness() { Double avgFitness = 0.0; int denominator = 0; for (Constraint cns : evaloMap.evaluationsOnLog.keySet()) { avgFitness += cns.getFitness(); denominator++; } return avgFitness / denominator; } public Double traceFitRatio() { int denominator = evaloMap.getFittingTracesCount() + evaloMap.getNonFittingTracesCount(); return evaloMap.getFittingTracesCount() * 1.0 / denominator; } public boolean isFullyFitting() { return avgFitness() >= 1.0; } public String printCSV() { String csv = this.evaloMap.printCSV(); String appendedAvgFitness = ";" + MessagePrinter.formatFloatNumForCSV(avgFitness()) + ";" + MessagePrinter.formatFloatNumForCSV(traceFitRatio()); csv = csv.replace("\n", appendedAvgFitness + "\n"); csv = csv.replace(ConstraintFitnessEvaluation.CSV_HEADER+appendedAvgFitness, ConstraintFitnessEvaluation.CSV_HEADER + CSV_POST_HEADER); return csv; } }
1,404
30.931818
147
java
Janus
Janus-master/src/minerful/checking/relevance/dao/TraceEvaluation.java
package minerful.checking.relevance.dao; public enum TraceEvaluation { NONE, VIOLATION, VACUOUS_SATISFACTION, SATISFACTION }
129
15.25
40
java
Janus
Janus-master/src/minerful/checking/relevance/dao/package-info.java
/** * Data Access Objects for the results of a relevance checking of the event log against a declarative process specification. * @author Claudio Di Ciccio ([email protected]) */ package minerful.checking.relevance.dao;
225
44.2
124
java
Janus
Janus-master/src/minerful/checking/relevance/walkers/RelevanceAutomatonMultiWalker.java
package minerful.checking.relevance.walkers; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import org.paukov.combinatorics.Factory; import org.paukov.combinatorics.Generator; import org.paukov.combinatorics.ICombinatoricsVector; import minerful.automaton.concept.relevance.VacuityAwareWildcardAutomaton; import minerful.concept.AbstractTaskClass; import minerful.logparser.LogParser; import minerful.logparser.LogTraceParser; /** * This class serves as a machine to walk on automata that abstract from the single specific event class. * The trick is, the automaton is parametric to the specific character that labels the action. * Multiple cursors ("walkers") point at the current state as if the underyling automaton was not parametric. * @author Claudio Di Ciccio ([email protected]) */ public class RelevanceAutomatonMultiWalker { private final String name; private VacuityAwareWildcardAutomaton vacuAwaWildAuto; private Map<Character, AbstractTaskClass> logTranslationMap; private List<RelevanceAutomatonWalker> walkers; private void init(VacuityAwareWildcardAutomaton vAwaWildAuto, Map<Character, AbstractTaskClass> logTranslationMap) { this.vacuAwaWildAuto = vAwaWildAuto; this.logTranslationMap = logTranslationMap; } public RelevanceAutomatonMultiWalker( String name, VacuityAwareWildcardAutomaton vAwaWildAuto, Map<Character, AbstractTaskClass> logTranslationMap) { this.name = name; init(vAwaWildAuto, logTranslationMap); this.walkers = setUpAllWalkersByPermutationsOfTasks(); } public RelevanceAutomatonMultiWalker( String name, VacuityAwareWildcardAutomaton vAwaWildAuto, Map<Character, AbstractTaskClass> logTranslationMap, List<List<Character>> charParametersList) { this.name = name; init(vAwaWildAuto, logTranslationMap); //System.out.println("Lurido merdonazzo charParametersList " + charParametersList); this.walkers = setupAllWalkers(charParametersList); } private List<RelevanceAutomatonWalker> setupAllWalkers(List<List<Character>> charParametersList) { List<Character> automAlphabetNoWildcard = charParametersList.get(0); ArrayList<RelevanceAutomatonWalker> walkers = new ArrayList<RelevanceAutomatonWalker>(charParametersList.size()); for (List<Character> charParameters : charParametersList) { //System.out.println("Lurido merdo charParameters " + charParameters); //System.out.println("Lurido merdo alphabetWithoutWildcard " + automAlphabetNoWildcard); walkers.add( new RelevanceAutomatonWalker( this.name + "/" + charParameters, charParameters, automAlphabetNoWildcard, logTranslationMap, vacuAwaWildAuto.getInitialWildState())); } //System.out.println("Lurido merdone logTranslationMap: " + logTranslationMap); return walkers; } private List<RelevanceAutomatonWalker> setUpAllWalkersByPermutationsOfTasks() { List<Character> alphabetWithoutWildcard = new ArrayList<Character>(vacuAwaWildAuto.getAlphabetWithoutWildcard()); int k = alphabetWithoutWildcard.size(); Set<Character> taskIdentifiersInLog = this.logTranslationMap.keySet(); if (taskIdentifiersInLog.size() < k) { throw new IllegalArgumentException("Not enough tasks in the log to instanciate the constraint"); } ICombinatoricsVector<Character> initialVector = Factory.createVector(taskIdentifiersInLog.toArray(new Character[k+1])); Iterator<ICombinatoricsVector<Character>> combosPermIterator = null; Generator<Character> comboGen = Factory.createSimpleCombinationGenerator(initialVector, k), combosPermGen = null; ArrayList<RelevanceAutomatonWalker> walkers = new ArrayList<RelevanceAutomatonWalker>(); List<Character> vectorOfChars = null; int i = 0; for (ICombinatoricsVector<Character> simpleCombo : comboGen) { combosPermGen = Factory.createPermutationGenerator(simpleCombo); combosPermIterator = combosPermGen.iterator(); while (combosPermIterator.hasNext()) { vectorOfChars = combosPermIterator.next().getVector(); walkers.add(i++, new RelevanceAutomatonWalker( this.name + "/" + vectorOfChars, vectorOfChars, alphabetWithoutWildcard, logTranslationMap, vacuAwaWildAuto.getInitialWildState())); } } return walkers; } public void run(LogParser log) { Iterator<LogTraceParser> logPar = log.traceIterator(); while (logPar.hasNext()) { this.run(logPar.next()); } } public void run(LogTraceParser traceParser) { this.reset(); AbstractTaskClass tasCla = null; while (!traceParser.isParsingOver()) { tasCla = traceParser.parseSubsequent().getEvent().getTaskClass(); for (RelevanceAutomatonWalker walker : walkers) { walker.step(tasCla); } } } public List<RelevanceAutomatonWalker> getWalkers() { return walkers; } public void reset() { for (RelevanceAutomatonWalker walker : this.walkers) { walker.reset(); } } public int getNumberOfWalkers() { return this.walkers.size(); } public boolean remove(RelevanceAutomatonWalker walker) { return this.walkers.remove(walker); } }
5,124
33.628378
117
java
Janus
Janus-master/src/minerful/checking/relevance/walkers/RelevanceAutomatonWalker.java
package minerful.checking.relevance.walkers; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.TreeMap; import minerful.automaton.concept.relevance.ActivationStatusWildcardAwareState; import minerful.automaton.concept.relevance.RelevanceAwareTransition; import minerful.automaton.concept.relevance.TransitionRelevance; import minerful.checking.relevance.dao.TraceEvaluation; import minerful.concept.AbstractTaskClass; import minerful.logparser.LogTraceParser; import minerful.utils.MessagePrinter; public class RelevanceAutomatonWalker { public static MessagePrinter logger = MessagePrinter.getInstance(RelevanceAutomatonWalker.class); private Map<AbstractTaskClass, Character> alteredInverseLogTranslationMap; private Map<Character, AbstractTaskClass> alteredLogTranslationMap; private ActivationStatusWildcardAwareState currentStateInTheWalk; private ActivationStatusWildcardAwareState initialState; private TraceEvaluation traceEvaluation; private boolean relevantTransitionTraversed; private boolean noNeedToCheckFurther; public final String name; public RelevanceAutomatonWalker(String name, List<Character> actualCharParams, List<Character> formalCharParams, Map<Character, AbstractTaskClass> logTranslationMap, ActivationStatusWildcardAwareState initialState) { this.name = name; this.alteredInverseLogTranslationMap = new HashMap<AbstractTaskClass, Character>(actualCharParams.size(), (float)1.0); Character[] formalCharParamsArray = formalCharParams.toArray(new Character[formalCharParams.size()]), actualCharParamsArray = actualCharParams.toArray(new Character[formalCharParams.size()]); for (int i = 0; i < actualCharParamsArray.length; i++) { //System.out.println("Merdaccia infame: actualCharParamsArray[i]: " + actualCharParamsArray[i] + " formalCharParamsArray[i] " + formalCharParamsArray[i]); alteredInverseLogTranslationMap.put(logTranslationMap.get(actualCharParamsArray[i]), new Character(formalCharParamsArray[i])); } this.initialState = initialState; this.setUpAlteredLogTranslationMap(); reset(); //System.out.println("Lurida merdazza alteredInverseLogTranslationMap " + alteredInverseLogTranslationMap); //System.out.println("Lurida merdazza formalCharParamsArray " + Arrays.toString(formalCharParamsArray)); //System.out.println("Lurida merdazza actualCharParamsArray " + Arrays.toString(actualCharParamsArray)); } public void reset() { this.traceEvaluation = TraceEvaluation.NONE; this.currentStateInTheWalk = this.initialState; this.relevantTransitionTraversed = false; this.noNeedToCheckFurther = false; } public Map<AbstractTaskClass, Character> getAlteredInverseLogTranslationMap() { return alteredInverseLogTranslationMap; } private void setUpAlteredLogTranslationMap() { alteredLogTranslationMap = new TreeMap<Character, AbstractTaskClass>(); for (AbstractTaskClass cls : alteredInverseLogTranslationMap.keySet()) { alteredLogTranslationMap.put(codify(cls), cls); } } public void run(LogTraceParser traceParser) { this.reset(); AbstractTaskClass tasCla = null; while (!traceParser.isParsingOver()) { tasCla = traceParser.parseSubsequent().getEvent().getTaskClass(); this.step(tasCla); } } public TraceEvaluation step(AbstractTaskClass taskClass) { if (!noNeedToCheckFurther) { ActivationStatusWildcardAwareState necState = null; RelevanceAwareTransition relAwaTrans = null; Character arg0 = null; //System.out.println("Lurido merdone: req. tasClass = " + taskClass + " alteredInverseLogTranslationMap.containsKey(taskClass) = " + alteredInverseLogTranslationMap.containsKey(taskClass) + (alteredInverseLogTranslationMap.containsKey(taskClass) ? " " + codify(taskClass): " e sto cazzo")); if (alteredInverseLogTranslationMap.containsKey(taskClass)) { arg0 = codify(taskClass); relAwaTrans = this.currentStateInTheWalk.getTransition(arg0); necState = ((ActivationStatusWildcardAwareState) this.currentStateInTheWalk.step(arg0)); // logger.info(taskClass + " => " + codify(taskClass) + " is involved in this constraint (" + this.name + ") and leads to " + (necState!=null?necState.getStatus():null)); } else { // logger.info(taskClass + " is not involved in this constraint (" + this.name + ")"); relAwaTrans = this.currentStateInTheWalk.getWildTransition(); necState = (ActivationStatusWildcardAwareState) this.currentStateInTheWalk.stepWild(); } if (necState != null) { this.currentStateInTheWalk = necState; this.evaluateTrace(relAwaTrans); } else { this.noNeedToCheckFurther = true; this.traceEvaluation = TraceEvaluation.VIOLATION; } } return this.traceEvaluation; } public Character codify(AbstractTaskClass taskClass) { return this.alteredInverseLogTranslationMap.get(taskClass); } public AbstractTaskClass decode(Character identifier) { return this.alteredLogTranslationMap.get(identifier); } private void evaluateTrace(RelevanceAwareTransition relAwaTrans) { this.relevantTransitionTraversed = this.relevantTransitionTraversed || relAwaTrans.getRelevance().equals(TransitionRelevance.RELEVANT); switch (this.currentStateInTheWalk.getStatus()) { case SAT_PERM: noNeedToCheckFurther = true; if (relevantTransitionTraversed) { this.traceEvaluation = TraceEvaluation.SATISFACTION; } else { this.traceEvaluation = TraceEvaluation.VACUOUS_SATISFACTION; } break; case SAT_TEMP: if (relevantTransitionTraversed) { this.traceEvaluation = TraceEvaluation.SATISFACTION; } else { this.traceEvaluation = TraceEvaluation.VACUOUS_SATISFACTION; } break; case VIO_TEMP: this.traceEvaluation = TraceEvaluation.VIOLATION; break; case VIO_PERM: noNeedToCheckFurther = true; this.traceEvaluation = TraceEvaluation.VIOLATION; break; } } public boolean isRelevantTransitionTraversed() { return relevantTransitionTraversed; } public ActivationStatusWildcardAwareState getCurrentStateInTheWalk() { return currentStateInTheWalk; } public ActivationStatusWildcardAwareState getInitialState() { return initialState; } public TraceEvaluation getTraceEvaluation() { return traceEvaluation; } }
6,263
37.666667
290
java
Janus
Janus-master/src/minerful/concept/AbstractTaskClass.java
package minerful.concept; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; @XmlAccessorType(XmlAccessType.FIELD) public class AbstractTaskClass implements TaskClass { public String className; protected AbstractTaskClass() {} @Override public String getName() { return this.className; } @Override public void setName(String className) { this.className = className; } @Override public int compareTo(TaskClass o) { return this.toString().compareTo(o.toString()); } @Override public String toString() { return getName(); } @Override public boolean equals(Object o) { if (o instanceof TaskClass) { return this.getName().equals(((TaskClass)o).getName()); } else { return false; } } }
775
17.926829
58
java
Janus
Janus-master/src/minerful/concept/Event.java
package minerful.concept; public class Event { public final AbstractTaskClass taskClass; public Event(AbstractTaskClass taskClass) { this.taskClass = taskClass; } public AbstractTaskClass getTaskClass() { return taskClass; } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("Event [taskClass="); builder.append(taskClass); builder.append("]"); return builder.toString(); } }
449
19.454545
46
java
Janus
Janus-master/src/minerful/concept/ProcessModel.java
package minerful.concept; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.NavigableMap; import java.util.Observable; import java.util.Observer; import java.util.Set; import java.util.SortedSet; import java.util.TreeMap; import java.util.TreeSet; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlTransient; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; import minerful.automaton.AutomatonFactory; import minerful.automaton.SubAutomaton; import minerful.automaton.utils.AutomatonUtils; import minerful.concept.constraint.Constraint; import minerful.concept.constraint.ConstraintsBag; import minerful.concept.constraint.MetaConstraintUtils; import minerful.concept.constraint.xmlenc.ConstraintsBagAdapter; import minerful.index.LinearConstraintsIndexFactory; import org.apache.log4j.Logger; import dk.brics.automaton.Automaton; @XmlRootElement(name = "processModel") @XmlAccessorType(XmlAccessType.FIELD) public class ProcessModel extends Observable implements Observer { @XmlTransient private static Logger logger = Logger.getLogger(ProcessModel.class.getCanonicalName()); @XmlTransient public static String DEFAULT_NAME = "Discovered model"; @XmlElement(name = "declarative-model", required = true) @XmlJavaTypeAdapter(type = TreeSet.class, value = ConstraintsBagAdapter.class) public ConstraintsBag bag; @XmlAttribute private String name; @XmlElement private TaskCharArchive taskCharArchive; @XmlTransient public static final String MINERFUL_XMLNS = "https://github.com/cdc08x/MINERful/"; protected ProcessModel() { } public ProcessModel(ConstraintsBag bag) { this(new TaskCharArchive(bag.getTaskChars()), bag, DEFAULT_NAME); } public ProcessModel(ConstraintsBag bag, String name) { this(new TaskCharArchive(bag.getTaskChars()), bag, name); } public ProcessModel(TaskCharArchive taskCharArchive, ConstraintsBag bag) { this(taskCharArchive, bag, DEFAULT_NAME); } public ProcessModel(TaskCharArchive taskCharArchive, ConstraintsBag bag, String name) { this.taskCharArchive = taskCharArchive; this.bag = bag; this.name = name; this.bag.addObserver(this); } public String getName() { return this.name; } public void setName(String name) { this.name = name; } public Set<TaskChar> getProcessAlphabet() { return this.bag.getTaskChars(); } public Automaton buildAutomaton() { return buildAutomatonByBondHeuristic(); } public Automaton buildAlphabetAcceptingAutomaton() { return AutomatonFactory.fromRegularExpressions(new ArrayList<String>(0), this.taskCharArchive.getIdentifiersAlphabet()); } public Collection<SubAutomaton> buildSubAutomata() { return buildSubAutomata(AutomatonFactory.NO_LIMITS_IN_ACTIONS_FOR_SUBAUTOMATA); } public Collection<SubAutomaton> buildSubAutomata(int maxActions) { NavigableMap<Character, Collection<String>> regExpsMap = new TreeMap<Character, Collection<String>>(); Collection<String> regExps = null; Collection<Constraint> cns = null; String alphabetLimitingRegularExpression = AutomatonUtils.createRegExpLimitingTheAlphabet(this.taskCharArchive.getIdentifiersAlphabet()); for (TaskChar tChr : this.bag.getTaskChars()) { cns = this.bag.getConstraintsOf(tChr); regExps = new ArrayList<String>(cns.size()); for (Constraint con : cns) { if (!con.isMarkedForExclusion()) { regExps.add(con.getRegularExpression()); } } regExps.add(alphabetLimitingRegularExpression); regExpsMap.put(tChr.identifier, regExps); } if (maxActions > AutomatonFactory.NO_LIMITS_IN_ACTIONS_FOR_SUBAUTOMATA) return AutomatonFactory.subAutomataFromRegularExpressionsInMultiThreading(regExpsMap, this.taskCharArchive.getIdentifiersAlphabet(), maxActions); else return AutomatonFactory.subAutomataFromRegularExpressionsInMultiThreading(regExpsMap, this.taskCharArchive.getIdentifiersAlphabet()); } /* * This turned out to be the best heuristic for computing the automaton! */ protected Automaton buildAutomatonByBondHeuristic() { Collection<String> regularExpressions = null; Collection<Constraint> constraints = LinearConstraintsIndexFactory.getAllUnmarkedConstraintsSortedByBoundsSupportFamilyConfidenceInterestFactorHierarchyLevel(this.bag); regularExpressions = new ArrayList<String>(constraints.size()); for (Constraint con : constraints) { regularExpressions.add(con.getRegularExpression()); } return AutomatonFactory.fromRegularExpressions(regularExpressions, this.taskCharArchive.getIdentifiersAlphabet()); } public TaskCharArchive getTaskCharArchive() { return this.taskCharArchive; } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("ProcessModel [bag="); builder.append(bag); builder.append(", name="); builder.append(name); builder.append(", taskCharArchive="); builder.append(taskCharArchive); builder.append("]"); return builder.toString(); } public static ProcessModel generateNonEvaluatedBinaryModel(TaskCharArchive taskCharArchive) { ProcessModel proMod = null; Iterator<TaskChar> actIter = taskCharArchive.getTaskChars().iterator(), auxActIter = null, extraActIter = null; TaskChar auxActiParam1 = null, auxActiParam2 = null, extraActiParam3 = null; Collection<Constraint> conSet = new TreeSet<Constraint>(), auxConSet = null, extraConSet = null; Collection<TaskChar> activitiesLeftToCombine = new TreeSet<TaskChar>(taskCharArchive.getTaskChars()); while (actIter.hasNext()) { auxActiParam1 = actIter.next(); auxConSet = MetaConstraintUtils.getAllDiscoverableExistenceConstraints(auxActiParam1); auxConSet = MetaConstraintUtils.createHierarchicalLinks(auxConSet); conSet.addAll(auxConSet); activitiesLeftToCombine.remove(auxActiParam1); auxActIter = activitiesLeftToCombine.iterator(); auxConSet = new TreeSet<Constraint>(); while (auxActIter.hasNext()) { auxActiParam2 = auxActIter.next(); auxConSet = MetaConstraintUtils.getAllDiscoverableRelationConstraints(auxActiParam1, auxActiParam2); auxConSet.addAll(MetaConstraintUtils.getAllDiscoverableRelationConstraints(auxActiParam2, auxActiParam1)); auxConSet = MetaConstraintUtils.createHierarchicalLinks(auxConSet); conSet.addAll(auxConSet); // Alessio: injection for non-DECLARE constraint with 3 variables /* extraActIter = activitiesLeftToCombine.iterator(); while(extraActIter.hasNext()){ extraActiParam3 = extraActIter.next(); extraConSet = MetaConstraintUtils.getAllDiscoverableExtraConstraints(auxActiParam1, auxActiParam2, extraActiParam3); extraConSet.addAll(MetaConstraintUtils.getAllDiscoverableExtraConstraints(auxActiParam1, extraActiParam3, auxActiParam2)); // extraConSet = MetaConstraintUtils.createHierarchicalLinks(extraConSet); conSet.addAll(extraConSet); } */ } } ConstraintsBag bag = new ConstraintsBag(taskCharArchive.getTaskChars(), conSet); proMod = new ProcessModel(taskCharArchive, bag); return proMod; } public SortedSet<Constraint> getAllConstraints() { return LinearConstraintsIndexFactory.getAllConstraints(bag); } public SortedSet<Constraint> getAllUnmarkedConstraints() { return LinearConstraintsIndexFactory.getAllUnmarkedConstraints(bag); } public int howManyConstraints() { return bag.howManyConstraints(); } public int howManyUnmarkedConstraints() { return bag.howManyUnmarkedConstraints(); } public int howManyTasks() { return this.taskCharArchive.size(); } public Set<TaskChar> getTasks() { return this.taskCharArchive.getTaskChars(); } public void resetMarks() { for (TaskChar tCh : this.bag.getTaskChars()) { for (Constraint con : this.bag.getConstraintsOf(tCh)) { con.resetMarks(); } } } @Override public void update(Observable o, Object arg) { this.setChanged(); this.notifyObservers(arg); this.clearChanged(); } /** * Unite the input process models into a new one containing the union of the alphabets and constraints of them. * * @param model1 * @param model2 * @return */ public static ProcessModel union(ProcessModel model1, ProcessModel model2) { Set<TaskChar> taskChars = model1.getTasks(); Set<TaskChar> taskChars2 = model2.getTasks(); taskChars.addAll(taskChars2); Collection<Constraint> constraints = model1.getAllConstraints(); Collection<Constraint> constraints2 = model2.getAllConstraints(); constraints.addAll(constraints2); ConstraintsBag newBag = new ConstraintsBag(taskChars, constraints); return new ProcessModel(newBag, "Union"); } /** * Return a new process model containing all the constraints not in common between the input models. * The alphabets are united anyway. * * @param model1 * @param model2 * @return */ public static ProcessModel difference(ProcessModel model1, ProcessModel model2) { Set<TaskChar> taskChars = model1.getTasks(); taskChars.addAll(model2.getTasks()); Collection<Constraint> constraints1 = model1.getAllConstraints(); Collection<Constraint> constraints2 = model2.getAllConstraints(); constraints1.removeAll(model2.getAllConstraints()); constraints2.removeAll(model1.getAllConstraints()); constraints1.addAll(constraints2); ConstraintsBag newBag = new ConstraintsBag(taskChars, constraints1); return new ProcessModel(newBag, "Union"); } }
10,736
35.151515
176
java
Janus
Janus-master/src/minerful/concept/TaskChar.java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package minerful.concept; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; import minerful.concept.xmlenc.CharAdapter; import minerful.logparser.CharTaskClass; import minerful.concept.xmlenc.TaskClassAdapter; /** * Class associating tasks to single-character identifiers and event classes as per the event log. * @author Claudio Di Ciccio ([email protected]) * */ @XmlRootElement(name="task") @XmlAccessorType(XmlAccessType.FIELD) public class TaskChar implements Comparable<TaskChar> { /** * Character identifier for this event class. */ @XmlAttribute // This is due to the ridiculous bug of the Metro implementation of JAXB. // Without an Adapter, you would have an Integer encoding the Character as a result. @XmlJavaTypeAdapter(value=CharAdapter.class) public Character identifier; /** * Event class mapper (can be depending on the XES event log, a pure string, etc.). */ @XmlAttribute @XmlJavaTypeAdapter(value=TaskClassAdapter.class) public final AbstractTaskClass taskClass; protected TaskChar() { this.identifier = null; this.taskClass = null; } public TaskChar(Character identifier) { this(identifier, new CharTaskClass(identifier)); } public TaskChar(Character identifier, AbstractTaskClass taskClass) { this.identifier = identifier; this.taskClass = taskClass; } /** * Returns {@link #getName() this.getName()}. */ @Override public String toString() { return this.getName(); } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final TaskChar other = (TaskChar) obj; if ((this.identifier == null) ? (other.identifier != null) : !this.identifier.equals(other.identifier)) { return false; } return true; } @Override public int hashCode() { return this.taskClass.hashCode(); } @Override public int compareTo(TaskChar t) { return this.identifier.compareTo(t.identifier); } /** * Returns the string version (say, human-readable name) of {@link #taskClass this.taskClass}. */ public String getName() { return this.taskClass.toString(); } }
2,603
26.410526
113
java
Janus
Janus-master/src/minerful/concept/TaskCharArchive.java
package minerful.concept; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.TreeMap; import java.util.TreeSet; import javax.xml.bind.Unmarshaller; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlElementWrapper; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlTransient; import minerful.io.encdec.TaskCharEncoderDecoder; import minerful.logparser.StringTaskClass; @XmlRootElement(name="processAlphabet") @XmlAccessorType(XmlAccessType.FIELD) /** * An archive of the tasks of a process. For each task, an identifying character is given, as per {@link minerful.concept.TaskChar TaskChar} * @author Claudio Di Ciccio */ public class TaskCharArchive { @XmlElementWrapper(name="tasks") @XmlElement(name="task") private TreeSet<TaskChar> taskChars; @XmlTransient private HashMap<Character, TaskChar> taskCharsMapById; @XmlTransient private HashMap<AbstractTaskClass, TaskChar> taskCharsMapByClass; public TaskCharArchive() { this.taskChars = new TreeSet<TaskChar>(); this.taskCharsMapById = null; this.taskCharsMapByClass = null; } public void computeIndices() { TreeMap<Character, TaskChar> fastTmpMapById = new TreeMap<Character, TaskChar>(); TreeMap<AbstractTaskClass, TaskChar> fastTmpMapByName = new TreeMap<AbstractTaskClass, TaskChar>(); for (TaskChar tChr : this.taskChars) { fastTmpMapById.put(tChr.identifier, tChr); fastTmpMapByName.put(tChr.taskClass, tChr); } this.taskCharsMapById = new HashMap<Character, TaskChar>(fastTmpMapById); this.taskCharsMapByClass = new HashMap<AbstractTaskClass, TaskChar>(fastTmpMapByName); } public TaskCharArchive(Character[] alphabet) { Collection<TaskChar> taskCharsCollection = toTaskChars(Arrays.asList(alphabet)); this.taskChars = new TreeSet<TaskChar>(taskCharsCollection); this.computeIndices(); } public TaskCharArchive(TaskChar... taskChars) { this.taskChars = new TreeSet<TaskChar>(Arrays.asList(taskChars)); this.computeIndices(); } public TaskCharArchive(Collection<TaskChar> taskChars) { this.taskChars = new TreeSet<TaskChar>(taskChars); this.computeIndices(); } public TaskCharArchive(Map<Character, AbstractTaskClass> roughTaskChars) { this.taskChars = new TreeSet<TaskChar>(); TreeMap<Character, TaskChar> fastTmpMapById = new TreeMap<Character, TaskChar>(); TreeMap<AbstractTaskClass, TaskChar> fastTmpMapByName = new TreeMap<AbstractTaskClass, TaskChar>(); for (Character chr : roughTaskChars.keySet()) { TaskChar nuTaskChar = new TaskChar(chr, roughTaskChars.get(chr)); this.taskChars.add(nuTaskChar); fastTmpMapById.put(chr, nuTaskChar); fastTmpMapByName.put(roughTaskChars.get(chr), nuTaskChar); } this.taskCharsMapById = new HashMap<Character, TaskChar>(fastTmpMapById); this.taskCharsMapByClass = new HashMap<AbstractTaskClass, TaskChar>(fastTmpMapByName); } public boolean isTranslationMapDefined() { return (this.taskCharsMapById != null); } /** * Returns a shallow copy of the translation map by identifier. * @return A shallow copy of the translation map by identifier */ public Map<Character, TaskChar> getTranslationMapById() { return new HashMap<Character, TaskChar>(this.taskCharsMapById); } /** * Returns a shallow copy of the translation map by task name. * @return A shallow copy of the translation map by task name */ public Map<AbstractTaskClass, TaskChar> getTranslationMapByName() { return new HashMap<AbstractTaskClass, TaskChar>(this.taskCharsMapByClass); } public TreeSet<TaskChar> getTaskChars() { return this.taskChars; } /** * Returns a shallow copy of the set of TaskChar's. * @return A shallow copy of the set of TaskChar's */ public TreeSet<TaskChar> getCopyOfTaskChars() { return new TreeSet<TaskChar>(this.taskChars); } public Collection<TaskChar> getTaskCharsIdentifiedByCharacters(Collection<Character> fromCharacters) { Collection<TaskChar> taskChars = new ArrayList<TaskChar>(fromCharacters.size()); for (Character chr : fromCharacters) { taskChars.add(this.getTaskChar(chr)); } return taskChars; } public Collection<TaskChar> getTaskCharsIdentifiedByTaskClasses(Collection<AbstractTaskClass> fromtTaskClasses) { Collection<TaskChar> taskChars = new ArrayList<TaskChar>(fromtTaskClasses.size()); for (AbstractTaskClass chr : fromtTaskClasses) { taskChars.add(this.getTaskChar(chr)); } return taskChars; } public Collection<TaskChar> getTaskCharsIdentifiedByStrings(Collection<String> taskNames) { Collection<TaskChar> taskChars = new ArrayList<TaskChar>(taskNames.size()); for (String taskName : taskNames) { taskChars.add(this.getTaskChar(taskName)); } return taskChars; } public void removeAllByClass(Collection<AbstractTaskClass> taskClassesToExclude) { Collection<TaskChar> taskCharsToExclude = new ArrayList<TaskChar>(taskClassesToExclude.size()); for (AbstractTaskClass taskClassToExclude : taskClassesToExclude) { taskCharsToExclude.add(this.getTaskChar(taskClassToExclude)); } this.taskChars.removeAll(taskCharsToExclude); this.computeIndices(); } public static Collection<TaskChar> toTaskChars(Collection<Character> characters) { Collection<TaskChar> taskChars = new ArrayList<TaskChar>(characters.size()); for (Character chr: characters) { taskChars.add(new TaskChar(chr)); } return taskChars; } public static Collection<Character> toCharacters(Collection<TaskChar> taskChars) { Collection<Character> characters = new ArrayList<Character>(taskChars.size()); for (TaskChar tChr: taskChars) { characters.add(tChr.identifier); } return characters; } public Character[] getAlphabetArray() { return this.getIdentifiersAlphabet().toArray(new Character[this.size()]); } public Collection<Character> getIdentifiersAlphabet() { return this.taskCharsMapById.keySet(); } public TaskChar getTaskChar(Character chr) { return this.taskCharsMapById.get(chr); } public TaskChar getTaskChar(String name) { return this.taskCharsMapByClass.get(new StringTaskClass(name)); } public TaskChar getTaskChar(AbstractTaskClass taskClass) { return this.taskCharsMapByClass.get(taskClass); } public boolean containsTaskCharByEvent(Event event) { return this.taskCharsMapByClass.containsKey(event.taskClass); } public TaskChar getTaskCharByEvent(Event event) { return this.taskCharsMapByClass.get(event.taskClass); } @Override public String toString() { return "TaskCharArchive [taskChars=" + taskChars + ", taskCharsMap=" + taskCharsMapById + "]"; } public int size() { return this.taskChars.size(); } public Collection<Set<TaskChar>> splitTaskCharsIntoSubsets(Integer parts) { if (parts <= 0) throw new IllegalArgumentException("The log cannot be split in " + parts + " parts. Only positive integer values are allowed"); int taskCharsPerSubset = this.taskChars.size() / parts; Collection<Set<TaskChar>> taskCharsSubsets = new ArrayList<Set<TaskChar>>(parts); Set<TaskChar> taskCharsSubset = null; Iterator<TaskChar> taChaIte = this.taskChars.iterator(); for (int j = 0; j < parts; j++) { taskCharsSubset = new TreeSet<TaskChar>(); for (int i = 0; i < taskCharsPerSubset; i++) { taskCharsSubset.add(taChaIte.next()); } taskCharsSubsets.add(taskCharsSubset); } // Flush remaining taskChars while (taChaIte.hasNext()) { taskCharsSubset.add(taChaIte.next()); } return taskCharsSubsets; } private void afterUnmarshal(Unmarshaller unmarshaller, Object parent) { this.computeIndices(); } }
7,824
32.440171
140
java
Janus
Janus-master/src/minerful/concept/TaskCharFactory.java
package minerful.concept; import minerful.io.encdec.TaskCharEncoderDecoder; import minerful.logparser.StringTaskClass; public class TaskCharFactory { private TaskCharEncoderDecoder taChaEncDec; public TaskCharFactory() { this(new TaskCharEncoderDecoder()); } public TaskCharEncoderDecoder getTaChaEncDec() { return this.taChaEncDec; } public TaskCharFactory(TaskCharEncoderDecoder taskCharEncoderDecoder) { this.taChaEncDec = taskCharEncoderDecoder; } public TaskChar makeTaskChar(AbstractTaskClass taskClass) { Character tChId = this.taChaEncDec.encode(taskClass); return new TaskChar(tChId,taskClass); } public TaskChar makeTaskChar(String taskName) { return this.makeTaskChar(new StringTaskClass(taskName)); } }
747
24.793103
72
java
Janus
Janus-master/src/minerful/concept/TaskCharSet.java
package minerful.concept; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlID; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; import minerful.concept.xmlenc.CharAdapter; import org.apache.commons.lang3.StringUtils; @XmlRootElement @XmlAccessorType(XmlAccessType.FIELD) public class TaskCharSet implements Comparable<TaskCharSet> { @XmlElement(name = "task") private final TaskChar[] taskChars; @XmlAttribute @XmlID private String joinedStringOfIdentifiers; @XmlAttribute @XmlJavaTypeAdapter(value = CharAdapter.class) private Collection<Character> listOfIdentifiers; public static final TaskCharSet VOID_TASK_CHAR_SET = new TaskCharSet(new TaskChar[0]); private TaskCharSet() { this.taskChars = null; this.joinedStringOfIdentifiers = null; this.listOfIdentifiers = null; } public TaskCharSet(TaskChar... taskChars) { if (taskChars.length < 1) { this.taskChars = taskChars; this.listOfIdentifiers = new ArrayList<Character>(0); this.joinedStringOfIdentifiers = ""; } else { this.taskChars = taskChars; this.refreshListOfIdentifiers(); } } public TaskCharSet(SortedSet<TaskChar> taskChars) { this(taskChars.toArray(new TaskChar[taskChars.size()])); } public TaskCharSet(List<TaskChar> taskChars) { this(new TreeSet<TaskChar>(taskChars)); } public TaskCharSet(Collection<TaskChar> taskChars) { this(new TreeSet<TaskChar>(taskChars)); } public TaskCharSet(TaskChar taskChar) { this.taskChars = new TaskChar[]{taskChar}; this.listOfIdentifiers = this.toListOfIdentifiers(); this.joinedStringOfIdentifiers = taskChar.identifier.toString(); } // For cloning purposes private TaskCharSet(TaskChar[] taskChars, String joinedStringOfIdentifiers, Collection<Character> listOfIdentifiers) { this.taskChars = taskChars; this.joinedStringOfIdentifiers = joinedStringOfIdentifiers; this.listOfIdentifiers = listOfIdentifiers; } public void refreshListOfIdentifiers() { this.listOfIdentifiers = this.toListOfIdentifiers(); this.joinedStringOfIdentifiers = this.toJoinedStringOfIdentifiers(); } public TaskChar[] getTaskCharsArray() { return taskChars; } public List<TaskChar> getTaskCharsList() { return Arrays.asList(taskChars); } public TaskChar getTaskChar(int number) { if (number < 0 || number > this.taskChars.length - 1) throw new IllegalArgumentException("TaskChar #" + number + "not found in set"); return this.taskChars[number]; } @Override public String toString() { if (this.size() == 1) { return this.taskChars[0].toString(); } StringBuilder builder = new StringBuilder(); builder.append("{"); builder.append(StringUtils.join(taskChars, ", ")); builder.append("}"); return builder.toString(); } @Override public int compareTo(TaskCharSet o) { return joinedStringOfIdentifiers.compareTo(o.joinedStringOfIdentifiers); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result; if (taskChars != null) { for (TaskChar t : taskChars) { result += t.hashCode(); } } return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; TaskCharSet other = (TaskCharSet) obj; if (taskChars == null) { if (other.taskChars != null) return false; } else { return this.toJoinedStringOfIdentifiers().equals(other.toJoinedStringOfIdentifiers()); } return true; } private String toJoinedStringOfIdentifiers() { StringBuilder sB = new StringBuilder(); for (TaskChar taskChar : this.getTaskCharsArray()) { sB.append(taskChar.identifier); } return sB.toString(); } private Collection<Character> toListOfIdentifiers() { ArrayList<Character> listOfIdentifiers = new ArrayList<Character>(this.getTaskCharsArray().length); for (TaskChar taskChar : this.getTaskCharsArray()) { listOfIdentifiers.add(taskChar.identifier); } return listOfIdentifiers; } public Collection<Character> getListOfIdentifiers() { return this.listOfIdentifiers; } public String getJoinedStringOfIdentifiers() { return joinedStringOfIdentifiers; } public int size() { return this.taskChars.length; } public boolean isSingleton() { return this.size() < 2; } public TaskCharSet removeLast() { TaskChar[] arrayOfTaskChars = Arrays.copyOf(this.taskChars, this.size() - 1); return new TaskCharSet(arrayOfTaskChars); } public TaskChar getLastTaskChar() { return this.taskChars[this.taskChars.length - 1]; } public TaskCharSet removeFirst() { TaskChar[] arrayOfTaskChars = new TaskChar[0]; if (this.taskChars.length > 1) arrayOfTaskChars = Arrays.copyOfRange(this.taskChars, 1, this.size() - 1); return new TaskCharSet(arrayOfTaskChars); } public TaskChar getFirstTaskChar() { return this.taskChars[0]; } public Set<TaskChar> getSetOfTaskChars() { return new TreeSet<TaskChar>(Arrays.asList(this.taskChars)); } public TaskCharSet pushAtLast(TaskChar taskChar) { TaskChar[] arrayOfTaskChars = Arrays.copyOf(this.taskChars, this.size() + 1); arrayOfTaskChars[this.taskChars.length] = taskChar; return new TaskCharSet(arrayOfTaskChars); } public String toPatternString() { return this.toPatternString(true); } public String toPatternString(boolean positive) { if (this.size() == 1) return this.taskChars[0].identifier.toString(); if (positive) { return StringUtils.join(this.joinedStringOfIdentifiers, ""); } else { // FIXME Cannot work, really return "^" + this.joinedStringOfIdentifiers; } } public boolean isPrefixOf(TaskCharSet other) { return StringUtils.startsWith(other.getJoinedStringOfIdentifiers(), this.getJoinedStringOfIdentifiers()); } public boolean strictlyIncludes(TaskCharSet other) { return this.listOfIdentifiers.size() > other.listOfIdentifiers.size() && this.listOfIdentifiers.containsAll(other.listOfIdentifiers); } }
7,338
30.229787
113
java
Janus
Janus-master/src/minerful/concept/TaskCharSetFactory.java
package minerful.concept; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; import org.paukov.combinatorics.Factory; import org.paukov.combinatorics.Generator; import org.paukov.combinatorics.ICombinatoricsVector; public class TaskCharSetFactory { private final TaskCharArchive taskCharArchive; public TaskCharSetFactory(TaskCharArchive taskCharArchive) { this.taskCharArchive = taskCharArchive; } public TaskCharSet createSetFromRawCharacters(Collection<Character> characters) { return new TaskCharSet(this.taskCharArchive.getTaskCharsIdentifiedByCharacters(characters)); } public TaskCharSet createSetFromTaskClasses(Collection<AbstractTaskClass> taskClasses) { return new TaskCharSet(this.taskCharArchive.getTaskCharsIdentifiedByTaskClasses(taskClasses)); } public TaskCharSet createSetFromTaskStrings(Collection<String> taskNames) { return new TaskCharSet(this.taskCharArchive.getTaskCharsIdentifiedByStrings(taskNames)); } public TaskCharSet[] createSetsFromTaskStringsCollection( List<Set<String>> parameters) { TaskCharSet[] sets = new TaskCharSet[parameters.size()]; int i = 0; for (Set<String> paramSet: parameters) { sets[i++] = this.createSetFromTaskStrings(paramSet); } return sets; } public TaskCharSet createSet(TaskCharSet existing, Character plus) { return existing.pushAtLast(this.taskCharArchive.getTaskChar(plus)); } public TaskCharSet createSet(TaskCharSet existing, TaskChar plus) { return existing.pushAtLast(plus); } public SortedSet<TaskCharSet> createAllMultiCharCombosExcludingOneTaskChar(TaskChar excluded, int maxSizeOfCombos) { Collection<TaskChar> alphabet = taskCharArchive.getTaskChars(); Collection<TaskChar> otherChrs = new ArrayList<TaskChar>(alphabet); if(excluded != null) otherChrs.remove(excluded); SortedSet<TaskCharSet> combos = new TreeSet<TaskCharSet>(); if (otherChrs.size() < 1) { return combos; } // Create the initial vector ICombinatoricsVector<TaskChar> initialVector = Factory.createVector(otherChrs); Generator<TaskChar> gen = null; Iterator<ICombinatoricsVector<TaskChar>> combosIterator = null; if (maxSizeOfCombos < otherChrs.size()) { for (int k=1; k <= maxSizeOfCombos; k++) { // Create a simple combination generator to generate k-combinations of the initial vector gen = Factory.createSimpleCombinationGenerator(initialVector, k); combosIterator = gen.iterator(); while (combosIterator.hasNext()) { combos.add(new TaskCharSet(combosIterator.next().getVector())); } } } else { Collection<TaskChar> auxComboVector = null; // Create an instance of the subset generator gen = Factory.createSubSetGenerator(initialVector); combosIterator = gen.iterator(); while (combosIterator.hasNext()) { auxComboVector = combosIterator.next().getVector(); if ( auxComboVector.size() > 0 && auxComboVector.size() <= otherChrs.size()) { combos.add(new TaskCharSet(auxComboVector)); } } } return combos; } public SortedSet<TaskCharSet> createAllMultiCharCombos(int maxSizeOfCombos) { return this.createAllMultiCharCombosExcludingOneTaskChar(null, maxSizeOfCombos); } }
3,313
33.520833
117
java
Janus
Janus-master/src/minerful/concept/TaskClass.java
package minerful.concept; public interface TaskClass extends Comparable<TaskClass> { public String getName(); void setName(String className); }
147
20.142857
58
java
Janus
Janus-master/src/minerful/concept/constraint/Constraint.java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package minerful.concept.constraint; import java.util.ArrayList; import java.util.List; import java.util.Observable; import java.util.Observer; import java.util.Set; import java.util.TreeSet; import javax.xml.bind.Unmarshaller; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlElementWrapper; import javax.xml.bind.annotation.XmlIDREF; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlSeeAlso; import javax.xml.bind.annotation.XmlTransient; import minerful.automaton.concept.relevance.VacuityAwareWildcardAutomaton; import minerful.concept.TaskChar; import minerful.concept.TaskCharSet; import minerful.concept.constraint.ConstraintChange.ChangedProperty; import minerful.concept.constraint.ConstraintFamily.ConstraintSubFamily; import minerful.concept.constraint.existence.ExistenceConstraint; import minerful.concept.constraint.relation.RelationConstraint; import minerful.io.encdec.TaskCharEncoderDecoder; import minerful.reactive.automaton.SeparatedAutomaton; @XmlRootElement(name="constraint") @XmlSeeAlso({RelationConstraint.class,ExistenceConstraint.class}) @XmlAccessorType(XmlAccessType.FIELD) public abstract class Constraint extends Observable implements Comparable<Constraint> { @XmlTransient public static final double MIN_SUPPORT = 0; @XmlTransient public static final double MAX_SUPPORT = 1.0; @XmlTransient public static final double DEFAULT_SUPPORT = MAX_SUPPORT; @XmlTransient public static final double MIN_INTEREST_FACTOR = MIN_SUPPORT; @XmlTransient public static final double MAX_INTEREST_FACTOR = MAX_SUPPORT; @XmlTransient public static final double DEFAULT_INTEREST_FACTOR = MIN_INTEREST_FACTOR; @XmlTransient public static final double MIN_CONFIDENCE = MIN_SUPPORT; @XmlTransient public static final double MAX_CONFIDENCE = MAX_SUPPORT; @XmlTransient public static final double DEFAULT_CONFIDENCE = MIN_CONFIDENCE; @XmlTransient public static final double MIN_FITNESS = 0; @XmlTransient public static final double MAX_FITNESS = 1.0; @XmlTransient public static final double DEFAULT_FITNESS = MAX_FITNESS; @XmlTransient public static final double RANGE_FOR_SUPPORT = (MAX_SUPPORT - MIN_SUPPORT); @XmlIDREF protected TaskCharSet base; @XmlElement protected double support; @XmlElement protected double confidence; @XmlElement protected double interestFactor; @XmlElement protected Double fitness; @XmlAttribute protected boolean evaluatedOnLog = false; @XmlTransient public final String type = this.getClass().getCanonicalName().substring(this.getClass().getCanonicalName().lastIndexOf('.') +1); @XmlAttribute protected boolean redundant = false; @XmlAttribute protected boolean conflicting = false; @XmlAttribute protected boolean belowSupportThreshold = false; @XmlAttribute protected boolean belowConfidenceThreshold = false; @XmlAttribute protected boolean belowInterestFactorThreshold = false; @XmlAttribute private boolean belowFitnessThreshold = false; @XmlTransient protected Constraint constraintWhichThisIsBasedUpon; @XmlElementWrapper(name="parameters") @XmlElement(name="parameter") protected List<TaskCharSet> parameters; @XmlTransient protected boolean silentToObservers = true; protected Constraint() { this.parameters = new ArrayList<TaskCharSet>(); } public Constraint(TaskChar param) { this(param, DEFAULT_SUPPORT); } public Constraint(TaskCharSet param) { this(param, DEFAULT_SUPPORT); } public Constraint(TaskChar... params) { this(DEFAULT_SUPPORT, params); } public Constraint(TaskCharSet... params) { this(DEFAULT_SUPPORT, params); } private boolean checkSupport(double support) { if (support < MIN_SUPPORT || support > MAX_SUPPORT) { throw new IllegalArgumentException("Provided support for " + toString() + " out of range: " + support); } return true; } private boolean checkConfidence(double confidence) { if (confidence < MIN_CONFIDENCE || confidence > MAX_CONFIDENCE) { throw new IllegalArgumentException("Provided confidence level for " + toString() + " out of range: " + confidence); } return true; } private boolean checkInterestFactor(double interestFactor) { if (interestFactor < MIN_INTEREST_FACTOR || interestFactor > MAX_INTEREST_FACTOR) { throw new IllegalArgumentException("Provided interest factor for " + toString() + " out of range: " + interestFactor); } return true; } private boolean checkFitness(double fitness) { if (fitness < MIN_FITNESS || fitness > MAX_FITNESS) { throw new IllegalArgumentException("Provided fitness for " + toString() + " out of range: " + fitness); } return true; } public Constraint(TaskChar param, double support) { this(support, param); } public Constraint(double support, TaskChar... params) { this.setSilentToObservers(true); this.base = new TaskCharSet(params[0]); this.parameters = new ArrayList<TaskCharSet>(params.length); for (TaskChar param : params) this.parameters.add(new TaskCharSet(param)); this.setSupport(support); this.setSilentToObservers(false); } public Constraint(TaskCharSet param, double support) { this(support, param); } public Constraint(double support, TaskCharSet... params) { this.setSilentToObservers(true); this.base = params[0]; this.parameters = new ArrayList<TaskCharSet>(params.length); for (TaskCharSet param : params) this.parameters.add(param); this.setSupport(support); this.setSilentToObservers(false); } @Override public String toString() { StringBuilder sBuil = new StringBuilder(); sBuil.append(getTemplateName()); sBuil.append("("); boolean firstParam = true; for (TaskCharSet param : getParameters()) { if (firstParam) { firstParam = false; } else { sBuil.append(", "); } sBuil.append(param); } sBuil.append(")"); return sBuil.toString(); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((base == null) ? 0 : base.hashCode()); result = prime * result + ((type == null) ? 0 : type.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Constraint other = (Constraint) obj; int paramsComparison = this.compareParameters(other.getParameters()); if (paramsComparison != 0) return false; if (base == null) { if (other.base != null) return false; } else if (!base.equals(other.base)) return false; if (type == null) { if (other.type != null) return false; } else if (!type.equals(other.type)) return false; return true; } @Override public int compareTo(Constraint t) { int result = this.compareParameters(t.getParameters()); return result; } protected int compareParameters(List<TaskCharSet> othersParameters) { int result = new Integer(this.parameters.size()).compareTo(othersParameters.size()); if (result == 0) { for (int i = 0; i < this.parameters.size() && result == 0; i++) { result = this.parameters.get(i).compareTo(othersParameters.get(i)); } } return result; } public boolean isRedundant() { return this.redundant; } public boolean isConflicting() { return this.conflicting; } public boolean isBelowSupportThreshold() { return belowSupportThreshold; } public void setBelowSupportThreshold(boolean belowSupportThreshold) { if (belowSupportThreshold != this.belowSupportThreshold) { this.belowSupportThreshold = belowSupportThreshold; this.notifyObservers(ChangedProperty.BELOW_SUPPORT_THRESHOLD, belowSupportThreshold); } } public boolean isBelowConfidenceThreshold() { return belowConfidenceThreshold; } public void setBelowConfidenceThreshold(boolean belowConfidenceThreshold) { if (belowConfidenceThreshold != this.belowConfidenceThreshold) { this.belowConfidenceThreshold = belowConfidenceThreshold; this.notifyObservers(ChangedProperty.BELOW_CONFIDENCE_THRESHOLD, belowConfidenceThreshold); } } public boolean isBelowInterestFactorThreshold() { return belowInterestFactorThreshold; } public void setBelowInterestFactorThreshold(boolean belowInterestFactorThreshold) { if (belowInterestFactorThreshold != this.belowInterestFactorThreshold) { this.belowInterestFactorThreshold = belowInterestFactorThreshold; this.notifyObservers(ChangedProperty.BELOW_INTEREST_FACTOR_THRESHOLD, belowInterestFactorThreshold); } } public boolean isBelowFitnessThreshold() { return belowFitnessThreshold; } public void setBelowFitnessThreshold(boolean belowFitnessThreshold) { if (belowFitnessThreshold != this.belowSupportThreshold) { this.belowFitnessThreshold = belowFitnessThreshold; this.notifyObservers(ChangedProperty.BELOW_FITNESS_THRESHOLD, belowFitnessThreshold); } } public void setRedundant(boolean redundant) { if (this.redundant != redundant) { this.redundant = redundant; this.notifyObservers(ConstraintChange.ChangedProperty.REDUNDANT, redundant); } } public void setConflicting(boolean conflicting) { if (this.conflicting != conflicting) { this.conflicting = conflicting; this.notifyObservers(ConstraintChange.ChangedProperty.CONFLICTING, conflicting); } } public double getSupport() { return support; } public void setSupport(double support) { if (this.support != support) { this.checkSupport(support); this.support = support; this.notifyObservers(ConstraintChange.ChangedProperty.SUPPORT, support); } } public double getConfidence() { return confidence; } public void setConfidence(double confidence) { if (this.confidence != confidence) { this.checkConfidence(confidence); this.confidence = confidence; this.notifyObservers(ConstraintChange.ChangedProperty.CONFIDENCE, confidence); } } public double getInterestFactor() { return interestFactor; } public void setInterestFactor(double interestFactor) { if (this.interestFactor != interestFactor) { this.checkInterestFactor(interestFactor); this.interestFactor = interestFactor; this.notifyObservers(ConstraintChange.ChangedProperty.INTEREST_FACTOR, interestFactor); } } public Double getFitness() { return fitness; } public void setFitness(double fitness) { if (this.fitness == null || this.fitness != fitness) { this.checkFitness(fitness); this.fitness = fitness; this.notifyObservers(ConstraintChange.ChangedProperty.FITNESS, interestFactor); } } public boolean isEvaluatedOnLog() { return evaluatedOnLog; } public void setEvaluatedOnLog(boolean evaluatedOnLog) { if (this.evaluatedOnLog != evaluatedOnLog) { this.evaluatedOnLog = evaluatedOnLog; this.notifyObservers(ConstraintChange.ChangedProperty.EVALUATED_ON_LOG, evaluatedOnLog); } } /** * Returns <code>true</code> if and only if the {@link #support support} of this constraint is equal to or higher than the given threshold. * @param threshold The threshold to which the {@link #support support} of this constraint is compared * @return <code>true</code> if the {@link #support support} of this constraint is equal to or higher than the given threshold, <code>false</code> otherwise. */ public boolean hasSufficientSupport(double threshold) { return this.support >= threshold; } /** * Returns <code>true</code> if and only if the {@link #confidence confidence} of this constraint is equal to or higher than the given threshold. * @param threshold The threshold to which the {@link #confidence confidence} of this constraint is compared * @return <code>true</code> if the {@link #confidence confidence} of this constraint is equal to or higher than the given threshold, <code>false</code> otherwise. */ public boolean hasSufficientConfidence(double threshold) { return this.confidence >= threshold; } /** * Returns <code>true</code> if and only if the {@link #interestFactor interest factor} of this constraint is equal to or higher than the given threshold. * @param threshold The threshold to which the {@link #interestFactor interest factor} of this constraint is compared * @return <code>true</code> if the {@link #interestFactor interestFactor} of this constraint is equal to or higher than the given threshold, <code>false</code> otherwise. */ public boolean hasSufficientInterestFactor(double threshold) { return this.interestFactor >= threshold; } public boolean isAboveThresholds() { return !( this.belowSupportThreshold || this.belowConfidenceThreshold || this.belowInterestFactorThreshold); } public boolean hasReasonableSupport(double threshold) { return ( (threshold == MAX_SUPPORT) ? (support - threshold == 0) : Math.abs(this.getRelativeSupport(threshold)) >= MIN_SUPPORT && Math.abs(this.getRelativeSupport(threshold)) <= MAX_SUPPORT ); } public double getRelativeSupport(double threshold) { if (MAX_SUPPORT - threshold == 0) { if (support - threshold == 0) { return MAX_SUPPORT; } else { return MIN_SUPPORT; } } return ((support - threshold) / (MAX_SUPPORT - threshold)); } /** * Returns the difference between {@link #MAX_SUPPORT MAX_SUPPORT} and the given support. * @param support The support to complement * @return The difference between {@link #MAX_SUPPORT MAX_SUPPORT} and the given support. */ public static double complementSupport(double support) { return MAX_SUPPORT - support; } public int getHierarchyLevel() { return 0; } /** * Returns <code>true</code> if and only if the {@link #support support} of this constraint is equal to {@link #MAX_SUPPORT MAX_SUPPORT}. * @return <code>true</code> if the support of this constraint is equal to {@link #MAX_SUPPORT MAX_SUPPORT}, <code>false</code> otherwise. */ public boolean hasMaximumSupport() { return this.support == MAX_SUPPORT; } /** * Returns <code>true</code> if and only if the {@link #support support} of this constraint is equal to {@link #MIN_SUPPORT MIN_SUPPORT}. * @return <code>true</code> if the support of this constraint is equal to {@link #MIN_SUPPORT MIN_SUPPORT}, <code>false</code> otherwise. */ public boolean hasLeastSupport() { return this.support == MIN_SUPPORT; } public String getTemplateName() { return MetaConstraintUtils.getTemplateName(this); } public TaskCharSet getBase() { return this.base; } public List<TaskCharSet> getParameters() { return parameters; } public void setParameters(List<TaskCharSet> parameters) { this.parameters = parameters; } /** * Returns the regular expression representing the semantics of this constraint. * @return The regular expression representing the semantics of this constraint. * @see Constraint#getRegularExpressionTemplate() getRegularExpressionTemplate() */ public String getRegularExpression() { return String.format(this.getRegularExpressionTemplate(), this.base.toPatternString(true)); } public abstract TaskCharSet getImplied(); public abstract String getRegularExpressionTemplate(); public boolean isBranched() { return (this.getBase() != null && this.getBase().size() > 1) || (this.getImplied() != null && this.getImplied().size() > 1); } public boolean isMoreInformativeThanGeneric() { if (!this.hasConstraintToBaseUpon()) return true; Integer moreReliableThanGeneric = new Double(this.support).compareTo(constraintWhichThisIsBasedUpon.support); if (moreReliableThanGeneric == 0) return constraintWhichThisIsBasedUpon.isMoreInformativeThanGeneric(); return (moreReliableThanGeneric > 0); } public Set<TaskChar> getInvolvedTaskChars() { TreeSet<TaskChar> involvedChars = new TreeSet<TaskChar>(); for (TaskCharSet param : this.parameters) { involvedChars.addAll(param.getSetOfTaskChars()); } return involvedChars; } public Set<Character> getInvolvedTaskCharIdentifiers() { TreeSet<Character> involvedChars = new TreeSet<Character>(); for (TaskCharSet param : this.parameters) { involvedChars.addAll(param.getListOfIdentifiers()); } return involvedChars; } public void setConstraintWhichThisIsBasedUpon(Constraint constraintWhichThisIsBasedUpon) { if (this.constraintWhichThisIsBasedUpon == null) { if (constraintWhichThisIsBasedUpon.getHierarchyLevel() >= this.getHierarchyLevel()) { throw new IllegalArgumentException("Wrong hierarchy provided"); } this.constraintWhichThisIsBasedUpon = constraintWhichThisIsBasedUpon; } } public boolean hasConstraintToBaseUpon() { return this.constraintWhichThisIsBasedUpon != null; } public Constraint getConstraintWhichThisIsBasedUpon() { return constraintWhichThisIsBasedUpon; } public boolean isChildOf(Constraint c) { Constraint baCon = this.suggestConstraintWhichThisShouldBeBasedUpon(); if (baCon == null) { return false; } return c.equals(baCon); } public boolean isDescendantAlongSameBranchOf(Constraint c) { return ( this.isTemplateDescendantAlongSameBranchOf(c) && this.base.equals(c.base) && ( this.getImplied() == null && c.getImplied() == null || this.getImplied().equals(c.getImplied()) ) ); } public boolean isTemplateDescendantAlongSameBranchOf(Constraint c) { return ( this.getFamily() == c.getFamily() && this.getSubFamily() == c.getSubFamily() && this.getHierarchyLevel() > c.getHierarchyLevel() ); } public boolean isDescendantOf(Constraint c) { return this.isChildOf(c) || isDescendantAlongSameBranchOf(c); } public abstract ConstraintFamily getFamily(); public abstract <T extends ConstraintSubFamily> T getSubFamily(); public abstract Constraint suggestConstraintWhichThisShouldBeBasedUpon(); /** * Returns instances of all constraints that would be derived from this one. * By default, it returns the {@link #suggestConstraintWhichThisShouldBeBasedUpon() suggestConstraintWhichThisShouldBeBasedUpon()} * @return */ public Constraint[] suggestImpliedConstraints() { return new Constraint[]{ this.suggestConstraintWhichThisShouldBeBasedUpon() }; } public Constraint createConstraintWhichThisShouldBeBasedUpon() { Constraint cns = suggestConstraintWhichThisShouldBeBasedUpon(); if (cns != null) { cns.support = this.support; cns.confidence = this.confidence; cns.interestFactor = this.interestFactor; } return cns; } public boolean isMarkedForExclusion() { return this.isRedundant() || !this.isAboveThresholds() || this.isConflicting(); } public abstract Constraint copy(TaskChar... taskChars); public abstract Constraint copy(TaskCharSet... taskCharSets); public abstract boolean checkParams(TaskChar... taskChars) throws IllegalArgumentException; public abstract boolean checkParams(TaskCharSet... taskCharSets) throws IllegalArgumentException; public VacuityAwareWildcardAutomaton getCheckAutomaton() { VacuityAwareWildcardAutomaton autom = new VacuityAwareWildcardAutomaton( this.toString(), this.getRegularExpression(), TaskCharEncoderDecoder.getTranslationMap(this.getInvolvedTaskChars())); return autom; } /** * Resets properties * {@link #belowSupportThreshold belowSupportThreshold}, * {@link #belowConfidenceThreshold belowConfidenceThreshold}, * {@link #belowInterestFactorThreshold belowInterestFactorThreshold}, * {@link #conflicting conflicting}, * {@link #redundant redundant} * to their default values. */ public void resetMarks() { this.belowSupportThreshold = false; this.belowConfidenceThreshold = false; this.belowInterestFactorThreshold = false; this.conflicting = false; this.redundant = false; } private void notifyObservers(ChangedProperty type, Object value) { if (!this.isSilentToObservers()) { ConstraintChange coCha = new ConstraintChange(this, type, value); this.setChanged(); this.notifyObservers(coCha); super.clearChanged(); } } @Override public void notifyObservers(Object arg) { // Should you add debug lines, do it here super.notifyObservers(arg); } @Override public synchronized void addObserver(Observer o) { // TODO Auto-generated method stub super.addObserver(o); } public boolean isSilentToObservers() { return silentToObservers; } protected void setSilentToObservers(boolean silentToObservers) { this.silentToObservers = silentToObservers; } protected void afterUnmarshal(Unmarshaller unmarshaller, Object parent) { if (this.getFamily().equals(ConstraintFamily.EXISTENCE)) { this.base = this.getParameters().get(0); } } /** * Constructs and returns the separated automaton for this constraint * @return parametric separated automaton related to the constraint type */ public SeparatedAutomaton buildParametricSeparatedAutomaton(){ /* TODO make it abstract and force the specific classes handle it*/ return null; } }
21,659
32.896714
175
java
Janus
Janus-master/src/minerful/concept/constraint/ConstraintChange.java
package minerful.concept.constraint; public class ConstraintChange { public final Constraint constraint; public final ChangedProperty property; public final Object value; public enum ChangedProperty { SUPPORT, CONFIDENCE, INTEREST_FACTOR, FITNESS, BELOW_SUPPORT_THRESHOLD, BELOW_CONFIDENCE_THRESHOLD, BELOW_INTEREST_FACTOR_THRESHOLD, BELOW_FITNESS_THRESHOLD, REDUNDANT, CONFLICTING, EVALUATED_ON_LOG, } public ConstraintChange(Constraint constraint, ChangedProperty type, Object value) { this.constraint = constraint; this.property = type; this.value = value; } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("ConstraintChange [constraint="); builder.append(constraint); builder.append(", property="); builder.append(property); builder.append(", value="); builder.append(value); builder.append("]"); return builder.toString(); } }
941
22.55
85
java
Janus
Janus-master/src/minerful/concept/constraint/ConstraintFamily.java
package minerful.concept.constraint; public enum ConstraintFamily implements Comparable<ConstraintFamily> { // The natural order implemented by this method is the order in which the constants are declared. EXISTENCE, RELATION; public static interface ConstraintSubFamily { } public static enum RelationConstraintSubFamily implements ConstraintSubFamily { COUPLING, SINGLE_ACTIVATION, NEGATIVE, NONE, } public static enum ExistenceConstraintSubFamily implements ConstraintSubFamily { POSITION, NUMEROSITY, NONE, } public static enum ConstraintImplicationVerse { BOTH, FORWARD, BACKWARD } }
674
22.275862
98
java
Janus
Janus-master/src/minerful/concept/constraint/ConstraintFamilyComparator.java
package minerful.concept.constraint; import java.util.Comparator; public class ConstraintFamilyComparator implements Comparator<ConstraintFamily> { @Override public int compare(ConstraintFamily o1, ConstraintFamily o2) { int result = o1.compareTo(o2); return result; } }
282
19.214286
81
java
Janus
Janus-master/src/minerful/concept/constraint/ConstraintSubFamilyComparator.java
package minerful.concept.constraint; import java.util.Comparator; import minerful.concept.constraint.ConstraintFamily.ConstraintSubFamily; import minerful.concept.constraint.ConstraintFamily.ExistenceConstraintSubFamily; import minerful.concept.constraint.ConstraintFamily.RelationConstraintSubFamily; public class ConstraintSubFamilyComparator implements Comparator<ConstraintSubFamily> { @Override public int compare(ConstraintSubFamily o1, ConstraintSubFamily o2) { if (o1 instanceof RelationConstraintSubFamily && o2 instanceof RelationConstraintSubFamily) return ((RelationConstraintSubFamily)o1).compareTo((RelationConstraintSubFamily)o2); else if (o1 instanceof ExistenceConstraintSubFamily && o2 instanceof ExistenceConstraintSubFamily) return ((ExistenceConstraintSubFamily)o1).compareTo((ExistenceConstraintSubFamily)o2); else throw new IllegalArgumentException( "Uncomparable sub-families provided as arguments: " + o1.getClass() + ", " + o1.getClass()); } }
997
44.363636
100
java
Janus
Janus-master/src/minerful/concept/constraint/ConstraintsBag.java
package minerful.concept.constraint; import java.util.*; import javax.xml.bind.annotation.XmlElementRef; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; import minerful.concept.TaskChar; import minerful.concept.TaskCharSet; import minerful.concept.constraint.xmlenc.ConstraintsBagAdapter; import minerful.reactive.automaton.SeparatedAutomaton; import minerful.reactive.automaton.SeparatedAutomatonOfflineRunner; import minerful.reactive.automaton.SeparatedAutomatonRunner; import org.apache.log4j.Logger; /** * The class managing the set of constraints of a declarative process model. * * @author Claudio Di Ciccio ([email protected]) */ @XmlRootElement @XmlJavaTypeAdapter(ConstraintsBagAdapter.class) //@XmlAccessorType(XmlAccessType.FIELD) public class ConstraintsBag extends Observable implements Cloneable, Observer { // @XmlTransient private static Logger logger = Logger.getLogger(ConstraintsBag.class.getCanonicalName()); @XmlElementRef private Map<TaskChar, TreeSet<Constraint>> bag; // @XmlTransient private Set<TaskChar> taskChars = new TreeSet<TaskChar>(); /** * Map containing the parametric separated auromata related to the constraint of this bag. * The key is the type of the constraint */ private Map<String, SeparatedAutomaton> automataBag; /** * Container of the runners for the specific constraints over the parametric automata */ private List<SeparatedAutomatonRunner> automataRunnersBag; /** * Container of the offline runners for the specific constraints over the parametric automata */ private List<SeparatedAutomatonOfflineRunner> automataOfflineRunnersBag; /** * Map to link separated automata runners to their respective constraint object * TODO embed it directly into constraint/runner object */ private Map<SeparatedAutomatonRunner, Constraint> runnersConstraintsMatching; /** * Map to link separated automata runners to their respective constraint object * TODO embed it directly into constraint/runner object */ private Map<SeparatedAutomatonOfflineRunner, Constraint> offlineRunnersConstraintsMatching; public ConstraintsBag() { this(new TreeSet<TaskChar>()); } public ConstraintsBag(Collection<TaskChar> taskChars) { this.initBag(); this.setAlphabet(taskChars); } public ConstraintsBag(Set<TaskChar> taskChars, Collection<Constraint> constraints) { this.initBag(); this.setAlphabet(taskChars); for (Constraint con : constraints) { this.add(con.base, con); } this.initAutomataBag(taskChars, constraints); } private void initBag() { this.bag = new TreeMap<TaskChar, TreeSet<Constraint>>(); } /** * Initialize the parametric separate automata and the runners related to the constraints of the bag with provided a given alphabet and constraint list */ private void initAutomataBag(Set<TaskChar> taskChars, Collection<Constraint> constraints) { // TODO this function is equal to initAutomataBag(). here the input variables are never used inside this.initAutomataBag(); } /** * Initialize the parametric separate automata and the runners related to the constraints given the current state of the bag */ public void initAutomataBag() { this.automataBag = new HashMap<>(); this.automataRunnersBag = new ArrayList<>(); this.automataOfflineRunnersBag = new ArrayList<>(); this.runnersConstraintsMatching = new HashMap<>(); this.offlineRunnersConstraintsMatching = new HashMap<>(); for (Constraint constr : getAllConstraints()) { // TODO memory issue here SeparatedAutomaton parametricAut = constr.buildParametricSeparatedAutomaton(); SeparatedAutomaton parametricOfflineAut = constr.buildParametricSeparatedAutomaton(); if (parametricAut == null) { /* if it is not possible to construct the automata it is pointless to keep the constraint, otherwise howManyConstraint() returns a number different form the actual constraints that are checked */ this.remove(constr); continue; } if (!automataBag.containsKey(constr.type)) { automataBag.put(constr.type, parametricAut); } /* TODO BEWARE * use constraint.parameters to construct the runners is unsecured: * it is ok for precedence and response but it is not know for other or general constraints. * */ List<Character> specificAlphabet = new ArrayList<>(); for (TaskCharSet cs : constr.parameters) { for (TaskChar c : cs.getTaskCharsArray()) { specificAlphabet.add(c.identifier); } } SeparatedAutomatonRunner runner = new SeparatedAutomatonRunner(parametricAut, specificAlphabet); automataRunnersBag.add(runner); runnersConstraintsMatching.put(runner, constr); SeparatedAutomatonOfflineRunner offlineRunner = new SeparatedAutomatonOfflineRunner(parametricOfflineAut, specificAlphabet); automataOfflineRunnersBag.add(offlineRunner); offlineRunnersConstraintsMatching.put(offlineRunner, constr); } } /** * Initialize the runners for the parametric automata structures given an alphabet. */ // private void initAutomataRunnersBag() { // this.automataRunnersBag = new ArrayList<>(); // // do not hardcode the maximal number of combination grouping // int maxCombinationSize = 2; // // // Generate the combination of 2 elements from the alphabet // Set<Character> alphabet = new HashSet<>(); // for (Iterator<TaskChar> it = taskChars.iterator(); it.hasNext(); ) { // alphabet.add(it.next().identifier); // } // ICombinatoricsVector<Character> initialVector = Factory.createVector(alphabet); // Generator<Character> gen = Factory.createSimpleCombinationGenerator(initialVector, maxCombinationSize); // // for (SeparatedAutomaton aut : this.automataBag.values()) { // for (ICombinatoricsVector<Character> combination : gen) { // List<Character> specificAlphabet = combination.getVector(); // if (aut == null) continue; // // One way i.e. a-b // automataRunnersBag.add(new SeparatedAutomatonRunner(aut, new ArrayList(specificAlphabet))); // // Other way i.e. b-a // Collections.reverse(specificAlphabet); // automataRunnersBag.add(new SeparatedAutomatonRunner(aut, specificAlphabet)); // } // } // } /** * @return List of the runners for the separated automata of this bag */ public List<SeparatedAutomatonRunner> getSeparatedAutomataRunners() { return this.automataRunnersBag; } /** * @return List of the runners for the separated automata of this bag */ public List<SeparatedAutomatonOfflineRunner> getSeparatedAutomataOfflineRunners() { return this.automataOfflineRunnersBag; } /** * @param runner * @return constraint of the given runner */ public Constraint getConstraintOfRunner(SeparatedAutomatonRunner runner) { return runnersConstraintsMatching.get(runner); } /** * @param runner * @return constraint of the given runner */ public Constraint getConstraintOfOfflineRunner(SeparatedAutomatonOfflineRunner runner) { return offlineRunnersConstraintsMatching.get(runner); } public boolean add(Constraint c) { if (this.add(c.base, c)) { return true; } return false; } public boolean add(TaskChar tCh, Constraint c) { if (!this.bag.containsKey(tCh)) { this.bag.put(tCh, new TreeSet<Constraint>()); this.taskChars.add(tCh); } if (this.bag.get(tCh).add(c)) { c.addObserver(this); return true; } return false; } public boolean add(TaskCharSet taskCharSet, Constraint c) { boolean added = false; for (TaskChar tCh : taskCharSet.getTaskCharsArray()) { added = added || this.add(tCh, c); } return added; } public boolean remove(TaskChar character, Constraint c) { if (!this.bag.containsKey(character)) { return false; } if (this.bag.get(character) == null) { return false; } if (this.bag.get(character).remove(c)) { c.deleteObserver(this); return true; } return false; } public boolean remove(Constraint c) { boolean removed = false; for (TaskChar tCh : c.base.getTaskCharsArray()) { if (this.bag.get(tCh) != null) { if (this.bag.get(tCh).remove(c)) { removed = removed || true; } } } return removed; } public void replace(TaskChar tCh, Constraint constraint) { this.remove(tCh, constraint); this.add(tCh, constraint); } public int eraseConstraintsOf(TaskChar taskChar) { int constraintsRemoved = 0; if (this.bag.containsKey(taskChar)) { for (Constraint c : this.getConstraintsOf(taskChar)) { c.deleteObserver(this); constraintsRemoved++; } this.bag.put(taskChar, new TreeSet<Constraint>()); } return constraintsRemoved; } /** * Removes all constraints. * * @return The number of erased constraints */ public int wipeOutConstraints() { int erasedConstraints = 0; for (TaskChar tChar : this.taskChars) { erasedConstraints += eraseConstraintsOf(tChar); } return erasedConstraints; } public boolean add(TaskChar tCh) { if (!this.bag.containsKey(tCh)) { this.bag.put(tCh, new TreeSet<Constraint>()); this.taskChars.add(tCh); return true; } return false; } public boolean addAll(TaskChar tCh, Collection<? extends Constraint> cs) { this.add(tCh); Set<Constraint> existingConSet = this.bag.get(tCh); for (Constraint c : cs) { if (!existingConSet.contains(c)) { c.addObserver(this); } } return this.bag.get(tCh).addAll(cs); } public Set<TaskChar> getTaskChars() { return this.taskChars; } public Set<Constraint> getConstraintsOf(TaskChar character) { if (this.bag.get(character) == null) return new TreeSet<Constraint>(); return this.bag.get(character); } public Constraint get(TaskChar character, Constraint searched) { if (!this.bag.containsKey(character)) { return null; } TreeSet<Constraint> cnsOf = this.bag.get(character); if (cnsOf == null) return null; if (!cnsOf.contains(searched)) { return null; } NavigableSet<Constraint> srCnss = cnsOf.headSet(searched, true); if (srCnss.isEmpty()) { return null; } return srCnss.last(); } public Constraint getOrAdd(TaskChar character, Constraint searched) { Constraint con = this.get(character, searched); if (con == null) { this.add(character, searched); con = this.get(character, searched); } return con; } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("ConstraintsBag [bag="); builder.append(bag); builder.append(", taskChars="); builder.append(taskChars); builder.append("]"); return builder.toString(); } @Override public Object clone() { ConstraintsBag clone = new ConstraintsBag(this.taskChars); for (TaskChar chr : this.taskChars) { for (Constraint c : this.getConstraintsOf(chr)) { clone.add(chr, c); } } return clone; } public ConstraintsBag createRedundantCopy(Collection<TaskChar> wholeAlphabet) { ConstraintsBag nuBag = (ConstraintsBag) this.clone(); Collection<TaskChar> bases = wholeAlphabet; Collection<TaskChar> implieds = wholeAlphabet; for (TaskChar base : bases) { nuBag.addAll(base, MetaConstraintUtils.getAllDiscoverableExistenceConstraints(base)); for (TaskChar implied : implieds) { if (!base.equals(implied)) nuBag.addAll(base, MetaConstraintUtils.getAllDiscoverableRelationConstraints(base, implied)); } } return nuBag; } public ConstraintsBag createEmptyIndexedCopy() { return new ConstraintsBag(getTaskChars()); } public ConstraintsBag createComplementOfCopyPrunedByThreshold(double supportThreshold) { ConstraintsBag nuBag = (ConstraintsBag) this.clone(); for (TaskChar key : this.taskChars) { for (Constraint con : this.getConstraintsOf(key)) { if (con.hasSufficientSupport(supportThreshold)) { nuBag.remove(key, con); } } } return nuBag; } public int howManyConstraints() { int numberOfConstraints = 0; for (TaskChar tCh : this.getTaskChars()) { numberOfConstraints += (this.bag.get(tCh) == null ? 0 : this.bag.get(tCh).size()); } return numberOfConstraints; } public int howManyUnmarkedConstraints() { int i = 0; for (TaskChar key : this.getTaskChars()) for (Constraint c : this.getConstraintsOf(key)) if (!c.isMarkedForExclusion()) i++; return i; } public Long howManyExistenceConstraints() { long i = 0L; for (TaskChar key : this.taskChars) for (Constraint c : this.getConstraintsOf(key)) if (MetaConstraintUtils.isExistenceConstraint(c)) i++; return i; } public void setAlphabet(Collection<TaskChar> alphabet) { for (TaskChar taskChr : alphabet) { if (!this.bag.containsKey(taskChr)) { this.bag.put(taskChr, new TreeSet<Constraint>()); this.taskChars.add(taskChr); } } } public boolean contains(TaskChar tCh) { return this.taskChars.contains(tCh); } public void merge(ConstraintsBag other) { for (TaskChar tCh : other.taskChars) { this.shallowReplace(tCh, other.bag.get(tCh)); } } public void shallowMerge(ConstraintsBag other) { for (TaskChar tCh : other.taskChars) { if (this.contains(tCh)) { this.addAll(tCh, other.getConstraintsOf(tCh)); } else { this.shallowReplace(tCh, other.bag.get(tCh)); } } } public void shallowReplace(TaskChar taskChar, TreeSet<Constraint> cs) { this.bag.put(taskChar, cs); } public int removeMarkedConstraints() { Constraint auxCon = null; int markedConstraintsRemoved = 0; for (TaskChar tChar : this.taskChars) { if (this.bag.get(tChar) != null) { Iterator<Constraint> constraIter = this.bag.get(tChar).iterator(); while (constraIter.hasNext()) { auxCon = constraIter.next(); if (auxCon.isMarkedForExclusion()) { constraIter.remove(); markedConstraintsRemoved++; } } } } return markedConstraintsRemoved; } public ConstraintsBag slice(Set<TaskChar> indexingTaskCharGroup) { ConstraintsBag slicedBag = new ConstraintsBag(indexingTaskCharGroup); for (TaskChar indexingTaskChar : indexingTaskCharGroup) { slicedBag.bag.put(indexingTaskChar, this.bag.get(indexingTaskChar)); } return slicedBag; } public Set<Constraint> getAllConstraints() { Set<Constraint> constraints = new TreeSet<Constraint>(); for (TaskChar tCh : this.getTaskChars()) { constraints.addAll(this.getConstraintsOf(tCh)); } return constraints; } public Collection<Constraint> getOnlyFullySupportedConstraints() { Collection<Constraint> constraints = new TreeSet<Constraint>(); for (TaskChar tCh : this.getTaskChars()) { for (Constraint cns : this.getConstraintsOf(tCh)) { if (cns.hasMaximumSupport()) { constraints.add(cns); } } } return constraints; } public ConstraintsBag getOnlyFullySupportedConstraintsInNewBag() { ConstraintsBag clone = (ConstraintsBag) this.clone(); for (TaskChar tCh : clone.getTaskChars()) { for (Constraint cns : this.getConstraintsOf(tCh)) { if (!cns.hasMaximumSupport()) { clone.remove(tCh, cns); } } } return clone; } @Override public void update(Observable o, Object arg) { if (Constraint.class.isAssignableFrom(o.getClass())) { this.setChanged(); this.notifyObservers(arg); this.clearChanged(); } } }
17,708
33.121387
155
java
Janus
Janus-master/src/minerful/concept/constraint/MetaConstraintUtils.java
package minerful.concept.constraint; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.TreeSet; import minerful.concept.TaskChar; import minerful.concept.TaskCharSet; import minerful.concept.constraint.ConstraintFamily.RelationConstraintSubFamily; import minerful.concept.constraint.existence.AtMostOne; import minerful.concept.constraint.existence.End; import minerful.concept.constraint.existence.ExistenceConstraint; import minerful.concept.constraint.existence.Init; import minerful.concept.constraint.existence.Participation; import minerful.concept.constraint.existence.Absence; import minerful.concept.constraint.nonDeclare.NonDeclareConstraint; import minerful.concept.constraint.relation.AlternatePrecedence; import minerful.concept.constraint.relation.AlternateResponse; import minerful.concept.constraint.relation.AlternateSuccession; import minerful.concept.constraint.relation.ChainPrecedence; import minerful.concept.constraint.relation.ChainResponse; import minerful.concept.constraint.relation.ChainSuccession; import minerful.concept.constraint.relation.CoExistence; import minerful.concept.constraint.relation.MutualRelationConstraint; import minerful.concept.constraint.relation.NegativeRelationConstraint; import minerful.concept.constraint.relation.NotChainSuccession; import minerful.concept.constraint.relation.NotCoExistence; import minerful.concept.constraint.relation.NotSuccession; import minerful.concept.constraint.relation.Precedence; import minerful.concept.constraint.relation.RelationConstraint; import minerful.concept.constraint.relation.RespondedExistence; import minerful.concept.constraint.relation.Response; import minerful.concept.constraint.relation.Succession; import minerful.concept.constraint.nonDeclare.BeforeThisOrLaterThat; import org.reflections.Reflections; public class MetaConstraintUtils { public static Collection<Class<? extends Constraint>> ALL_DISCOVERABLE_CONSTRAINT_TEMPLATES = getAllDiscoverableConstraintTemplates(); public static Collection<Class<? extends Constraint>> ALL_DISCOVERABLE_RELATION_CONSTRAINT_TEMPLATES = getRelationConstraintTemplates(ALL_DISCOVERABLE_CONSTRAINT_TEMPLATES); public static Map<String, Class<? extends Constraint>> ALL_DISCOVERABLE_CONSTRAINT_TEMPLATE_NAMES_MAP = getAllDiscoverableConstraintTemplateNamesMap(); public static Collection<Class<? extends Constraint>> ALL_DISCOVERABLE_EXISTENCE_CONSTRAINT_TEMPLATES = getExistenceConstraintTemplates(ALL_DISCOVERABLE_CONSTRAINT_TEMPLATES); public static Collection<Class<? extends Constraint>> ALL_CONSTRAINT_TEMPLATES = getAllConstraintTemplates(); public static Map<String, Class<? extends Constraint>> ALL_CONSTRAINT_TEMPLATE_NAMES_MAP = getAllConstraintTemplateNamesMap(); public static Collection<Class<? extends Constraint>> ALL_RELATION_CONSTRAINT_TEMPLATES = getRelationConstraintTemplates(ALL_CONSTRAINT_TEMPLATES); public static Collection<Class<? extends Constraint>> ALL_EXISTENCE_CONSTRAINT_TEMPLATES = getExistenceConstraintTemplates(ALL_CONSTRAINT_TEMPLATES); public static Collection<Class<? extends Constraint>> ALL_NON_DECLARE_CONSTRAINT_TEMPLATES = getNonDeclareConstraintTemplates(ALL_CONSTRAINT_TEMPLATES); public static int NUMBER_OF_DISCOVERABLE_RELATION_CONSTRAINT_TEMPLATES = ALL_DISCOVERABLE_RELATION_CONSTRAINT_TEMPLATES.size(); public static int NUMBER_OF_DISCOVERABLE_EXISTENCE_CONSTRAINT_TEMPLATES = ALL_DISCOVERABLE_EXISTENCE_CONSTRAINT_TEMPLATES.size(); public static int NUMBER_OF_RELATION_CONSTRAINT_TEMPLATES = ALL_RELATION_CONSTRAINT_TEMPLATES.size(); public static int NUMBER_OF_EXISTENCE_CONSTRAINT_TEMPLATES = ALL_EXISTENCE_CONSTRAINT_TEMPLATES.size(); public static int NUMBER_OF_NON_DECLARE_CONSTRAINT_TEMPLATES = ALL_NON_DECLARE_CONSTRAINT_TEMPLATES.size(); public static int NUMBER_OF_CONSTRAINT_TEMPLATES = ALL_CONSTRAINT_TEMPLATES.size(); public static Map<String, Class<? extends Constraint>> getAllConstraintTemplateNamesMap() { return getTemplateNamesMap(ALL_CONSTRAINT_TEMPLATES); } public static Map<String, Class<? extends Constraint>> getAllDiscoverableConstraintTemplateNamesMap() { return getTemplateNamesMap(ALL_DISCOVERABLE_CONSTRAINT_TEMPLATES); } private static Map<String, Class<? extends Constraint>> getTemplateNamesMap(Collection<Class<? extends Constraint>> templates) { Map<String, Class<? extends Constraint>> constraintTemplateNames = new HashMap<String, Class<? extends Constraint>>(templates.size(), (float) 1.0); for (Class<? extends Constraint> cnsClass : templates) { constraintTemplateNames.put(getTemplateName(cnsClass), cnsClass); } return constraintTemplateNames; } public static String getTemplateName(Constraint constraint) { return getTemplateName(constraint.getClass()); } public static String getTemplateName(Class<? extends Constraint> constraintClass) { return constraintClass.getCanonicalName().substring(constraintClass.getCanonicalName().lastIndexOf('.') + 1); } public static Collection<Constraint> createHierarchicalLinks(Collection<Constraint> constraints) { TreeSet<Constraint> treeConSet = new TreeSet<Constraint>(constraints); for (Constraint con : constraints) { Constraint constraintWhichThisShouldBeBasedUpon = con.suggestConstraintWhichThisShouldBeBasedUpon(); if (constraintWhichThisShouldBeBasedUpon != null && treeConSet.contains(constraintWhichThisShouldBeBasedUpon) ) { con.setConstraintWhichThisIsBasedUpon(treeConSet.tailSet(constraintWhichThisShouldBeBasedUpon).first()); } if (con.getSubFamily().equals(RelationConstraintSubFamily.COUPLING)) { MutualRelationConstraint coReCon = (MutualRelationConstraint) con; if (!coReCon.hasForwardConstraint() && treeConSet.contains(coReCon.getPossibleForwardConstraint())) { coReCon.setForwardConstraint((RelationConstraint) treeConSet.tailSet(coReCon.getPossibleForwardConstraint()).first()); } if (!coReCon.hasBackwardConstraint() && constraints.contains(coReCon.getPossibleBackwardConstraint())) { coReCon.setBackwardConstraint((RelationConstraint) treeConSet.tailSet(coReCon.getPossibleBackwardConstraint()).first()); } } if (con.getSubFamily().equals(RelationConstraintSubFamily.NEGATIVE)) { NegativeRelationConstraint negaCon = (NegativeRelationConstraint) con; if (!negaCon.hasOpponent() && treeConSet.contains(negaCon.getSupposedOpponentConstraint())) { negaCon.setOpponent((RelationConstraint) treeConSet.tailSet(negaCon.getSupposedOpponentConstraint()).first()); } } } return constraints; } /** * The coolest method I have probably coded, ever! */ public Collection<Class<? extends Constraint>> getAllPossibleConstraintTemplatesStylish() { Reflections reflections = new Reflections(this.getClass().getPackage().getName()); Set<Class<? extends Constraint>> constraintSubClasses = reflections.getSubTypesOf(Constraint.class); ArrayList<Class<? extends Constraint>> constraintTemplates = new ArrayList<Class<? extends Constraint>>(constraintSubClasses.size()); for (Class<? extends Constraint> constraintSubClass : constraintSubClasses) { if (!Modifier.isAbstract(constraintSubClass.getModifiers())) { constraintTemplates.add(constraintSubClass); } } constraintTemplates.trimToSize(); return constraintTemplates; } public static Collection<Class<? extends Constraint>> getAllDiscoverableConstraintTemplates() { ArrayList<Class<? extends Constraint>> constraintTemplates = new ArrayList<Class<? extends Constraint>>(18); // Existence constraintTemplates.addAll(getAllDiscoverableExistenceConstraintTemplates()); // Relation onwards constraintTemplates.addAll(getAllDiscoverableForwardRelationConstraintTemplates()); // Relation backwards constraintTemplates.addAll(getAllDiscoverableBackwardRelationConstraintTemplates()); // Mutual relation constraintTemplates.addAll(getAllDiscoverableMutualRelationConstraintTemplates()); // Negation relation constraintTemplates.addAll(getAllDiscoverableNegativeRelationConstraintTemplates()); return constraintTemplates; } public static Collection<Class<? extends Constraint>> getAllConstraintTemplates() { ArrayList<Class<? extends Constraint>> constraintTemplates = new ArrayList<Class<? extends Constraint>>(18); // Existence constraintTemplates.addAll(getAllExistenceConstraintTemplates()); // Relation onwards constraintTemplates.addAll(getAllForwardRelationConstraintTemplates()); // Relation backwards constraintTemplates.addAll(getAllBackwardRelationConstraintTemplates()); // Mutual relation constraintTemplates.addAll(getAllMutualRelationConstraintTemplates()); // Negation relation constraintTemplates.addAll(getAllNegativeRelationConstraintTemplates()); // Non Declare constraintTemplates.addAll(getAllNonDeclareConstraintTemplates()); return constraintTemplates; } public static Collection<Class<? extends Constraint>> getAllExistenceConstraintTemplates() { // TODO Change it if new definitions of not yet discoverable templates are given return getAllDiscoverableExistenceConstraintTemplates(); } public static Collection<Class<? extends Constraint>> getAllDiscoverableExistenceConstraintTemplates() { ArrayList<Class<? extends Constraint>> constraintTemplates = new ArrayList<Class<? extends Constraint>>(4); // Existence constraintTemplates.add(End.class); constraintTemplates.add(Init.class); constraintTemplates.add(Participation.class); constraintTemplates.add(AtMostOne.class); constraintTemplates.add(Absence.class); return constraintTemplates; } public static Collection<Class<? extends Constraint>> getAllForwardRelationConstraintTemplates() { // TODO Change it if new definitions of not yet discoverable templates are given return getAllDiscoverableForwardRelationConstraintTemplates(); } public static Collection<Class<? extends Constraint>> getAllDiscoverableForwardRelationConstraintTemplates() { ArrayList<Class<? extends Constraint>> constraintTemplates = new ArrayList<Class<? extends Constraint>>(4); // Relation onwards constraintTemplates.add(RespondedExistence.class); constraintTemplates.add(Response.class); constraintTemplates.add(AlternateResponse.class); constraintTemplates.add(ChainResponse.class); return constraintTemplates; } public static Collection<Class<? extends Constraint>> getAllBackwardRelationConstraintTemplates() { // TODO Change it if new definitions of not yet discoverable templates are given return getAllDiscoverableBackwardRelationConstraintTemplates(); } public static Collection<Class<? extends Constraint>> getAllDiscoverableBackwardRelationConstraintTemplates() { ArrayList<Class<? extends Constraint>> constraintTemplates = new ArrayList<Class<? extends Constraint>>(3); // Relation backwards constraintTemplates.add(Precedence.class); constraintTemplates.add(AlternatePrecedence.class); constraintTemplates.add(ChainPrecedence.class); return constraintTemplates; } public static Collection<Class<? extends Constraint>> getAllMutualRelationConstraintTemplates() { // TODO Change it if new definitions of not yet discoverable templates are given return getAllDiscoverableMutualRelationConstraintTemplates(); } public static Collection<Class<? extends Constraint>> getAllDiscoverableMutualRelationConstraintTemplates() { ArrayList<Class<? extends Constraint>> constraintTemplates = new ArrayList<Class<? extends Constraint>>(4); // Mutual relation constraintTemplates.add(CoExistence.class); constraintTemplates.add(Succession.class); constraintTemplates.add(AlternateSuccession.class); constraintTemplates.add(ChainSuccession.class); return constraintTemplates; } public static Collection<Class<? extends Constraint>> getAllNegativeRelationConstraintTemplates() { // TODO Change it if new definitions of not yet discoverable templates are given return getAllDiscoverableNegativeRelationConstraintTemplates(); } public static Collection<Class<? extends Constraint>> getAllDiscoverableNegativeRelationConstraintTemplates() { ArrayList<Class<? extends Constraint>> constraintTemplates = new ArrayList<Class<? extends Constraint>>(3); // Negation relation constraintTemplates.add(NotCoExistence.class); constraintTemplates.add(NotChainSuccession.class); constraintTemplates.add(NotSuccession.class); return constraintTemplates; } /** * Returns the template of all non-DECLARE constraints * * @return */ public static Collection<Class<? extends Constraint>> getAllNonDeclareConstraintTemplates() { ArrayList<Class<? extends Constraint>> constraintTemplates = new ArrayList<Class<? extends Constraint>>(); // Mutual relation constraintTemplates.add(BeforeThisOrLaterThat.class); return constraintTemplates; } public static boolean isExistenceConstraint(Constraint c) { return c instanceof ExistenceConstraint; } public static boolean isRelationConstraint(Constraint c) { return c instanceof RelationConstraint; } public static boolean isExistenceTemplate(Class<? extends Constraint> template) { return ExistenceConstraint.class.isAssignableFrom(template); } public static boolean isRelationTemplate(Class<? extends Constraint> template) { return RelationConstraint.class.isAssignableFrom(template); } public static boolean isNonDeclareTemplate(Class<? extends Constraint> template) { return NonDeclareConstraint.class.isAssignableFrom(template); } public static Collection<Class<? extends Constraint>> getRelationConstraintTemplates(Collection<Class<? extends Constraint>> constraintTemplates) { Collection<Class<? extends Constraint>> relConTemplates = new ArrayList<Class<? extends Constraint>>(); for (Class<? extends Constraint> cnsTemplate : constraintTemplates) { if (RelationConstraint.class.isAssignableFrom(cnsTemplate)) { relConTemplates.add(cnsTemplate); } } return relConTemplates; } public static Collection<Class<? extends Constraint>> getExistenceConstraintTemplates(Collection<Class<? extends Constraint>> constraintTemplates) { Collection<Class<? extends Constraint>> relConTemplates = new ArrayList<Class<? extends Constraint>>(); for (Class<? extends Constraint> cnsTemplate : constraintTemplates) { if (ExistenceConstraint.class.isAssignableFrom(cnsTemplate)) { relConTemplates.add(cnsTemplate); } } return relConTemplates; } public static Collection<Class<? extends Constraint>> getNonDeclareConstraintTemplates(Collection<Class<? extends Constraint>> constraintTemplates) { Collection<Class<? extends Constraint>> relConTemplates = new ArrayList<Class<? extends Constraint>>(); for (Class<? extends Constraint> cnsTemplate : constraintTemplates) { if (NonDeclareConstraint.class.isAssignableFrom(cnsTemplate)) { relConTemplates.add(cnsTemplate); } } return relConTemplates; } public static Collection<Class<? extends Constraint>> getDiscoverableExtraConstraints(Collection<Class<? extends Constraint>> constraintTemplates) { Collection<Class<? extends Constraint>> relConTemplates = new ArrayList<Class<? extends Constraint>>(); for (Class<? extends Constraint> cnsTemplate : constraintTemplates) { if (NonDeclareConstraint.class.isAssignableFrom(cnsTemplate)) { relConTemplates.add(cnsTemplate); } } return relConTemplates; } public static int howManyPossibleExistenceConstraints(int numOfTasksToQueryFor) { // TODO Change it if new definitions of not yet discoverable templates are given return howManyDiscoverableExistenceConstraints(numOfTasksToQueryFor); } public static int howManyDiscoverableExistenceConstraints(int numOfTasksToQueryFor) { return NUMBER_OF_DISCOVERABLE_EXISTENCE_CONSTRAINT_TEMPLATES * numOfTasksToQueryFor; } public static int howManyPossibleRelationConstraints(int numOfTasksToQueryFor, int alphabetSize) { // TODO Change it if new definitions of not yet discoverable templates are given return howManyDiscoverableRelationConstraints(numOfTasksToQueryFor, alphabetSize); } public static int howManyDiscoverableRelationConstraints(int numOfTasksToQueryFor, int alphabetSize) { return NUMBER_OF_DISCOVERABLE_RELATION_CONSTRAINT_TEMPLATES * numOfTasksToQueryFor * (alphabetSize - 1); } public static int howManyPossibleConstraints(int numOfTasksToQueryFor, int alphabetSize) { // TODO Change it if new definitions of not yet discoverable templates are given return howManyDiscoverableConstraints(numOfTasksToQueryFor, alphabetSize); } public static int howManyDiscoverableConstraints(int numOfTasksToQueryFor, int alphabetSize) { return howManyDiscoverableRelationConstraints(numOfTasksToQueryFor, alphabetSize) + howManyDiscoverableExistenceConstraints(numOfTasksToQueryFor); } public static int howManyPossibleConstraints(int alphabetSize) { // TODO Change it if new definitions of not yet discoverable templates are given return howManyDiscoverableConstraints(alphabetSize); } public static int howManyDiscoverableConstraints(int alphabetSize) { return howManyDiscoverableRelationConstraints(alphabetSize, alphabetSize) + howManyDiscoverableExistenceConstraints(alphabetSize); } public static Collection<Constraint> getAllPossibleRelationConstraints(TaskChar base, TaskChar implied) { // TODO Change it if new definitions of not yet discoverable templates are given return getAllDiscoverableRelationConstraints(base, implied); } /* The second coolest method I ever coded! */ public static Constraint makeConstraint(Class<? extends Constraint> template, TaskCharSet... params) { Constraint con = null; Constructor<? extends Constraint> constructor = null; try { if (isExistenceTemplate(template)) { constructor = template.getConstructor(TaskCharSet.class); con = constructor.newInstance(params[0]); } else if (isRelationTemplate(template)) { constructor = template.getConstructor(TaskCharSet.class, TaskCharSet.class); con = constructor.newInstance(params[0], params[1]); } else if (isNonDeclareTemplate(template)){ constructor = template.getConstructor(TaskCharSet.class, TaskCharSet.class); con = constructor.newInstance(params[0], params[1]); } } catch (NoSuchMethodException | SecurityException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { // TODO Auto-generated catch block e.printStackTrace(); } return con; } /* The second coolest method I ever coded! */ public static Constraint makeRelationConstraint(Class<? extends Constraint> template, TaskCharSet param1, TaskCharSet param2) { Constraint con = null; Constructor<? extends Constraint> constructor = null; try { constructor = template.getConstructor(TaskCharSet.class, TaskCharSet.class); con = constructor.newInstance(param1, param2); } catch (NoSuchMethodException | SecurityException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { // TODO Auto-generated catch block e.printStackTrace(); } return con; } /* The second coolest method I ever coded! */ public static Constraint makeExistenceConstraint(Class<? extends Constraint> template, TaskCharSet param) { Constraint con = null; Constructor<? extends Constraint> constructor = null; try { constructor = template.getConstructor(TaskCharSet.class); con = constructor.newInstance(param); } catch (NoSuchMethodException | SecurityException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { // TODO Auto-generated catch block e.printStackTrace(); } return con; } /* The second-and-a-half coolest method I ever coded! */ public static Collection<Constraint> getAllDiscoverableRelationConstraints(TaskChar base, TaskChar implied) { Collection<Constraint> relCons = new ArrayList<Constraint>(); Constructor<? extends Constraint> tmpConstructor = null; try { for (Class<? extends Constraint> relationConstraintTypeClass : getAllDiscoverableForwardRelationConstraintTemplates()) { tmpConstructor = relationConstraintTypeClass.getConstructor( TaskChar.class, TaskChar.class, Double.TYPE); relCons.add(tmpConstructor.newInstance(base, implied, 0.0)); } for (Class<? extends Constraint> relationConstraintTypeClass : getAllDiscoverableBackwardRelationConstraintTemplates()) { tmpConstructor = relationConstraintTypeClass.getConstructor( TaskChar.class, TaskChar.class, Double.TYPE); relCons.add(tmpConstructor.newInstance(implied, base, 0.0)); } for (Class<? extends Constraint> relationConstraintTypeClass : getAllDiscoverableNegativeRelationConstraintTemplates()) { tmpConstructor = relationConstraintTypeClass.getConstructor( TaskChar.class, TaskChar.class, Double.TYPE); relCons.add(tmpConstructor.newInstance(base, implied, 0.0)); } for (Class<? extends Constraint> relationConstraintTypeClass : getAllDiscoverableMutualRelationConstraintTemplates()) { tmpConstructor = relationConstraintTypeClass.getConstructor( TaskChar.class, TaskChar.class, Double.TYPE); relCons.add(tmpConstructor.newInstance(base, implied, 0.0)); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); System.exit(1); } return relCons; } public static Collection<Constraint> getAllPossibleExistenceConstraints(TaskChar base) { // TODO Change it if new definitions of not yet discoverable templates are given return getAllDiscoverableExistenceConstraints(base); } /* The third coolest method I ever coded! */ public static Collection<Constraint> getAllDiscoverableExistenceConstraints(TaskChar base) { Collection<Constraint> exiCons = new ArrayList<Constraint>(); Collection<Class<? extends Constraint>> existenceConstraintTypeClasses = ALL_DISCOVERABLE_EXISTENCE_CONSTRAINT_TEMPLATES; Constructor<? extends Constraint> tmpConstructor = null; for (Class<? extends Constraint> existenceConstraintTypeClass : existenceConstraintTypeClasses) { if (!Modifier.isAbstract(existenceConstraintTypeClass.getModifiers())) { try { tmpConstructor = existenceConstraintTypeClass .getConstructor(TaskChar.class, Double.TYPE); exiCons.add( tmpConstructor .newInstance(base, 0.0)); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); System.exit(1); } } } return exiCons; } /** * Returns all the possible non-DECLARE constraints with 1 activator and 2 variables. * First method with a JavaDoc that says what it does. * * @param auxActiParam1 Activator event * @param auxActiParam2 first event * @param extraActiParam3 second event * @return */ public static Collection<Constraint> getAllDiscoverableExtraConstraints(TaskChar auxActiParam1, TaskChar auxActiParam2, TaskChar extraActiParam3) { Collection<Constraint> extraCons = new ArrayList<Constraint>(); Constructor<? extends Constraint> tmpConstructor = null; try { for (Class<? extends Constraint> nonDeclareConstraintTypeClass : getAllNonDeclareConstraintTemplates()) { tmpConstructor = nonDeclareConstraintTypeClass.getConstructor( TaskChar.class, TaskChar.class, TaskChar.class); extraCons.add(tmpConstructor.newInstance(auxActiParam1, auxActiParam2, extraActiParam3)); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); System.exit(1); } return extraCons; } }
26,322
49.71869
179
java
Janus
Janus-master/src/minerful/concept/constraint/existence/Absence.java
package minerful.concept.constraint.existence; import dk.brics.automaton.Automaton; import minerful.concept.TaskChar; import minerful.concept.TaskCharSet; import minerful.concept.constraint.Constraint; import minerful.concept.constraint.ConstraintFamily.ExistenceConstraintSubFamily; import minerful.reactive.automaton.ConjunctAutomata; import minerful.reactive.automaton.SeparatedAutomaton; import minerful.reactive.automaton.Utils; import javax.xml.bind.annotation.XmlRootElement; import java.util.ArrayList; import java.util.List; @XmlRootElement public class Absence extends ExistenceConstraint { @Override public String getRegularExpressionTemplate() { // return "[^%1$s]*([%1$s][^%1$s]*){1,}[^%1$s]*"; return "^((?!%1$s).)*$"; //Double check } protected Absence() { super(); } public Absence(TaskChar param1, double support) { super(param1, support); } public Absence(TaskChar param1) { super(param1); } public Absence(TaskCharSet param1, double support) { super(param1, support); } public Absence(TaskCharSet param1) { super(param1); } @Override public Constraint suggestConstraintWhichThisShouldBeBasedUpon() { return null; } @Override public ExistenceConstraintSubFamily getSubFamily() { return ExistenceConstraintSubFamily.NUMEROSITY; } @Override public Constraint copy(TaskChar... taskChars) { super.checkParams(taskChars); // check that parameters are OK return new Absence(taskChars[0]); } @Override public Constraint copy(TaskCharSet... taskCharSets) { super.checkParams(taskCharSets); // check that parameters are OK return new Absence(taskCharSets[0]); } @Override public SeparatedAutomaton buildParametricSeparatedAutomaton() { char[] alphabet = {'a', 'z'}; char[] others = {alphabet[1]}; Automaton activator = Utils.getExistentialActivatorAutomaton(alphabet); List<ConjunctAutomata> disjunctAutomata = new ArrayList<ConjunctAutomata>(); Automaton futureAutomaton = Utils.getNegativeEventualityAutomaton(alphabet[0], others); ConjunctAutomata conjunctAutomaton = new ConjunctAutomata(null, null, futureAutomaton); disjunctAutomata.add(conjunctAutomaton); SeparatedAutomaton res = new SeparatedAutomaton(activator, disjunctAutomata, alphabet); res.setNominalID(this.type); return res; } }
2,300
27.7625
89
java
Janus
Janus-master/src/minerful/concept/constraint/existence/AtMostOne.java
package minerful.concept.constraint.existence; import javax.xml.bind.annotation.XmlRootElement; import dk.brics.automaton.Automaton; import minerful.concept.TaskChar; import minerful.concept.TaskCharSet; import minerful.concept.constraint.Constraint; import minerful.concept.constraint.ConstraintFamily.ExistenceConstraintSubFamily; import minerful.reactive.automaton.ConjunctAutomata; import minerful.reactive.automaton.SeparatedAutomaton; import minerful.reactive.automaton.Utils; import java.util.ArrayList; import java.util.List; @XmlRootElement public class AtMostOne extends ExistenceConstraint { @Override public String getRegularExpressionTemplate() { return "[^%1$s]*([%1$s][^%1$s]*){0,1}[^%1$s]*"; } protected AtMostOne() { super(); } public AtMostOne(TaskChar param1, double support) { super(param1, support); } public AtMostOne(TaskChar param1) { super(param1); } public AtMostOne(TaskCharSet param1, double support) { super(param1, support); } public AtMostOne(TaskCharSet param1) { super(param1); } @Override public Constraint suggestConstraintWhichThisShouldBeBasedUpon() { return null; } @Override public ExistenceConstraintSubFamily getSubFamily() { return ExistenceConstraintSubFamily.NUMEROSITY; } @Override public Constraint copy(TaskChar... taskChars) { super.checkParams(taskChars); return new AtMostOne(taskChars[0]); } @Override public Constraint copy(TaskCharSet... taskCharSets) { super.checkParams(taskCharSets); return new AtMostOne(taskCharSets[0]); } @Override public SeparatedAutomaton buildParametricSeparatedAutomaton() { char[] alphabet = {'a', 'z'}; char[] others = {alphabet[1]}; Automaton activator = Utils.getSingleCharActivatorAutomaton(alphabet[0], others); List<ConjunctAutomata> disjunctAutomata = new ArrayList<ConjunctAutomata>(); Automaton futureAutomaton = Utils.getNextNegativeEventualityAutomaton(alphabet[0], others); Automaton pastAutomaton = Utils.getReversedNextNegativeEventualityAutomaton(alphabet[0], others); ConjunctAutomata conjunctAutomaton = new ConjunctAutomata(pastAutomaton, null, futureAutomaton); disjunctAutomata.add(conjunctAutomaton); SeparatedAutomaton res = new SeparatedAutomaton(activator, disjunctAutomata, alphabet); res.setNominalID(this.type); return res; } }
2,329
28.125
99
java
Janus
Janus-master/src/minerful/concept/constraint/existence/End.java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package minerful.concept.constraint.existence; import javax.xml.bind.annotation.XmlRootElement; import dk.brics.automaton.Automaton; import minerful.concept.TaskChar; import minerful.concept.TaskCharSet; import minerful.concept.constraint.Constraint; import minerful.concept.constraint.ConstraintFamily.ExistenceConstraintSubFamily; import minerful.reactive.automaton.ConjunctAutomata; import minerful.reactive.automaton.SeparatedAutomaton; import minerful.reactive.automaton.Utils; import java.util.ArrayList; import java.util.List; @XmlRootElement public class End extends Participation { @Override public String getRegularExpressionTemplate() { return ".*[%1$s]"; } protected End() { super(); } public End(TaskChar param1) { super(param1); } public End(TaskChar param1, double support) { super(param1, support); } public End(TaskCharSet param1, double support) { super(param1, support); } public End(TaskCharSet param1) { super(param1); } @Override public int getHierarchyLevel() { return super.getHierarchyLevel() + 1; } @Override public Constraint suggestConstraintWhichThisShouldBeBasedUpon() { return new Participation(this.base); } @Override public ExistenceConstraintSubFamily getSubFamily() { return ExistenceConstraintSubFamily.POSITION; } @Override public Constraint copy(TaskChar... taskChars) { super.checkParams(taskChars); // check that parameters are OK return new End(taskChars[0]); } @Override public Constraint copy(TaskCharSet... taskCharSets) { super.checkParams(taskCharSets); // check that parameters are OK return new End(taskCharSets[0]); } @Override public SeparatedAutomaton buildParametricSeparatedAutomaton() { char[] alphabet = {'a', 'z'}; Automaton activator = Utils.getExistentialActivatorAutomaton(alphabet); List<ConjunctAutomata> disjunctAutomata = new ArrayList<ConjunctAutomata>(); char[] others = {alphabet[1]}; Automaton futureAutomaton = Utils.getLastAutomaton(alphabet[0], others); ConjunctAutomata conjunctAutomaton = new ConjunctAutomata(null, null, futureAutomaton); disjunctAutomata.add(conjunctAutomaton); SeparatedAutomaton res = new SeparatedAutomaton(activator, disjunctAutomata, alphabet); res.setNominalID(this.type); return res; } }
2,405
26.033708
89
java
Janus
Janus-master/src/minerful/concept/constraint/existence/ExactlyOne.java
package minerful.concept.constraint.existence; import javax.xml.bind.annotation.XmlRootElement; import dk.brics.automaton.Automaton; import minerful.concept.TaskChar; import minerful.concept.TaskCharSet; import minerful.concept.constraint.Constraint; import minerful.concept.constraint.ConstraintFamily.ExistenceConstraintSubFamily; import minerful.reactive.automaton.ConjunctAutomata; import minerful.reactive.automaton.SeparatedAutomaton; import minerful.reactive.automaton.Utils; import java.util.ArrayList; import java.util.List; @XmlRootElement public class ExactlyOne extends ExistenceConstraint { @Override public String getRegularExpressionTemplate() { return "[^%1$s]*([%1$s][^%1$s]*){1,1}[^%1$s]*"; } protected ExactlyOne() { super(); } public ExactlyOne(TaskChar param1, double support) { super(param1, support); } public ExactlyOne(TaskChar param1) { super(param1); } public ExactlyOne(TaskCharSet param1, double support) { super(param1, support); } public ExactlyOne(TaskCharSet param1) { super(param1); } @Override public Constraint suggestConstraintWhichThisShouldBeBasedUpon() { return new Participation(getBase()); } @Override public Constraint[] suggestImpliedConstraints() { Constraint[] impliCons = null; Constraint[] inheritedImpliCons = super.suggestImpliedConstraints(); int i = 0; if (inheritedImpliCons != null) { impliCons = new Constraint[inheritedImpliCons.length + 1]; for (Constraint impliCon : inheritedImpliCons) { impliCons[i++] = impliCon; } } else { impliCons = new Constraint[1]; } impliCons[i++] = new AtMostOne(getBase()); return impliCons; } @Override public ExistenceConstraintSubFamily getSubFamily() { return ExistenceConstraintSubFamily.NUMEROSITY; } @Override public Constraint copy(TaskChar... taskChars) { super.checkParams(taskChars); return new ExactlyOne(taskChars[0]); } @Override public Constraint copy(TaskCharSet... taskCharSets) { super.checkParams(taskCharSets); return new ExactlyOne(taskCharSets[0]); } @Override public SeparatedAutomaton buildParametricSeparatedAutomaton() { char[] alphabet = {'a', 'z'}; char[] others = {alphabet[1]}; Automaton activator = Utils.getExistentialActivatorAutomaton(alphabet); List<ConjunctAutomata> disjunctAutomata = new ArrayList<ConjunctAutomata>(); Automaton futureAutomaton = Utils.getPreciseParticipationAutomaton(alphabet[0], others, 1); ConjunctAutomata conjunctAutomaton = new ConjunctAutomata(null, null, futureAutomaton); disjunctAutomata.add(conjunctAutomaton); SeparatedAutomaton res = new SeparatedAutomaton(activator, disjunctAutomata, alphabet); res.setNominalID(this.type); return res; } }
2,730
26.867347
93
java
Janus
Janus-master/src/minerful/concept/constraint/existence/ExistenceConstraint.java
package minerful.concept.constraint.existence; import javax.xml.bind.annotation.XmlType; import minerful.concept.TaskChar; import minerful.concept.TaskCharSet; import minerful.concept.constraint.Constraint; import minerful.concept.constraint.ConstraintFamily; import minerful.concept.constraint.ConstraintFamily.ExistenceConstraintSubFamily; @XmlType public abstract class ExistenceConstraint extends Constraint { protected ExistenceConstraint() { super(); } public ExistenceConstraint(TaskChar param1, double support) { super(param1, support); } public ExistenceConstraint(TaskChar param1) { super(param1); } public ExistenceConstraint(TaskCharSet param1, double support) { super(param1, support); } public ExistenceConstraint(TaskCharSet param1) { super(param1); } public static String toExistenceQuantifiersString(Participation least, AtMostOne atMost) { String min = "0", max = "*"; if (least != null) { min = "1"; } if (atMost != null) { max = "*"; } return "[ " + min + " ... " + max + " ]"; } @Override public int compareTo(Constraint t) { int result = super.compareTo(t); if (result == 0) { return this.getClass().getCanonicalName().compareTo( t.getClass().getCanonicalName()); } return result; } @Override public String toString() { return super.toString(); } @Override public TaskCharSet getImplied() { return null; } @Override public ConstraintFamily getFamily() { return ConstraintFamily.EXISTENCE; } @Override public ExistenceConstraintSubFamily getSubFamily() { return ExistenceConstraintSubFamily.NONE; } @Override public String getRegularExpressionTemplate() { // TODO Auto-generated method stub return null; } @Override public Constraint suggestConstraintWhichThisShouldBeBasedUpon() { // TODO Auto-generated method stub return null; } @Override public boolean checkParams(TaskChar... taskChars) throws IllegalArgumentException { if (taskChars.length > 1) throw new IllegalArgumentException("Too many parameters"); return true; } @Override public boolean checkParams(TaskCharSet... taskCharSets) throws IllegalArgumentException { if (taskCharSets.length > 1) throw new IllegalArgumentException("Too many parameters"); return true; } }
2,492
24.438776
91
java
Janus
Janus-master/src/minerful/concept/constraint/existence/ExistenceLimitsConstraint.java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package minerful.concept.constraint.existence; import minerful.concept.TaskChar; import minerful.concept.TaskCharSet; import minerful.concept.constraint.Constraint; /** * Substituted by {@link Participation} * @author cdc */ @Deprecated public abstract class ExistenceLimitsConstraint extends Constraint { public static final int NO_MAX_EXISTENCE_CONSTRAINT = Integer.MAX_VALUE; public static final int NO_MIN_EXISTENCE_CONSTRAINT = 0; private int minimum; private int maximum; public int getMaximum() { return maximum; } public void setMaximum(int maximum) { this.maximum = maximum; } public int getMinimum() { return minimum; } public void setMinimum(TaskChar param1, int minimum) { this.minimum = minimum; } public ExistenceLimitsConstraint(TaskChar param1, int minimum, int maximum) { super(param1); this.minimum = minimum; this.maximum = maximum; } @Override public String toString() { return super.toString() + "{ [" + ( this.minimum == NO_MIN_EXISTENCE_CONSTRAINT ? "0" : String.valueOf(this.minimum) ) + "…" + ( this.maximum == NO_MAX_EXISTENCE_CONSTRAINT ? "*" : String.valueOf(this.maximum) ) + "] }"; } @Override public int compareTo(Constraint t) { int result = this.base.compareTo(t.getBase()); if (result == 0) { if (!this.getClass().getCanonicalName().equals(t.getClass().getCanonicalName())) { return 1; } } return result; } @Override public TaskCharSet getImplied() { return null; } }
1,979
24.714286
94
java
Janus
Janus-master/src/minerful/concept/constraint/existence/Init.java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package minerful.concept.constraint.existence; import javax.xml.bind.annotation.XmlRootElement; import dk.brics.automaton.Automaton; import minerful.concept.TaskChar; import minerful.concept.TaskCharSet; import minerful.concept.constraint.Constraint; import minerful.concept.constraint.ConstraintFamily.ExistenceConstraintSubFamily; import minerful.reactive.automaton.ConjunctAutomata; import minerful.reactive.automaton.SeparatedAutomaton; import minerful.reactive.automaton.Utils; import java.util.ArrayList; import java.util.List; @XmlRootElement public class Init extends Participation { @Override public String getRegularExpressionTemplate() { return "[%1$s].*"; } protected Init() { super(); } public Init(TaskChar param1, double support) { super(param1, support); } public Init(TaskChar param1) { super(param1); } public Init(TaskCharSet param1, double support) { super(param1, support); } public Init(TaskCharSet param1) { super(param1); } @Override public int getHierarchyLevel() { return super.getHierarchyLevel() + 1; } @Override public Constraint suggestConstraintWhichThisShouldBeBasedUpon() { return new Participation(this.base); } @Override public ExistenceConstraintSubFamily getSubFamily() { return ExistenceConstraintSubFamily.POSITION; } @Override public Constraint copy(TaskChar... taskChars) { super.checkParams(taskChars); // check that parameters are OK return new Init(taskChars[0]); } @Override public Constraint copy(TaskCharSet... taskCharSets) { super.checkParams(taskCharSets); // check that parameters are OK return new Init(taskCharSets[0]); } @Override public SeparatedAutomaton buildParametricSeparatedAutomaton() { char[] alphabet = {'a', 'z'}; Automaton activator = Utils.getExistentialActivatorAutomaton(alphabet); List<ConjunctAutomata> disjunctAutomata = new ArrayList<ConjunctAutomata>(); char[] others = {alphabet[1]}; Automaton futureAutomaton = Utils.getFirstAutomaton(alphabet[0], others); ConjunctAutomata conjunctAutomaton = new ConjunctAutomata(null, null, futureAutomaton); disjunctAutomata.add(conjunctAutomaton); SeparatedAutomaton res = new SeparatedAutomaton(activator, disjunctAutomata, alphabet); res.setNominalID(this.type); return res; } }
2,420
26.511364
89
java
Janus
Janus-master/src/minerful/concept/constraint/existence/Participation.java
package minerful.concept.constraint.existence; import javax.xml.bind.annotation.XmlRootElement; import dk.brics.automaton.Automaton; import minerful.concept.TaskChar; import minerful.concept.TaskCharSet; import minerful.concept.constraint.Constraint; import minerful.concept.constraint.ConstraintFamily.ExistenceConstraintSubFamily; import minerful.reactive.automaton.ConjunctAutomata; import minerful.reactive.automaton.SeparatedAutomaton; import minerful.reactive.automaton.Utils; import java.util.ArrayList; import java.util.List; @XmlRootElement public class Participation extends ExistenceConstraint { @Override public String getRegularExpressionTemplate() { return "[^%1$s]*([%1$s][^%1$s]*){1,}[^%1$s]*"; } protected Participation() { super(); } public Participation(TaskChar param1, double support) { super(param1, support); } public Participation(TaskChar param1) { super(param1); } public Participation(TaskCharSet param1, double support) { super(param1, support); } public Participation(TaskCharSet param1) { super(param1); } @Override public Constraint suggestConstraintWhichThisShouldBeBasedUpon() { return null; } @Override public ExistenceConstraintSubFamily getSubFamily() { return ExistenceConstraintSubFamily.NUMEROSITY; } @Override public Constraint copy(TaskChar... taskChars) { super.checkParams(taskChars); // check that parameters are OK return new Participation(taskChars[0]); } @Override public Constraint copy(TaskCharSet... taskCharSets) { super.checkParams(taskCharSets); // check that parameters are OK return new Participation(taskCharSets[0]); } @Override public SeparatedAutomaton buildParametricSeparatedAutomaton() { char[] alphabet = {'a', 'z'}; char[] others = {alphabet[1]}; Automaton activator = Utils.getExistentialActivatorAutomaton(alphabet); List<ConjunctAutomata> disjunctAutomata = new ArrayList<ConjunctAutomata>(); Automaton futureAutomaton = Utils.getEventualityAutomaton(alphabet[0], others); ConjunctAutomata conjunctAutomaton = new ConjunctAutomata(null, null, futureAutomaton); disjunctAutomata.add(conjunctAutomaton); SeparatedAutomaton res = new SeparatedAutomaton(activator, disjunctAutomata, alphabet); res.setNominalID(this.type); return res; } }
2,298
27.7375
89
java
Janus
Janus-master/src/minerful/concept/constraint/nonDeclare/BeforeThisOrLaterThat.java
package minerful.concept.constraint.nonDeclare; import dk.brics.automaton.Automaton; import minerful.concept.TaskChar; import minerful.concept.TaskCharSet; import minerful.concept.constraint.Constraint; import minerful.concept.constraint.ConstraintFamily; import minerful.reactive.automaton.ConjunctAutomata; import minerful.reactive.automaton.SeparatedAutomaton; import minerful.reactive.automaton.Utils; import javax.xml.bind.annotation.XmlRootElement; import java.util.ArrayList; import java.util.List; @XmlRootElement public class BeforeThisOrLaterThat extends NonDeclareConstraint { public BeforeThisOrLaterThat() { super(); } public BeforeThisOrLaterThat(TaskChar param1, TaskChar param2, TaskChar param3) { super(); this.parameters.add(new TaskCharSet(param1)); this.parameters.add(new TaskCharSet(param2)); this.parameters.add(new TaskCharSet(param3)); this.base = new TaskCharSet(param1); } public BeforeThisOrLaterThat(TaskChar param1, TaskChar param2, TaskChar param3, double support) { super(); this.parameters.add(new TaskCharSet(param1)); this.parameters.add(new TaskCharSet(param2)); this.parameters.add(new TaskCharSet(param3)); this.base = new TaskCharSet(param1); this.support = support; } public BeforeThisOrLaterThat(TaskCharSet param1, TaskCharSet param23, double support) { super(param1, param23, support); } public BeforeThisOrLaterThat(TaskCharSet param1, TaskCharSet param23) { super(param1, param23); } @Override public String getRegularExpressionTemplate() { return "([^%1$s]*)|([^%1$s]*%1$s[^%2$s]*)|([^%1$s]*%1$s[^%2$s]*%2$s[^%3$s]*%3$s[^%1$s]*)"; // "([^A]*)|([^A]*A[^B]*)|([^A]*A[^B]*B[^X]*X[^A]*)"; } @Override public String getRegularExpression() { return String.format(this.getRegularExpressionTemplate(), this.parameters.get(0).toPatternString(), this.parameters.get(1).toPatternString(), this.parameters.get(2).toPatternString() ); } @Override public ConstraintFamily.ConstraintImplicationVerse getImplicationVerse() { return ConstraintFamily.ConstraintImplicationVerse.FORWARD; } @Override public TaskCharSet getImplied() { return null; } @Override public Constraint suggestConstraintWhichThisShouldBeBasedUpon() { return null; } @Override public Constraint copy(TaskChar... taskChars) { this.checkParams(taskChars); return new BeforeThisOrLaterThat(taskChars[0], taskChars[1], taskChars[2]); } @Override public Constraint copy(TaskCharSet... taskCharSets) { // TODO Auto-generated method stub return null; } @Override public boolean checkParams(TaskChar... taskChars) throws IllegalArgumentException { return true; } @Override public boolean checkParams(TaskCharSet... taskCharSets) throws IllegalArgumentException { return true; } @Override public ConstraintFamily getFamily() { // TODO Auto-generated method stub return null; } @Override public int compareTo(Constraint t) { int result = super.compareTo(t); if (result == 0) { result = this.getClass().getCanonicalName().compareTo(t.getClass().getCanonicalName()); } return result; } @Override public boolean isBranched() { return false; } @Override public SeparatedAutomaton buildParametricSeparatedAutomaton() { char[] alphabet = {'a', 'b', 'c', 'z'}; Automaton activator = Utils.getSingleCharActivatorAutomaton(alphabet[0], alphabet); List<ConjunctAutomata> disjunctAutomata = new ArrayList<ConjunctAutomata>(); // Eventually in the future B char[] othersFut = {alphabet[0], alphabet[2], alphabet[3]}; Automaton futureAutomaton = Utils.getEventualityAutomaton(alphabet[1], othersFut); ConjunctAutomata conjunctAutomatonFut = new ConjunctAutomata(null, null, futureAutomaton); disjunctAutomata.add(conjunctAutomatonFut); // Eventually in the past C char[] othersPast = {alphabet[0], alphabet[1], alphabet[3]}; Automaton pastAutomaton = Utils.getEventualityAutomaton(alphabet[2], othersPast); ConjunctAutomata conjunctAutomatonPast = new ConjunctAutomata(pastAutomaton, null, null); disjunctAutomata.add(conjunctAutomatonPast); SeparatedAutomaton res = new SeparatedAutomaton(activator, disjunctAutomata, alphabet); res.setNominalID(this.type); return res; } }
4,745
31.067568
101
java
Janus
Janus-master/src/minerful/concept/constraint/nonDeclare/NonDeclareConstraint.java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package minerful.concept.constraint.nonDeclare; import minerful.concept.TaskChar; import minerful.concept.TaskCharSet; import minerful.concept.constraint.Constraint; import minerful.concept.constraint.ConstraintFamily; import minerful.concept.constraint.ConstraintFamily.ConstraintImplicationVerse; import minerful.concept.constraint.ConstraintFamily.RelationConstraintSubFamily; import minerful.concept.constraint.relation.MutualRelationConstraint; import minerful.concept.constraint.relation.NegativeRelationConstraint; import minerful.concept.constraint.relation.RespondedExistence; import minerful.concept.constraint.relation.UnidirectionalRelationConstraint; import javax.xml.bind.Unmarshaller; import javax.xml.bind.annotation.XmlIDREF; import javax.xml.bind.annotation.XmlSeeAlso; import javax.xml.bind.annotation.XmlType; @XmlType @XmlSeeAlso({MutualRelationConstraint.class, NegativeRelationConstraint.class, UnidirectionalRelationConstraint.class}) public abstract class NonDeclareConstraint extends Constraint { public static enum ImplicationVerse { FORWARD, BACKWARD, BOTH } @XmlIDREF // @XmlTransient protected TaskCharSet implied; protected NonDeclareConstraint() { super(); // implied = null; } public NonDeclareConstraint(TaskCharSet param1, TaskCharSet param23,double support) { super(support, param1, param23); super.setSilentToObservers(true); this.implied = param23; super.setSilentToObservers(false); } public NonDeclareConstraint(TaskCharSet param1, TaskCharSet param23) { super(param1, param23); super.setSilentToObservers(true); this.implied = param23; super.setSilentToObservers(false); } public NonDeclareConstraint(TaskChar param1, TaskChar param2, TaskChar param3, double support) { super(support, param1, param2, param3); super.setSilentToObservers(true); this.implied = new TaskCharSet(param2); super.setSilentToObservers(false); } public NonDeclareConstraint(TaskChar param1, TaskChar param2, TaskChar param3) { super(param1, param2, param3); super.setSilentToObservers(true); this.implied = new TaskCharSet(param2); super.setSilentToObservers(false); } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((implied == null) ? 0 : implied.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (getClass() != obj.getClass()) return false; NonDeclareConstraint other = (NonDeclareConstraint) obj; if (implied == null) { if (other.implied != null) return false; } else if (!implied.equals(other.implied)) return false; return true; } @Override public int compareTo(Constraint o) { int result = super.compareTo(o); if (result == 0) { if (o instanceof NonDeclareConstraint) { NonDeclareConstraint other = (NonDeclareConstraint) o; result = this.getFamily().compareTo(other.getFamily()); if (result == 0) { result = this.getSubFamily().compareTo(other.getSubFamily()); if (result == 0) { result = this.getImplicationVerse().compareTo(other.getImplicationVerse()); if (result == 0) { result = this.getTemplateName().compareTo(other.getTemplateName()); if (result != 0) { if (this.getClass().isInstance(o)) { result = -1; } else if (o.getClass().isInstance(this)) { result = +1; } else { result = 0; } } } } } } else { result = 1; } } return result; } @Override public ConstraintFamily getFamily() { return ConstraintFamily.RELATION; } @SuppressWarnings("unchecked") @Override public RelationConstraintSubFamily getSubFamily() { return RelationConstraintSubFamily.NONE; } @Override public int getHierarchyLevel() { return super.getHierarchyLevel()+1; } public boolean regardsTheSameChars(NonDeclareConstraint relCon) { return this.base.equals(relCon.base) && this.implied.equals(relCon.implied); } @Override public TaskCharSet getImplied() { return this.implied; } @Override public String getRegularExpression() { return String.format(this.getRegularExpressionTemplate(), base.toPatternString(), implied.toPatternString()); } public abstract ConstraintImplicationVerse getImplicationVerse(); public boolean isActivationBranched() { return this.base.size() > 1 && this.implied.size() < 3; } public boolean isTargetBranched() { return this.implied.size() > 1 && this.base.size() < 3; } public boolean isBranchedBothWays() { return this.isActivationBranched() && this.isTargetBranched(); } public boolean hasActivationSetStrictlyIncludingTheOneOf(Constraint c) { return this.isActivationBranched() && this.base.strictlyIncludes(c.getBase()); } public boolean hasTargetSetStrictlyIncludingTheOneOf(Constraint c) { return this.isTargetBranched() && this.implied.strictlyIncludes(c.getImplied()); } @Override public boolean isDescendantAlongSameBranchOf(Constraint c) { if (super.isDescendantAlongSameBranchOf(c) == false) { return false; } if (!(c instanceof NonDeclareConstraint)) { return false; } NonDeclareConstraint relaCon = ((NonDeclareConstraint)c); return this.getImplicationVerse() == relaCon.getImplicationVerse() // FIXME This is a trick which could be inconsistent with possible model extensions || relaCon.getClass().equals(RespondedExistence.class); } @Override public boolean isTemplateDescendantAlongSameBranchOf(Constraint c) { if (super.isTemplateDescendantAlongSameBranchOf(c) == false) { return false; } if (!(c instanceof NonDeclareConstraint)) { return false; } NonDeclareConstraint relaCon = ((NonDeclareConstraint)c); return this.getImplicationVerse() == relaCon.getImplicationVerse() // FIXME This is a trick which could be inconsistent with possible model extensions || relaCon.getClass().equals(RespondedExistence.class); } @Override protected void afterUnmarshal(Unmarshaller unmarshaller, Object parent) { if (this.getFamily().equals(ConstraintFamily.RELATION)) { this.base = this.getParameters().get(0); this.implied = this.getParameters().get(1); } } @Override public String getRegularExpressionTemplate() { // TODO Auto-generated method stub return null; } @Override public Constraint suggestConstraintWhichThisShouldBeBasedUpon() { // TODO Auto-generated method stub return null; } @Override public boolean checkParams(TaskChar... taskChars) throws IllegalArgumentException { if (taskChars.length != 3) throw new IllegalArgumentException("Too many parameters"); return true; } @Override public boolean checkParams(TaskCharSet... taskCharSets) throws IllegalArgumentException { if (taskCharSets.length != 3) throw new IllegalArgumentException("Too many parameters"); return true; } /** * Returns the target parameter of this relation constraint. * @return The target parameter of this relation constraint. */ public TaskCharSet getTarget() { return this.getImplied(); } /** * Returns the activation parameter of this relation constraint. * @return The activation parameter of this relation constraint. */ public TaskCharSet getActivation() { return this.getBase(); } }
8,044
29.823755
119
java
Janus
Janus-master/src/minerful/concept/constraint/relation/AlternatePrecedence.java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package minerful.concept.constraint.relation; import javax.xml.bind.annotation.XmlRootElement; import dk.brics.automaton.Automaton; import minerful.concept.TaskChar; import minerful.concept.TaskCharSet; import minerful.concept.constraint.Constraint; import minerful.reactive.automaton.ConjunctAutomata; import minerful.reactive.automaton.SeparatedAutomaton; import minerful.reactive.automaton.Utils; import java.util.ArrayList; import java.util.List; @XmlRootElement public class AlternatePrecedence extends Precedence { @Override public String getRegularExpressionTemplate() { // return "[^%2$s]*(%1$s[^%2$s]*%2$s[^%2$s]*)*[^%2$s]*"; // return "[^%1$s]*([%2$s][^%1$s]*[%1$s])*[^%1$s]*"; return "[^%1$s]*([%2$s][^%1$s]*[%1$s][^%1$s]*)*[^%1$s]*"; } protected AlternatePrecedence() { super(); } public AlternatePrecedence(TaskChar param1, TaskChar param2) { super(param1, param2); } public AlternatePrecedence(TaskChar param1, TaskChar param2, double support) { super(param1, param2, support); } public AlternatePrecedence(TaskCharSet param1, TaskCharSet param2, double support) { super(param1, param2, support); } public AlternatePrecedence(TaskCharSet param1, TaskCharSet param2) { super(param1, param2); } @Override public int getHierarchyLevel() { return super.getHierarchyLevel() + 1; } @Override public Constraint suggestConstraintWhichThisShouldBeBasedUpon() { return new Precedence(implied, base); } @Override public Constraint copy(TaskChar... taskChars) { super.checkParams(taskChars); return new AlternatePrecedence(taskChars[0], taskChars[1]); } @Override public Constraint copy(TaskCharSet... taskCharSets) { super.checkParams(taskCharSets); return new AlternatePrecedence(taskCharSets[0], taskCharSets[1]); } @Override public SeparatedAutomaton buildParametricSeparatedAutomaton() { char[] alphabet = {'a', 'b', 'z'}; char[] alphabetOthers = {alphabet[0], alphabet[2]}; Automaton activator = Utils.getSingleCharActivatorAutomaton(alphabet[1], alphabetOthers); List<ConjunctAutomata> disjunctAutomata = new ArrayList<ConjunctAutomata>(); char[] others = {alphabet[2]}; Automaton pastAutomaton = Utils.getReversedNextNegativeUntilAutomaton(alphabet[1], alphabet[0], others); ConjunctAutomata conjunctAutomaton = new ConjunctAutomata(pastAutomaton, null, null); disjunctAutomata.add(conjunctAutomaton); SeparatedAutomaton res = new SeparatedAutomaton(activator, disjunctAutomata, alphabet); res.setNominalID(this.type); return res; } }
2,679
29.804598
106
java
Janus
Janus-master/src/minerful/concept/constraint/relation/AlternateResponse.java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package minerful.concept.constraint.relation; import javax.xml.bind.annotation.XmlRootElement; import dk.brics.automaton.Automaton; import minerful.concept.TaskChar; import minerful.concept.TaskCharSet; import minerful.concept.constraint.Constraint; import minerful.reactive.automaton.ConjunctAutomata; import minerful.reactive.automaton.SeparatedAutomaton; import minerful.reactive.automaton.Utils; import java.util.ArrayList; import java.util.List; @XmlRootElement public class AlternateResponse extends Response { @Override public String getRegularExpressionTemplate() { return "[^%1$s]*([%1$s][^%1$s]*[%2$s][^%1$s]*)*[^%1$s]*"; } protected AlternateResponse() { super(); } public AlternateResponse(TaskChar param1, TaskChar param2) { super(param1, param2); } public AlternateResponse(TaskChar param1, TaskChar param2, double support) { super(param1, param2, support); } public AlternateResponse(TaskCharSet param1, TaskCharSet param2, double support) { super(param1, param2, support); } public AlternateResponse(TaskCharSet param1, TaskCharSet param2) { super(param1, param2); } @Override public int getHierarchyLevel() { return super.getHierarchyLevel() + 1; } @Override public Constraint suggestConstraintWhichThisShouldBeBasedUpon() { return new Response(base, implied); } @Override public Constraint copy(TaskChar... taskChars) { super.checkParams(taskChars); return new AlternateResponse(taskChars[0], taskChars[1]); } @Override public Constraint copy(TaskCharSet... taskCharSets) { super.checkParams(taskCharSets); return new AlternateResponse(taskCharSets[0], taskCharSets[1]); } @Override public SeparatedAutomaton buildParametricSeparatedAutomaton() { char[] alphabet = {'a', 'b', 'z'}; char[] alphabetOthers = {alphabet[1], alphabet[2]}; Automaton activator = Utils.getSingleCharActivatorAutomaton(alphabet[0], alphabetOthers); List<ConjunctAutomata> disjunctAutomata = new ArrayList<ConjunctAutomata>(); char[] others = {alphabet[2]}; Automaton futureAutomaton = Utils.getNextNegativeUntilAutomaton(alphabet[0], alphabet[1], others); ConjunctAutomata conjunctAutomaton = new ConjunctAutomata(null, null, futureAutomaton); disjunctAutomata.add(conjunctAutomaton); SeparatedAutomaton res = new SeparatedAutomaton(activator, disjunctAutomata, alphabet); res.setNominalID(this.type); return res; } }
2,545
28.264368
100
java
Janus
Janus-master/src/minerful/concept/constraint/relation/AlternateSuccession.java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package minerful.concept.constraint.relation; import javax.xml.bind.annotation.XmlRootElement; import dk.brics.automaton.Automaton; import minerful.concept.TaskChar; import minerful.concept.TaskCharSet; import minerful.concept.constraint.Constraint; import minerful.reactive.automaton.ConjunctAutomata; import minerful.reactive.automaton.SeparatedAutomaton; import minerful.reactive.automaton.Utils; import java.util.ArrayList; import java.util.List; @XmlRootElement public class AlternateSuccession extends Succession { @Override public String getRegularExpressionTemplate() { return "[^%1$s%2$s]*([%1$s][^%1$s%2$s]*[%2$s][^%1$s%2$s]*)*[^%1$s%2$s]*"; } protected AlternateSuccession() { super(); } public AlternateSuccession(RespondedExistence forwardConstraint, RespondedExistence backwardConstraint, double support) { super(forwardConstraint, backwardConstraint, support); } public AlternateSuccession(RespondedExistence forwardConstraint, RespondedExistence backwardConstraint) { super(forwardConstraint, backwardConstraint); } public AlternateSuccession(TaskChar param1, TaskChar param2) { super(param1, param2); } public AlternateSuccession(TaskChar param1, TaskChar param2, double support) { super(param1, param2, support); } public AlternateSuccession(TaskCharSet param1, TaskCharSet param2, double support) { super(param1, param2, support); } public AlternateSuccession(TaskCharSet param1, TaskCharSet param2) { super(param1, param2); } @Override public int getHierarchyLevel() { return super.getHierarchyLevel() + 1; } @Override public Constraint suggestConstraintWhichThisShouldBeBasedUpon() { return new Succession(base, implied); } @Override public AlternateResponse getPossibleForwardConstraint() { return new AlternateResponse(base, implied); } @Override public AlternatePrecedence getPossibleBackwardConstraint() { return new AlternatePrecedence(base, implied); } @Override public Constraint copy(TaskChar... taskChars) { super.checkParams(taskChars); return new AlternateSuccession(taskChars[0], taskChars[1]); } @Override public Constraint copy(TaskCharSet... taskCharSets) { super.checkParams(taskCharSets); return new AlternateSuccession(taskCharSets[0], taskCharSets[1]); } @Override public SeparatedAutomaton buildParametricSeparatedAutomaton() { char[] alphabet = {'a', 'b', 'z'}; char[] alphabetActivators = {alphabet[0], alphabet[1]}; char[] alphabetOthers = {alphabet[2]}; Automaton activator = Utils.getMultiCharActivatorAutomaton(alphabetActivators, alphabetOthers); List<ConjunctAutomata> disjunctAutomata = new ArrayList<ConjunctAutomata>(); // B & not B since in the past A char[] others_0 = {alphabet[2]}; // B Z char[] others_0p = {alphabet[0], alphabet[2]}; // B Z Automaton presentAutomaton_0 = Utils.getPresentAutomaton(alphabet[1], others_0p); // now B Automaton pastAutomaton_0 = Utils.getReversedNextNegativeUntilAutomaton(alphabet[1], alphabet[0], others_0); // eventually past A ConjunctAutomata conjunctAutomatonPast_0 = new ConjunctAutomata(pastAutomaton_0, presentAutomaton_0, null); disjunctAutomata.add(conjunctAutomatonPast_0); // A & not A until in the future B char[] others_1 = {alphabet[2]}; // A Z char[] others_1p = {alphabet[1], alphabet[2]}; // A Z Automaton presentAutomaton_1 = Utils.getPresentAutomaton(alphabet[0], others_1p); // now A Automaton futureAutomaton_1 = Utils.getNextNegativeUntilAutomaton(alphabet[0], alphabet[1] ,others_1); // eventually future B ConjunctAutomata conjunctAutomatonFut_1 = new ConjunctAutomata(null, presentAutomaton_1, futureAutomaton_1); disjunctAutomata.add(conjunctAutomatonFut_1); SeparatedAutomaton res = new SeparatedAutomaton(activator, disjunctAutomata, alphabet); res.setNominalID(this.type); return res; } }
4,162
34.887931
138
java
Janus
Janus-master/src/minerful/concept/constraint/relation/ChainPrecedence.java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package minerful.concept.constraint.relation; import javax.xml.bind.annotation.XmlRootElement; import dk.brics.automaton.Automaton; import minerful.concept.TaskChar; import minerful.concept.TaskCharSet; import minerful.concept.constraint.Constraint; import minerful.reactive.automaton.ConjunctAutomata; import minerful.reactive.automaton.SeparatedAutomaton; import minerful.reactive.automaton.Utils; import java.util.ArrayList; import java.util.List; @XmlRootElement public class ChainPrecedence extends AlternatePrecedence { @Override public String getRegularExpressionTemplate() { // return "[^%2$s]*(%1$s%2$s[^%2$s]*)*[^%2$s]*"; return "[^%1$s]*([%2$s][%1$s][^%1$s]*)*[^%1$s]*"; } protected ChainPrecedence() { super(); } public ChainPrecedence(TaskChar param1, TaskChar param2) { super(param1, param2); } public ChainPrecedence(TaskChar param1, TaskChar param2, double support) { super(param1, param2, support); } public ChainPrecedence(TaskCharSet param1, TaskCharSet param2, double support) { super(param1, param2, support); } public ChainPrecedence(TaskCharSet param1, TaskCharSet param2) { super(param1, param2); } @Override public int getHierarchyLevel() { return super.getHierarchyLevel() + 1; } @Override public Constraint suggestConstraintWhichThisShouldBeBasedUpon() { return new AlternatePrecedence(implied, base); } @Override public Constraint copy(TaskChar... taskChars) { super.checkParams(taskChars); return new ChainPrecedence(taskChars[0], taskChars[1]); } @Override public Constraint copy(TaskCharSet... taskCharSets) { super.checkParams(taskCharSets); return new ChainPrecedence(taskCharSets[0], taskCharSets[1]); } @Override public SeparatedAutomaton buildParametricSeparatedAutomaton() { char[] alphabet = {'a', 'b', 'z'}; char[] alphabetOthers = {alphabet[0], alphabet[2]}; Automaton activator = Utils.getSingleCharActivatorAutomaton(alphabet[1], alphabetOthers); List<ConjunctAutomata> disjunctAutomata = new ArrayList<ConjunctAutomata>(); char[] others = {alphabet[1],alphabet[2]}; Automaton pastAutomaton = Utils.getReversedNextAutomaton(alphabet[0], others); ConjunctAutomata conjunctAutomaton = new ConjunctAutomata(pastAutomaton, null, null); disjunctAutomata.add(conjunctAutomaton); SeparatedAutomaton res = new SeparatedAutomaton(activator, disjunctAutomata, alphabet); res.setNominalID(this.type); return res; } }
2,583
29.046512
91
java
Janus
Janus-master/src/minerful/concept/constraint/relation/ChainResponse.java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package minerful.concept.constraint.relation; import javax.xml.bind.annotation.XmlRootElement; import dk.brics.automaton.Automaton; import minerful.concept.TaskChar; import minerful.concept.TaskCharSet; import minerful.concept.constraint.Constraint; import minerful.reactive.automaton.ConjunctAutomata; import minerful.reactive.automaton.SeparatedAutomaton; import minerful.reactive.automaton.Utils; import java.util.ArrayList; import java.util.List; @XmlRootElement public class ChainResponse extends AlternateResponse { @Override public String getRegularExpressionTemplate() { return "[^%1$s]*([%1$s][%2$s][^%1$s]*)*[^%1$s]*"; } protected ChainResponse() { super(); } public ChainResponse(TaskChar param1, TaskChar param2) { super(param1, param2); } public ChainResponse(TaskChar param1, TaskChar param2, double support) { super(param1, param2, support); } public ChainResponse(TaskCharSet param1, TaskCharSet param2, double support) { super(param1, param2, support); } public ChainResponse(TaskCharSet param1, TaskCharSet param2) { super(param1, param2); } @Override public int getHierarchyLevel() { return super.getHierarchyLevel() + 1; } @Override public Constraint suggestConstraintWhichThisShouldBeBasedUpon() { return new AlternateResponse(base, implied); } @Override public Constraint copy(TaskChar... taskChars) { super.checkParams(taskChars); return new ChainResponse(taskChars[0], taskChars[1]); } @Override public Constraint copy(TaskCharSet... taskCharSets) { super.checkParams(taskCharSets); return new ChainResponse(taskCharSets[0], taskCharSets[1]); } @Override public SeparatedAutomaton buildParametricSeparatedAutomaton() { char[] alphabet = {'a', 'b', 'z'}; char[] alphabetOthers = {alphabet[1], alphabet[2]}; Automaton activator = Utils.getSingleCharActivatorAutomaton(alphabet[0], alphabetOthers); List<ConjunctAutomata> disjunctAutomata = new ArrayList<ConjunctAutomata>(); char[] others = {alphabet[0], alphabet[2]}; Automaton futureAutomaton = Utils.getNextAutomaton(alphabet[1], others); ConjunctAutomata conjunctAutomaton = new ConjunctAutomata(null, null, futureAutomaton); disjunctAutomata.add(conjunctAutomaton); SeparatedAutomaton res = new SeparatedAutomaton(activator, disjunctAutomata, alphabet); res.setNominalID(this.type); return res; } }
2,466
27.686047
91
java
Janus
Janus-master/src/minerful/concept/constraint/relation/ChainSuccession.java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package minerful.concept.constraint.relation; import javax.xml.bind.annotation.XmlRootElement; import dk.brics.automaton.Automaton; import minerful.concept.TaskChar; import minerful.concept.TaskCharSet; import minerful.concept.constraint.Constraint; import minerful.reactive.automaton.ConjunctAutomata; import minerful.reactive.automaton.SeparatedAutomaton; import minerful.reactive.automaton.Utils; import java.util.ArrayList; import java.util.List; @XmlRootElement public class ChainSuccession extends AlternateSuccession { @Override public String getRegularExpressionTemplate() { return "[^%1$s%2$s]*([%1$s][%2$s][^%1$s%2$s]*)*[^%1$s%2$s]*"; } protected ChainSuccession() { super(); } public ChainSuccession(RespondedExistence forwardConstraint, RespondedExistence backwardConstraint) { super(forwardConstraint, backwardConstraint); } public ChainSuccession(RespondedExistence forwardConstraint, RespondedExistence backwardConstraint, double support) { super(forwardConstraint, backwardConstraint, support); } public ChainSuccession(TaskChar param1, TaskChar param2) { super(param1, param2); } public ChainSuccession(TaskChar param1, TaskChar param2, double support) { super(param1, param2, support); } public ChainSuccession(TaskCharSet param1, TaskCharSet param2, double support) { super(param1, param2, support); } public ChainSuccession(TaskCharSet param1, TaskCharSet param2) { super(param1, param2); } @Override public int getHierarchyLevel() { return super.getHierarchyLevel()+1; } @Override public Constraint suggestConstraintWhichThisShouldBeBasedUpon() { return new AlternateSuccession(base, implied); } @Override public ChainResponse getPossibleForwardConstraint() { return new ChainResponse(base, implied); } @Override public ChainPrecedence getPossibleBackwardConstraint() { return new ChainPrecedence(base, implied); } @Override public Constraint copy(TaskChar... taskChars) { super.checkParams(taskChars); return new ChainSuccession(taskChars[0], taskChars[1]); } @Override public Constraint copy(TaskCharSet... taskCharSets) { super.checkParams(taskCharSets); return new ChainSuccession(taskCharSets[0], taskCharSets[1]); } @Override public SeparatedAutomaton buildParametricSeparatedAutomaton() { char[] alphabet = {'a', 'b', 'z'}; char[] alphabetActivators = {alphabet[0], alphabet[1]}; char[] alphabetOthers = {alphabet[2]}; Automaton activator = Utils.getMultiCharActivatorAutomaton(alphabetActivators, alphabetOthers); List<ConjunctAutomata> disjunctAutomata = new ArrayList<ConjunctAutomata>(); // B & previous A char[] others_0 = {alphabet[1], alphabet[2]}; // B Z char[] others_0p = {alphabet[0], alphabet[2]}; Automaton presentAutomaton_0 = Utils.getPresentAutomaton(alphabet[1], others_0p); // now B Automaton pastAutomaton_0 = Utils.getReversedNextAutomaton(alphabet[0], others_0); ConjunctAutomata conjunctAutomatonPast_0 = new ConjunctAutomata(pastAutomaton_0, presentAutomaton_0, null); disjunctAutomata.add(conjunctAutomatonPast_0); // A & next B char[] others_1 = {alphabet[0], alphabet[2]}; // A Z char[] others_1p = {alphabet[1], alphabet[2]}; Automaton presentAutomaton_1 = Utils.getPresentAutomaton(alphabet[0], others_1p); // now A Automaton futureAutomaton_1 = Utils.getNextAutomaton(alphabet[1] ,others_1); ConjunctAutomata conjunctAutomatonFut_1 = new ConjunctAutomata(null, presentAutomaton_1, futureAutomaton_1); disjunctAutomata.add(conjunctAutomatonFut_1); SeparatedAutomaton res = new SeparatedAutomaton(activator, disjunctAutomata, alphabet); res.setNominalID(this.type); return res; } }
3,835
32.649123
121
java
Janus
Janus-master/src/minerful/concept/constraint/relation/CoExistence.java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package minerful.concept.constraint.relation; import javax.xml.bind.annotation.XmlRootElement; import dk.brics.automaton.Automaton; import minerful.concept.TaskChar; import minerful.concept.TaskCharSet; import minerful.concept.constraint.Constraint; import minerful.reactive.automaton.ConjunctAutomata; import minerful.reactive.automaton.SeparatedAutomaton; import minerful.reactive.automaton.Utils; import java.util.ArrayList; import java.util.List; @XmlRootElement public class CoExistence extends MutualRelationConstraint { @Override public String getRegularExpressionTemplate() { return "[^%1$s%2$s]*(([%1$s].*[%2$s].*)|([%2$s].*[%1$s].*))*[^%1$s%2$s]*"; } protected CoExistence() { super(); } public CoExistence(RespondedExistence forwardConstraint, RespondedExistence backwardConstraint, double support) { this(forwardConstraint.getBase(), forwardConstraint.getImplied(), support); if (!this.ckeckConsistency(forwardConstraint, backwardConstraint)) { throw new IllegalArgumentException("Illegal constraints combination: provided " + forwardConstraint + " and " + backwardConstraint + " resp. as forward and backward constraints of " + this); } this.forwardConstraint = forwardConstraint; this.backwardConstraint = backwardConstraint; } public CoExistence(RespondedExistence forwardConstraint, RespondedExistence backwardConstraint) { this(forwardConstraint.getBase(), forwardConstraint.getImplied()); this.forwardConstraint = forwardConstraint; this.backwardConstraint = backwardConstraint; } public CoExistence(TaskCharSet param1, TaskCharSet param2, double support) { super(param1, param2, support); } public CoExistence(TaskCharSet param1, TaskCharSet param2) { super(param1, param2); } public CoExistence(TaskChar param1, TaskChar param2, double support) { super(param1, param2, support); } public CoExistence(TaskChar param1, TaskChar param2) { super(param1, param2); } @Override public Constraint suggestConstraintWhichThisShouldBeBasedUpon() { return null; } @Override public RespondedExistence getPossibleForwardConstraint() { return new RespondedExistence(base, implied); } @Override public RespondedExistence getPossibleBackwardConstraint() { return new RespondedExistence(implied, base); } @Override public Constraint copy(TaskChar... taskChars) { super.checkParams(taskChars); return new CoExistence(taskChars[0], taskChars[1]); } @Override public Constraint copy(TaskCharSet... taskCharSets) { super.checkParams(taskCharSets); return new CoExistence(taskCharSets[0], taskCharSets[1]); } @Override public SeparatedAutomaton buildParametricSeparatedAutomaton() { char[] alphabet = {'a', 'b', 'z'}; char[] alphabetActivators = {alphabet[0], alphabet[1]}; char[] alphabetOthers = {alphabet[2]}; Automaton activator = Utils.getMultiCharActivatorAutomaton(alphabetActivators, alphabetOthers); List<ConjunctAutomata> disjunctAutomata = new ArrayList<ConjunctAutomata>(); char[] others_0 = {alphabet[1], alphabet[2]}; // B Z char[] others_1 = {alphabet[0], alphabet[2]}; //A Z Automaton presentAutomaton_0 = Utils.getPresentAutomaton(alphabet[0], others_0); // now A Automaton presentAutomaton_1 = Utils.getPresentAutomaton(alphabet[1], others_1); // now B Automaton futureAutomaton_0 = Utils.getEventualityAutomaton(alphabet[0], others_0); // eventually future A Automaton futureAutomaton_1 = Utils.getEventualityAutomaton(alphabet[1], others_1); // eventually future B Automaton pastAutomaton_0 = Utils.getEventualityAutomaton(alphabet[0], others_0); // eventually past A Automaton pastAutomaton_1 = Utils.getEventualityAutomaton(alphabet[1], others_1); // eventually past B // A & Eventually in the future B ConjunctAutomata conjunctAutomatonFut_0 = new ConjunctAutomata(null, presentAutomaton_0, futureAutomaton_1); disjunctAutomata.add(conjunctAutomatonFut_0); // A & Eventually in the past B ConjunctAutomata conjunctAutomatonPast_0 = new ConjunctAutomata(pastAutomaton_1, presentAutomaton_0, null); disjunctAutomata.add(conjunctAutomatonPast_0); // B & Eventually in the future A ConjunctAutomata conjunctAutomatonFut_1 = new ConjunctAutomata(null, presentAutomaton_1, futureAutomaton_0); disjunctAutomata.add(conjunctAutomatonFut_1); // B & Eventually in the past A ConjunctAutomata conjunctAutomatonPast_1 = new ConjunctAutomata(pastAutomaton_0, presentAutomaton_1, null); disjunctAutomata.add(conjunctAutomatonPast_1); SeparatedAutomaton res = new SeparatedAutomaton(activator, disjunctAutomata, alphabet); res.setNominalID(this.type); return res; } }
5,150
38.320611
202
java
Janus
Janus-master/src/minerful/concept/constraint/relation/MutualRelationConstraint.java
package minerful.concept.constraint.relation; import java.util.ArrayList; import java.util.Arrays; import javax.xml.bind.annotation.XmlSeeAlso; import javax.xml.bind.annotation.XmlTransient; import javax.xml.bind.annotation.XmlType; import minerful.concept.TaskChar; import minerful.concept.TaskCharSet; import minerful.concept.constraint.Constraint; import minerful.concept.constraint.ConstraintFamily.ConstraintImplicationVerse; import minerful.concept.constraint.ConstraintFamily.RelationConstraintSubFamily; @XmlType @XmlSeeAlso({CoExistence.class}) public abstract class MutualRelationConstraint extends RelationConstraint { @XmlTransient protected RelationConstraint forwardConstraint; @XmlTransient protected RelationConstraint backwardConstraint; public MutualRelationConstraint() { super(); } public MutualRelationConstraint(TaskCharSet param1, TaskCharSet param2, double support) { super(param1, param2, support); } public MutualRelationConstraint(TaskCharSet param1, TaskCharSet param2) { super(param1, param2); } public MutualRelationConstraint(TaskChar param1, TaskChar param2, double support) { super(param1, param2, support); } public MutualRelationConstraint(TaskChar param1, TaskChar param2) { super(param1, param2); } @Override public ConstraintImplicationVerse getImplicationVerse() { return ConstraintImplicationVerse.BOTH; } @Override public RelationConstraintSubFamily getSubFamily() { return RelationConstraintSubFamily.COUPLING; } @Override public int getHierarchyLevel() { return super.getHierarchyLevel() + 1; } public RelationConstraint getForwardConstraint() { return forwardConstraint; } public RelationConstraint getBackwardConstraint() { return backwardConstraint; } public boolean hasForwardConstraint() { return forwardConstraint != null; } public boolean hasBackwardConstraint() { return backwardConstraint != null; } public void setImplyingConstraints(RelationConstraint forwardConstraint, RelationConstraint backwardConstraint) { this.forwardConstraint = forwardConstraint; this.backwardConstraint = backwardConstraint; } public boolean isAsInformativeAsTheImplyingConstraints() { return this.support >= forwardConstraint.getSupport() && this.support >= backwardConstraint.getSupport(); } public boolean isMoreInformativeThanAnyOfImplyingConstraints() { return this.support >= forwardConstraint.getSupport() || this.support >= backwardConstraint.getSupport(); } public boolean isMoreInformativeThanForwardConstraint() { return this.support >= forwardConstraint.getSupport(); } public boolean isMoreInformativeThanBackwardConstraints() { return this.support >= backwardConstraint.getSupport(); } protected boolean ckeckConsistency(RelationConstraint forwardConstraint, RelationConstraint backwardConstraint) { return forwardConstraint.getParameters().containsAll(backwardConstraint.getParameters()) && backwardConstraint.getParameters().containsAll(forwardConstraint.getParameters()) && this.getHierarchyLevel() == forwardConstraint.getHierarchyLevel() && this.getHierarchyLevel() == backwardConstraint.getHierarchyLevel(); } public boolean hasImplyingConstraints() { return this.forwardConstraint != null && this.backwardConstraint != null; } public void setForwardConstraint(RelationConstraint forwardConstraint) { this.forwardConstraint = forwardConstraint; } public void setBackwardConstraint(RelationConstraint backwardConstraint) { this.backwardConstraint = backwardConstraint; } public RelationConstraint getPossibleForwardConstraint() { if (this.hasForwardConstraint()) return this.getForwardConstraint(); return null; } public RelationConstraint getPossibleBackwardConstraint() { if (this.hasBackwardConstraint()) return this.getBackwardConstraint(); return null; } @Override public Constraint[] suggestImpliedConstraints() { Constraint[] impliCons = null; Constraint[] inheritedImpliCons = super.suggestImpliedConstraints(); int i = 0; if (inheritedImpliCons != null) { impliCons = new Constraint[inheritedImpliCons.length + 2]; for (Constraint impliCon : inheritedImpliCons) { impliCons[i++] = impliCon; } } else { impliCons = new Constraint[2]; } impliCons[i++] = getPossibleForwardConstraint(); impliCons[i++] = getPossibleBackwardConstraint(); return impliCons; } }
4,504
28.834437
114
java
Janus
Janus-master/src/minerful/concept/constraint/relation/NegativeRelationConstraint.java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package minerful.concept.constraint.relation; import javax.xml.bind.annotation.XmlSeeAlso; import javax.xml.bind.annotation.XmlTransient; import minerful.concept.TaskChar; import minerful.concept.TaskCharSet; import minerful.concept.constraint.Constraint; import minerful.concept.constraint.ConstraintFamily.ConstraintImplicationVerse; import minerful.concept.constraint.ConstraintFamily.RelationConstraintSubFamily; @XmlSeeAlso({NotChainSuccession.class,NotSuccession.class,NotCoExistence.class}) public abstract class NegativeRelationConstraint extends RelationConstraint { @XmlTransient protected RelationConstraint opponent; protected NegativeRelationConstraint() { super(); } public NegativeRelationConstraint(TaskChar param1, TaskChar param2, double support) { super(param1, param2, support); } public NegativeRelationConstraint(TaskChar param1, TaskChar param2) { super(param1, param2); } public NegativeRelationConstraint(TaskCharSet param1, TaskCharSet param2, double support) { super(param1, param2, support); } public NegativeRelationConstraint(TaskCharSet param1, TaskCharSet param2) { super(param1, param2); } @Override public ConstraintImplicationVerse getImplicationVerse() { return ConstraintImplicationVerse.BOTH; } @Override public RelationConstraintSubFamily getSubFamily() { return RelationConstraintSubFamily.NEGATIVE; } @Override public int getHierarchyLevel() { return super.getHierarchyLevel()+1; } protected void setOpponent(RelationConstraint opposedTo, Class<?> expectedClass) { if (!opposedTo.getClass().equals(expectedClass)) throw new IllegalArgumentException("Illegal opponent constraint"); this.opponent = opposedTo; } public boolean isMoreReliableThanTheOpponent() { if (!this.hasOpponent()) throw new IllegalStateException("No opponent constraint is set"); return this.support > opponent.getSupport(); } public boolean hasOpponent() { return this.opponent != null; } public RelationConstraint getOpponent() { return opponent; } public void setOpponent(RelationConstraint opponent) { this.opponent = opponent; } public abstract Constraint getSupposedOpponentConstraint(); }
2,456
29.7125
89
java
Janus
Janus-master/src/minerful/concept/constraint/relation/NotChainSuccession.java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package minerful.concept.constraint.relation; import javax.xml.bind.annotation.XmlRootElement; import dk.brics.automaton.Automaton; import minerful.concept.TaskChar; import minerful.concept.TaskCharSet; import minerful.concept.constraint.Constraint; import minerful.reactive.automaton.ConjunctAutomata; import minerful.reactive.automaton.SeparatedAutomaton; import minerful.reactive.automaton.Utils; import java.util.ArrayList; import java.util.List; @XmlRootElement public class NotChainSuccession extends NegativeRelationConstraint { @Override public String getRegularExpressionTemplate() { // return "[^%1$s]*([%1$s][%1$s]*[^%1$s%2$s][^%1$s]*)*([^%1$s]*|[%1$s])"; return "[^%1$s]*([%1$s][%1$s]*[^%1$s%2$s][^%1$s]*)*([^%1$s]*|[%1$s]*)"; } protected NotChainSuccession() { super(); } public NotChainSuccession(TaskChar param1, TaskChar param2, double support) { super(param1, param2, support); } public NotChainSuccession(TaskChar param1, TaskChar param2) { super(param1, param2); } public NotChainSuccession(TaskCharSet param1, TaskCharSet param2, double support) { super(param1, param2, support); } public NotChainSuccession(TaskCharSet param1, TaskCharSet param2) { super(param1, param2); } @Override public int getHierarchyLevel() { return super.getHierarchyLevel()+1; } public void setOpposedTo(RelationConstraint opposedTo) { super.setOpponent(opposedTo, ChainSuccession.class); } @Override public Constraint suggestConstraintWhichThisShouldBeBasedUpon() { return null; } @Override public Constraint getSupposedOpponentConstraint() { return new ChainSuccession(base, implied); } @Override public Constraint copy(TaskChar... taskChars) { super.checkParams(taskChars); return new NotChainSuccession(taskChars[0], taskChars[1]); } @Override public Constraint copy(TaskCharSet... taskCharSets) { super.checkParams(taskCharSets); return new NotChainSuccession(taskCharSets[0], taskCharSets[1]); } // @Override // public SeparatedAutomaton buildParametricSeparatedAutomaton() { // char[] alphabet = {'a', 'b', 'z'}; // char[] alphabetActivators = {alphabet[0], alphabet[1]}; // char[] alphabetOthers = {alphabet[2]}; // Automaton activator = Utils.getMultiCharActivatorAutomaton(alphabetActivators, alphabetOthers); // // List<ConjunctAutomata> disjunctAutomata = new ArrayList<ConjunctAutomata>(); // // char[] others_0 = {alphabet[1], alphabet[2]}; // B Z // char[] others_1 = {alphabet[0], alphabet[2]}; // A Z // // Automaton presentAutomaton_0 = Utils.getPresentAutomaton(alphabet[0], others_0); // now A // Automaton presentAutomaton_1 = Utils.getPresentAutomaton(alphabet[1], others_1); // now B // Automaton futureAutomaton_1 = Utils.getNegativeNextAutomaton(alphabet[1], others_1); // not next B // Automaton pastAutomaton_0 = Utils.getNegativeReversedNextAutomaton(alphabet[0], others_0); // not previous A // //// A & not eventually in the future B // ConjunctAutomata conjunctAutomatonFut_0 = new ConjunctAutomata(null, presentAutomaton_0, futureAutomaton_1); // disjunctAutomata.add(conjunctAutomatonFut_0); // //// B & not eventually in the past A // ConjunctAutomata conjunctAutomatonPast_1 = new ConjunctAutomata(pastAutomaton_0, presentAutomaton_1, null); // disjunctAutomata.add(conjunctAutomatonPast_1); // // SeparatedAutomaton res = new SeparatedAutomaton(activator, disjunctAutomata, alphabet); // res.setNominalID(this.type); // return res; // } }
3,645
33.074766
113
java
Janus
Janus-master/src/minerful/concept/constraint/relation/NotCoExistence.java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package minerful.concept.constraint.relation; import javax.xml.bind.annotation.XmlRootElement; import dk.brics.automaton.Automaton; import minerful.concept.TaskChar; import minerful.concept.TaskCharSet; import minerful.concept.constraint.Constraint; import minerful.reactive.automaton.ConjunctAutomata; import minerful.reactive.automaton.SeparatedAutomaton; import minerful.reactive.automaton.Utils; import java.util.ArrayList; import java.util.List; @XmlRootElement public class NotCoExistence extends NotSuccession { @Override public String getRegularExpressionTemplate() { return "[^%1$s%2$s]*(([%1$s][^%2$s]*)|([%2$s][^%1$s]*))?"; } protected NotCoExistence() { super(); } public NotCoExistence(TaskChar param1, TaskChar param2, double support) { super(param1, param2, support); } public NotCoExistence(TaskChar param1, TaskChar param2) { super(param1, param2); } public NotCoExistence(TaskCharSet param1, TaskCharSet param2, double support) { super(param1, param2, support); } public NotCoExistence(TaskCharSet param1, TaskCharSet param2) { super(param1, param2); } @Override public int getHierarchyLevel() { return super.getHierarchyLevel() + 1; } @Override public void setOpposedTo(RelationConstraint opposedTo) { super.setOpponent(opposedTo, CoExistence.class); } @Override public Constraint suggestConstraintWhichThisShouldBeBasedUpon() { return new NotSuccession(base, implied); } @Override public Constraint getSupposedOpponentConstraint() { return new CoExistence(base, implied); } @Override public Constraint copy(TaskChar... taskChars) { super.checkParams(taskChars); return new NotCoExistence(taskChars[0], taskChars[1]); } @Override public Constraint copy(TaskCharSet... taskCharSets) { super.checkParams(taskCharSets); return new NotCoExistence(taskCharSets[0], taskCharSets[1]); } @Override public SeparatedAutomaton buildParametricSeparatedAutomaton() { char[] alphabet = {'a', 'b', 'z'}; char[] alphabetActivators = {alphabet[0], alphabet[1]}; char[] alphabetOthers = {alphabet[2]}; Automaton activator = Utils.getMultiCharActivatorAutomaton(alphabetActivators, alphabetOthers); List<ConjunctAutomata> disjunctAutomata = new ArrayList<ConjunctAutomata>(); char[] others_0 = {alphabet[1], alphabet[2]}; // B Z char[] others_1 = {alphabet[0], alphabet[2]}; //A Z Automaton presentAutomaton_0 = Utils.getPresentAutomaton(alphabet[0], others_0); // now A Automaton presentAutomaton_1 = Utils.getPresentAutomaton(alphabet[1], others_1); // now B Automaton futureAutomaton_0 = Utils.getNegativeEventualityAutomaton(alphabet[0], others_0); // not eventually future A Automaton futureAutomaton_1 = Utils.getNegativeEventualityAutomaton(alphabet[1], others_1); // not eventually future B Automaton pastAutomaton_0 = Utils.getNegativeEventualityAutomaton(alphabet[0], others_0); // not eventually past A Automaton pastAutomaton_1 = Utils.getNegativeEventualityAutomaton(alphabet[1], others_1); // not eventually past B // A & Not Eventually in the future & past B ConjunctAutomata conjunctAutomaton_0 = new ConjunctAutomata(pastAutomaton_1, presentAutomaton_0, futureAutomaton_1); disjunctAutomata.add(conjunctAutomaton_0); // B & Not Eventually in the past & future A ConjunctAutomata conjunctAutomaton_1 = new ConjunctAutomata(pastAutomaton_0, presentAutomaton_1, futureAutomaton_0); disjunctAutomata.add(conjunctAutomaton_1); SeparatedAutomaton res = new SeparatedAutomaton(activator, disjunctAutomata, alphabet); res.setNominalID(this.type); return res; } }
4,024
34.619469
126
java
Janus
Janus-master/src/minerful/concept/constraint/relation/NotSuccession.java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package minerful.concept.constraint.relation; import javax.xml.bind.annotation.XmlRootElement; import dk.brics.automaton.Automaton; import minerful.concept.TaskChar; import minerful.concept.TaskCharSet; import minerful.concept.constraint.Constraint; import minerful.reactive.automaton.ConjunctAutomata; import minerful.reactive.automaton.SeparatedAutomaton; import minerful.reactive.automaton.Utils; import java.util.ArrayList; import java.util.List; @XmlRootElement public class NotSuccession extends NotChainSuccession { @Override public String getRegularExpressionTemplate() { return "[^%1$s]*([%1$s][^%2$s]*)*[^%1$s%2$s]*"; } protected NotSuccession() { super(); } public NotSuccession(TaskChar param1, TaskChar param2) { super(param1, param2); } public NotSuccession(TaskChar param1, TaskChar param2, double support) { super(param1, param2, support); } public NotSuccession(TaskCharSet param1, TaskCharSet param2, double support) { super(param1, param2, support); } public NotSuccession(TaskCharSet param1, TaskCharSet param2) { super(param1, param2); } @Override public int getHierarchyLevel() { return super.getHierarchyLevel()+1; } @Override public void setOpposedTo(RelationConstraint opposedTo) { super.setOpponent(opposedTo, Succession.class); } @Override public Constraint suggestConstraintWhichThisShouldBeBasedUpon() { return new NotChainSuccession(base, implied); } @Override public Constraint getSupposedOpponentConstraint() { return new Succession(base, implied); } @Override public Constraint copy(TaskChar... taskChars) { super.checkParams(taskChars); return new NotSuccession(taskChars[0], taskChars[1]); } @Override public Constraint copy(TaskCharSet... taskCharSets) { super.checkParams(taskCharSets); return new NotSuccession(taskCharSets[0], taskCharSets[1]); } @Override public SeparatedAutomaton buildParametricSeparatedAutomaton() { char[] alphabet = {'a', 'b', 'z'}; char[] alphabetActivators = {alphabet[0], alphabet[1]}; char[] alphabetOthers = {alphabet[2]}; Automaton activator = Utils.getMultiCharActivatorAutomaton(alphabetActivators, alphabetOthers); List<ConjunctAutomata> disjunctAutomata = new ArrayList<ConjunctAutomata>(); char[] others_0 = {alphabet[1], alphabet[2]}; // B Z char[] others_1 = {alphabet[0], alphabet[2]}; // A Z Automaton presentAutomaton_0 = Utils.getPresentAutomaton(alphabet[0], others_0); // now A Automaton presentAutomaton_1 = Utils.getPresentAutomaton(alphabet[1], others_1); // now B Automaton futureAutomaton_1 = Utils.getNegativeEventualityAutomaton(alphabet[1], others_1); // not eventually future B Automaton pastAutomaton_0 = Utils.getReversedNextNegativeEventualityAutomaton(alphabet[0], others_0); // not eventually past A // A & not eventually in the future B ConjunctAutomata conjunctAutomatonFut_0 = new ConjunctAutomata(null, presentAutomaton_0, futureAutomaton_1); disjunctAutomata.add(conjunctAutomatonFut_0); // B & not eventually in the past A ConjunctAutomata conjunctAutomatonPast_1 = new ConjunctAutomata(pastAutomaton_0, presentAutomaton_1, null); disjunctAutomata.add(conjunctAutomatonPast_1); SeparatedAutomaton res = new SeparatedAutomaton(activator, disjunctAutomata, alphabet); res.setNominalID(this.type); return res; } }
3,495
31.672897
129
java
Janus
Janus-master/src/minerful/concept/constraint/relation/Precedence.java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package minerful.concept.constraint.relation; import java.util.ArrayList; import java.util.Collections; import java.util.List; import javax.xml.bind.Unmarshaller; import javax.xml.bind.annotation.XmlRootElement; import dk.brics.automaton.Automaton; import minerful.concept.TaskChar; import minerful.concept.TaskCharSet; import minerful.concept.constraint.Constraint; import minerful.concept.constraint.ConstraintFamily; import minerful.concept.constraint.ConstraintFamily.ConstraintImplicationVerse; import minerful.reactive.automaton.ConjunctAutomata; import minerful.reactive.automaton.SeparatedAutomaton; import minerful.reactive.automaton.Utils; @XmlRootElement public class Precedence extends RespondedExistence { @Override public String getRegularExpressionTemplate() { return "[^%1$s]*([%2$s].*[%1$s])*[^%1$s]*"; } protected Precedence() { super(); } public Precedence(TaskChar param1, TaskChar param2) { super(param2, param1); this.invertOrderOfParams(); } public Precedence(TaskChar param1, TaskChar param2, double support) { super(param2, param1, support); this.invertOrderOfParams(); } public Precedence(TaskCharSet param1, TaskCharSet param2, double support) { super(param2, param1, support); this.invertOrderOfParams(); } public Precedence(TaskCharSet param1, TaskCharSet param2) { super(param2, param1); this.invertOrderOfParams(); } protected void invertOrderOfParams() { Collections.reverse(this.parameters); } @Override public ConstraintImplicationVerse getImplicationVerse() { return ConstraintImplicationVerse.BACKWARD; } @Override public int getHierarchyLevel() { return super.getHierarchyLevel() + 1; } @Override public Integer getMaximumExpectedDistance() { if (this.isExpectedDistanceConfidenceIntervalProvided()) return (int) Math.min(-1, StrictMath.round(expectedDistance + confidenceIntervalMargin)); return null; } @Override public Constraint suggestConstraintWhichThisShouldBeBasedUpon() { return new RespondedExistence(base, implied); } @Override protected void afterUnmarshal(Unmarshaller unmarshaller, Object parent) { if (this.getFamily().equals(ConstraintFamily.RELATION)) { this.base = this.getParameters().get(1); this.implied = this.getParameters().get(0); } } @Override public Constraint copy(TaskChar... taskChars) { super.checkParams(taskChars); return new Precedence(taskChars[0], taskChars[1]); } @Override public Constraint copy(TaskCharSet... taskCharSets) { super.checkParams(taskCharSets); return new Precedence(taskCharSets[0], taskCharSets[1]); } @Override public SeparatedAutomaton buildParametricSeparatedAutomaton() { char[] alphabet = {'a', 'b', 'z'}; char[] alphabetOthers = {alphabet[0], alphabet[2]}; Automaton activator = Utils.getSingleCharActivatorAutomaton(alphabet[1], alphabetOthers); List<ConjunctAutomata> disjunctAutomata = new ArrayList<ConjunctAutomata>(); char[] others = {alphabet[1], alphabet[2]}; Automaton pastAutomaton = Utils.getEventualityAutomaton(alphabet[0], others); ConjunctAutomata conjunctAutomaton = new ConjunctAutomata(pastAutomaton, null, null); disjunctAutomata.add(conjunctAutomaton); SeparatedAutomaton res = new SeparatedAutomaton(activator, disjunctAutomata, alphabet); res.setNominalID(this.type); return res; } }
3,440
27.675
92
java
Janus
Janus-master/src/minerful/concept/constraint/relation/RelationConstraint.java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package minerful.concept.constraint.relation; import javax.xml.bind.Unmarshaller; import javax.xml.bind.annotation.XmlIDREF; import javax.xml.bind.annotation.XmlSeeAlso; import javax.xml.bind.annotation.XmlType; import minerful.concept.TaskChar; import minerful.concept.TaskCharSet; import minerful.concept.constraint.Constraint; import minerful.concept.constraint.ConstraintFamily; import minerful.concept.constraint.ConstraintFamily.ConstraintImplicationVerse; import minerful.concept.constraint.ConstraintFamily.RelationConstraintSubFamily; @XmlType @XmlSeeAlso({MutualRelationConstraint.class,NegativeRelationConstraint.class,UnidirectionalRelationConstraint.class}) public abstract class RelationConstraint extends Constraint { public static enum ImplicationVerse { FORWARD, BACKWARD, BOTH } @XmlIDREF // @XmlTransient protected TaskCharSet implied; protected RelationConstraint() { super(); // implied = null; } public RelationConstraint(TaskCharSet param1, TaskCharSet param2, double support) { super(support, param1, param2); super.setSilentToObservers(true); this.implied = param2; super.setSilentToObservers(false); } public RelationConstraint(TaskCharSet param1, TaskCharSet param2) { super(param1, param2); super.setSilentToObservers(true); this.implied = param2; super.setSilentToObservers(false); } public RelationConstraint(TaskChar param1, TaskChar param2, double support) { super(support, param1, param2); super.setSilentToObservers(true); this.implied = new TaskCharSet(param2); super.setSilentToObservers(false); } public RelationConstraint(TaskChar param1, TaskChar param2) { super(param1, param2); super.setSilentToObservers(true); this.implied = new TaskCharSet(param2); super.setSilentToObservers(false); } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((implied == null) ? 0 : implied.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (getClass() != obj.getClass()) return false; RelationConstraint other = (RelationConstraint) obj; if (implied == null) { if (other.implied != null) return false; } else if (!implied.equals(other.implied)) return false; return true; } @Override public int compareTo(Constraint o) { int result = super.compareTo(o); if (result == 0) { if (o instanceof RelationConstraint) { RelationConstraint other = (RelationConstraint) o; result = this.getFamily().compareTo(other.getFamily()); if (result == 0) { result = this.getSubFamily().compareTo(other.getSubFamily()); if (result == 0) { result = this.getImplicationVerse().compareTo(other.getImplicationVerse()); if (result == 0) { result = this.getTemplateName().compareTo(other.getTemplateName()); if (result != 0) { if (this.getClass().isInstance(o)) { result = -1; } else if (o.getClass().isInstance(this)) { result = +1; } else { result = 0; } } } } } } else { result = 1; } } return result; } @Override public ConstraintFamily getFamily() { return ConstraintFamily.RELATION; } @SuppressWarnings("unchecked") @Override public RelationConstraintSubFamily getSubFamily() { return RelationConstraintSubFamily.NONE; } @Override public int getHierarchyLevel() { return super.getHierarchyLevel()+1; } public boolean regardsTheSameChars(RelationConstraint relCon) { return this.base.equals(relCon.base) && this.implied.equals(relCon.implied); } @Override public TaskCharSet getImplied() { return this.implied; } @Override public String getRegularExpression() { return String.format(this.getRegularExpressionTemplate(), base.toPatternString(), implied.toPatternString()); } public abstract ConstraintImplicationVerse getImplicationVerse(); public boolean isActivationBranched() { return this.base.size() > 1 && this.implied.size() < 2; } public boolean isTargetBranched() { return this.implied.size() > 1 && this.base.size() < 2; } public boolean isBranchedBothWays() { return this.isActivationBranched() && this.isTargetBranched(); } public boolean hasActivationSetStrictlyIncludingTheOneOf(Constraint c) { return this.isActivationBranched() && this.base.strictlyIncludes(c.getBase()); } public boolean hasTargetSetStrictlyIncludingTheOneOf(Constraint c) { return this.isTargetBranched() && this.implied.strictlyIncludes(c.getImplied()); } @Override public boolean isDescendantAlongSameBranchOf(Constraint c) { if (super.isDescendantAlongSameBranchOf(c) == false) { return false; } if (!(c instanceof RelationConstraint)) { return false; } RelationConstraint relaCon = ((RelationConstraint)c); return this.getImplicationVerse() == relaCon.getImplicationVerse() // FIXME This is a trick which could be inconsistent with possible model extensions || relaCon.getClass().equals(RespondedExistence.class); } @Override public boolean isTemplateDescendantAlongSameBranchOf(Constraint c) { if (super.isTemplateDescendantAlongSameBranchOf(c) == false) { return false; } if (!(c instanceof RelationConstraint)) { return false; } RelationConstraint relaCon = ((RelationConstraint)c); return this.getImplicationVerse() == relaCon.getImplicationVerse() // FIXME This is a trick which could be inconsistent with possible model extensions || relaCon.getClass().equals(RespondedExistence.class); } @Override protected void afterUnmarshal(Unmarshaller unmarshaller, Object parent) { if (this.getFamily().equals(ConstraintFamily.RELATION)) { this.base = this.getParameters().get(0); this.implied = this.getParameters().get(1); } } @Override public String getRegularExpressionTemplate() { // TODO Auto-generated method stub return null; } @Override public Constraint suggestConstraintWhichThisShouldBeBasedUpon() { // TODO Auto-generated method stub return null; } @Override public boolean checkParams(TaskChar... taskChars) throws IllegalArgumentException { if (taskChars.length != 2) throw new IllegalArgumentException("Too many parameters"); return true; } @Override public boolean checkParams(TaskCharSet... taskCharSets) throws IllegalArgumentException { if (taskCharSets.length != 2) throw new IllegalArgumentException("Too many parameters"); return true; } /** * Returns the target parameter of this relation constraint. * @return The target parameter of this relation constraint. */ public TaskCharSet getTarget() { return this.getImplied(); } /** * Returns the activation parameter of this relation constraint. * @return The activation parameter of this relation constraint. */ public TaskCharSet getActivation() { return this.getBase(); } }
7,666
28.832685
117
java
Janus
Janus-master/src/minerful/concept/constraint/relation/RespondedExistence.java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package minerful.concept.constraint.relation; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlTransient; import dk.brics.automaton.Automaton; import minerful.concept.TaskChar; import minerful.concept.TaskCharSet; import minerful.concept.constraint.Constraint; import minerful.concept.constraint.ConstraintFamily.ConstraintImplicationVerse; import minerful.concept.constraint.ConstraintFamily.RelationConstraintSubFamily; import minerful.reactive.automaton.ConjunctAutomata; import minerful.reactive.automaton.SeparatedAutomaton; import minerful.reactive.automaton.Utils; import java.util.ArrayList; import java.util.List; @XmlRootElement public class RespondedExistence extends RelationConstraint { public static final String DISTANCE_PRINT_TEMPLATE = " <%+d \u00F7 %+d> "; @XmlTransient public Double expectedDistance; @XmlTransient public Double confidenceIntervalMargin; @Override public String getRegularExpressionTemplate() { return "[^%1$s]*(([%1$s].*[%2$s].*)|([%2$s].*[%1$s].*))*[^%1$s]*"; } protected RespondedExistence() { super(); } public RespondedExistence(TaskChar param1, TaskChar param2) { super(param1, param2); } public RespondedExistence(TaskChar param1, TaskChar param2, double support) { super(param1, param2, support); } public RespondedExistence(TaskCharSet param1, TaskCharSet param2, double support) { super(param1, param2, support); } public RespondedExistence(TaskCharSet param1, TaskCharSet param2) { super(param1, param2); } @Override public int getHierarchyLevel() { return super.getHierarchyLevel()+1; } public boolean isExpectedDistanceConfidenceIntervalProvided() { return expectedDistance != null && confidenceIntervalMargin != null; } @Override public ConstraintImplicationVerse getImplicationVerse() { return ConstraintImplicationVerse.FORWARD; } @Override public RelationConstraintSubFamily getSubFamily() { return RelationConstraintSubFamily.SINGLE_ACTIVATION; } @Override public String toString() { if (isExpectedDistanceConfidenceIntervalProvided()) { return super.toString().replace(", ", printDistances()); } return super.toString(); } protected String printDistances() { return String.format(RespondedExistence.DISTANCE_PRINT_TEMPLATE, getMinimumExpectedDistance(), getMaximumExpectedDistance()); } public Integer getMinimumExpectedDistance() { if (this.isExpectedDistanceConfidenceIntervalProvided()) return (int)StrictMath.round(expectedDistance - confidenceIntervalMargin); return null; } public Integer getMaximumExpectedDistance() { if (this.isExpectedDistanceConfidenceIntervalProvided()) return (int)StrictMath.round(expectedDistance + confidenceIntervalMargin); return null; } @Override public Constraint suggestConstraintWhichThisShouldBeBasedUpon() { return null; } @Override public Constraint copy(TaskChar... taskChars) { super.checkParams(taskChars); return new RespondedExistence(taskChars[0], taskChars[1]); } @Override public Constraint copy(TaskCharSet... taskCharSets) { super.checkParams(taskCharSets); return new RespondedExistence(taskCharSets[0], taskCharSets[1]); } @Override public SeparatedAutomaton buildParametricSeparatedAutomaton() { char[] alphabet = {'a', 'b', 'z'}; char[] alphabetOthers = {alphabet[1], alphabet[2]}; Automaton activator = Utils.getSingleCharActivatorAutomaton(alphabet[0], alphabetOthers); List<ConjunctAutomata> disjunctAutomata = new ArrayList<ConjunctAutomata>(); char[] others = {alphabet[0], alphabet[2]}; // Eventually in the future B Automaton futureAutomaton = Utils.getEventualityAutomaton(alphabet[1], others); ConjunctAutomata conjunctAutomatonFut = new ConjunctAutomata(null, null, futureAutomaton); disjunctAutomata.add(conjunctAutomatonFut); // Eventually in the past B Automaton pastAutomaton = Utils.getEventualityAutomaton(alphabet[1], others); ConjunctAutomata conjunctAutomatonPast = new ConjunctAutomata(pastAutomaton, null, null); disjunctAutomata.add(conjunctAutomatonPast); SeparatedAutomaton res = new SeparatedAutomaton(activator, disjunctAutomata, alphabet); res.setNominalID(this.type); return res; } }
4,524
31.321429
92
java
Janus
Janus-master/src/minerful/concept/constraint/relation/Response.java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package minerful.concept.constraint.relation; import javax.xml.bind.annotation.XmlRootElement; import dk.brics.automaton.Automaton; import minerful.concept.TaskChar; import minerful.concept.TaskCharSet; import minerful.concept.constraint.Constraint; import minerful.concept.constraint.ConstraintFamily.ConstraintImplicationVerse; import minerful.reactive.automaton.ConjunctAutomata; import minerful.reactive.automaton.SeparatedAutomaton; import minerful.reactive.automaton.Utils; import java.util.ArrayList; import java.util.List; @XmlRootElement public class Response extends RespondedExistence { @Override public String getRegularExpressionTemplate() { return "[^%1$s]*([%1$s].*[%2$s])*[^%1$s]*"; // [^a]*(a.*b)*[^a]* } protected Response() { super(); } public Response(TaskChar param1, TaskChar param2) { super(param1, param2); } public Response(TaskChar param1, TaskChar param2, double support) { super(param1, param2, support); } public Response(TaskCharSet param1, TaskCharSet param2, double support) { super(param1, param2, support); } public Response(TaskCharSet param1, TaskCharSet param2) { super(param1, param2); } @Override public ConstraintImplicationVerse getImplicationVerse() { return ConstraintImplicationVerse.FORWARD; } @Override public int getHierarchyLevel() { return super.getHierarchyLevel()+1; } @Override public Integer getMinimumExpectedDistance() { if (this.isExpectedDistanceConfidenceIntervalProvided()) return (int)Math.max(1, StrictMath.round(expectedDistance - confidenceIntervalMargin)); return null; } @Override public Constraint suggestConstraintWhichThisShouldBeBasedUpon() { return new RespondedExistence(base, implied); } @Override public Constraint copy(TaskChar... taskChars) { super.checkParams(taskChars); return new Response(taskChars[0], taskChars[1]); } @Override public Constraint copy(TaskCharSet... taskCharSets) { super.checkParams(taskCharSets); return new Response(taskCharSets[0], taskCharSets[1]); } @Override public SeparatedAutomaton buildParametricSeparatedAutomaton() { char[] alphabet = {'a', 'b', 'z'}; char[] alphabetOthers = {alphabet[1], alphabet[2]}; Automaton activator = Utils.getSingleCharActivatorAutomaton(alphabet[0], alphabetOthers); List<ConjunctAutomata> disjunctAutomata = new ArrayList<ConjunctAutomata>(); char[] others = {alphabet[0], alphabet[2]}; Automaton futureAutomaton = Utils.getEventualityAutomaton(alphabet[1], others); ConjunctAutomata conjunctAutomaton = new ConjunctAutomata(null, null, futureAutomaton); disjunctAutomata.add(conjunctAutomaton); SeparatedAutomaton res = new SeparatedAutomaton(activator, disjunctAutomata, alphabet); res.setNominalID(this.type); return res; } }
2,974
29.050505
93
java
Janus
Janus-master/src/minerful/concept/constraint/relation/Succession.java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package minerful.concept.constraint.relation; import javax.xml.bind.annotation.XmlRootElement; import dk.brics.automaton.Automaton; import minerful.concept.TaskChar; import minerful.concept.TaskCharSet; import minerful.concept.constraint.Constraint; import minerful.reactive.automaton.ConjunctAutomata; import minerful.reactive.automaton.SeparatedAutomaton; import minerful.reactive.automaton.Utils; import java.util.ArrayList; import java.util.List; @XmlRootElement public class Succession extends CoExistence { @Override public String getRegularExpressionTemplate() { return "[^%1$s%2$s]*([%1$s].*[%2$s])*[^%1$s%2$s]*"; } protected Succession() { super(); } public Succession(RespondedExistence forwardConstraint, RespondedExistence backwardConstraint) { super(forwardConstraint, backwardConstraint); } public Succession(RespondedExistence forwardConstraint, RespondedExistence backwardConstraint, double support) { super(forwardConstraint, backwardConstraint, support); } public Succession(TaskChar param1, TaskChar param2) { super(param1, param2); } public Succession(TaskChar param1, TaskChar param2, double support) { super(param1, param2, support); } public Succession(TaskCharSet param1, TaskCharSet param2, double support) { super(param1, param2, support); } public Succession(TaskCharSet param1, TaskCharSet param2) { super(param1, param2); } @Override public int getHierarchyLevel() { return super.getHierarchyLevel()+1; } @Override protected boolean ckeckConsistency( RelationConstraint forwardConstraint, RelationConstraint backwardConstraint) { return super.ckeckConsistency(forwardConstraint, backwardConstraint); } @Override public Constraint suggestConstraintWhichThisShouldBeBasedUpon() { return new CoExistence(base, implied); } @Override public Response getPossibleForwardConstraint() { return new Response(base, implied); } @Override public Precedence getPossibleBackwardConstraint() { return new Precedence(base, implied); } @Override public Constraint copy(TaskChar... taskChars) { super.checkParams(taskChars); return new Succession(taskChars[0], taskChars[1]); } @Override public Constraint copy(TaskCharSet... taskCharSets) { super.checkParams(taskCharSets); return new Succession(taskCharSets[0], taskCharSets[1]); } @Override public SeparatedAutomaton buildParametricSeparatedAutomaton() { char[] alphabet = {'a', 'b', 'z'}; char[] alphabetActivators = {alphabet[0], alphabet[1]}; char[] alphabetOthers = {alphabet[2]}; Automaton activator = Utils.getMultiCharActivatorAutomaton(alphabetActivators, alphabetOthers); List<ConjunctAutomata> disjunctAutomata = new ArrayList<ConjunctAutomata>(); char[] others_0 = {alphabet[1], alphabet[2]}; // B Z char[] others_1 = {alphabet[0], alphabet[2]}; // A Z Automaton presentAutomaton_0 = Utils.getPresentAutomaton(alphabet[0], others_0); // now A Automaton presentAutomaton_1 = Utils.getPresentAutomaton(alphabet[1], others_1); // now B Automaton futureAutomaton_1 = Utils.getEventualityAutomaton(alphabet[1], others_1); // eventually future B Automaton pastAutomaton_0 = Utils.getEventualityAutomaton(alphabet[0], others_0); // eventually past A // A & eventually in the future B ConjunctAutomata conjunctAutomatonFut_0 = new ConjunctAutomata(null, presentAutomaton_0, futureAutomaton_1); disjunctAutomata.add(conjunctAutomatonFut_0); // B & eventually in the past A ConjunctAutomata conjunctAutomatonPast_1 = new ConjunctAutomata(pastAutomaton_0, presentAutomaton_1, null); disjunctAutomata.add(conjunctAutomatonPast_1); SeparatedAutomaton res = new SeparatedAutomaton(activator, disjunctAutomata, alphabet); res.setNominalID(this.type); return res; } }
4,079
33.285714
116
java
Janus
Janus-master/src/minerful/concept/constraint/relation/UnidirectionalRelationConstraint.java
package minerful.concept.constraint.relation; public abstract class UnidirectionalRelationConstraint extends RelationConstraint { }
133
25.8
83
java
Janus
Janus-master/src/minerful/concept/constraint/xmlenc/ConstraintsBagAdapter.java
package minerful.concept.constraint.xmlenc; import javax.xml.bind.annotation.adapters.XmlAdapter; import minerful.concept.constraint.ConstraintsBag; public class ConstraintsBagAdapter extends XmlAdapter<ConstraintsBagDto, ConstraintsBag>{ @Override public ConstraintsBag unmarshal(ConstraintsBagDto v) throws Exception { return v.toConstraintsBag(); } @Override public ConstraintsBagDto marshal(ConstraintsBag v) throws Exception { return new ConstraintsBagDto(v); } }
484
24.526316
89
java
Janus
Janus-master/src/minerful/concept/constraint/xmlenc/ConstraintsBagDto.java
package minerful.concept.constraint.xmlenc; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElementRef; import javax.xml.bind.annotation.XmlRootElement; import minerful.concept.constraint.Constraint; import minerful.concept.constraint.ConstraintsBag; @XmlRootElement(name="constraintsSet") @XmlAccessorType(XmlAccessType.FIELD) public class ConstraintsBagDto { @XmlElementRef(required=true) public List<Constraint> constraints; public ConstraintsBagDto() { this.constraints = new ArrayList<Constraint>(); } public ConstraintsBagDto(ConstraintsBag bag) { this.constraints = new ArrayList<Constraint>(bag.howManyConstraints()); this.constraints.addAll(bag.getAllConstraints()); } public ConstraintsBag toConstraintsBag() { ConstraintsBag bag = new ConstraintsBag(); for (Constraint cns : constraints) { cns.setParameters(cns.getParameters()); bag.add(cns.getBase(), cns); } return bag; } }
1,061
27.702703
73
java
Janus
Janus-master/src/minerful/concept/constraint/xmlenc/ConstraintsBagMapAdapter.java
package minerful.concept.constraint.xmlenc; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlElements; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.adapters.XmlAdapter; import minerful.concept.TaskChar; import minerful.concept.constraint.Constraint; public class ConstraintsBagMapAdapter extends XmlAdapter<ConstraintsBagMapAdapter.KeyValueList, Map<TaskChar, Set<Constraint>>> { @XmlType(name="distances") @XmlAccessorType(XmlAccessType.FIELD) public static class KeyValueList { @XmlType(name="distance") @XmlAccessorType(XmlAccessType.FIELD) public static class Item { @XmlElement(name="at") public TaskChar key; public Set<Constraint> value; public Item(TaskChar key, Set<Constraint> value) { this.key = key; this.value = value; } public Item() { } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("Item [key="); builder.append(key); builder.append(", value="); builder.append(value); builder.append("]"); return builder.toString(); } } @XmlElements({ @XmlElement(name="constraints") }) public final List<Item> list; public KeyValueList() { this.list = new ArrayList<ConstraintsBagMapAdapter.KeyValueList.Item>(); } public KeyValueList(List<Item> list) { this.list = list; } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("KeyValueList [list="); builder.append(list); builder.append("]"); return builder.toString(); } } @Override public KeyValueList marshal( Map<TaskChar, Set<Constraint>> v) throws Exception { Set<TaskChar> keys = v.keySet(); ArrayList<ConstraintsBagMapAdapter.KeyValueList.Item> results = new ArrayList<ConstraintsBagMapAdapter.KeyValueList.Item>(v.size()); for (TaskChar key : keys) { results.add(new ConstraintsBagMapAdapter.KeyValueList.Item(key, v.get(key))); } return new ConstraintsBagMapAdapter.KeyValueList(results); } @Override public Map<TaskChar, Set<Constraint>> unmarshal( KeyValueList v) throws Exception { Map<TaskChar, Set<Constraint>> repetitionsMap = new HashMap<TaskChar, Set<Constraint>>(v.list.size()); for (ConstraintsBagMapAdapter.KeyValueList.Item item : v.list) { repetitionsMap.put(item.key, item.value); } return repetitionsMap; } }
2,663
28.6
134
java