List of usage examples for java.util Deque removeLast
E removeLast();
From source file:Main.java
public static void main(String[] args) { Deque<Integer> deque = new ArrayDeque<Integer>(8); deque.add(15);//from ww w . ja v a 2 s . c o m deque.add(30); deque.add(25); deque.add(40); System.out.println(deque); // this will remove element at last position int retval = deque.removeLast(); System.out.println("Element removed is: " + retval); System.out.println(deque); }
From source file:com.willwinder.universalgcodesender.utils.Settings.java
private static void updateRecent(Deque<String> stack, int maxSize, String element) { stack.remove(element);/*w w w . jav a 2 s.com*/ stack.push(element); while (stack.size() > maxSize) stack.removeLast(); }
From source file:ivorius.ivtoolkit.maze.components.MazeComponentConnector.java
public static <M extends WeightedMazeComponent<C>, C> List<ShiftedMazeComponent<M, C>> randomlyConnect( MorphingMazeComponent<C> morphingComponent, List<M> components, ConnectionStrategy<C> connectionStrategy, final MazeComponentPlacementStrategy<M, C> placementStrategy, Random random) {//from w w w . j a v a2 s. c o m List<ShiftedMazeComponent<M, C>> result = new ArrayList<>(); Deque<Triple<MazeRoom, MazeRoomConnection, C>> exitStack = new ArrayDeque<>(); Predicate<ShiftedMazeComponent<M, C>> componentPredicate = Predicates.and( MazeComponents.<M, C>compatibilityPredicate(morphingComponent, connectionStrategy), MazeComponentPlacementStrategies.placeable(placementStrategy)); WeightedSelector.WeightFunction<ShiftedMazeComponent<M, C>> weightFunction = getWeightFunction(); addAllExits(placementStrategy, exitStack, morphingComponent.exits().entrySet()); while (exitStack.size() > 0) { Triple<MazeRoom, MazeRoomConnection, C> triple = exitStack.removeLast(); MazeRoom room = triple.getLeft(); if (morphingComponent.rooms().contains(room)) continue; // Has been filled while queued MazeRoomConnection exit = triple.getMiddle(); C connection = triple.getRight(); List<ShiftedMazeComponent<M, C>> placeable = FluentIterable.from(components) .transformAndConcat(MazeComponents.<M, C>shiftAllFunction(exit, connection, connectionStrategy)) .filter(componentPredicate).toList(); if (placeable.size() == 0) { IvToolkitCoreContainer.logger.warn("Did not find fitting component for maze!"); IvToolkitCoreContainer.logger.warn("Suggested: X with exits " + FluentIterable.from(morphingComponent.exits().entrySet()).filter(entryConnectsTo(room))); continue; } ShiftedMazeComponent<M, C> selected = WeightedSelector.canSelect(placeable, weightFunction) ? WeightedSelector.select(random, placeable, weightFunction) : placeable.get(random.nextInt(placeable.size())); // All weight 0 = select at random addAllExits(placementStrategy, exitStack, selected.exits().entrySet()); morphingComponent.add(selected); result.add(selected); } return result; }
From source file:com.linuxbox.enkive.message.MultiPartHeaderImpl.java
@Override public void generateAttachmentSummaries(List<AttachmentSummary> result, Deque<Integer> positionsAbove) { int counter = 1; for (ContentHeader header : getPartHeaders()) { positionsAbove.addLast(counter); header.generateAttachmentSummaries(result, positionsAbove); positionsAbove.removeLast(); ++counter;/*from www. j ava 2 s .c o m*/ } }
From source file:com.espertech.esper.epl.spec.PatternStreamSpecRaw.java
private static void recursiveCompile(EvalFactoryNode evalNode, StatementContext context, ExprEvaluatorContext evaluatorContext, Set<String> eventTypeReferences, boolean isInsertInto, MatchEventSpec tags, Deque<Integer> subexpressionIdStack, Stack<EvalFactoryNode> parentNodeStack, LinkedHashSet<String> allTagNamesOrdered) throws ExprValidationException { int counter = 0; parentNodeStack.push(evalNode);//from w ww . j av a2s . c om for (EvalFactoryNode child : evalNode.getChildNodes()) { subexpressionIdStack.addLast(counter++); recursiveCompile(child, context, evaluatorContext, eventTypeReferences, isInsertInto, tags, subexpressionIdStack, parentNodeStack, allTagNamesOrdered); subexpressionIdStack.removeLast(); } parentNodeStack.pop(); LinkedHashMap<String, Pair<EventType, String>> newTaggedEventTypes = null; LinkedHashMap<String, Pair<EventType, String>> newArrayEventTypes = null; if (evalNode instanceof EvalFilterFactoryNode) { EvalFilterFactoryNode filterNode = (EvalFilterFactoryNode) evalNode; String eventName = filterNode.getRawFilterSpec().getEventTypeName(); EventType resolvedEventType = FilterStreamSpecRaw.resolveType(context.getEngineURI(), eventName, context.getEventAdapterService(), context.getPlugInTypeResolutionURIs()); EventType finalEventType = resolvedEventType; String optionalTag = filterNode.getEventAsName(); boolean isPropertyEvaluation = false; boolean isParentMatchUntil = isParentMatchUntil(evalNode, parentNodeStack); // obtain property event type, if final event type is properties if (filterNode.getRawFilterSpec().getOptionalPropertyEvalSpec() != null) { PropertyEvaluator optionalPropertyEvaluator = PropertyEvaluatorFactory.makeEvaluator( filterNode.getRawFilterSpec().getOptionalPropertyEvalSpec(), resolvedEventType, filterNode.getEventAsName(), context.getEventAdapterService(), context.getMethodResolutionService(), context.getSchedulingService(), context.getVariableService(), context.getEngineURI(), context.getStatementId(), context.getStatementName(), context.getAnnotations(), subexpressionIdStack, context.getConfigSnapshot()); finalEventType = optionalPropertyEvaluator.getFragmentEventType(); isPropertyEvaluation = true; } if (finalEventType instanceof EventTypeSPI) { eventTypeReferences.add(((EventTypeSPI) finalEventType).getMetadata().getPrimaryName()); } // If a tag was supplied for the type, the tags must stay with this type, i.e. a=BeanA -> b=BeanA -> a=BeanB is a no if (optionalTag != null) { Pair<EventType, String> pair = tags.getTaggedEventTypes().get(optionalTag); EventType existingType = null; if (pair != null) { existingType = pair.getFirst(); } if (existingType == null) { pair = tags.getArrayEventTypes().get(optionalTag); if (pair != null) { throw new ExprValidationException("Tag '" + optionalTag + "' for event '" + eventName + "' used in the repeat-until operator cannot also appear in other filter expressions"); } } if ((existingType != null) && (existingType != finalEventType)) { throw new ExprValidationException("Tag '" + optionalTag + "' for event '" + eventName + "' has already been declared for events of type " + existingType.getUnderlyingType().getName()); } pair = new Pair<EventType, String>(finalEventType, eventName); // add tagged type if (isPropertyEvaluation || isParentMatchUntil) { newArrayEventTypes = new LinkedHashMap<String, Pair<EventType, String>>(); newArrayEventTypes.put(optionalTag, pair); } else { newTaggedEventTypes = new LinkedHashMap<String, Pair<EventType, String>>(); newTaggedEventTypes.put(optionalTag, pair); } } // For this filter, filter types are all known tags at this time, // and additionally stream 0 (self) is our event type. // Stream type service allows resolution by property name event if that name appears in other tags. // by defaulting to stream zero. // Stream zero is always the current event type, all others follow the order of the map (stream 1 to N). String selfStreamName = optionalTag; if (selfStreamName == null) { selfStreamName = "s_" + UuidGenerator.generate(); } LinkedHashMap<String, Pair<EventType, String>> filterTypes = new LinkedHashMap<String, Pair<EventType, String>>(); Pair<EventType, String> typePair = new Pair<EventType, String>(finalEventType, eventName); filterTypes.put(selfStreamName, typePair); filterTypes.putAll(tags.getTaggedEventTypes()); // for the filter, specify all tags used LinkedHashMap<String, Pair<EventType, String>> filterTaggedEventTypes = new LinkedHashMap<String, Pair<EventType, String>>( tags.getTaggedEventTypes()); filterTaggedEventTypes.remove(optionalTag); // handle array tags (match-until clause) LinkedHashMap<String, Pair<EventType, String>> arrayCompositeEventTypes = null; if (tags.getArrayEventTypes() != null && !tags.getArrayEventTypes().isEmpty()) { arrayCompositeEventTypes = new LinkedHashMap<String, Pair<EventType, String>>(); String patternSubexEventType = getPatternSubexEventType(context.getStatementId(), "pattern", subexpressionIdStack); for (Map.Entry<String, Pair<EventType, String>> entry : tags.getArrayEventTypes().entrySet()) { LinkedHashMap<String, Pair<EventType, String>> specificArrayType = new LinkedHashMap<String, Pair<EventType, String>>(); specificArrayType.put(entry.getKey(), entry.getValue()); EventType arrayTagCompositeEventType = context.getEventAdapterService() .createSemiAnonymousMapType(patternSubexEventType, Collections.<String, Pair<EventType, String>>emptyMap(), specificArrayType, isInsertInto); String tag = entry.getKey(); if (!filterTypes.containsKey(tag)) { Pair<EventType, String> pair = new Pair<EventType, String>(arrayTagCompositeEventType, tag); filterTypes.put(tag, pair); arrayCompositeEventTypes.put(tag, pair); } } } StreamTypeService streamTypeService = new StreamTypeServiceImpl(filterTypes, context.getEngineURI(), true, false); List<ExprNode> exprNodes = filterNode.getRawFilterSpec().getFilterExpressions(); FilterSpecCompiled spec = FilterSpecCompiler.makeFilterSpec(resolvedEventType, eventName, exprNodes, filterNode.getRawFilterSpec().getOptionalPropertyEvalSpec(), filterTaggedEventTypes, arrayCompositeEventTypes, streamTypeService, null, context, subexpressionIdStack); filterNode.setFilterSpec(spec); } else if (evalNode instanceof EvalObserverFactoryNode) { EvalObserverFactoryNode observerNode = (EvalObserverFactoryNode) evalNode; try { ObserverFactory observerFactory = context.getPatternResolutionService() .create(observerNode.getPatternObserverSpec()); StreamTypeService streamTypeService = getStreamTypeService(context.getEngineURI(), context.getStatementId(), context.getEventAdapterService(), tags.getTaggedEventTypes(), tags.getArrayEventTypes(), subexpressionIdStack, "observer"); ExprValidationContext validationContext = new ExprValidationContext(streamTypeService, context.getMethodResolutionService(), null, context.getSchedulingService(), context.getVariableService(), evaluatorContext, context.getEventAdapterService(), context.getStatementName(), context.getStatementId(), context.getAnnotations(), context.getContextDescriptor()); List<ExprNode> validated = validateExpressions( observerNode.getPatternObserverSpec().getObjectParameters(), validationContext); MatchedEventConvertor convertor = new MatchedEventConvertorImpl(tags.getTaggedEventTypes(), tags.getArrayEventTypes(), allTagNamesOrdered, context.getEventAdapterService()); observerNode.setObserverFactory(observerFactory); observerFactory.setObserverParameters(validated, convertor); } catch (ObserverParameterException e) { throw new ExprValidationException("Invalid parameter for pattern observer: " + e.getMessage(), e); } catch (PatternObjectException e) { throw new ExprValidationException("Failed to resolve pattern observer: " + e.getMessage(), e); } } else if (evalNode instanceof EvalGuardFactoryNode) { EvalGuardFactoryNode guardNode = (EvalGuardFactoryNode) evalNode; try { GuardFactory guardFactory = context.getPatternResolutionService() .create(guardNode.getPatternGuardSpec()); StreamTypeService streamTypeService = getStreamTypeService(context.getEngineURI(), context.getStatementId(), context.getEventAdapterService(), tags.getTaggedEventTypes(), tags.getArrayEventTypes(), subexpressionIdStack, "guard"); ExprValidationContext validationContext = new ExprValidationContext(streamTypeService, context.getMethodResolutionService(), null, context.getSchedulingService(), context.getVariableService(), evaluatorContext, context.getEventAdapterService(), context.getStatementName(), context.getStatementId(), context.getAnnotations(), context.getContextDescriptor()); List<ExprNode> validated = validateExpressions( guardNode.getPatternGuardSpec().getObjectParameters(), validationContext); MatchedEventConvertor convertor = new MatchedEventConvertorImpl(tags.getTaggedEventTypes(), tags.getArrayEventTypes(), allTagNamesOrdered, context.getEventAdapterService()); guardNode.setGuardFactory(guardFactory); guardFactory.setGuardParameters(validated, convertor); } catch (GuardParameterException e) { throw new ExprValidationException("Invalid parameter for pattern guard: " + e.getMessage(), e); } catch (PatternObjectException e) { throw new ExprValidationException("Failed to resolve pattern guard: " + e.getMessage(), e); } } else if (evalNode instanceof EvalEveryDistinctFactoryNode) { EvalEveryDistinctFactoryNode distinctNode = (EvalEveryDistinctFactoryNode) evalNode; MatchEventSpec matchEventFromChildNodes = analyzeMatchEvent(distinctNode); StreamTypeService streamTypeService = getStreamTypeService(context.getEngineURI(), context.getStatementId(), context.getEventAdapterService(), matchEventFromChildNodes.getTaggedEventTypes(), matchEventFromChildNodes.getArrayEventTypes(), subexpressionIdStack, "every-distinct"); ExprValidationContext validationContext = new ExprValidationContext(streamTypeService, context.getMethodResolutionService(), null, context.getSchedulingService(), context.getVariableService(), evaluatorContext, context.getEventAdapterService(), context.getStatementName(), context.getStatementId(), context.getAnnotations(), context.getContextDescriptor()); List<ExprNode> validated; try { validated = validateExpressions(distinctNode.getExpressions(), validationContext); } catch (ExprValidationPropertyException ex) { throw new ExprValidationPropertyException(ex.getMessage() + ", every-distinct requires that all properties resolve from sub-expressions to the every-distinct", ex.getCause()); } MatchedEventConvertor convertor = new MatchedEventConvertorImpl( matchEventFromChildNodes.getTaggedEventTypes(), matchEventFromChildNodes.getArrayEventTypes(), allTagNamesOrdered, context.getEventAdapterService()); distinctNode.setConvertor(convertor); // Determine whether some expressions are constants or time period List<ExprNode> distinctExpressions = new ArrayList<ExprNode>(); Long msecToExpire = null; for (ExprNode expr : validated) { if (expr instanceof ExprTimePeriod) { Double secondsExpire = (Double) ((ExprTimePeriod) expr).evaluate(null, true, evaluatorContext); if ((secondsExpire != null) && (secondsExpire > 0)) { msecToExpire = Math.round(1000d * secondsExpire); } log.debug("Setting every-distinct msec-to-expire to " + msecToExpire); } else if (expr.isConstantResult()) { log.warn( "Every-distinct node utilizes an expression returning a constant value, please check expression '" + expr.toExpressionString() + "', not adding expression to distinct-value expression list"); } else { distinctExpressions.add(expr); } } if (distinctExpressions.isEmpty()) { throw new ExprValidationException( "Every-distinct node requires one or more distinct-value expressions that each return non-constant result values"); } distinctNode.setDistinctExpressions(distinctExpressions, msecToExpire); } else if (evalNode instanceof EvalMatchUntilFactoryNode) { EvalMatchUntilFactoryNode matchUntilNode = (EvalMatchUntilFactoryNode) evalNode; // compile bounds expressions, if any MatchEventSpec untilMatchEventSpec = new MatchEventSpec(tags.getTaggedEventTypes(), tags.getArrayEventTypes()); StreamTypeService streamTypeService = getStreamTypeService(context.getEngineURI(), context.getStatementId(), context.getEventAdapterService(), untilMatchEventSpec.getTaggedEventTypes(), untilMatchEventSpec.getArrayEventTypes(), subexpressionIdStack, "until"); ExprValidationContext validationContext = new ExprValidationContext(streamTypeService, context.getMethodResolutionService(), null, context.getSchedulingService(), context.getVariableService(), evaluatorContext, context.getEventAdapterService(), context.getStatementName(), context.getStatementId(), context.getAnnotations(), context.getContextDescriptor()); String message = "Match-until bounds value expressions must return a numeric value"; if (matchUntilNode.getLowerBounds() != null) { ExprNode validated = ExprNodeUtility.getValidatedSubtree(matchUntilNode.getLowerBounds(), validationContext); matchUntilNode.setLowerBounds(validated); if ((validated.getExprEvaluator().getType() == null) || (!JavaClassHelper.isNumeric(validated.getExprEvaluator().getType()))) { throw new ExprValidationException(message); } } if (matchUntilNode.getUpperBounds() != null) { ExprNode validated = ExprNodeUtility.getValidatedSubtree(matchUntilNode.getUpperBounds(), validationContext); matchUntilNode.setUpperBounds(validated); if ((validated.getExprEvaluator().getType() == null) || (!JavaClassHelper.isNumeric(validated.getExprEvaluator().getType()))) { throw new ExprValidationException(message); } } MatchedEventConvertor convertor = new MatchedEventConvertorImpl( untilMatchEventSpec.getTaggedEventTypes(), untilMatchEventSpec.getArrayEventTypes(), allTagNamesOrdered, context.getEventAdapterService()); matchUntilNode.setConvertor(convertor); // compile new tag lists Set<String> arrayTags = null; EvalNodeAnalysisResult matchUntilAnalysisResult = EvalNodeUtil .recursiveAnalyzeChildNodes(matchUntilNode.getChildNodes().get(0)); for (EvalFilterFactoryNode filterNode : matchUntilAnalysisResult.getFilterNodes()) { String optionalTag = filterNode.getEventAsName(); if (optionalTag != null) { if (arrayTags == null) { arrayTags = new HashSet<String>(); } arrayTags.add(optionalTag); } } if (arrayTags != null) { for (String arrayTag : arrayTags) { if (!tags.getArrayEventTypes().containsKey(arrayTag)) { tags.getArrayEventTypes().put(arrayTag, tags.getTaggedEventTypes().get(arrayTag)); tags.getTaggedEventTypes().remove(arrayTag); } } } matchUntilNode.setTagsArrayedSet(getIndexesForTags(allTagNamesOrdered, arrayTags)); } else if (evalNode instanceof EvalFollowedByFactoryNode) { EvalFollowedByFactoryNode followedByNode = (EvalFollowedByFactoryNode) evalNode; StreamTypeService streamTypeService = new StreamTypeServiceImpl(context.getEngineURI(), false); ExprValidationContext validationContext = new ExprValidationContext(streamTypeService, context.getMethodResolutionService(), null, context.getSchedulingService(), context.getVariableService(), evaluatorContext, context.getEventAdapterService(), context.getStatementName(), context.getStatementId(), context.getAnnotations(), context.getContextDescriptor()); if (followedByNode.getOptionalMaxExpressions() != null) { List<ExprNode> validated = new ArrayList<ExprNode>(); for (ExprNode maxExpr : followedByNode.getOptionalMaxExpressions()) { if (maxExpr == null) { validated.add(null); } else { ExprNodeSummaryVisitor visitor = new ExprNodeSummaryVisitor(); maxExpr.accept(visitor); if (!visitor.isPlain()) { String errorMessage = "Invalid maximum expression in followed-by, " + visitor.getMessage() + " are not allowed within the expression"; log.error(errorMessage); throw new ExprValidationException(errorMessage); } ExprNode validatedExpr = ExprNodeUtility.getValidatedSubtree(maxExpr, validationContext); validated.add(validatedExpr); if ((validatedExpr.getExprEvaluator().getType() == null) || (!JavaClassHelper.isNumeric(validatedExpr.getExprEvaluator().getType()))) { String message = "Invalid maximum expression in followed-by, the expression must return an integer value"; throw new ExprValidationException(message); } } } followedByNode.setOptionalMaxExpressions(validated); } } if (newTaggedEventTypes != null) { tags.getTaggedEventTypes().putAll(newTaggedEventTypes); } if (newArrayEventTypes != null) { tags.getArrayEventTypes().putAll(newArrayEventTypes); } }
From source file:com.roche.sequencing.bioinformatics.common.utils.FileUtil.java
/** * taken from here http://codereview.stackexchange.com/questions/47923/simplifying-a-path -Kurt Heilman * /*from w ww . j av a2 s. c om*/ * @param path * @return */ public static String simplifyPath(String path) { String simplifiedPath = null; Deque<String> pathDeterminer = new ArrayDeque<String>(); path = path.replaceAll(Pattern.quote("\\"), "/"); path = path.replaceAll(Pattern.quote("\\\\"), "/"); String[] pathSplitter = path.split("/"); StringBuilder absolutePath = new StringBuilder(); for (String term : pathSplitter) { if (term == null || term.length() == 0 || term.equals(".")) { /* ignore these guys */ } else if (term.equals("..")) { if (pathDeterminer.size() > 0) { pathDeterminer.removeLast(); } } else { pathDeterminer.addLast(term); } } if (pathDeterminer.isEmpty()) { simplifiedPath = "/"; } else { while (!pathDeterminer.isEmpty()) { absolutePath.insert(0, pathDeterminer.removeLast()); absolutePath.insert(0, "/"); } simplifiedPath = absolutePath.toString(); } return simplifiedPath; }
From source file:com.epam.cme.storefront.history.impl.DefaultBrowseHistory.java
@Override public void addBrowseHistoryEntry(final BrowseHistoryEntry browseHistoryEntry) { // Get the actual history entry list stored in the session final Deque<BrowseHistoryEntry> browseHistoryEntries = getBrowseHistoryEntries(); if (browseHistoryEntries != null) { // Lock on the entries to ensure that we modify it atomically synchronized (browseHistoryEntries) { // Add the entry browseHistoryEntries.addFirst(browseHistoryEntry); // Remove any entries that are over capacity while (browseHistoryEntries.size() > getCapacity()) { browseHistoryEntries.removeLast(); }/*from www . ja v a 2s . c o m*/ } } }
From source file:gov.nih.nci.cacis.common.util.ExtractSchematron.java
private void processElement(Deque<XSElementDeclaration> eltStack, XSElementDeclaration element) { eltStack.addLast(element);// w ww . j a v a 2 s . c o m processElement(eltStack); eltStack.removeLast(); }
From source file:com.blm.orc.OrcRawRecordMerger.java
@Override public ObjectInspector getObjectInspector() { // Read the configuration parameters String columnNameProperty = conf.get(serdeConstants.LIST_COLUMNS); // NOTE: if "columns.types" is missing, all columns will be of String type String columnTypeProperty = conf.get(serdeConstants.LIST_COLUMN_TYPES); // Parse the configuration parameters ArrayList<String> columnNames = new ArrayList<String>(); Deque<Integer> virtualColumns = new ArrayDeque<Integer>(); if (columnNameProperty != null && columnNameProperty.length() > 0) { String[] colNames = columnNameProperty.split(","); for (int i = 0; i < colNames.length; i++) { if (VirtualColumn.VIRTUAL_COLUMN_NAMES.contains(colNames[i])) { virtualColumns.addLast(i); } else { columnNames.add(colNames[i]); }/*from w w w . ja v a2s . co m*/ } } if (columnTypeProperty == null) { // Default type: all string StringBuilder sb = new StringBuilder(); for (int i = 0; i < columnNames.size(); i++) { if (i > 0) { sb.append(":"); } sb.append("string"); } columnTypeProperty = sb.toString(); } ArrayList<TypeInfo> fieldTypes = TypeInfoUtils.getTypeInfosFromTypeString(columnTypeProperty); while (virtualColumns.size() > 0) { fieldTypes.remove(virtualColumns.removeLast()); } StructTypeInfo rowType = new StructTypeInfo(); rowType.setAllStructFieldNames(columnNames); rowType.setAllStructFieldTypeInfos(fieldTypes); return OrcRecordUpdater.createEventSchema(OrcStruct.createObjectInspector(rowType)); }
From source file:de.uni_potsdam.hpi.asg.logictool.mapping.SequenceBasedAndGateDecomposer.java
public boolean decomposeAND(NetlistTerm term) { logger.info("Decomposition of " + term.toString()); Set<Signal> signals = netlist.getDrivenSignalsTransitive(term); if (signals.isEmpty()) { logger.warn("No signal(s) for term " + term + " found"); return false; } else if (signals.size() > 1) { logger.warn("Term " + term + " drives more than one signal. This is not supported yet"); return false; }//from w w w .j a v a 2 s.c o m Signal origsig = signals.iterator().next(); if (!isAOC(term, origsig)) { logger.warn("Algorithm not applicable for non-AOC architectures"); return false; } int startgatesize = BDDHelper.numberOfVars(term.getBdd()); BDD bdd = term.getBdd(); Set<Signal> origrelevant = findRelevantSigs(bdd); if (origrelevant == null) { return false; } StateGraph sg2 = sghelper.getNewStateGraph(origrelevant, origsig); if (sg2 == null) { logger.warn("Failed to generate new SG. Using the original one."); sg2 = origsg; } BiMap<Signal, Signal> sigmap = HashBiMap.create(); Set<Signal> relevant = new HashSet<>(); boolean found; for (Signal oldSig : origrelevant) { found = false; for (Signal newSig : sg2.getAllSignals()) { if (oldSig.getName().equals(newSig.getName())) { sigmap.put(oldSig, newSig); found = true; break; } } if (!found) { logger.error("Signal " + oldSig.getName() + " not found"); return false; } relevant.add(sigmap.get(oldSig)); } found = false; for (Signal newSig : sg2.getAllSignals()) { if (origsig.getName().equals(newSig.getName())) { sigmap.put(origsig, newSig); found = true; break; } } if (!found) { logger.error("Signal " + origsig.getName() + " not found"); return false; } Signal sig = sigmap.get(origsig); Map<Signal, Boolean> posnegmap = getInputsPosOrNeg(term, sigmap); BDD newbdd = factory.one(); for (Entry<Signal, Boolean> entry : posnegmap.entrySet()) { if (entry.getValue()) { newbdd = newbdd.andWith(getPosBDD(entry.getKey())); } else { newbdd = newbdd.andWith(getNegBDD(entry.getKey())); } if (entry.getKey() instanceof QuasiSignal) { relevant.add(entry.getKey()); } } Set<State> startStates = new HashSet<>(); for (State s : sg2.getStates()) { for (Entry<Transition, State> entry2 : s.getNextStates().entrySet()) { if (entry2.getKey().getSignal() == sig) { startStates.add(entry2.getValue()); } } } List<List<Signal>> fallingPartitions = new ArrayList<>(); for (Signal sig2 : relevant) { List<Signal> tmp = new ArrayList<>(); tmp.add(sig2); fallingPartitions.add(tmp); } SortedSet<IOBehaviour> sequencesFront = new TreeSet<>(new SequenceFrontCmp()); SortedSet<IOBehaviour> sequencesBack = new TreeSet<>(new SequenceBackCmp()); Set<IOBehaviour> newSequences = new HashSet<>(); Set<IOBehaviour> rmSequences = new HashSet<>(); Deque<IOBehaviourSimulationStep> steps = new ArrayDeque<>(); pool = new IOBehaviourSimulationStepPool(new IOBehaviourSimulationStepFactory()); pool.setMaxTotal(-1); try { root = pool.borrowObject(); } catch (Exception e) { e.printStackTrace(); logger.error("Could not borrow object"); return false; } IOBehaviourSimulationStep newStep; for (State s : startStates) { try { newStep = pool.borrowObject(); } catch (Exception e) { e.printStackTrace(); logger.error("Could not borrow object"); return false; } root.getNextSteps().add(newStep); newStep.setPrevStep(root); newStep.setStart(s); newStep.setNextState(s); steps.add(newStep); } if (steps.isEmpty()) { return false; } final long checkThreshold = 100; long stepsEvaledTotal = 0; IOBehaviourSimulationStep step = null; while (!steps.isEmpty()) { step = steps.removeLast(); // System.out.println("#Step: " + step.toString()); getNewSteps(step, sig, newSequences, steps, relevant); stepsEvaledTotal++; if (newSequences.size() >= checkThreshold) { removeCandidates(sequencesFront, sequencesBack, newSequences, rmSequences); } } removeCandidates(sequencesFront, sequencesBack, newSequences, rmSequences); logger.debug("Sequences: " + sequencesFront.size() + " - Tmp Sequences: " + newSequences.size() + " - Steps to evaluate: " + steps.size() + " - Steps evaluated: " + stepsEvaledTotal); logger.debug("Pool: " + "Created: " + pool.getCreatedCount() + ", Borrowed: " + pool.getBorrowedCount() + ", Returned: " + pool.getReturnedCount() + ", Active: " + pool.getNumActive() + ", Idle: " + pool.getNumIdle()); logger.debug("RmSub: " + rmSub + " // RmFall: " + rmFall); SortedSet<IOBehaviour> sequences = new TreeSet<>(sequencesFront); sequencesFront.clear(); sequencesBack.clear(); // System.out.println(sequences.toString()); List<IOBehaviour> falling = new ArrayList<>(); List<IOBehaviour> rising = new ArrayList<>(); List<IOBehaviour> constant = new ArrayList<>(); if (!categoriseSequences(newbdd, sequences, falling, rising, constant)) { return false; } // System.out.println("Falling:"); // for(IOBehaviour beh : falling) { // System.out.println(beh.toString()); // } // System.out.println("Rising:"); // for(IOBehaviour beh : rising) { // System.out.println(beh.toString()); // } // System.out.println("Constant:"); // for(IOBehaviour beh : constant) { // System.out.println(beh.toString()); // } fallingPartitions = getPossiblePartitionsFromFalling(falling, relevant); // System.out.println("FallingPartitions: " + fallingPartitions.toString()); Map<Integer, List<Partition>> partitions = getPartitions(relevant, startgatesize); if (partitions == null) { logger.error("There was a problem while creating partions for signal " + sig.getName()); return false; } // System.out.println("Init:"); // for(Entry<Integer, List<Partition>> entry : partitions.entrySet()) { // System.out.println(entry.getKey()); // for(Partition p : entry.getValue()) { // System.out.println("\t" + p.toString()); // } // } filterPartitions(partitions, fallingPartitions); if (partitions.isEmpty()) { logger.error("No suitable partions found"); return false; } // System.out.println("After filter Falling:"); // for(Entry<Integer, List<Partition>> entry : partitions.entrySet()) { // System.out.println(entry.getKey()); // for(Partition p : entry.getValue()) { // System.out.println("\t" + p.toString()); // } // } // System.out.println("posneg: " + posnegmap.toString()); setPartitionBDDs(partitions, posnegmap); if (!checkRising(rising, partitions)) { logger.error("Check rising failed"); return false; } if (partitions.isEmpty()) { logger.error("No suitable partions found"); return false; } // System.out.println("After filter Rising:"); // for(Entry<Integer, List<Partition>> entry : partitions.entrySet()) { // System.out.println(entry.getKey()); // for(Partition p : entry.getValue()) { // System.out.println("\t" + p.toString()); // } // } if (!checkConstant(constant, partitions)) { logger.error("Check constant failed"); return false; } if (partitions.isEmpty()) { logger.error("No suitable partions found"); return false; } // System.out.println("After filter Constant:"); // for(Entry<Integer, List<Partition>> entry : partitions.entrySet()) { // System.out.println(entry.getKey()); // for(Partition p : entry.getValue()) { // System.out.println("\t" + p.toString()); // } // } applyDecoResult(term, partitions, posnegmap, sigmap); return true; }