List of usage examples for java.util PriorityQueue poll
public E poll()
From source file:exploration.rendezvous.MultiPointRendezvousStrategy.java
private void calculateRendezvousRandomSampling(int timeElapsed) { RendezvousAgentData rvd = agent.getRendezvousAgentData(); // Only calculate rv every several time steps at most if (rvd.getTimeSinceLastRVCalc() < SimConstants.RV_REPLAN_INTERVAL) { return;/* www. j a va2s.c om*/ } else { rvd.setTimeSinceLastRVCalc(0); } TeammateAgent relay = agent.getParentTeammate(); generatedPoints = SampleEnvironmentPoints(agent, settings.SamplePointDensity); connectionsToBase = FindCommLinks(generatedPoints, agent); PriorityQueue<NearRVPoint> pointsNearFrontier = GetPointsWithinDistOfFrontier(generatedPoints, 100); int pathsCalculated = 0; //Now for top K points, let's calculate p' distances to base, and find the nearest point connected to base PriorityQueue<NearRVPoint> pointsNearFrontierReal = new PriorityQueue<NearRVPoint>(); for (int k = 0; (k < 50) && !pointsNearFrontier.isEmpty(); k++) { NearRVPoint p = pointsNearFrontier.poll(); double minDistToBase = Double.MAX_VALUE; for (CommLink link : p.commLinks) { NearRVPoint connectedPoint = link.getRemotePoint(); pathsCalculated = findNearestPointInBaseCommRange(connectedPoint, connectionsToBase, agent); if (connectedPoint.distanceToParent < minDistToBase) { minDistToBase = connectedPoint.distanceToParent; p.commLinkClosestToBase = link; } } //At this point, for p, we know: // 1. Connected point p' that is nearest to comm range of Base // 2. Distance from p' to comm range of Base // 3. Nearest point from p' that is within comm range of Base //So we know how long each point p will have to wait for relay, and so can estimate //where explorer will be at the time, to calculate regret accurately. //For now, just calculate accurate distance to next frontier: Path pathToFrontier = agent.calculatePath(p, getExplorerFrontier(), false, false); double distToFrontier = Double.MAX_VALUE; if (pathToFrontier.found) { distToFrontier = pathToFrontier.getLength(); } pathsCalculated++; p.setDistanceToFrontier(distToFrontier); if (p.commLinkClosestToBase == null || p.commLinkClosestToBase.getRemotePoint() == null) { //something went wrong, set RV to our current location and return Rendezvous meetingLocation = new Rendezvous(agent.getLocation()); Point baseLocation = agent.getTeammate(agent.getParentTeammate().getParent()).getLocation(); meetingLocation.parentsRVLocation = new Rendezvous(baseLocation); rvd.setParentRendezvous(meetingLocation); calculateRVTimings(timeElapsed); return; } p.utility = NearRVPoint.getFullRVUtility(p.distanceToFrontier, p.commLinkClosestToBase.getRemotePoint().distanceToParent, p.commLinkClosestToBase.numObstacles); pointsNearFrontierReal.add(p); } //Now just need to retrieve the best point NearRVPoint childPoint = pointsNearFrontierReal.peek(); NearRVPoint parentPoint = childPoint.commLinkClosestToBase.getRemotePoint(); Rendezvous meetingLocation = new Rendezvous(childPoint); meetingLocation.setParentLocation(parentPoint); Rendezvous parentsMeetingLocation = new Rendezvous(parentPoint.parentPoint); Point baseLocation = agent.getTeammate(agent.getParentTeammate().getParent()).getLocation(); parentsMeetingLocation .setParentLocation(agent.getTeammate(agent.getParentTeammate().getParent()).getLocation()); meetingLocation.parentsRVLocation = parentsMeetingLocation; rvd.setParentRendezvous(meetingLocation); Rendezvous backupRV = new Rendezvous(childPoint); rvd.setParentBackupRendezvous(backupRV); calculateRVTimings(timeElapsed); displayData.setGeneratedPoints(generatedPoints); displayData.setPointsNearFrontier(pointsNearFrontier); }
From source file:org.apache.hadoop.hbase.io.hfile.bucket.BucketCache.java
/** * Free the space if the used size reaches acceptableSize() or one size block * couldn't be allocated. When freeing the space, we use the LRU algorithm and * ensure there must be some blocks evicted *//*from w w w.j a v a 2 s. c o m*/ private void freeSpace() { // Ensure only one freeSpace progress at a time if (!freeSpaceLock.tryLock()) return; try { freeInProgress = true; long bytesToFreeWithoutExtra = 0; /* * Calculate free byte for each bucketSizeinfo */ StringBuffer msgBuffer = new StringBuffer(); BucketAllocator.IndexStatistics[] stats = bucketAllocator.getIndexStatistics(); long[] bytesToFreeForBucket = new long[stats.length]; for (int i = 0; i < stats.length; i++) { bytesToFreeForBucket[i] = 0; long freeGoal = (long) Math.floor(stats[i].totalCount() * (1 - DEFAULT_MIN_FACTOR)); freeGoal = Math.max(freeGoal, 1); if (stats[i].freeCount() < freeGoal) { bytesToFreeForBucket[i] = stats[i].itemSize() * (freeGoal - stats[i].freeCount()); bytesToFreeWithoutExtra += bytesToFreeForBucket[i]; msgBuffer.append("Free for bucketSize(" + stats[i].itemSize() + ")=" + StringUtils.byteDesc(bytesToFreeForBucket[i]) + ", "); } } msgBuffer.append("Free for total=" + StringUtils.byteDesc(bytesToFreeWithoutExtra) + ", "); if (bytesToFreeWithoutExtra <= 0) { return; } long currentSize = bucketAllocator.getUsedSize(); long totalSize = bucketAllocator.getTotalSize(); LOG.debug("Bucket cache free space started; Attempting to " + msgBuffer.toString() + " of current used=" + StringUtils.byteDesc(currentSize) + ",actual cacheSize=" + StringUtils.byteDesc(realCacheSize.get()) + ",total=" + StringUtils.byteDesc(totalSize)); long bytesToFreeWithExtra = (long) Math .floor(bytesToFreeWithoutExtra * (1 + DEFAULT_EXTRA_FREE_FACTOR)); // Instantiate priority buckets BucketEntryGroup bucketSingle = new BucketEntryGroup(bytesToFreeWithExtra, blockSize, singleSize()); BucketEntryGroup bucketMulti = new BucketEntryGroup(bytesToFreeWithExtra, blockSize, multiSize()); BucketEntryGroup bucketMemory = new BucketEntryGroup(bytesToFreeWithExtra, blockSize, memorySize()); // Scan entire map putting bucket entry into appropriate bucket entry // group for (Map.Entry<BlockCacheKey, BucketEntry> bucketEntryWithKey : backingMap.entrySet()) { switch (bucketEntryWithKey.getValue().getPriority()) { case SINGLE: { bucketSingle.add(bucketEntryWithKey); break; } case MULTI: { bucketMulti.add(bucketEntryWithKey); break; } case MEMORY: { bucketMemory.add(bucketEntryWithKey); break; } } } PriorityQueue<BucketEntryGroup> bucketQueue = new PriorityQueue<BucketEntryGroup>(3); bucketQueue.add(bucketSingle); bucketQueue.add(bucketMulti); bucketQueue.add(bucketMemory); int remainingBuckets = 3; long bytesFreed = 0; BucketEntryGroup bucketGroup; while ((bucketGroup = bucketQueue.poll()) != null) { long overflow = bucketGroup.overflow(); if (overflow > 0) { long bucketBytesToFree = Math.min(overflow, (bytesToFreeWithoutExtra - bytesFreed) / remainingBuckets); bytesFreed += bucketGroup.free(bucketBytesToFree); } remainingBuckets--; } /** * Check whether need extra free because some bucketSizeinfo still needs * free space */ stats = bucketAllocator.getIndexStatistics(); boolean needFreeForExtra = false; for (int i = 0; i < stats.length; i++) { long freeGoal = (long) Math.floor(stats[i].totalCount() * (1 - DEFAULT_MIN_FACTOR)); freeGoal = Math.max(freeGoal, 1); if (stats[i].freeCount() < freeGoal) { needFreeForExtra = true; break; } } if (needFreeForExtra) { bucketQueue.clear(); remainingBuckets = 2; bucketQueue.add(bucketSingle); bucketQueue.add(bucketMulti); while ((bucketGroup = bucketQueue.poll()) != null) { long bucketBytesToFree = (bytesToFreeWithExtra - bytesFreed) / remainingBuckets; bytesFreed += bucketGroup.free(bucketBytesToFree); remainingBuckets--; } } if (LOG.isDebugEnabled()) { long single = bucketSingle.totalSize(); long multi = bucketMulti.totalSize(); long memory = bucketMemory.totalSize(); LOG.debug("Bucket cache free space completed; " + "freed=" + StringUtils.byteDesc(bytesFreed) + ", " + "total=" + StringUtils.byteDesc(totalSize) + ", " + "single=" + StringUtils.byteDesc(single) + ", " + "multi=" + StringUtils.byteDesc(multi) + ", " + "memory=" + StringUtils.byteDesc(memory)); } } finally { cacheStats.evict(); freeInProgress = false; freeSpaceLock.unlock(); } }
From source file:com.mentor.questa.vrm.jenkins.QuestaVrmHostAction.java
private CategoryDataset buildDataSet(StaplerRequest req) { boolean showAction = Boolean.valueOf(req.getParameter("showActions")) || getActionCookie(req); DataSetBuilder<String, Long> dsb = new DataSetBuilder<String, Long>(); PriorityQueue<Pair> pq = new PriorityQueue<Pair>(); HashMap<String, Integer> hostCount = new HashMap<String, Integer>(); for (TestResult temp : getRegressionResult().getActions()) { QuestaVrmAbstractResult action = (QuestaVrmAbstractResult) temp; if (showAction || action instanceof QuestaVrmTestResult) { if (action.getStartTime() == -1 || action.getDoneTime() == -1) { continue; }//w w w.j a v a2s.c o m pq.add(new Pair(action.getStartTimeDate(), action.getHost(), 1)); pq.add(new Pair(action.getDoneTimeDate(), action.getHost(), -1)); hostCount.put(action.getHost(), 0); } } if (pq.isEmpty()) { return dsb.build(); } long offset = getRegressionResult().getRegressionBegin().getTime(); int noOfTests; HashSet<String> visited = new HashSet<String>(); while (!pq.isEmpty()) { long currentKey = pq.peek().date.getTime(); while (!pq.isEmpty() && pq.peek().date.getTime() == currentKey) { Pair current = pq.peek(); noOfTests = hostCount.get(current.host); while (!pq.isEmpty() && pq.peek().compareTo(current) == 0) { noOfTests += pq.poll().diff; } dsb.add(noOfTests, current.host, (current.date.getTime() - offset) / 1000); hostCount.put(current.host, noOfTests); visited.add(current.host); } for (String host : hostCount.keySet()) { if (!visited.contains(host)) { dsb.add(hostCount.get(host), host, (currentKey - offset) / 1000); } } visited.clear(); } return dsb.build(); }
From source file:delfos.group.grs.consensus.ConsensusGRS.java
public File getConsensusOutputXMLwithDesiredConsensusDegree(File consensusInputXML, double consensusDegree) { File consensusOutputDirectory = (File) getParameterValue(CONSENSUS_OUTPUT_FILES_DIRECTORY); String consensusInputXMLFileNameNoExtension = consensusInputXML.getName().substring(0, consensusInputXML.getName().lastIndexOf(".")); String consensusInputXMLInOutputDirectoryAbsolutePath = consensusOutputDirectory.getAbsolutePath() + File.separator + consensusInputXMLFileNameNoExtension; File consensusInputXMLInOutputDirectory = new File(consensusInputXMLInOutputDirectoryAbsolutePath); if (!consensusInputXML.exists()) { Global.showWarning("The input XML '" + consensusInputXMLInOutputDirectory + "' does not exists in the output directory"); return null; }//from ww w . ja va 2 s. co m if (!consensusOutputDirectory.exists()) { Global.showWarning("'" + consensusOutputDirectory.getAbsolutePath() + "' not exists"); return null; } if (!consensusOutputDirectory.isDirectory()) { Global.showWarning("'" + consensusOutputDirectory.getAbsolutePath() + "' is not a directory"); return null; } List<File> childrenFiles = new ArrayList<>(Arrays.asList(consensusOutputDirectory.listFiles())); PriorityQueue<PriorityItem<File>> queue = new PriorityQueue<>(Collections.reverseOrder()); for (File consensusOutputFile : childrenFiles) { final String outputFileNameNoExtension = consensusOutputFile.getName().substring(0, consensusOutputFile.getName().lastIndexOf(".")); if (outputFileNameNoExtension.startsWith(consensusInputXMLFileNameNoExtension) && outputFileNameNoExtension.contains("Consenso")) { try { Global.showln(consensusOutputFile.getAbsolutePath()); double thisFileConsensusDegree = ConsensusOfIndividualRecommendationsToXML .readConsensusOutputXML(consensusOutputFile).consensusDegree; queue.add(new PriorityItem<>(consensusOutputFile, thisFileConsensusDegree)); } catch (JDOMException | IOException ex) { Global.showWarning(ex); } } } if (queue.isEmpty()) { return null; } if (Global.isVerboseAnnoying()) { Global.showInfoMessage("Found " + queue.size() + " consensus files"); } while (!queue.isEmpty()) { PriorityItem<File> priorityItem = queue.poll(); double consensusDegreeThisFile = priorityItem.getPriority(); if (consensusDegreeThisFile >= consensusDegree) { return priorityItem.getKey(); } } throw new IllegalStateException( "Consensus degree not reached for '" + consensusInputXMLFileNameNoExtension + "'"); }
From source file:com.linkedin.pinot.routing.builder.GeneratorBasedRoutingTableBuilder.java
@Override public List<ServerToSegmentSetMap> computeRoutingTableFromExternalView(String tableName, ExternalView externalView, List<InstanceConfig> instanceConfigList) { // The default routing table algorithm tries to balance all available segments across all servers, so that each // server is hit on every query. This works fine with small clusters (say less than 20 servers) but for larger // clusters, this adds up to significant overhead (one request must be enqueued for each server, processed, // returned, deserialized, aggregated, etc.). ////ww w .j a va 2 s. c o m // For large clusters, we want to avoid hitting every server, as this also has an adverse effect on client tail // latency. This is due to the fact that a query cannot return until it has received a response from each server, // and the greater the number of servers that are hit, the more likely it is that one of the servers will be a // straggler (eg. due to contention for query processing threads, GC, etc.). We also want to balance the segments // within any given routing table so that each server in the routing table has approximately the same number of // segments to process. // // To do so, we have a routing table generator that generates routing tables by picking a random subset of servers. // With this set of servers, we check if the set of segments served by these servers is complete. If the set of // segments served does not cover all of the segments, we compute the list of missing segments and pick a random // server that serves these missing segments until we have complete coverage of all the segments. // // We then order the segments in ascending number of replicas within our server set, in order to allocate the // segments with fewer replicas first. This ensures that segments that are 'easier' to allocate are more likely to // end up on a replica with fewer segments. // // Then, we pick a random replica for each segment, iterating from fewest replicas to most replicas, inversely // weighted by the number of segments already assigned to that replica. This ensures that we build a routing table // that's as even as possible. // // The algorithm to generate a routing table is thus: // 1. Compute the inverse external view, a mapping of servers to segments // 2. For each routing table to generate: // a) Pick TARGET_SERVER_COUNT_PER_QUERY distinct servers // b) Check if the server set covers all the segments; if not, add additional servers until it does. // c) Order the segments in our server set in ascending order of number of replicas present in our server set // d) For each segment, pick a random replica with proper weighting // e) Return that routing table // // Given that we can generate routing tables at will, we then generate many routing tables and use them to optimize // according to two criteria: the variance in workload per server for any individual table as well as the variance // in workload per server across all the routing tables. To do so, we generate an initial set of routing tables // according to a per-routing table metric and discard the worst routing tables. RoutingTableGenerator routingTableGenerator = buildRoutingTableGenerator(); routingTableGenerator.init(externalView, instanceConfigList); PriorityQueue<Pair<Map<String, Set<String>>, Float>> topRoutingTables = new PriorityQueue<>( ROUTING_TABLE_COUNT, new Comparator<Pair<Map<String, Set<String>>, Float>>() { @Override public int compare(Pair<Map<String, Set<String>>, Float> left, Pair<Map<String, Set<String>>, Float> right) { // Float.compare sorts in ascending order and we want a max heap, so we need to return the negative of the comparison return -Float.compare(left.getValue(), right.getValue()); } }); for (int i = 0; i < ROUTING_TABLE_COUNT; i++) { topRoutingTables.add(generateRoutingTableWithMetric(routingTableGenerator)); } // Generate routing more tables and keep the ROUTING_TABLE_COUNT top ones for (int i = 0; i < (ROUTING_TABLE_GENERATION_COUNT - ROUTING_TABLE_COUNT); ++i) { Pair<Map<String, Set<String>>, Float> newRoutingTable = generateRoutingTableWithMetric( routingTableGenerator); Pair<Map<String, Set<String>>, Float> worstRoutingTable = topRoutingTables.peek(); // If the new routing table is better than the worst one, keep it if (newRoutingTable.getRight() < worstRoutingTable.getRight()) { topRoutingTables.poll(); topRoutingTables.add(newRoutingTable); } } // Return the best routing tables List<ServerToSegmentSetMap> routingTables = new ArrayList<>(topRoutingTables.size()); while (!topRoutingTables.isEmpty()) { Pair<Map<String, Set<String>>, Float> routingTableWithMetric = topRoutingTables.poll(); routingTables.add(new ServerToSegmentSetMap(routingTableWithMetric.getKey())); } return routingTables; }
From source file:com.github.wolfdogs.kemono.util.event.RootEventManager.java
@Override public <T extends Event> void dispatchEvent(ThrowableHandler throwableHandler, T event, Object... objects) { if (throwableHandler == null) throwableHandler = DEFAULT_THROWABLE_HANDLER; if (objects.length == 0) objects = new Object[] { new Object() }; Class<? extends Event> type = event.getClass(); PriorityQueue<HandlerEntry> handlerEntryQueue = new PriorityQueue<HandlerEntry>(16, HANDLER_ENTRY_PRIORITY_COMPARATOR); Map<Object, Queue<HandlerEntry>> objectEntriesMap = handlerEntryContainersMap.get(type); if (objectEntriesMap == null) return;//ww w.jav a 2 s . c om for (Object object : objects) { Class<?> cls = object.getClass(); Queue<HandlerEntry> entries = objectEntriesMap.get(object); if (entries != null) { for (HandlerEntry entry : entries) handlerEntryQueue.add(entry); } Class<?>[] interfaces = cls.getInterfaces(); for (Class<?> clz : interfaces) { Queue<HandlerEntry> classEntries = objectEntriesMap.get(clz); if (classEntries != null) { for (HandlerEntry entry : classEntries) handlerEntryQueue.add(entry); } } for (Class<?> clz = cls; clz != null; clz = clz.getSuperclass()) { Queue<HandlerEntry> classEntries = objectEntriesMap.get(clz); if (classEntries != null) { for (HandlerEntry entry : classEntries) handlerEntryQueue.add(entry); } } } while (handlerEntryQueue.isEmpty() == false && event.isInterrupted() == false) { HandlerEntry entry = handlerEntryQueue.poll(); EventHandler handler = entry.getHandler(); if (handler == null) continue; try { handler.handleEvent(event); } catch (Throwable e) { throwableHandler.handleThrowable(e); } } }
From source file:com.linkedin.pinot.broker.routing.builder.GeneratorBasedRoutingTableBuilder.java
@Override public void computeRoutingTableFromExternalView(String tableName, ExternalView externalView, List<InstanceConfig> instanceConfigs) { // The default routing table algorithm tries to balance all available segments across all servers, so that each // server is hit on every query. This works fine with small clusters (say less than 20 servers) but for larger // clusters, this adds up to significant overhead (one request must be enqueued for each server, processed, // returned, deserialized, aggregated, etc.). ///*from w w w.jav a 2 s . co m*/ // For large clusters, we want to avoid hitting every server, as this also has an adverse effect on client tail // latency. This is due to the fact that a query cannot return until it has received a response from each server, // and the greater the number of servers that are hit, the more likely it is that one of the servers will be a // straggler (eg. due to contention for query processing threads, GC, etc.). We also want to balance the segments // within any given routing table so that each server in the routing table has approximately the same number of // segments to process. // // To do so, we have a routing table generator that generates routing tables by picking a random subset of servers. // With this set of servers, we check if the set of segments served by these servers is complete. If the set of // segments served does not cover all of the segments, we compute the list of missing segments and pick a random // server that serves these missing segments until we have complete coverage of all the segments. // // We then order the segments in ascending number of replicas within our server set, in order to allocate the // segments with fewer replicas first. This ensures that segments that are 'easier' to allocate are more likely to // end up on a server with fewer segments. // // Then, we pick a server with least segments already assigned for each segment. This ensures that we build a // routing table that's as even as possible. // // The algorithm to generate a routing table is thus: // 1. Compute the inverse external view, a mapping of servers to segments // 2. For each routing table to generate: // a) Pick _targetNumServersPerQuery distinct servers // b) Check if the server set covers all the segments; if not, add additional servers until it does // c) Order the segments in our server set in ascending order of number of replicas present in our server set // d) For each segment, pick a server with least segments already assigned // e) Return that routing table // // Given that we can generate routing tables at will, we then generate many routing tables and use them to optimize // according to two criteria: the variance in workload per server for any individual table as well as the variance // in workload per server across all the routing tables. To do so, we generate an initial set of routing tables // according to a per-routing table metric and discard the worst routing tables. RoutingTableGenerator routingTableGenerator = buildRoutingTableGenerator(); routingTableGenerator.init(externalView, instanceConfigs); PriorityQueue<Pair<Map<String, List<String>>, Float>> topRoutingTables = new PriorityQueue<>( ROUTING_TABLE_COUNT, new Comparator<Pair<Map<String, List<String>>, Float>>() { @Override public int compare(Pair<Map<String, List<String>>, Float> left, Pair<Map<String, List<String>>, Float> right) { // Float.compare sorts in ascending order and we want a max heap, so we need to return the negative of the comparison return -Float.compare(left.getValue(), right.getValue()); } }); for (int i = 0; i < ROUTING_TABLE_COUNT; i++) { topRoutingTables.add(generateRoutingTableWithMetric(routingTableGenerator)); } // Generate routing more tables and keep the ROUTING_TABLE_COUNT top ones for (int i = 0; i < (ROUTING_TABLE_GENERATION_COUNT - ROUTING_TABLE_COUNT); ++i) { Pair<Map<String, List<String>>, Float> newRoutingTable = generateRoutingTableWithMetric( routingTableGenerator); Pair<Map<String, List<String>>, Float> worstRoutingTable = topRoutingTables.peek(); // If the new routing table is better than the worst one, keep it if (newRoutingTable.getRight() < worstRoutingTable.getRight()) { topRoutingTables.poll(); topRoutingTables.add(newRoutingTable); } } // Return the best routing tables List<Map<String, List<String>>> routingTables = new ArrayList<>(topRoutingTables.size()); while (!topRoutingTables.isEmpty()) { routingTables.add(topRoutingTables.poll().getKey()); } setRoutingTables(routingTables); }
From source file:edu.snu.leader.hidden.SpatialIndividual.java
/** * Finds the nearest neighbors for this individual * * @param simState//from w w w .j a v a 2 s .co m */ public void findNearestNeighbors(SimulationState simState) { _LOG.trace("Entering findNearestNeighbors( simState )"); // Get the number of nearest neighbors _nearestNeighborCount = simState.getNearestNeighborCount(); // Build a priority queue to sort things for us PriorityQueue<Neighbor> sortedNeighbors = new PriorityQueue<Neighbor>(); // Iterate through all the individuals Iterator<SpatialIndividual> indIter = simState.getAllIndividuals().iterator(); while (indIter.hasNext()) { // Get the individual SpatialIndividual ind = indIter.next(); // If it is us, continue on if (_id.equals(ind._id)) { continue; } // Build a neighbor out of it and put it in the queue Neighbor neighbor = new Neighbor((float) _location.distance(ind._location), ind); sortedNeighbors.add(neighbor); } // Get the "nearest" neighbors int count = Math.min(sortedNeighbors.size(), _nearestNeighborCount); for (int i = 0; i < count; i++) { Neighbor neighbor = sortedNeighbors.poll(); _nearestNeighbors.add(neighbor); neighbor.getIndividual().signalNearestNeighborStatus(this); // _LOG.debug( "Nearest neighbor: id=[" // + getID() // + "] neighbor=[" // + neighbor.getIndividual().getID() // + "]" ); } _LOG.trace("Leaving findNearestNeighbors( simState )"); }
From source file:io.warp10.script.functions.OPTDTW.java
@Override public Object apply(WarpScriptStack stack) throws WarpScriptException { Object o = stack.pop();// w w w .ja v a 2 s . c o m if (!(o instanceof Number)) { throw new WarpScriptException( getName() + " expects a count of best restults to return on top of the stack."); } int count = ((Number) o).intValue(); o = stack.pop(); if (!(o instanceof List)) { throw new WarpScriptException(getName() + " expects a numeric list to use as query below the count."); } double[] query = new double[((List) o).size()]; int i = 0; for (Object oo : (List) o) { query[i++] = ((Number) oo).doubleValue(); } // Z-Normalize query double[] musigma = DoubleUtils.musigma(query, true); for (i = 0; i < query.length; i++) { query[i] = (query[i] - musigma[0]) / musigma[1]; } o = stack.pop(); if (!(o instanceof List)) { throw new WarpScriptException(getName() + " expects a numeric list as the sequence in which to find best matches below the 'query' list."); } double[] sequence = new double[((List) o).size()]; i = 0; for (Object oo : (List) o) { sequence[i++] = ((Number) oo).doubleValue(); } if (sequence.length <= query.length) { throw new WarpScriptException( getName() + " expects the query list to be shorter than the sequence list."); } double mindist = 0.0; PriorityQueue<Pair<Integer, Double>> distances = new PriorityQueue<Pair<Integer, Double>>( new Comparator<Pair<Integer, Double>>() { @Override public int compare(Pair<Integer, Double> o1, Pair<Integer, Double> o2) { return o1.getValue().compareTo(o2.getValue()); } }); double[] subsequence = new double[query.length]; for (i = 0; i <= sequence.length - query.length; i++) { System.arraycopy(sequence, i, subsequence, 0, query.length); // Z-Normalize the subsequence musigma = DoubleUtils.musigma(subsequence, true); for (int j = 0; j < subsequence.length; j++) { subsequence[j] = (subsequence[j] - musigma[0]) / musigma[1]; } double dist = dtw.compute(query, 0, query.length, subsequence, 0, query.length, mindist); if (dist < 0) { continue; } distances.add(new Pair<Integer, Double>(i, dist)); // // If the priority queue is of 'count' size, retrieve the largest distance and // use it as the threshold for the DTW computation // if (count > 0 && distances.size() >= count) { Object adist[] = distances.toArray(); mindist = ((Pair<Integer, Double>) adist[count - 1]).getValue(); } } List<List<Object>> results = new ArrayList<List<Object>>(); while (!distances.isEmpty()) { Pair<Integer, Double> entry = distances.poll(); List<Object> result = new ArrayList<Object>(); result.add(entry.getKey()); result.add(entry.getValue()); results.add(result); if (count > 0 && count == results.size()) { break; } } stack.push(results); return stack; }
From source file:edu.oregonstate.eecs.mcplan.domains.firegirl.FireGirlState.java
private FireResult doFire(final RandomGenerator rng, final boolean suppress) { final int reach = params.fire_param_reach; final double end_time = drawEndOfFire(rng); double current_time = 0; // Construct the priority queue and add the first cell to it with time = 0 final PriorityQueue<PrioritizedLocation> pqueue = new PriorityQueue<PrioritizedLocation>(); pqueue.add(new PrioritizedLocation(0, ignite_loc)); // setting a variable that will hold the lowest of all the ingition times in the queue. // final int next_ign = 1000; final boolean[][] burned = new boolean[params.width][params.height]; final boolean[][] crown_burned = new boolean[params.width][params.height]; // start the queue loop int iter_count = 0; while (true) { //check to make sure that there is at least one queued arrival if (pqueue.isEmpty()) { //no queued arrivals, so there's no fire, so we're done //print("Priority Queue Exiting: No more queued ignitions") break; }/* w w w. jav a2 s .c o m*/ //look through all the queued ignitions and find the earliest ignition // time. final PrioritizedLocation next_ign = pqueue.poll(); //now check to see if the soonest arrival happens before the time is up. if (next_ign.priority >= end_time) { //no fire arrivals (ignitions) are in queue within the alloted time // so the firespread has stopped. //print("Priority Queue Exiting: Remaining queued ignitions are past the time limit") break; } //moving current time up to this ignition current_time = next_ign.priority; final int xloc = next_ign.location[0]; final int yloc = next_ign.location[1]; if (burned[xloc][yloc]) { continue; } //we haven't left the loop, so the next arrival is valid, so look at // it and add its neighbors to the queue //failsafe exit iter_count += 1; if (iter_count > params.fire_iter_cap) { Log.warn("! Stopping fire early. time: {}", current_time); break; } //setting this cell to burned burned[xloc][yloc] = true; //Calculating this cell's fire spreadrate, which needs it's fuel load, too final int fuel_ld = fuel_load[xloc][yloc]; double spreadrate = calcFireSpreadRate(ignite_wind, ignite_temp, fuel_ld); //add the effects of suppression if (suppress) { spreadrate *= params.fire_suppression_rate; } // Check if the crown will burn (if the spreadrate is > 0) // Timber loss is a probabalistic function based on the // calcCrownFireRisk() function. This function will return // a probability of crownfire, and we'll roll a uniform // number against it. // NOTE: Deviation from Python if (rng.nextDouble() < calcCrownFireRisk(fuel_ld)) { crown_burned[xloc][yloc] = true; } //if the fire spreadrate of this fire is 0, then don't bother checking // for neighbors and calculating arrival times... there won't be any // spread, and for that matter, we'll get a divide-by-zero error. if (spreadrate == 0) { //no spreadrate, so we can't calculate arrival times, etc... //pqueue.remove([current_time,[xloc,yloc]]) // Note: Already removed the element continue; } //recording information in the Logbook item //function signature is: FireGirlfireLog.addIgnitionEvent(time, location, spread_rate, crown_burned): // fire_log_item.addIgnitionEvent(current_time, [xloc,yloc], spreadrate, crown_burned[xloc][yloc]) //setting iteration final ranges final int x_low = Math.max(xloc - reach, 0); final int x_high = Math.min(xloc + reach + 1, params.width - 1); final int y_low = Math.max(yloc - reach, 0); final int y_high = Math.min(yloc + reach + 1, params.height - 1); // #checking bounds // if (x_low < 0): x_low = 0 // if (y_low < 0): y_low = 0 // if (x_high >= self.width): x_high = self.width - 1 // if (y_high >= self.height): y_high = self.height - 1 // FIXME: I think this indexing is incorrect (one short) due to // how x/y_high are capped above // Resolved: Changed '<' to '<=' for (int i = x_low; i <= x_high; ++i) { //i in range(x_low, x_high): for (int j = y_low; j <= y_high; ++j) { //for j in range(y_low, y_high): // #don't calculate time to the current cell if (!((xloc == i) && (yloc == j))) { // #we're checking each neighbor within the reach range, so // # first, we need to check whether it's already been // # burned over if (!burned[i][j]) { // #this neighbor hasn't burned over yet, so: // # 1) calculate a new time-till arrival // # 2) check to see if this neighbor is already in the queue // # 2a) if it is, then check to see if this arrival time is sooner // # and if so, update it. Otherwise, just move on. // # 2b) if it isn't in the queue, then add it as a new queue item // # 1) final arrival time for this neighbor final double dist = Math.sqrt((xloc - i) * (xloc - i) + (yloc - j) * (yloc - j)); final double arrival_time = (dist / spreadrate) + current_time; // Just add it again; we filter duplicates by checking if they're already burned. pqueue.add(new PrioritizedLocation(arrival_time, new int[] { i, j })); //// # 2) checking to see if this neighbor is already queued // boolean found_in_q = false; // final Iterator<PrioritizedLocation> itr = pqueue.iterator(); // while( itr.hasNext() ) { // final PrioritizedLocation ign = itr.next(); // if( ign.location[0] == i && ign.location[1] == j ) { //// #this neighbor IS in the queue already, so check its arrival time //// #print(" neighbor found in queue... updating...") // found_in_q = true; // //// #updating it's arrival time if need be // if( arrival_time < ign.priority ) { // itr.remove(); //// #the new arrival time is sooner, so update this queue item // pqueue.add( new PrioritizedLocation( arrival_time, ign.location ) ); // } // break; // } // } // // //// #check to see if we ever found this neighbor // if( !found_in_q ) { //// #we never found it, so it wasn't in the queue, and it's not burned, so add it // pqueue.add( new PrioritizedLocation( arrival_time, new int[] { i, j } ) ); // } } } } } // # we've now finished checking the neighbors, so it's time to remove this item from the queue // pqueue.remove([current_time,[xloc,yloc]]) } // priority queue empty // # and now we've exited the priority queue as well // #look through the burned cells and update the actual grid values // #Also, record losses double timber_loss = 0; int cells_burned = 0; int cells_crowned = 0; for (int i = 0; i < params.width; ++i) { for (int j = 0; j < params.height; ++j) { if (burned[i][j]) { cells_burned += 1; // #this cell was burned, so set the fuel_load to zero, and apply // # the crown-burning model to the timber_value fuel_load[i][j] = 0; // #adding up timber loss if (crown_burned[i][j]) { //this was set when spreadrate was calculated earlier // #the crown burned, so record the loss and set it to zero // #SPEED // ####BOTH Lines are modified for self.getPresentTimberValue(i,j)########### timber_loss += getPresentTimberValue(i, j); //self.timber_value[i][j] // #self.timber_value[i][j] = 0 // #################### cells_crowned += 1; // #and reset the age so that self.year + self.stand_age = 0 // stand_age[i][j] = -1 * year; // NOTE: Deviation from Python code stand_age[i][j] = 0; } } } } // #Adding the final results to the fire_log_item // fire_log_item.updateResults(timber_loss, cells_burned, cells_crowned) // #Adding the lists (final maps) as well // fire_log_item.map_burned = burned // fire_log_item.map_crowned = crown_burned // #add the FireLog item to the pathway's list (it's just an ordinary list) // self.FireLog.append(fire_log_item) // #add up suppression cost and record it int sup_cost = 0; if (suppress) { sup_cost += cells_burned * params.fire_suppression_cost_per_cell; sup_cost += end_time * params.fire_suppression_cost_per_day; } // self.yearly_suppression_costs.append(sup_cost) // #and finally, return the loss data return new FireResult(timber_loss, cells_burned, cells_crowned, sup_cost, end_time); // return [timber_loss, cells_burned, sup_cost, end_time, cells_crowned] }