List of usage examples for java.util SortedMap get
V get(Object key);
From source file:com.google.gwt.emultest.java.util.TreeMapTest.java
public void testHeadMapLjava_lang_ObjectZL() { K[] keys = getSortedKeys();/* ww w . j a v a2s . co m*/ V[] values = getSortedValues(); NavigableMap<K, V> map = createNavigableMap(); for (int i = 0; i < keys.length; i++) { map.put(keys[i], values[i]); } // normal case SortedMap<K, V> subMap = map.headMap(keys[2], true); assertEquals(3, subMap.size()); subMap = map.headMap(keys[3], true); assertEquals(4, subMap.size()); for (int i = 0; i < 4; i++) { assertEquals(values[i], subMap.get(keys[i])); } subMap = map.headMap(keys[2], false); assertEquals(2, subMap.size()); assertNull(subMap.get(keys[3])); // Exceptions assertEquals(0, map.headMap(keys[0], false).size()); try { map.headMap(null, true); assertTrue("expected exception", useNullKey()); } catch (NullPointerException e) { assertFalse("unexpected NPE", useNullKey()); } try { map.headMap(null, false); assertTrue("expected exception", useNullKey()); } catch (NullPointerException e) { assertFalse("unexpected NPE", useNullKey()); } subMap = map.headMap(keys[2]); assertEquals(2, subMap.size()); try { subMap.put(keys[2], values[2]); fail("should throw IllegalArgumentException"); } catch (IllegalArgumentException expected) { } assertEquals(keys.length, map.size()); subMap = map.headMap(keys[2], true); assertEquals(3, subMap.size()); subMap.remove(keys[1]); assertFalse(subMap.containsKey(keys[1])); assertFalse(subMap.containsValue(values[1])); assertFalse(map.containsKey(keys[1])); assertFalse(map.containsValue(values[1])); assertEquals(2, subMap.size()); assertEquals(keys.length - 1, map.size()); subMap.put(keys[1], values[1]); try { subMap.subMap(keys[1], keys[3]); fail("should throw IllegalArgumentException"); } catch (IllegalArgumentException expected) { } try { subMap.subMap(keys[3], keys[1]); fail("should throw IllegalArgumentException"); } catch (IllegalArgumentException expected) { } if (useNullKey() && useNullValue()) { map.put(null, null); subMap = map.headMap(null, true); assertEquals(1, subMap.size()); assertTrue(subMap.containsValue(null)); assertNull(subMap.get(null)); subMap = map.subMap(null, false, keys[2], true); assertEquals(3, subMap.size()); Set<K> keySet = subMap.keySet(); assertEquals(3, keySet.size()); Set<Map.Entry<K, V>> entrySet = subMap.entrySet(); assertEquals(3, entrySet.size()); Collection<V> valueCollection = subMap.values(); assertEquals(3, valueCollection.size()); map.remove(null); } // head map of head map NavigableMap<K, V> headMap = map.headMap(keys[3], true); assertEquals(4, headMap.size()); headMap = headMap.headMap(keys[3], false); assertEquals(3, headMap.size()); headMap = headMap.headMap(keys[2], false); assertEquals(2, headMap.size()); headMap = headMap.tailMap(keys[0], false); assertEquals(1, headMap.size()); headMap = headMap.tailMap(keys[1], false); assertEquals(0, headMap.size()); }
From source file:org.apache.accumulo.tserver.tablet.Tablet.java
private SplitRowSpec findSplitRow(Collection<FileRef> files) { // never split the root tablet // check if we already decided that we can never split // check to see if we're big enough to split long splitThreshold = tableConfiguration.getMemoryInBytes(Property.TABLE_SPLIT_THRESHOLD); long maxEndRow = tableConfiguration.getMemoryInBytes(Property.TABLE_MAX_END_ROW_SIZE); if (extent.isRootTablet() || estimateTabletSize() <= splitThreshold) { return null; }//from w ww. ja v a 2 s. c o m // have seen a big row before, do not bother checking unless a minor compaction or map file import has occurred. if (sawBigRow) { if (timeOfLastMinCWhenBigFreakinRowWasSeen != lastMinorCompactionFinishTime || timeOfLastImportWhenBigFreakinRowWasSeen != lastMapFileImportTime) { // a minor compaction or map file import has occurred... check again sawBigRow = false; } else { // nothing changed, do not split return null; } } SortedMap<Double, Key> keys = null; try { // we should make .25 below configurable keys = FileUtil.findMidPoint(getTabletServer().getFileSystem(), getTabletServer().getConfiguration(), extent.getPrevEndRow(), extent.getEndRow(), FileUtil.toPathStrings(files), .25); } catch (IOException e) { log.error("Failed to find midpoint " + e.getMessage()); return null; } // check to see if one row takes up most of the tablet, in which case we can not split try { Text lastRow; if (extent.getEndRow() == null) { Key lastKey = (Key) FileUtil.findLastKey(getTabletServer().getFileSystem(), getTabletServer().getConfiguration(), files); lastRow = lastKey.getRow(); } else { lastRow = extent.getEndRow(); } // We expect to get a midPoint for this set of files. If we don't get one, we have a problem. final Key mid = keys.get(.5); if (null == mid) { throw new IllegalStateException("Could not determine midpoint for files"); } // check to see that the midPoint is not equal to the end key if (mid.compareRow(lastRow) == 0) { if (keys.firstKey() < .5) { Key candidate = keys.get(keys.firstKey()); if (candidate.getLength() > maxEndRow) { log.warn("Cannot split tablet " + extent + ", selected split point too long. Length : " + candidate.getLength()); sawBigRow = true; timeOfLastMinCWhenBigFreakinRowWasSeen = lastMinorCompactionFinishTime; timeOfLastImportWhenBigFreakinRowWasSeen = lastMapFileImportTime; return null; } if (candidate.compareRow(lastRow) != 0) { // we should use this ratio in split size estimations if (log.isTraceEnabled()) log.trace(String.format( "Splitting at %6.2f instead of .5, row at .5 is same as end row%n", keys.firstKey())); return new SplitRowSpec(keys.firstKey(), candidate.getRow()); } } log.warn("Cannot split tablet " + extent + " it contains a big row : " + lastRow); sawBigRow = true; timeOfLastMinCWhenBigFreakinRowWasSeen = lastMinorCompactionFinishTime; timeOfLastImportWhenBigFreakinRowWasSeen = lastMapFileImportTime; return null; } Text text = mid.getRow(); SortedMap<Double, Key> firstHalf = keys.headMap(.5); if (firstHalf.size() > 0) { Text beforeMid = firstHalf.get(firstHalf.lastKey()).getRow(); Text shorter = new Text(); int trunc = longestCommonLength(text, beforeMid); shorter.set(text.getBytes(), 0, Math.min(text.getLength(), trunc + 1)); text = shorter; } if (text.getLength() > maxEndRow) { log.warn("Cannot split tablet " + extent + ", selected split point too long. Length : " + text.getLength()); sawBigRow = true; timeOfLastMinCWhenBigFreakinRowWasSeen = lastMinorCompactionFinishTime; timeOfLastImportWhenBigFreakinRowWasSeen = lastMapFileImportTime; return null; } return new SplitRowSpec(.5, text); } catch (IOException e) { // don't split now, but check again later log.error("Failed to find lastkey " + e.getMessage()); return null; } }
From source file:com.aurel.track.report.dashboard.StatusOverTimeGraph.java
/** * Create a map of hierarchical data with TStateChangeBeans for the workItems in the periods * - key: year//from w ww.ja v a 2 s . co m * - value: map * - key: period * - Set of HistorySelectValues * @param statusChangeList * @param timeInterval * @param sample sample (only last from the period) or action (all statuses during a period) * @return */ private static SortedMap<Integer, SortedMap<Integer, List<HistorySelectValues>>> getStatusChangesMap( List<HistorySelectValues> statusChangeList, int timeInterval, boolean sample) { SortedMap<Integer, SortedMap<Integer, List<HistorySelectValues>>> yearToIntervalToStatusChangeBeans = new TreeMap<Integer, SortedMap<Integer, List<HistorySelectValues>>>(); Map yearToIntervalToWorkItemIDs = new HashMap(); int yearValue; int intervalValue; Integer workItemID; if (statusChangeList != null && !statusChangeList.isEmpty()) { Calendar calendarLastModified = Calendar.getInstance(); //get them in the reverse order (the later first) Iterator iterator = statusChangeList.iterator(); int calendarInterval = getCalendarInterval(timeInterval); Set workItemsIDsForInterval = new HashSet(); while (iterator.hasNext()) { HistorySelectValues stateChangeBean = (HistorySelectValues) iterator.next(); workItemID = stateChangeBean.getWorkItemID(); calendarLastModified.setTime(stateChangeBean.getLastEdit()); yearValue = calendarLastModified.get(Calendar.YEAR); intervalValue = calendarLastModified.get(calendarInterval); if (Calendar.WEEK_OF_YEAR == calendarInterval) { //avoid adding the first week of the new year as the first week of the old year, //because it can be that the year is the old one but the last days of the year belong to the first week of the next year //and that would add an entry with the first week of the old year int monthValue = calendarLastModified.get(Calendar.MONTH); if (monthValue >= 11 && intervalValue == 1) { yearValue = yearValue + 1; } } if (sample) { Map intervalToWorkItems = (Map) yearToIntervalToWorkItemIDs.get(new Integer(yearValue)); if (intervalToWorkItems == null) { yearToIntervalToWorkItemIDs.put(new Integer(yearValue), new HashMap()); intervalToWorkItems = (Map) yearToIntervalToWorkItemIDs.get(new Integer(yearValue)); } workItemsIDsForInterval = (Set) intervalToWorkItems.get(new Integer(intervalValue)); if (workItemsIDsForInterval == null) { intervalToWorkItems.put(new Integer(intervalValue), new HashSet()); workItemsIDsForInterval = (Set) intervalToWorkItems.get(new Integer(intervalValue)); } } //add the stateChangeBean if: //1. if not sample add all stateChangeBeans //2. if sample: add only one (the latest i.e. the first one from the list) for each period if (!sample || !workItemsIDsForInterval.contains(workItemID)) { if (sample) { //add workItemID to forbid adding the same workItemID again for the same period workItemsIDsForInterval.add(workItemID); //the last state change bean for the period for the workItem is //a change to a status which is not selected to be shown, so simply neglect it /*if (!statusIDsSet.contains(stateChangeBean.getNewValue())) { continue; }*/ } //workItemIDsSet.add(workItemID); SortedMap<Integer, List<HistorySelectValues>> intervalToStatusChangeBeans = yearToIntervalToStatusChangeBeans .get(new Integer(yearValue)); if (intervalToStatusChangeBeans == null) { yearToIntervalToStatusChangeBeans.put(new Integer(yearValue), new TreeMap<Integer, List<HistorySelectValues>>()); intervalToStatusChangeBeans = yearToIntervalToStatusChangeBeans.get(new Integer(yearValue)); } List<HistorySelectValues> statusChangeBeansForInterval = intervalToStatusChangeBeans .get(new Integer(intervalValue)); if (statusChangeBeansForInterval == null) { intervalToStatusChangeBeans.put(new Integer(intervalValue), new ArrayList()); statusChangeBeansForInterval = intervalToStatusChangeBeans.get(new Integer(intervalValue)); } statusChangeBeansForInterval.add(stateChangeBean); } } } return yearToIntervalToStatusChangeBeans; }
From source file:org.codehaus.mojo.license.api.DefaultDependenciesTool.java
/** * {@inheritDoc}/*from www . ja v a2 s.c o m*/ */ public SortedMap<String, MavenProject> loadProjectDependencies(MavenProject project, MavenProjectDependenciesConfigurator configuration, ArtifactRepository localRepository, List<ArtifactRepository> remoteRepositories, SortedMap<String, MavenProject> cache) { boolean haveNoIncludedGroups = StringUtils.isEmpty(configuration.getIncludedGroups()); boolean haveNoIncludedArtifacts = StringUtils.isEmpty(configuration.getIncludedArtifacts()); boolean haveExcludedGroups = StringUtils.isNotEmpty(configuration.getExcludedGroups()); boolean haveExcludedArtifacts = StringUtils.isNotEmpty(configuration.getExcludedArtifacts()); boolean haveExclusions = haveExcludedGroups || haveExcludedArtifacts; Pattern includedGroupPattern = null; Pattern includedArtifactPattern = null; Pattern excludedGroupPattern = null; Pattern excludedArtifactPattern = null; if (!haveNoIncludedGroups) { includedGroupPattern = Pattern.compile(configuration.getIncludedGroups()); } if (!haveNoIncludedArtifacts) { includedArtifactPattern = Pattern.compile(configuration.getIncludedArtifacts()); } if (haveExcludedGroups) { excludedGroupPattern = Pattern.compile(configuration.getExcludedGroups()); } if (haveExcludedArtifacts) { excludedArtifactPattern = Pattern.compile(configuration.getExcludedArtifacts()); } Set<?> depArtifacts; if (configuration.isIncludeTransitiveDependencies()) { // All project dependencies depArtifacts = project.getArtifacts(); } else { // Only direct project dependencies depArtifacts = project.getDependencyArtifacts(); } List<String> includedScopes = configuration.getIncludedScopes(); List<String> excludeScopes = configuration.getExcludedScopes(); boolean verbose = configuration.isVerbose(); SortedMap<String, MavenProject> result = new TreeMap<String, MavenProject>(); for (Object o : depArtifacts) { Artifact artifact = (Artifact) o; if (DefaultThirdPartyTool.LICENSE_DB_TYPE.equals(artifact.getType())) { // the special dependencies for license databases don't count. // Note that this will still see transitive deps of a license db; so using the build helper inside of another project // to make them will be noisy. continue; } String scope = artifact.getScope(); if (CollectionUtils.isNotEmpty(includedScopes) && !includedScopes.contains(scope)) { // not in included scopes continue; } if (excludeScopes.contains(scope)) { // in excluded scopes continue; } Logger log = getLogger(); String id = MojoHelper.getArtifactId(artifact); if (verbose) { log.info("detected artifact " + id); } // Check if the project should be included // If there is no specified artifacts and group to include, include all boolean isToInclude = haveNoIncludedArtifacts && haveNoIncludedGroups || isIncludable(artifact, includedGroupPattern, includedArtifactPattern); // Check if the project should be excluded boolean isToExclude = isToInclude && haveExclusions && isExcludable(artifact, excludedGroupPattern, excludedArtifactPattern); if (!isToInclude || isToExclude) { if (verbose) { log.info("skip artifact " + id); } continue; } MavenProject depMavenProject = null; if (cache != null) { // try to get project from cache depMavenProject = cache.get(id); } if (depMavenProject != null) { if (verbose) { log.info("add dependency [" + id + "] (from cache)"); } } else { // build project try { depMavenProject = mavenProjectBuilder.buildFromRepository(artifact, remoteRepositories, localRepository, true); depMavenProject.getArtifact().setScope(artifact.getScope()); } catch (ProjectBuildingException e) { log.warn("Unable to obtain POM for artifact : " + artifact, e); continue; } if (verbose) { log.info("add dependency [" + id + "]"); } if (cache != null) { // store it also in cache cache.put(id, depMavenProject); } } // keep the project result.put(id, depMavenProject); } return result; }
From source file:org.apache.accumulo.server.tabletserver.Tablet.java
private SplitRowSpec findSplitRow(Collection<FileRef> files) { // never split the root tablet // check if we already decided that we can never split // check to see if we're big enough to split long splitThreshold = acuTableConf.getMemoryInBytes(Property.TABLE_SPLIT_THRESHOLD); if (extent.isRootTablet() || estimateTabletSize() <= splitThreshold) { return null; }/*from ww w . ja v a 2 s . c om*/ // have seen a big row before, do not bother checking unless a minor compaction or map file import has occurred. if (sawBigRow) { if (timeOfLastMinCWhenBigFreakinRowWasSeen != lastMinorCompactionFinishTime || timeOfLastImportWhenBigFreakinRowWasSeen != lastMapFileImportTime) { // a minor compaction or map file import has occurred... check again sawBigRow = false; } else { // nothing changed, do not split return null; } } SortedMap<Double, Key> keys = null; try { // we should make .25 below configurable keys = FileUtil.findMidPoint(fs, tabletServer.getSystemConfiguration(), extent.getPrevEndRow(), extent.getEndRow(), files, .25); } catch (IOException e) { log.error("Failed to find midpoint " + e.getMessage()); return null; } // check to see if one row takes up most of the tablet, in which case we can not split try { Text lastRow; if (extent.getEndRow() == null) { Key lastKey = (Key) FileUtil.findLastKey(fs, tabletServer.getSystemConfiguration(), files); lastRow = lastKey.getRow(); } else { lastRow = extent.getEndRow(); } // check to see that the midPoint is not equal to the end key if (keys.get(.5).compareRow(lastRow) == 0) { if (keys.firstKey() < .5) { Key candidate = keys.get(keys.firstKey()); if (candidate.compareRow(lastRow) != 0) { // we should use this ratio in split size estimations if (log.isTraceEnabled()) log.trace(String.format( "Splitting at %6.2f instead of .5, row at .5 is same as end row%n", keys.firstKey())); return new SplitRowSpec(keys.firstKey(), candidate.getRow()); } } log.warn("Cannot split tablet " + extent + " it contains a big row : " + lastRow); sawBigRow = true; timeOfLastMinCWhenBigFreakinRowWasSeen = lastMinorCompactionFinishTime; timeOfLastImportWhenBigFreakinRowWasSeen = lastMapFileImportTime; return null; } Key mid = keys.get(.5); Text text = (mid == null) ? null : mid.getRow(); SortedMap<Double, Key> firstHalf = keys.headMap(.5); if (firstHalf.size() > 0) { Text beforeMid = firstHalf.get(firstHalf.lastKey()).getRow(); Text shorter = new Text(); int trunc = longestCommonLength(text, beforeMid); shorter.set(text.getBytes(), 0, Math.min(text.getLength(), trunc + 1)); text = shorter; } return new SplitRowSpec(.5, text); } catch (IOException e) { // don't split now, but check again later log.error("Failed to find lastkey " + e.getMessage()); return null; } }
From source file:org.apache.accumulo.tserver.Tablet.java
private SplitRowSpec findSplitRow(Collection<FileRef> files) { // never split the root tablet // check if we already decided that we can never split // check to see if we're big enough to split long splitThreshold = acuTableConf.getMemoryInBytes(Property.TABLE_SPLIT_THRESHOLD); if (extent.isRootTablet() || estimateTabletSize() <= splitThreshold) { return null; }/*from ww w . java 2 s. c o m*/ // have seen a big row before, do not bother checking unless a minor compaction or map file import has occurred. if (sawBigRow) { if (timeOfLastMinCWhenBigFreakinRowWasSeen != lastMinorCompactionFinishTime || timeOfLastImportWhenBigFreakinRowWasSeen != lastMapFileImportTime) { // a minor compaction or map file import has occurred... check again sawBigRow = false; } else { // nothing changed, do not split return null; } } SortedMap<Double, Key> keys = null; try { // we should make .25 below configurable keys = FileUtil.findMidPoint(fs, tabletServer.getSystemConfiguration(), extent.getPrevEndRow(), extent.getEndRow(), FileUtil.toPathStrings(files), .25); } catch (IOException e) { log.error("Failed to find midpoint " + e.getMessage()); return null; } // check to see if one row takes up most of the tablet, in which case we can not split try { Text lastRow; if (extent.getEndRow() == null) { Key lastKey = (Key) FileUtil.findLastKey(fs, tabletServer.getSystemConfiguration(), files); lastRow = lastKey.getRow(); } else { lastRow = extent.getEndRow(); } // check to see that the midPoint is not equal to the end key if (keys.get(.5).compareRow(lastRow) == 0) { if (keys.firstKey() < .5) { Key candidate = keys.get(keys.firstKey()); if (candidate.compareRow(lastRow) != 0) { // we should use this ratio in split size estimations if (log.isTraceEnabled()) log.trace(String.format( "Splitting at %6.2f instead of .5, row at .5 is same as end row%n", keys.firstKey())); return new SplitRowSpec(keys.firstKey(), candidate.getRow()); } } log.warn("Cannot split tablet " + extent + " it contains a big row : " + lastRow); sawBigRow = true; timeOfLastMinCWhenBigFreakinRowWasSeen = lastMinorCompactionFinishTime; timeOfLastImportWhenBigFreakinRowWasSeen = lastMapFileImportTime; return null; } Key mid = keys.get(.5); Text text = (mid == null) ? null : mid.getRow(); SortedMap<Double, Key> firstHalf = keys.headMap(.5); if (firstHalf.size() > 0) { Text beforeMid = firstHalf.get(firstHalf.lastKey()).getRow(); Text shorter = new Text(); int trunc = longestCommonLength(text, beforeMid); shorter.set(text.getBytes(), 0, Math.min(text.getLength(), trunc + 1)); text = shorter; } return new SplitRowSpec(.5, text); } catch (IOException e) { // don't split now, but check again later log.error("Failed to find lastkey " + e.getMessage()); return null; } }
From source file:org.kuali.coeus.common.budget.impl.calculator.BudgetCalculationServiceImpl.java
protected SortedMap<RateType, List<ScaleTwoDecimal>> calculateExpenseTotals(Budget budget, boolean personnelFlag) { SortedMap<RateType, List<ScaleTwoDecimal>> calculatedExpenseTotals = new TreeMap<>(); List<ScaleTwoDecimal> calculatedDirectCostSummaryTotals = new ArrayList<>(); for (int i = 0; i < budget.getBudgetPeriods().size(); i++) { calculatedDirectCostSummaryTotals.add(i, ScaleTwoDecimal.ZERO); }/*from w ww . j a v a2 s . co m*/ final String totalsMapKey; if (personnelFlag) { totalsMapKey = "personnelCalculatedExpenseSummaryTotals"; } else { totalsMapKey = "nonPersonnelCalculatedExpenseSummaryTotals"; } budget.getBudgetSummaryTotals().put(totalsMapKey, calculatedDirectCostSummaryTotals); for (BudgetPeriod budgetPeriod : budget.getBudgetPeriods()) { for (BudgetLineItem budgetLineItem : budgetPeriod.getBudgetLineItems()) { if ((personnelFlag && StringUtils.equals( budgetLineItem.getCostElementBO().getBudgetCategory().getBudgetCategoryTypeCode(), "P")) || (!personnelFlag && !StringUtils.equals( budgetLineItem.getCostElementBO().getBudgetCategory().getBudgetCategoryTypeCode(), "P"))) { // get calculated expenses QueryList<BudgetLineItemCalculatedAmount> lineItemCalcAmtQueryList = new QueryList<>(); lineItemCalcAmtQueryList.addAll(budgetLineItem.getBudgetLineItemCalculatedAmounts()); List<RateType> rateTypes = new ArrayList<>(); for (Object item : budgetLineItem.getBudgetLineItemCalculatedAmounts()) { BudgetLineItemCalculatedAmount budgetLineItemCalculatedAmount = (BudgetLineItemCalculatedAmount) item; RateType rateType = createRateType(budgetLineItemCalculatedAmount); RateClass rateClass = null; if (rateType != null) { rateType.refreshReferenceObject("rateClass"); rateClass = rateType.getRateClass(); } if (((personnelFlag && rateClass != null && !StringUtils.equals(rateClass.getRateClassTypeCode(), "E")) || !personnelFlag) && !rateTypes.contains(rateType)) { rateTypes.add(rateType); Equals equalsRC = new Equals("rateClassCode", budgetLineItemCalculatedAmount.getRateClassCode()); Equals equalsRT = new Equals("rateTypeCode", budgetLineItemCalculatedAmount.getRateTypeCode()); And RCandRT = new And(equalsRC, equalsRT); ScaleTwoDecimal rateTypeTotalInThisPeriod = lineItemCalcAmtQueryList .sumObjects(CALCULATED_COST, RCandRT); if (!calculatedExpenseTotals.containsKey(rateType)) { List<ScaleTwoDecimal> rateTypePeriodTotals = new ArrayList<>(); for (int i = 0; i < budget.getBudgetPeriods().size(); i++) { rateTypePeriodTotals.add(i, ScaleTwoDecimal.ZERO); } calculatedExpenseTotals.put(rateType, rateTypePeriodTotals); } calculatedExpenseTotals.get(rateType).set(budgetPeriod.getBudgetPeriod() - 1, (calculatedExpenseTotals.get(rateType).get(budgetPeriod.getBudgetPeriod() - 1)) .add(rateTypeTotalInThisPeriod)); if (!StringUtils.equals(rateClass.getRateClassTypeCode(), RateClassType.OVERHEAD.getRateClassType())) { budget.getBudgetSummaryTotals().get(totalsMapKey).set( budgetPeriod.getBudgetPeriod() - 1, ((budget.getBudgetSummaryTotals().get(totalsMapKey) .get(budgetPeriod.getBudgetPeriod() - 1))) .add(rateTypeTotalInThisPeriod)); } budgetPeriod .setExpenseTotal(budgetPeriod.getExpenseTotal().add(rateTypeTotalInThisPeriod)); } } } } } return calculatedExpenseTotals; }
From source file:playground.sergioo.workplaceCapacities2012.MainWorkplaceCapacities.java
private static Map<Tuple<Id<TransitStopFacility>, Id<ActivityFacility>>, Tuple<Boolean, Double>> calculateAreaStopTravelTimes( SortedMap<String, Coord> stopsBase, Map<Id<TransitStopFacility>, Double> stopsCapacities, Network network) throws BadStopException, IOException, InstantiationException, IllegalAccessException, ClassNotFoundException, SQLException, NoConnectionException { List<Map<String, Id<Link>>> linksStops; try {//from w ww . j av a2 s. co m ObjectInputStream ois = new ObjectInputStream(new FileInputStream(LINKS_MAP_FILE)); linksStops = (List<Map<String, Id<Link>>>) ois.readObject(); ois.close(); } catch (EOFException e) { linksStops = new ArrayList<Map<String, Id<Link>>>(); for (int n = 0; n < NUM_NEAR; n++) { linksStops.add(new HashMap<String, Id<Link>>()); for (Entry<String, Coord> stopBase : stopsBase.entrySet()) { Id<Link> nearest = network.getLinks().values().iterator().next().getId(); double nearestDistance = CoordUtils.calcDistance(network.getLinks().get(nearest).getCoord(), stopBase.getValue()); for (Link link : network.getLinks().values()) if (link.getAllowedModes().contains("car")) { boolean selected = false; for (int p = 0; p < n; p++) if (linksStops.get(p).get(stopBase.getKey()).equals(link.getId())) selected = true; if (!selected && CoordUtils.calcDistance(link.getToNode().getCoord(), stopBase.getValue()) < nearestDistance) { nearest = link.getId(); nearestDistance = CoordUtils.calcDistance( network.getLinks().get(nearest).getCoord(), stopBase.getValue()); } } linksStops.get(n).put(stopBase.getKey(), nearest); } } ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(LINKS_MAP_FILE)); oos.writeObject(linksStops); oos.close(); } //Compute stops facilities weights TravelDisutility travelMinCost = new TravelDisutility() { @Override public double getLinkTravelDisutility(final Link link, final double time, final Person person, final Vehicle vehicle) { return getLinkMinimumTravelDisutility(link); } @Override public double getLinkMinimumTravelDisutility(Link link) { return link.getLength() / WALKING_SPEED; } }; TravelTime timeFunction = new TravelTime() { @Override public double getLinkTravelTime(Link link, double time, Person person, Vehicle vehicle) { return link.getLength() / WALKING_SPEED; } }; PreProcessLandmarks preProcessData = new PreProcessLandmarks(travelMinCost); preProcessData.run(network); AStarLandmarks aStarLandmarks = new AStarLandmarks(network, preProcessData, timeFunction); Map<Tuple<Id<TransitStopFacility>, Id<ActivityFacility>>, Tuple<Boolean, Double>> weights = new HashMap<Tuple<Id<TransitStopFacility>, Id<ActivityFacility>>, Tuple<Boolean, Double>>(); Collection<Tuple<Id<TransitStopFacility>, Integer>> removeStops = new ArrayList<Tuple<Id<TransitStopFacility>, Integer>>(); travelTimes = new ArrayList<List<Double>>(); int s = 0; for (Entry<String, Coord> stop : stopsBase.entrySet()) { String stopKey = stop.getKey(); boolean mrtStop = stopKey.startsWith("STN"); /*Coord stopCoord = stop.getValue(); boolean inStop = stopCoord.getX()>downLeft.getX() && stopCoord.getX()<upRight.getX() && stopCoord.getY()>downLeft.getY() && stopCoord.getY()<upRight.getY(); if(inStop)*/ travelTimes.add(new ArrayList<Double>()); double maxTimeFromStop = 0; Collection<Id<Link>> linkIds = new ArrayList<Id<Link>>(); for (int n = 0; n < NUM_NEAR; n++) if (CoordUtils.calcDistance( network.getLinks().get(linksStops.get(n).get(stopKey)).getToNode().getCoord(), stop.getValue()) < MAX_TRAVEL_TIME * WALKING_SPEED / 5) linkIds.add(linksStops.get(n).get(stopKey)); Id<TransitStopFacility> stopId = Id.create(stopKey, TransitStopFacility.class); double maxCapacityNearFacilities = 0; int w = 0; for (MPAreaData mPArea : dataMPAreas.values()) { double distance = CoordUtils.calcDistance(stopsBase.get(stopKey), mPArea.getCoord()); /*Coord areaCoord = mPArea.getCoord(); boolean inArea = areaCoord.getX()>downLeft.getX() && areaCoord.getX()<upRight.getX() && areaCoord.getY()>downLeft.getY() && areaCoord.getY()<upRight.getY(); if(inStop && inArea) {*/ travelTimes.get(travelTimes.size() - 1).add(getCost(mrtStop, Math.floor(36000.0 + distance + 0.5))); w++; //} if (distance < MIN_TRAVEL_TIME * WALKING_SPEED) { weights.put(new Tuple<Id<TransitStopFacility>, Id<ActivityFacility>>(stopId, mPArea.getId()), new Tuple<Boolean, Double>(true, getCost(mrtStop, distance / WALKING_SPEED))); //if(inStop && inArea) { travelTimes.get(travelTimes.size() - 1).set(w - 1, getCost(mrtStop, distance / WALKING_SPEED)); mPArea.addTravelTime(stopId, distance / WALKING_SPEED); //} if (distance / WALKING_SPEED > maxTimeFromStop) maxTimeFromStop = distance / WALKING_SPEED; maxCapacityNearFacilities += maximumAreaCapacities.get(mPArea.getId()); } else if (distance < MAX_TRAVEL_TIME * WALKING_SPEED) { double walkingTime = Double.MAX_VALUE; for (Id<Link> linkId : linkIds) for (Id<Link> linkId2 : mPArea.getLinkIds()) { double walkingTimeA = aStarLandmarks.calcLeastCostPath( network.getLinks().get(linkId).getToNode(), network.getLinks().get(linkId2).getFromNode(), 0, null, null).travelCost + CoordUtils.calcDistance( network.getLinks().get(linkId2).getFromNode().getCoord(), mPArea.getCoord()) / WALKING_SPEED; if (walkingTimeA < walkingTime) walkingTime = walkingTimeA; } if (walkingTime <= MAX_TRAVEL_TIME) { weights.put( new Tuple<Id<TransitStopFacility>, Id<ActivityFacility>>(stopId, mPArea.getId()), new Tuple<Boolean, Double>(true, getCost(mrtStop, walkingTime))); //if(inStop && inArea) { travelTimes.get(travelTimes.size() - 1).set(w - 1, getCost(mrtStop, walkingTime)); mPArea.addTravelTime(stopId, walkingTime); //} if (walkingTime > maxTimeFromStop) maxTimeFromStop = walkingTime; maxCapacityNearFacilities += maximumAreaCapacities.get(mPArea.getId()); } } } if (stopsCapacities.get(stopId) > maxCapacityNearFacilities) { double maxCapacityNear2Facilities = maxCapacityNearFacilities; w = 0; for (MPAreaData mPArea : dataMPAreas.values()) { /*Coord areaCoord = mPArea.getCoord(); boolean inArea = areaCoord.getX()>downLeft.getX() && areaCoord.getX()<upRight.getX() && areaCoord.getY()>downLeft.getY() && areaCoord.getY()<upRight.getY(); if(inStop && inArea)*/ w++; if (CoordUtils.calcDistance(stopsBase.get(stopKey), mPArea.getCoord()) < (MAX_TRAVEL_TIME * 2 / 3) * PRIVATE_BUS_SPEED) { double walkingTime = Double.MAX_VALUE; for (Id<Link> linkId : linkIds) for (Id<Link> linkId2 : mPArea.getLinkIds()) { double walkingTimeA = aStarLandmarks.calcLeastCostPath( network.getLinks().get(linkId).getToNode(), network.getLinks().get(linkId2).getFromNode(), 0, null, null).travelCost + CoordUtils.calcDistance( network.getLinks().get(linkId2).getFromNode().getCoord(), mPArea.getCoord()) / WALKING_SPEED; if (walkingTimeA < walkingTime) walkingTime = walkingTimeA; } double privateBusTime = Double.MAX_VALUE; for (Id<Link> linkId : linkIds) for (Id<Link> linkId2 : mPArea.getLinkIds()) { double privateBusTimeA = aStarLandmarks.calcLeastCostPath( network.getLinks().get(linkId).getToNode(), network.getLinks().get(linkId2).getFromNode(), 0, null, null).travelCost * WALKING_SPEED / PRIVATE_BUS_SPEED + CoordUtils.calcDistance( network.getLinks().get(linkId2).getFromNode().getCoord(), mPArea.getCoord()) / WALKING_SPEED; if (privateBusTimeA < privateBusTime) privateBusTime = privateBusTimeA; } if (walkingTime > MAX_TRAVEL_TIME && privateBusTime <= (MAX_TRAVEL_TIME * 2 / 3)) { weights.put( new Tuple<Id<TransitStopFacility>, Id<ActivityFacility>>(stopId, mPArea.getId()), new Tuple<Boolean, Double>(false, getCost(mrtStop, privateBusTime))); //if(inStop && inArea) { travelTimes.get(travelTimes.size() - 1).set(w - 1, getCost(mrtStop, privateBusTime)); mPArea.addTravelTime(stopId, privateBusTime); //} if (privateBusTime > maxTimeFromStop) maxTimeFromStop = privateBusTime; maxCapacityNear2Facilities += maximumAreaCapacities.get(mPArea.getId()); } } } if (stopsCapacities.get(stopId) > maxCapacityNear2Facilities) { System.out.println("Far" + stopId); double maxCapacityNear3Facilities = maxCapacityNear2Facilities; w = 0; for (MPAreaData mPArea : dataMPAreas.values()) { /*Coord areaCoord = mPArea.getCoord(); boolean inArea = areaCoord.getX()>downLeft.getX() && areaCoord.getX()<upRight.getX() && areaCoord.getY()>downLeft.getY() && areaCoord.getY()<upRight.getY(); if(inStop && inArea)*/ w++; if (CoordUtils.calcDistance(stopsBase.get(stopKey), mPArea.getCoord()) < MAX_TRAVEL_TIME * PRIVATE_BUS_SPEED) { double privateBusTime = Double.MAX_VALUE; for (Id<Link> linkId : linkIds) for (Id<Link> linkId2 : mPArea.getLinkIds()) { double privateBusTimeA = aStarLandmarks.calcLeastCostPath( network.getLinks().get(linkId).getToNode(), network.getLinks().get(linkId2).getFromNode(), 0, null, null).travelCost * WALKING_SPEED / PRIVATE_BUS_SPEED + CoordUtils.calcDistance( network.getLinks().get(linkId2).getFromNode().getCoord(), mPArea.getCoord()) / WALKING_SPEED; if (privateBusTimeA < privateBusTime) privateBusTime = privateBusTimeA; } if (privateBusTime > (MAX_TRAVEL_TIME * 2 / 3) && privateBusTime <= MAX_TRAVEL_TIME) { weights.put( new Tuple<Id<TransitStopFacility>, Id<ActivityFacility>>(stopId, mPArea.getId()), new Tuple<Boolean, Double>(false, getCost(mrtStop, privateBusTime))); //if(inStop && inArea) { travelTimes.get(travelTimes.size() - 1).set(w - 1, getCost(mrtStop, privateBusTime)); mPArea.addTravelTime(stopId, privateBusTime); //} if (privateBusTime > maxTimeFromStop) maxTimeFromStop = privateBusTime; maxCapacityNear3Facilities += maximumAreaCapacities.get(mPArea.getId()); } } } if (stopsCapacities.get(stopId) > maxCapacityNear3Facilities) { System.out.println("Very far" + stopId); removeStops.add(new Tuple<Id<TransitStopFacility>, Integer>(stopId, s)); } } } double totalTimeFromStop = 0; maxTimeFromStop++; for (Entry<Tuple<Id<TransitStopFacility>, Id<ActivityFacility>>, Tuple<Boolean, Double>> weight : weights .entrySet()) if (weight.getKey().getFirst().equals(stopId)) { double correctWeight = maxTimeFromStop - weight.getValue().getSecond(); weights.put(weight.getKey(), new Tuple<Boolean, Double>(weight.getValue().getFirst(), correctWeight)); totalTimeFromStop += correctWeight; } if (totalTimeFromStop != 0) for (Entry<Tuple<Id<TransitStopFacility>, Id<ActivityFacility>>, Tuple<Boolean, Double>> weight : weights .entrySet()) if (weight.getKey().getFirst().equals(stopId)) weights.put(weight.getKey(), new Tuple<Boolean, Double>(weight.getValue().getFirst(), weight.getValue().getSecond() / totalTimeFromStop)); if (s++ % 100 == 0) System.out.println(s + " of " + stopsBase.size()); } int num = 0; for (Tuple<Id<TransitStopFacility>, Integer> stopId : removeStops) { num += stopsCapacities.get(stopId.getFirst()); /*stopsCapacities.remove(stopId.getFirst()); stopsBase.remove(stopId.getFirst().toString()); stopScheduleCapacities.remove(stopId.getSecond().intValue()); travelTimes.remove(stopId.getSecond().intValue());*/ } System.out.println(num + " workers lost."); ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(AREAS_MAP_FILE)); oos.writeObject(dataMPAreas); oos.close(); return weights; }