diff --git a/contribs/common/src/main/java/org/matsim/contrib/common/zones/systems/grid/h3/H3ZoneSystem.java b/contribs/common/src/main/java/org/matsim/contrib/common/zones/systems/grid/h3/H3ZoneSystem.java index e9c84bccc4a..286bc9a09ca 100644 --- a/contribs/common/src/main/java/org/matsim/contrib/common/zones/systems/grid/h3/H3ZoneSystem.java +++ b/contribs/common/src/main/java/org/matsim/contrib/common/zones/systems/grid/h3/H3ZoneSystem.java @@ -13,8 +13,12 @@ import org.matsim.core.utils.geometry.CoordinateTransformation; import org.matsim.core.utils.geometry.transformations.TransformationFactory; -import java.util.*; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.Optional; import java.util.function.Predicate; +import java.util.stream.Collectors; /** * @author nkuehnel / MOIA @@ -39,41 +43,38 @@ public H3ZoneSystem(String crs, int resolution, Network network, Predicate this.resolution = resolution; this.network = network; this.filter = filter; - this.network.getLinks().values().forEach(l -> getZoneForCoord(l.getToNode().getCoord())); + init(); } - - @Override - public Optional getZoneForCoord(Coord coord) { - - long h3Address = getH3Cell(coord); - Id zoneId = Id.create(h3Address, Zone.class); - - if(zones.containsKey(zoneId)) { - return Optional.of(zones.get(zoneId)); - } else { - Optional zone = H3Utils.createZone(h3Address, fromLatLong); - if(zone.isPresent() && filter.test(zone.get())) { - initZone(zone.get(), h3Address); - return zone; - } else { - return Optional.empty(); - } + private void init() { + Map> linksToH3 = + this.network.getLinks().values() + .stream() + .collect(Collectors.groupingBy(link -> getH3Cell(link.getToNode().getCoord()))); + for (Map.Entry> linksH3 : linksToH3.entrySet()) { + Optional maybeZone = createZone(linksH3.getKey()); + maybeZone.ifPresent(z -> { + zones.put(z.getId(), z); + zoneToLinksMap.put(z.getId(), linksH3.getValue()); + }); } } - private void initZone(Zone zone, long h3Address) { - if(filter.test(zone)) { - zones.put(zone.getId(), zone); - for (Link link : network.getLinks().values()) { - long linkH3Address = getH3Cell(link.getToNode().getCoord()); - - if (linkH3Address == h3Address) { - List links = zoneToLinksMap.computeIfAbsent(zone.getId(), id -> new ArrayList<>()); - links.add(link); - } - } + private Optional createZone(Long h3) { + Optional zone = H3Utils.createZone(h3, fromLatLong); + if(zone.isPresent() && filter.test(zone.get())) { + return zone; } + return Optional.empty(); + } + + @Override + public Optional getZoneForCoord(Coord coord) { + long h3Address = getH3Cell(coord); + Id zoneId = Id.create(h3Address, Zone.class); + // create new zone if absent, should not be linked to existing links in the network, + // as all of them are covered in the init() phase. + return Optional.ofNullable(zones.computeIfAbsent(zoneId, id -> createZone(h3Address).orElse(null))); } private long getH3Cell(Coord coord) { @@ -106,4 +107,4 @@ public List getLinksForZoneId(Id zone) { public Map, Zone> getZones() { return Collections.unmodifiableMap(zones); } -} +} \ No newline at end of file diff --git a/contribs/common/src/main/java/org/matsim/contrib/common/zones/systems/grid/square/SquareGridZoneSystem.java b/contribs/common/src/main/java/org/matsim/contrib/common/zones/systems/grid/square/SquareGridZoneSystem.java index f11fa58f614..b1319fed1a9 100644 --- a/contribs/common/src/main/java/org/matsim/contrib/common/zones/systems/grid/square/SquareGridZoneSystem.java +++ b/contribs/common/src/main/java/org/matsim/contrib/common/zones/systems/grid/square/SquareGridZoneSystem.java @@ -66,11 +66,11 @@ public SquareGridZoneSystem(Network network, double cellSize, Predicate zo } public SquareGridZoneSystem(Network network, double cellSize, boolean filterByNetwork, Predicate zoneFilter) { this.zoneFilter = zoneFilter; - Preconditions.checkArgument(!network.getNodes().isEmpty(), "Cannot create SquareGrid if no nodes"); - this.network = network; this.cellSize = cellSize; + Preconditions.checkArgument(!network.getNodes().isEmpty(), "Cannot create SquareGrid if no nodes"); + initBounds(); this.rows = Math.max(1, (int) Math.ceil((maxY - minY) / cellSize)); diff --git a/contribs/drt-extensions/src/test/java/org/matsim/contrib/drt/extension/h3/drtZone/H3DrtZonalSystemTest.java b/contribs/common/src/test/java/org/matsim/contrib/common/zones/systems/h3/H3DrtZonalSystemTest.java similarity index 55% rename from contribs/drt-extensions/src/test/java/org/matsim/contrib/drt/extension/h3/drtZone/H3DrtZonalSystemTest.java rename to contribs/common/src/test/java/org/matsim/contrib/common/zones/systems/h3/H3DrtZonalSystemTest.java index 3724d5d8eac..723e4026825 100644 --- a/contribs/drt-extensions/src/test/java/org/matsim/contrib/drt/extension/h3/drtZone/H3DrtZonalSystemTest.java +++ b/contribs/common/src/test/java/org/matsim/contrib/common/zones/systems/h3/H3DrtZonalSystemTest.java @@ -18,7 +18,7 @@ * *********************************************************************** * */ -package org.matsim.contrib.drt.extension.h3.drtZone; +package org.matsim.contrib.common.zones.systems.h3; import org.junit.jupiter.api.Test; import org.matsim.api.core.v01.Id; @@ -48,20 +48,20 @@ void test_Holzkirchen_Resolution3() { Network network = getNetwork(); String crs = TransformationFactory.DHDN_GK4; int resolution = 3; - ZoneSystem drtZonalSystem = new H3ZoneSystem(crs, resolution, network, z -> true); + ZoneSystem zoneSystem = new H3ZoneSystem(crs, resolution, network, z -> true); - assertThat(drtZonalSystem.getZones().containsKey(createZoneId("590526392240701439"))).isTrue(); + assertThat(zoneSystem.getZones().containsKey(createZoneId("590526392240701439"))).isTrue(); // center of Holzkirchen - assertThat(drtZonalSystem.getZoneForLinkId(Id.createLinkId(358598)).orElseThrow().getId()).isEqualTo(createZoneId("590526667118608383")); + assertThat(zoneSystem.getZoneForLinkId(Id.createLinkId(358598)).orElseThrow().getId()).isEqualTo(createZoneId("590526667118608383")); // Thanning (Western border of network) - assertThat(drtZonalSystem.getZoneForLinkId(Id.createLinkId(78976)).orElseThrow().getId()).isEqualTo(createZoneId("590526667118608383")); + assertThat(zoneSystem.getZoneForLinkId(Id.createLinkId(78976)).orElseThrow().getId()).isEqualTo(createZoneId("590526667118608383")); // between Gross- and Kleinpienzenau (Southeastern border of network) - assertThat(drtZonalSystem.getZoneForLinkId(Id.createLinkId(59914)).orElseThrow().getId()).isEqualTo(createZoneId("590526392240701439")); + assertThat(zoneSystem.getZoneForLinkId(Id.createLinkId(59914)).orElseThrow().getId()).isEqualTo(createZoneId("590526392240701439")); //check all links are mapped for (Link link : network.getLinks().values()) { - assertNotNull(drtZonalSystem.getZoneForLinkId(link.getId())); + assertNotNull(zoneSystem.getZoneForLinkId(link.getId())); } } @@ -71,23 +71,23 @@ void test_Holzkirchen_Resolution5() { String crs = TransformationFactory.DHDN_GK4; int resolution = 5; - ZoneSystem drtZonalSystem = new H3ZoneSystem(crs, resolution, network, z -> true); + ZoneSystem zoneSystem = new H3ZoneSystem(crs, resolution, network, z -> true); - assertThat(drtZonalSystem.getZones().containsKey(createZoneId("599533579684282367"))).isTrue(); - assertThat(drtZonalSystem.getZones().containsKey(createZoneId("599533826644901887"))).isTrue(); - assertThat(drtZonalSystem.getZones().containsKey(createZoneId("599533499153645567"))).isTrue(); - assertThat(drtZonalSystem.getZones().containsKey(createZoneId("599533503448612863"))).isTrue(); + assertThat(zoneSystem.getZones().containsKey(createZoneId("599533579684282367"))).isTrue(); + assertThat(zoneSystem.getZones().containsKey(createZoneId("599533826644901887"))).isTrue(); + assertThat(zoneSystem.getZones().containsKey(createZoneId("599533499153645567"))).isTrue(); + assertThat(zoneSystem.getZones().containsKey(createZoneId("599533503448612863"))).isTrue(); // center of Holzkirchen - assertThat(drtZonalSystem.getZoneForLinkId(Id.createLinkId(358598)).orElseThrow().getId()).isEqualTo(createZoneId("599533826644901887")); + assertThat(zoneSystem.getZoneForLinkId(Id.createLinkId(358598)).orElseThrow().getId()).isEqualTo(createZoneId("599533826644901887")); // Thanning (Western border of network) - assertThat(drtZonalSystem.getZoneForLinkId(Id.createLinkId(78976)).orElseThrow().getId()).isEqualTo(createZoneId("599533503448612863")); + assertThat(zoneSystem.getZoneForLinkId(Id.createLinkId(78976)).orElseThrow().getId()).isEqualTo(createZoneId("599533503448612863")); // between Gross- and Kleinpienzenau (Southeastern border of network) - assertThat(drtZonalSystem.getZoneForLinkId(Id.createLinkId(59914)).orElseThrow().getId()).isEqualTo(createZoneId("599533579684282367")); + assertThat(zoneSystem.getZoneForLinkId(Id.createLinkId(59914)).orElseThrow().getId()).isEqualTo(createZoneId("599533579684282367")); //check all links are mapped for (Link link : network.getLinks().values()) { - assertNotNull(drtZonalSystem.getZoneForLinkId(link.getId())); + assertNotNull(zoneSystem.getZoneForLinkId(link.getId())); } } @@ -97,18 +97,18 @@ void test_Holzkirchen_Resolution6() { String crs = TransformationFactory.DHDN_GK4; int resolution = 6; - ZoneSystem drtZonalSystem = new H3ZoneSystem(crs, resolution, network, z -> true); + ZoneSystem zoneSystem = new H3ZoneSystem(crs, resolution, network, z -> true); // center of Holzkirchen - assertThat(drtZonalSystem.getZoneForLinkId(Id.createLinkId(358598)).orElseThrow().getId()).isEqualTo(createZoneId("604037425601183743")); + assertThat(zoneSystem.getZoneForLinkId(Id.createLinkId(358598)).orElseThrow().getId()).isEqualTo(createZoneId("604037425601183743")); // Thanning (Western border of network) - assertThat(drtZonalSystem.getZoneForLinkId(Id.createLinkId(78976)).orElseThrow().getId()).isEqualTo(createZoneId("604037102136459263")); + assertThat(zoneSystem.getZoneForLinkId(Id.createLinkId(78976)).orElseThrow().getId()).isEqualTo(createZoneId("604037102136459263")); // between Gross- and Kleinpienzenau (Southeastern border of network) - assertThat(drtZonalSystem.getZoneForLinkId(Id.createLinkId(59914)).orElseThrow().getId()).isEqualTo(createZoneId("604037178372128767")); + assertThat(zoneSystem.getZoneForLinkId(Id.createLinkId(59914)).orElseThrow().getId()).isEqualTo(createZoneId("604037178372128767")); //check all links are mapped for (Link link : network.getLinks().values()) { - assertNotNull(drtZonalSystem.getZoneForLinkId(link.getId())); + assertNotNull(zoneSystem.getZoneForLinkId(link.getId())); } } @@ -117,18 +117,18 @@ void test_Holzkirchen_Resolution10() { Network network = getNetwork(); String crs = TransformationFactory.DHDN_GK4; int resolution = 10; - ZoneSystem drtZonalSystem = new H3ZoneSystem(crs, resolution, network, z -> true); + ZoneSystem zoneSystem = new H3ZoneSystem(crs, resolution, network, z -> true); // center of Holzkirchen - assertThat(drtZonalSystem.getZoneForLinkId(Id.createLinkId(358598)).orElseThrow().getId()).isEqualTo(createZoneId("622051824027533311")); + assertThat(zoneSystem.getZoneForLinkId(Id.createLinkId(358598)).orElseThrow().getId()).isEqualTo(createZoneId("622051824027533311")); // Thanning (Western border of network) - assertThat(drtZonalSystem.getZoneForLinkId(Id.createLinkId(78976)).orElseThrow().getId()).isEqualTo(createZoneId("622051500514213887")); + assertThat(zoneSystem.getZoneForLinkId(Id.createLinkId(78976)).orElseThrow().getId()).isEqualTo(createZoneId("622051500514213887")); // between Gross- and Kleinpienzenau (Southeastern border of network) - assertThat(drtZonalSystem.getZoneForLinkId(Id.createLinkId(59914)).orElseThrow().getId()).isEqualTo(createZoneId("622051576862081023")); + assertThat(zoneSystem.getZoneForLinkId(Id.createLinkId(59914)).orElseThrow().getId()).isEqualTo(createZoneId("622051576862081023")); //check all links are mapped for (Link link : network.getLinks().values()) { - assertNotNull(drtZonalSystem.getZoneForLinkId(link.getId())); + assertNotNull(zoneSystem.getZoneForLinkId(link.getId())); } } @@ -138,19 +138,19 @@ void test_Holzkirchen_Resolution12() { String crs = TransformationFactory.DHDN_GK4; int resolution = 12; - ZoneSystem drtZonalSystem = new H3ZoneSystem(crs, resolution, network, z -> true); + ZoneSystem zoneSystem = new H3ZoneSystem(crs, resolution, network, z -> true); // center of Holzkirchen - assertThat(drtZonalSystem.getZoneForLinkId(Id.createLinkId(358598)).orElseThrow().getId()).isEqualTo(createZoneId("631059023282267135")); + assertThat(zoneSystem.getZoneForLinkId(Id.createLinkId(358598)).orElseThrow().getId()).isEqualTo(createZoneId("631059023282267135")); // Thanning (Western border of network) - assertThat(drtZonalSystem.getZoneForLinkId(Id.createLinkId(78976)).orElseThrow().getId()).isEqualTo(createZoneId("631058699768943103")); + assertThat(zoneSystem.getZoneForLinkId(Id.createLinkId(78976)).orElseThrow().getId()).isEqualTo(createZoneId("631058699768943103")); // between Gross- and Kleinpienzenau (Southeastern border of network) - assertThat(drtZonalSystem.getZoneForLinkId(Id.createLinkId(59914)).orElseThrow().getId()).isEqualTo(createZoneId("631058776116789759")); + assertThat(zoneSystem.getZoneForLinkId(Id.createLinkId(59914)).orElseThrow().getId()).isEqualTo(createZoneId("631058776116789759")); //check all links are mapped for (Link link : network.getLinks().values()) { - assertNotNull(drtZonalSystem.getZoneForLinkId(link.getId())); + assertNotNull(zoneSystem.getZoneForLinkId(link.getId())); } } diff --git a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/ColdEmissionAnalysisModule.java b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/ColdEmissionAnalysisModule.java index 45013b10201..52ab385cf7d 100644 --- a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/ColdEmissionAnalysisModule.java +++ b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/ColdEmissionAnalysisModule.java @@ -17,7 +17,7 @@ * (at your option) any later version. * * See also COPYING, LICENSE and WARRANTY file * * * - * + * * *********************************************************************** */ package org.matsim.contrib.emissions; @@ -130,7 +130,7 @@ private Map calculateColdEmissions(Id vehicleId, dou final Map coldEmissionsOfEvent = new EnumMap<>( Pollutant.class ); - logger.debug("VehId: " + vehicleId + " ; Tuple.first = " +vehicleInformationTuple.getFirst()); + logger.debug("VehId: {} ; Tuple.first = {}", vehicleId, vehicleInformationTuple.getFirst()); // fallback vehicle types that we cannot or do not want to map onto a hbefa vehicle type: if ( vehicleInformationTuple.getFirst()==HbefaVehicleCategory.NON_HBEFA_VEHICLE ) { for ( Pollutant coldPollutant : coldPollutants) { @@ -155,20 +155,15 @@ private Map calculateColdEmissions(Id vehicleId, dou //HBEFA 3 provides cold start emissions for "pass. car" and Light_Commercial_Vehicles (LCV) only. //HBEFA 4.1 provides cold start emissions for "pass. car" and Light_Commercial_Vehicles (LCV) only. //see https://www.hbefa.net/e/documents/HBEFA41_Development_Report.pdf (WP 4 , page 23) kturner, may'20 - //Mapping everything except "motorcycle" to "pass.car", since this was done in the last years for HGV. - //This may can be improved: What should be better set to LGV or zero???? kturner, may'20 - if (vehicleInformationTuple.getFirst().equals(HbefaVehicleCategory.HEAVY_GOODS_VEHICLE)) { - changeVehCategory(key, HbefaVehicleCategory.HEAVY_GOODS_VEHICLE, HbefaVehicleCategory.PASSENGER_CAR); - } - if (vehicleInformationTuple.getFirst().equals(HbefaVehicleCategory.URBAN_BUS)) { - changeVehCategory(key, HbefaVehicleCategory.URBAN_BUS, HbefaVehicleCategory.PASSENGER_CAR ); - } - if (vehicleInformationTuple.getFirst().equals(HbefaVehicleCategory.COACH)) { - changeVehCategory(key, HbefaVehicleCategory.COACH, HbefaVehicleCategory.PASSENGER_CAR); - } - if (vehicleInformationTuple.getFirst().equals(HbefaVehicleCategory.MOTORCYCLE)){ - changeVehCategory(key, HbefaVehicleCategory.MOTORCYCLE, HbefaVehicleCategory.PASSENGER_CAR); - return coldEmissionsOfEvent; + if (vehicleInformationTuple.getFirst().equals(HbefaVehicleCategory.HEAVY_GOODS_VEHICLE) || + vehicleInformationTuple.getFirst().equals(HbefaVehicleCategory.COACH) || + vehicleInformationTuple.getFirst().equals(HbefaVehicleCategory.URBAN_BUS) || + vehicleInformationTuple.getFirst().equals(HbefaVehicleCategory.MOTORCYCLE)) { + if (vehInfoWarnHDVCnt < maxWarnCnt) { + vehInfoWarnHDVCnt++; + logger.warn("Automagic changing of VehCategory is disabled. Please make sure that your table contains the necessary values for {}", HbefaVehicleCategory.HEAVY_GOODS_VEHICLE.name()); + if (vehInfoWarnHDVCnt == maxWarnCnt) logger.warn(Gbl.FUTURE_SUPPRESSED); + } } if(this.detailedHbefaColdTable != null) { @@ -197,33 +192,6 @@ private Map calculateColdEmissions(Id vehicleId, dou return coldEmissionsOfEvent; } - /** - * Replace the vehicleCategory with HbefaVehicleCategory.PASSENGER_CAR - * This is the old behaviour as it was until Aug 21. - * (Aug'21, KMT) This does not help, since the emConcepts are not the same. So it is _not_ usable if using - * some kind of detailed values. - * @param key - * @param originVehCat - * @param targetvehCat - */ - //TODO Mabe make the behaviour settable by an enum? -> keep some kind of backwards capability or just return a 0.0 as it is for motorcycle? - private void changeVehCategory(HbefaColdEmissionFactorKey key, HbefaVehicleCategory originVehCat, HbefaVehicleCategory targetvehCat) { -// key.setVehicleCategory(targetvehCat); -// if (vehInfoWarnHDVCnt < maxWarnCnt) { -// vehInfoWarnHDVCnt++; -// logger.warn("HBEFA does not provide cold start emission factors for " + -// originVehCat + -// ". Setting vehicle category to " + targetvehCat + "..."); -// if (vehInfoWarnHDVCnt == maxWarnCnt) logger.warn(Gbl.FUTURE_SUPPRESSED); -// } - if (vehInfoWarnHDVCnt < maxWarnCnt) { - vehInfoWarnHDVCnt++; - logger.warn("Automagic changing of VehCategory is disabled. Please make sure that your table contains the " + - "necessary values for " + originVehCat.name()); - if (vehInfoWarnHDVCnt == maxWarnCnt) logger.warn(Gbl.FUTURE_SUPPRESSED); - } - } - private HbefaColdEmissionFactor getEmissionsFactor(Tuple vehicleInformationTuple, int distance_km, HbefaColdEmissionFactorKey efkey, Pollutant coldPollutant) { efkey.setDistance(distance_km); @@ -241,7 +209,7 @@ private HbefaColdEmissionFactor getEmissionsFactor(Tuple; average; average'"); logger.warn(Gbl.ONLYONCE); logger.warn(Gbl.FUTURE_SUPPRESSED); @@ -306,7 +274,7 @@ private HbefaColdEmissionFactor getEmissionsFactor(Tuple; average; average" should, I think, just be entered as such. kai, feb'20 @@ -336,7 +304,7 @@ private HbefaColdEmissionFactor getEmissionsFactor(Tuple; average; average'"); logger.warn(Gbl.ONLYONCE); logger.warn(Gbl.FUTURE_SUPPRESSED); @@ -370,7 +338,7 @@ private HbefaColdEmissionFactor getEmissionsFactor(Tuple; average; average" should, I think, just be entered as such. kai, feb'20 @@ -387,7 +355,7 @@ private HbefaColdEmissionFactor getEmissionsFactor(Tuple list = new ArrayList<>(this.avgHbefaColdTable.keySet()); list.sort(Comparator.comparing(HbefaColdEmissionFactorKey::toString)); for (HbefaColdEmissionFactorKey key : list) { @@ -420,7 +388,7 @@ private HbefaColdEmissionFactor getEmissionsFactor(Tuple vehicleId, EmissionsConfigGroup emi + " Aborting..." ); case ignore: if ( noVehWarnCnt < 10 ){ - logger.warn( - "No vehicle defined for id " + vehicleId + ". The vehicle will be ignored." ); + logger.warn("No vehicle defined for id {}. The vehicle will be ignored.", vehicleId); noVehWarnCnt++; if ( noVehWarnCnt == 10 ) logger.warn( Gbl.FUTURE_SUPPRESSED ); } @@ -201,7 +200,7 @@ public void handleEvent(VehicleEntersTrafficEvent event) { private void warnIfZeroLinkLength(Id linkId, double linkLength) { if (linkLength == 0.) { if (zeroLinkLengthWarnCnt == 0) { - logger.warn("Length of the link " + linkId + " is zero. No emissions will be estimated for this link. Make sure, this is intentional."); + logger.warn("Length of the link {} is zero. No emissions will be estimated for this link. Make sure, this is intentional.", linkId); logger.warn(Gbl.ONLYONCE); zeroLinkLengthWarnCnt++; } diff --git a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/EmissionModule.java b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/EmissionModule.java index 196d7e77255..39e58239d09 100644 --- a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/EmissionModule.java +++ b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/EmissionModule.java @@ -77,11 +77,13 @@ public EmissionModule(final Scenario scenario, final EventsManager eventsManager // Event handlers are now added to the event manager inside the respective Handlers, jm march '18 } + @SuppressWarnings("ClassEscapesDefinedScope") public WarmEmissionAnalysisModule getWarmEmissionAnalysisModule() { // makes sense to have this public for externalization computations. kai, jan'20 return this.warmEmissionHandler.getWarmEmissionAnalysisModule(); } + @SuppressWarnings("ClassEscapesDefinedScope") public ColdEmissionAnalysisModule getColdEmissionAnalysisModule() { // makes sense to have this public for externalization computations. kai, jan'20 return this.coldEmissionHandler.getColdEmissionAnalysisModule(); @@ -103,27 +105,19 @@ public EventsManager getEmissionEventsManager() { } public void writeEmissionInformation() { - logger.info("Warm emissions were not calculated for " + warmEmissionHandler.getLinkLeaveWarnCnt() + " of " + - warmEmissionHandler.getLinkLeaveCnt() + " link leave events (no corresponding link enter event)."); + logger.info("Warm emissions were not calculated for {} of {} link leave events (no corresponding link enter event).", warmEmissionHandler.getLinkLeaveWarnCnt(), warmEmissionHandler.getLinkLeaveCnt()); int noVehicleLeavesTrafficEmissions = warmEmissionHandler.getSameLinkTrafficLeaveWarnCnt() + warmEmissionHandler.getUnusualTrafficLeaveWarnCnt(); - logger.info("Warm emissions were not calculated for " + noVehicleLeavesTrafficEmissions + " of " + warmEmissionHandler.getTrafficLeaveCnt() + - " vehicle leaves traffic events (no corresponding link enter event)."); + logger.info("Warm emissions were not calculated for {} of {} vehicle leaves traffic events (no corresponding link enter event).", noVehicleLeavesTrafficEmissions, warmEmissionHandler.getTrafficLeaveCnt()); if ( warmEmissionHandler.getUnusualTrafficLeaveWarnCnt() > 0 ) { - logger.info(warmEmissionHandler.getUnusualTrafficLeaveWarnCnt() + " events occurred where the vehicle left traffic without entering ANY link " + - "(no warm emissions calculated). These events might need to be investigated."); } + logger.info("{} events occurred where the vehicle left traffic without entering ANY link (no warm emissions calculated). These events might need to be investigated.", warmEmissionHandler.getUnusualTrafficLeaveWarnCnt()); } WarmEmissionAnalysisModule wam = warmEmissionHandler.getWarmEmissionAnalysisModule(); - logger.info("Emission calculation based on `Free flow only' occured for " + wam.getFreeFlowOccurences() + " of " + - wam.getWarmEmissionEventCounter() + " warm emission events."); - logger.info("Emission calculation based on `Stop&Go only' occured for " + wam.getStopGoOccurences() + " of " + - wam.getWarmEmissionEventCounter() + " warm emission events."); - logger.info("Emission calculation based on `Fractions' occured for " + wam.getFractionOccurences() + " of " + - wam.getWarmEmissionEventCounter() + " warm emission events."); - logger.info("Free flow occured on " + wam.getFreeFlowKmCounter() + " km of total " + - wam.getKmCounter() + " km, where emissions were calculated."); - logger.info("Stop&Go occured on " + wam.getStopGoKmCounter() + " km of total " + - wam.getKmCounter() + " km, where emissions were calculated."); + logger.info("Emission calculation based on `Free flow only' occurred for {} of {} warm emission events.", wam.getFreeFlowOccurences(), wam.getWarmEmissionEventCounter()); + logger.info("Emission calculation based on `Stop&Go only' occurred for {} of {} warm emission events.", wam.getStopGoOccurences(), wam.getWarmEmissionEventCounter()); + logger.info("Emission calculation based on `Fractions' occurred for {} of {} warm emission events.", wam.getFractionOccurences(), wam.getWarmEmissionEventCounter()); + logger.info("Free flow occurred on {} km of total {} km, where emissions were calculated.", wam.getFreeFlowKmCounter(), wam.getKmCounter()); + logger.info("Stop&Go occurred on {} km of total {} km, where emissions were calculated.", wam.getStopGoKmCounter(), wam.getKmCounter()); logger.info("Emission calculation terminated. Emission events can be found in regular events file."); } @@ -171,9 +165,10 @@ private void createLookupTables() { if (shouldCreateAverageTables()) { this.avgHbefaColdTable = HbefaTables.loadAverageCold(emissionConfigGroup.getAverageColdEmissionFactorsFileURL(scenario.getConfig().getContext())); addPollutantsToMap(coldPollutants, avgHbefaColdTable.keySet()); - // yy The naming and signature of the above should presumably be changed: (1) addPollutantsToX implies signature (pollutants, - // X). But it is actually the other way round (even if it does not read that way. (2) "coldPollutants" is not a Map. Since - // this is a private method, maybe one could also have a method "memorizeColdPollutants" and then not have coldPollutants as + // yy The naming and signature of the above should presumably be changed: + // (1) addPollutantsToX implies signature (pollutants,X). But it is actually the other way round (even if it does not read that way.) + // (2) "coldPollutants" is not a Map. + // Since this is a private method, maybe one could also have a method "memorizeColdPollutants" and then not have coldPollutants as // field. kai, dec'22 this.avgHbefaWarmTable = HbefaTables.loadAverageWarm(emissionConfigGroup.getAverageWarmEmissionFactorsFileURL(scenario.getConfig().getContext())); @@ -205,24 +200,17 @@ private void addPollutantsToMap(Set addTo, Set true; + default -> false; + }; } private boolean shouldCreateDetailedTables() { - switch (emissionConfigGroup.getDetailedVsAverageLookupBehavior()) { - case onlyTryDetailedElseAbort: - case tryDetailedThenTechnologyAverageElseAbort: - case tryDetailedThenTechnologyAverageThenAverageTable: - return true; - default: - return false; - } + return switch (emissionConfigGroup.getDetailedVsAverageLookupBehavior()) { + case onlyTryDetailedElseAbort, tryDetailedThenTechnologyAverageElseAbort, tryDetailedThenTechnologyAverageThenAverageTable -> true; + default -> false; + }; } private void createEmissionHandlers() { diff --git a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/EmissionUtils.java b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/EmissionUtils.java index a24186833db..bd28e89992c 100644 --- a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/EmissionUtils.java +++ b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/EmissionUtils.java @@ -97,7 +97,7 @@ public static Map, SortedMap> setNonCalculatedEmis for (Pollutant pollutant : pollutants) { emissionType2Value.put(pollutant, 0.0); } - } else { // person in map, but some emissions are not set; setting these to 0.0 + } else { // person in map, but some emissions are not set; setting these to 0.0 emissionType2Value = totalEmissions.get(personId); for (Pollutant pollutant : emissionType2Value.keySet()) { // else do nothing @@ -225,7 +225,7 @@ static Tuple convertVehicleDescrip EngineInformation engineInformation; // get information from where it used to be in previous versions and move to where it should be now: - logger.debug("emissionsConfigGroup.getHbefaVehicleDescriptionSource=" + emissionsConfigGroup.getHbefaVehicleDescriptionSource()); + logger.debug("emissionsConfigGroup.getHbefaVehicleDescriptionSource={}", emissionsConfigGroup.getHbefaVehicleDescriptionSource()); switch( emissionsConfigGroup.getHbefaVehicleDescriptionSource() ) { case usingVehicleTypeId: // (v1, hbefa vehicle description is in vehicle type id. Copy to where it is expected now) @@ -320,7 +320,7 @@ public static HbefaVehicleCategory mapString2HbefaVehicleCategory(String string) try{ hbefaVehicleCategory = HbefaVehicleCategory.valueOf(string); } catch (IllegalArgumentException e) { - logger.warn("Could not map String " + string + " to any HbefaVehicleCategory; please check syntax in hbefa input file."); + logger.warn("Could not map String {} to any HbefaVehicleCategory; please check syntax in hbefa input file.", string); throw new RuntimeException(); } } @@ -329,22 +329,15 @@ public static HbefaVehicleCategory mapString2HbefaVehicleCategory(String string) public static String mapHbefaVehicleCategory2String(HbefaVehicleCategory category) { - switch (category) { - case COACH: - return "coach"; - case HEAVY_GOODS_VEHICLE: - return "HGV"; - case LIGHT_COMMERCIAL_VEHICLE: - return "LCV"; - case MOTORCYCLE: - return "motorcycle"; - case PASSENGER_CAR: - return "pass. car"; - case URBAN_BUS: - return "urban bus"; - default: - throw new RuntimeException("Could not transform category to string: " + category); - } + return switch (category) { + case COACH -> "coach"; + case HEAVY_GOODS_VEHICLE -> "HGV"; + case LIGHT_COMMERCIAL_VEHICLE -> "LCV"; + case MOTORCYCLE -> "motorcycle"; + case PASSENGER_CAR -> "pass. car"; + case URBAN_BUS -> "urban bus"; + default -> throw new RuntimeException("Could not transform category to string: " + category); + }; } static Pollutant getPollutant( String pollutantString ){ @@ -353,37 +346,20 @@ static Pollutant getPollutant( String pollutantString ){ // setCo2TotalKeys( Set keys ) // as we have it, e.g., with network modes. kai, feb'20 - Pollutant pollutant; - switch( pollutantString ){ - case "CO2(total)": - pollutant = Pollutant.CO2_TOTAL; - break; - case "CO2(rep)": - pollutant = Pollutant.CO2_rep; - break; - case "PM2.5 (non-exhaust)": - pollutant = Pollutant.PM2_5_non_exhaust; - break; - case "PM2.5": - pollutant = Pollutant.PM2_5; - break; - case "PM (non-exhaust)": - pollutant = Pollutant.PM_non_exhaust; - break; - case "BC (exhaust)": - pollutant = Pollutant.BC_exhaust; - break; - case "BC (non-exhaust)": - pollutant = Pollutant.BC_non_exhaust; - break; - default: - pollutant = Pollutant.valueOf( pollutantString ); - // the Pollutant.valueOf(...) should fail if the incoming key is not consistent with what is available in the enum. Two possibilities: - // (1) it is a new pollutant. In that case, just add to the enum. - // (2) It is a different spelling of an already existing pollutant. In that case, see above. - // kai, jan'20 - } - return pollutant; + return switch (pollutantString) { + case "CO2(total)" -> Pollutant.CO2_TOTAL; + case "CO2(rep)" -> Pollutant.CO2_rep; + case "PM2.5 (non-exhaust)" -> Pollutant.PM2_5_non_exhaust; + case "PM2.5" -> Pollutant.PM2_5; + case "PM (non-exhaust)" -> Pollutant.PM_non_exhaust; + case "BC (exhaust)" -> Pollutant.BC_exhaust; + case "BC (non-exhaust)" -> Pollutant.BC_non_exhaust; + default -> Pollutant.valueOf(pollutantString); + // the Pollutant.valueOf(...) should fail if the incoming key is not consistent with what is available in the enum. Two possibilities: + // (1) it is a new pollutant. In that case, just add to the enum. + // (2) It is a different spelling of an already existing pollutant. In that case, see above. + // kai, jan'20 + }; } /** diff --git a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/HbefaEmissionFactorKey.java b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/HbefaEmissionFactorKey.java index aa11fc55018..3ce7f9632e7 100644 --- a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/HbefaEmissionFactorKey.java +++ b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/HbefaEmissionFactorKey.java @@ -66,13 +66,11 @@ public void setComponent(Pollutant component) { @Override public boolean equals(Object o) { if (this == o) return true; - if (!(o instanceof HbefaEmissionFactorKey)) return false; + if (!(o instanceof HbefaEmissionFactorKey efk)) return false; - var that = (HbefaEmissionFactorKey) o; - - if (vehicleCategory != that.getVehicleCategory()) return false; - if (!Objects.equals(vehicleAttributes, that.vehicleAttributes)) return false; - return Objects.equals(component, that.component); + if (vehicleCategory != efk.getVehicleCategory()) return false; + if (!Objects.equals(vehicleAttributes, efk.vehicleAttributes)) return false; + return Objects.equals(component, efk.component); } @Override diff --git a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/HbefaRoadTypeMapping.java b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/HbefaRoadTypeMapping.java index bca754b259d..5074b708db5 100644 --- a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/HbefaRoadTypeMapping.java +++ b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/HbefaRoadTypeMapping.java @@ -33,11 +33,11 @@ public void addHbefaMappings(Network network) { network.getLinks().values().parallelStream() .forEach(link -> { - String hbefaString = determineHebfaType(link); + String hbefaString = determineHbefaType(link); EmissionUtils.setHbefaRoadType(link, hbefaString); }); } - protected abstract String determineHebfaType(Link link); + protected abstract String determineHbefaType(Link link); } diff --git a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/HbefaTables.java b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/HbefaTables.java index b3d23dedb82..f01d42bb0f7 100644 --- a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/HbefaTables.java +++ b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/HbefaTables.java @@ -125,7 +125,7 @@ private static HbefaTrafficSituation mapString2HbefaTrafficSituation(String stri else if (string.endsWith("St+Go")) return HbefaTrafficSituation.STOPANDGO; else if (string.endsWith("St+Go2")) return HbefaTrafficSituation.STOPANDGO_HEAVY; else { - logger.warn("Could not map String " + string + " to any HbefaTrafficSituation; please check syntax in hbefa input file."); + logger.warn("Could not map String {} to any HbefaTrafficSituation; please check syntax in hbefa input file.", string); throw new RuntimeException(); } } diff --git a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/OsmHbefaMapping.java b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/OsmHbefaMapping.java index 4938d75e993..ccce2492711 100644 --- a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/OsmHbefaMapping.java +++ b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/OsmHbefaMapping.java @@ -22,24 +22,22 @@ package org.matsim.contrib.emissions; import com.google.inject.Provides; -import org.apache.commons.lang3.StringUtils; import org.matsim.api.core.v01.network.Link; import org.matsim.core.network.NetworkUtils; -import java.util.Arrays; import java.util.HashMap; -import java.util.List; import java.util.Map; +import java.util.stream.Stream; /** * Created by molloyj on 01.12.2017. - * + *

* * handled OSM road types: * motorway,trunk,primary,secondary, tertiary, unclassified,residential,service * motorway_link, trunk_link,primary_link, secondary_link * tertiary_link, living_street, pedestrian,track,road - * + *

* Hbefa categories and respective speeds * URB/MW-Nat./80 - 130 * URB/MW-City/60 - 110 @@ -48,7 +46,7 @@ * URB/Distr/50 - 80 * URB/Local/50 - 60 * URB/Access/30 - 50 - * + *

* Conversions from OSM to hbefa types * motorway;MW * primary;Trunk @@ -63,14 +61,14 @@ public class OsmHbefaMapping extends HbefaRoadTypeMapping { private final Map hbfeaMap = new HashMap<>(); static class Hbefa { - String name; - int min; - int max; + final String name; + final int min_speed; + final int max_speed; - Hbefa(String name, int min, int max) { + Hbefa(String name, int min_speed, int max) { this.name = name; - this.min = min; - this.max = max; + this.min_speed = min_speed; + this.max_speed = max; } } @@ -96,7 +94,7 @@ private void put(String s, Hbefa hbefa) { } @Override - public String determineHebfaType(Link link) { + public String determineHbefaType(Link link) { String roadType = NetworkUtils.getHighwayType(link); double allowedSpeed = NetworkUtils.getAllowedSpeed(link); @@ -110,7 +108,7 @@ private String getHEBFAtype(String type, double speed) { /* * speed attributes are sometimes rounded beforehand. - * make sure the speed is a multiple of 10, as the HBEFA emission key factors are and otherwise we get problems later... + * make sure the speed is a multiple of 10, as the HBEFA emission key factors are, and otherwise we get problems later... */ freeVelocity_kmh = Math.round(freeVelocity_kmh/10.0) * 10; @@ -125,8 +123,7 @@ private String getHEBFAtype(String type, double speed) { //sometimes link type is smth like 'motorway_link' or 'living_street' or 'primary|railway.tram'. We only care about the first part, here - int idx = Arrays.asList(type.indexOf('.'), type.indexOf('|'), type.indexOf('_'), type.indexOf(',')) - .stream() + int idx = Stream.of(type.indexOf('.'), type.indexOf('|'), type.indexOf('_'), type.indexOf(',')) .filter(i -> i>= 0) //if chrc is not in String indexOf returns -1 .min(Integer::compare) .orElse(type.length()); @@ -139,8 +136,8 @@ private String getHEBFAtype(String type, double speed) { if (!hbfeaMap.containsKey(type)) { throw new RuntimeException("'" + type + "' not in hbefa map"); } - int min_speed = hbfeaMap.get(type).min; - int max_speed = hbfeaMap.get(type).max; + int min_speed = hbfeaMap.get(type).min_speed; + int max_speed = hbfeaMap.get(type).max_speed; int clamped_speed = (int) Math.min(Math.max(min_speed, freeVelocity_kmh), max_speed); return "URB/" + hbfeaMap.get(type).name + "/" + clamped_speed; diff --git a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/Pollutant.java b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/Pollutant.java index 7e0f815d747..2db4b9607e9 100644 --- a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/Pollutant.java +++ b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/Pollutant.java @@ -33,11 +33,11 @@ public enum Pollutant{ NMHC, // non-methane hydro carbons NOx, // nitrogen oxide NO2, // provided as g/km, but based on %-values of NOx - PM, // = PM10 --> particulate matterof size below 10μm, i.e. equivalent to PM10. unit = g/km + PM, // = PM10 --> particulate matter of size below 10μm, i.e. equivalent to PM10. unit = g/km SO2, //sulphur dioxide FC_MJ, // fuel consumption in MJ/km - CO2_rep, // CO2(reported): = carbon dioxide “reported”, i.e. withoutthe biofuel share in the fuel -> input for CO2e calculation - CO2e, // CO2 equivalents (WTW basis), CO2 equivalents contain CO2, CH4 and N2O, i.e. the relevant greenhouse gases from thetransport sector,multiplied with their respective 100-year Global Warming Potentials and summed up. + CO2_rep, // CO2(reported): = carbon dioxide “reported”, i.e. without the biofuel share in the fuel -> input for CO2e calculation + CO2e, // CO2 equivalents (WTW basis), CO2 equivalents contain CO2, CH4 and N2O, i.e. the relevant greenhouse gases from the transport sector, multiplied with their respective 100-year Global Warming Potentials and summed up. PM2_5, // particle mass for particles < 2.5 µm. unit = g/km PM2_5_non_exhaust, // tire wear! PM_non_exhaust, // PM10 from non-exhaust sources(e.g. road, tyre wear) diff --git a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/PositionEmissionsModule.java b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/PositionEmissionsModule.java index 4652c3d7339..d43d1f941e2 100644 --- a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/PositionEmissionsModule.java +++ b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/PositionEmissionsModule.java @@ -111,7 +111,7 @@ Map calculateColdEmissions(Vehicle vehicle, double parkingDur } private Tuple getVehicleAttributes(Vehicle vehicle) { - // the following block fixes the vehicle types's emission information whenusing an old vehicle type format + // the following block fixes the vehicle type's emission information when using an old vehicle type format // the unit test I found uses an old format, so have it here. { String hbefaVehicleTypeDescription = EmissionUtils.getHbefaVehicleDescription(vehicle.getType(), emissionsConfigGroup); @@ -209,7 +209,7 @@ private void handlePositionEvent(PositionEvent event) { return; // only calculate emissions for cars if (!vehiclesInTraffic.containsKey(event.getVehicleId())) - return; // only collect positions if vehicle has entered traffic (if vehicle is wait2link its position is calculated but it hasn't entered traffic yet. + return; // only collect positions if vehicle has entered traffic (if vehicle is wait2link its position is calculated, but it hasn't entered traffic yet.) if (trajectories.containsKey(event.getVehicleId())) { computeCombinedEmissionEvent(event); @@ -223,23 +223,23 @@ private void handlePositionEvent(PositionEvent event) { private Map computeColdEmissions(PositionEvent event, Vehicle vehicle, double distanceToLastPosition) { - // we remember the vehicles which are currently emmitting cold emissions if not stored here return nothing + // we remember the vehicles which are currently emitting cold emissions if not stored here return nothing if (!vehiclesEmittingColdEmissions.contains(vehicle.getId())) return emissionCalculator.getEmptyColdEmissions(); double distance = calculateTravelledDistance(event); // this model assumes vehicles to emmit cold emissions for the first 2000m of a trip remove a vehicle from - // the list of emmiting vehicles if the current trajectory is longer than 2000m + // the list of emitting vehicles if the current trajectory is longer than 2000m if (distance > 2000) { vehiclesEmittingColdEmissions.remove(vehicle.getId()); return emissionCalculator.getEmptyColdEmissions(); } - // HBEFA assumes a constantly decreasing ammount of cold emissions depending on the distance travelled + // HBEFA assumes a constantly decreasing amount of cold emissions depending on the distance travelled // the underlying emission module simplifies this into two steps. Between 0-1km and 1-2km. We use the same // classes here because we don't want to rewrite all the stuff. The cold emission module computes emissions - // for 1000m. We take these as is and muliply with distanceToLastPosition / 1000. This way we have the fraction + // for 1000m. We take these as is and multiply with distanceToLastPosition / 1000. This way we have the fraction // of cold emissions for the distance travelled during the last time step janek oct' 2021 int distanceClass = distance <= 1000 ? 1 : 2; @@ -290,7 +290,7 @@ private void computeCombinedEmissionEvent(PositionEvent event) { eventsManager.processEvent(new PositionEmissionEvent(event, combinedEmissions, "combined")); } else { - log.warn("speed was too fast: " + speed + "m/s Current time: " + event.getTime() + " prev time: " + previousPosition.getTime() + " current linkId: " + event.getLinkId() + " prev linkId: " + previousPosition.getLinkId() + " agentId: " + event.getPersonId()); + log.warn("speed was too fast: {}m/s Current time: {} prev time: {} current linkId: {} prev linkId: {} agentId: {}", speed, event.getTime(), previousPosition.getTime(), event.getLinkId(), previousPosition.getLinkId(), event.getPersonId()); } } else { // if the vehicle hasn't moved, issue an event with 0 emissions. This way there is an event for every timestep diff --git a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/VisumHbefaRoadTypeMapping.java b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/VisumHbefaRoadTypeMapping.java index e822003f09f..1fce8b282cb 100644 --- a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/VisumHbefaRoadTypeMapping.java +++ b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/VisumHbefaRoadTypeMapping.java @@ -46,7 +46,7 @@ private VisumHbefaRoadTypeMapping() { } @Override - public String determineHebfaType(Link link) { + public String determineHbefaType(Link link) { String roadType = NetworkUtils.getType(link); return mapping.get(roadType); } diff --git a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/VspHbefaRoadTypeMapping.java b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/VspHbefaRoadTypeMapping.java index 12fb81ea572..8a990e6d5ab 100644 --- a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/VspHbefaRoadTypeMapping.java +++ b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/VspHbefaRoadTypeMapping.java @@ -13,7 +13,7 @@ public VspHbefaRoadTypeMapping() { } @Override - protected String determineHebfaType(Link link) { + protected String determineHbefaType(Link link) { var freespeed = link.getFreespeed() <= 13.888889 ? link.getFreespeed() * 2 : link.getFreespeed(); diff --git a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/WarmEmissionAnalysisModule.java b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/WarmEmissionAnalysisModule.java index ff055cf31fd..8eff2d52a29 100644 --- a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/WarmEmissionAnalysisModule.java +++ b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/WarmEmissionAnalysisModule.java @@ -63,10 +63,6 @@ public final class WarmEmissionAnalysisModule implements LinkEmissionsCalculator private int detailedFallbackAverageTableWarnCnt = 0; private int averageReadingInfoCnt = 0; - // The following was tested to slow down significantly, therefore counters were commented out: -// Set vehAttributesNotSpecified = Collections.synchronizedSet(new HashSet()); -// Set vehicleIdSet = Collections.synchronizedSet(new HashSet()); - private int freeFlowCounter = 0; private int saturatedCounter = 0; private int heavyFlowCounter = 0; @@ -104,7 +100,7 @@ public WarmEmissionAnalysisModule( // The following tests if the detailed table is consistent, i.e. if there exist all combinations of entries. There used to be some test // cases where this was deliberately not the case, implying that this was assumed as plausible also for studies. This is now forbidding it. // If this causes too many problems, we could insert a switch (or attach it to the fallback behavior switch). kai, feb'20 - // Eventually vehicle category and vehicle attribute should be alligned in order to make the allCombinations setting useful + // Eventually vehicle category and vehicle attribute should be aligned in order to make the allCombinations setting useful // see discussion in https://github.com/matsim-org/matsim-libs/issues/1226 kturner, nov'20 Set roadCategories = new HashSet<>(); Set trafficSituations = EnumSet.noneOf(HbefaTrafficSituation.class); @@ -149,7 +145,7 @@ public WarmEmissionAnalysisModule( // conditions exist for a certain lookup. So we could still have some road categories, vehicle categories or vehicle attributes // where some detailed values exist and others don't. So the thing to check would be if for each existing // roadCategory x vehicleCategory x vehicleAttribute x pollutant - // there is a freeflow and a stopgo entry. Maybe something like this here: + // there is a freeflow and a stop-go entry. Maybe something like this here: Set freeflowSet = new HashSet<>(); Set stopgoSet = new HashSet<>(); for (HbefaWarmEmissionFactorKey key : detailedHbefaWarmTable.keySet()) { @@ -275,7 +271,7 @@ Map calculateWarmEmissions(double travelTime_sec, String road } if ((averageSpeed_kmh - freeVelocity_ms * 3.6) > 1.0){ if (ecg.getHandleHighAverageSpeeds()) { - logger.warn("averageSpeed was capped from " + averageSpeed_kmh + " to" + freeVelocity_ms * 3.6 ); + logger.warn("averageSpeed was capped from {} to{}", averageSpeed_kmh, freeVelocity_ms * 3.6); averageSpeed_kmh = freeVelocity_ms * 3.6; } else { throw new RuntimeException("Average speed has been calculated to be greater than free flow speed; this might produce negative warm emissions. Aborting..."); @@ -307,7 +303,7 @@ Map calculateWarmEmissions(double travelTime_sec, String road // compute emissions from stop-go fraction: efkey.setTrafficSituation(STOPANDGO); efStopGo_gpkm = getEf(vehicleInformationTuple, efkey).getFactor(); - logger.debug("pollutant=" + warmPollutant + "; efStopGo=" + efStopGo_gpkm); + logger.debug("pollutant={}; efStopGo={}", warmPollutant, efStopGo_gpkm); } @@ -316,7 +312,7 @@ Map calculateWarmEmissions(double travelTime_sec, String road // compute emissions for free-flow fraction: efkey.setTrafficSituation(FREEFLOW); efFreeFlow_gpkm = getEf(vehicleInformationTuple, efkey).getFactor(); - logger.debug("pollutant=" + warmPollutant + "; efFreeFlow=" + efFreeFlow_gpkm); + logger.debug("pollutant={}; efFreeFlow={}", warmPollutant, efFreeFlow_gpkm); } // sum them up: @@ -334,7 +330,7 @@ Map calculateWarmEmissions(double travelTime_sec, String road } // update counters: - // yy I don't now what this is good for; I would base downstream analysis rather on events. kai, jan'20 + // yy I don't know what this is good for; I would base downstream analysis rather on events. kai, jan'20 if (ecg.getEmissionsComputationMethod() == StopAndGoFraction) { incrementCountersFractional( linkLength_m / 1000, fractionStopGo ); } @@ -379,7 +375,7 @@ private HbefaWarmEmissionFactor getEf(Tuple; average; average'" ); logger.warn( Gbl.ONLYONCE ); logger.warn( Gbl.FUTURE_SUPPRESSED ); @@ -444,7 +440,7 @@ private HbefaWarmEmissionFactor getEf(Tuple; average; average" should, I think, just be entered as such. kai, feb'20 @@ -462,7 +458,7 @@ private HbefaWarmEmissionFactor getEf(Tuple; average; average'" ); logger.warn( Gbl.ONLYONCE ); logger.warn( Gbl.FUTURE_SUPPRESSED ); @@ -496,7 +492,7 @@ private HbefaWarmEmissionFactor getEf(Tuple; average; average" should, I think, just be entered as such. kai, feb'20 @@ -513,7 +509,7 @@ private HbefaWarmEmissionFactor getEf(Tuple list = new ArrayList<>( this.avgHbefaWarmTable.keySet() ); list.sort( Comparator.comparing( HbefaWarmEmissionFactorKey::toString ) ); for ( HbefaWarmEmissionFactorKey key : list ) { @@ -556,7 +552,7 @@ private HbefaTrafficSituation getTrafficSituation(HbefaWarmEmissionFactorKey efk HbefaRoadVehicleCategoryKey hbefaRoadVehicleCategoryKey = new HbefaRoadVehicleCategoryKey(efkey); Map trafficSpeeds = this.hbefaRoadTrafficSpeeds.get(hbefaRoadVehicleCategoryKey); - //TODO: Hier die Berechunung einfügen, die die trafficSpeedTabelle entsprechend aus den Werten erstellt? + //TODO: Hier die Berechnung einfügen, die die trafficSpeedTabelle entsprechend aus den Werten erstellt? //Frage Laufzeit: Einmal berechnen ha if (trafficSpeeds == null || !trafficSpeeds.containsKey(FREEFLOW)) { @@ -576,7 +572,7 @@ private HbefaTrafficSituation getTrafficSituation(HbefaWarmEmissionFactorKey efk trafficSituation = STOPANDGO; } } - /*FIXME The following lines should be added to account for the HBEFA 4.1's additiona traffic situation, + /*FIXME The following lines should be added to account for the HBEFA 4.1's additional traffic situation, but it currently causes a test failure (jwj, Nov'20) */ // if (trafficSpeeds.containsKey(STOPANDGO_HEAVY) && averageSpeed_kmh <= trafficSpeeds.get(STOPANDGO_HEAVY)) { // if (averageSpeed_kmh != trafficSpeeds.get(FREEFLOW)) { //handle case testCheckVehicleInfoAndCalculateWarmEmissions_and_throwWarmEmissionEvent6 @@ -593,8 +589,8 @@ private void incrementCountersFractional(double linkLength_km, double fractionSt freeFlowKmCounter += linkLength_km * (1-fractionStopGo); stopGoKmCounter += linkLength_km * fractionStopGo; - freeFlowCounter += 1-fractionStopGo; - stopGoCounter += fractionStopGo; + freeFlowCounter += (int) (1-fractionStopGo); + stopGoCounter += (int) fractionStopGo; fractionCounter += (fractionStopGo < 1.0 && fractionStopGo > 0.0) ? 1 : 0; } @@ -626,7 +622,7 @@ private void incrementCountersAverage(HbefaTrafficSituation hbefaTrafficSituatio } } - //------ These (occurrences) seem do be used only for logging statements and tests. KMT/GR Jul'20 + //------ These (occurrences) seem to be used only for logging statements and tests. KMT/GR Jul'20 /*package-private*/ int getFreeFlowOccurences() { return freeFlowCounter; } diff --git a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/WarmEmissionHandler.java b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/WarmEmissionHandler.java index 8213320fdff..03a57d63b17 100644 --- a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/WarmEmissionHandler.java +++ b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/WarmEmissionHandler.java @@ -123,12 +123,10 @@ public void handleEvent(VehicleLeavesTrafficEvent event) { handleNullVehicle(vehicleId); } } else if ( this.vehicleEntersTrafficMap.containsKey( vehicleId ) ) { - logger.warn("At time " + event.getTime() + ", vehicle " + event.getVehicleId() + " enters and leaves traffic without" + - " having entered link " + event.getLinkId() + ". Thus, no emissions are calculated for travel along this link."); + logger.warn("At time {}, vehicle {} enters and leaves traffic without having entered link {}. Thus, no emissions are calculated for travel along this link.", event.getTime(), event.getVehicleId(), event.getLinkId()); sameLinkTrafficLeaveWarnCnt++; } else { - logger.warn("At time " + event.getTime() + ", vehicle " + event.getVehicleId() + " left traffic without entering traffic " + - "or ANY link. Thus, no emissions are calculated for this unusual event."); + logger.warn("At time {}, vehicle {} left traffic without entering traffic or ANY link. Thus, no emissions are calculated for this unusual event.", event.getTime(), event.getVehicleId()); unusualTrafficLeaveWarnCnt++; } } @@ -191,7 +189,7 @@ private void emissionsCalculation(Id vehicleId, Vehicle vehicle, Link l private boolean linkLengthIsZero( Id linkId, double linkLength) { if (linkLength == 0.) { if (zeroLinkLengthWarnCnt == 0) { - logger.warn("Length of the link " + linkId + " is zero. No emissions will be estimated for this link. Make sure that this is intentional."); + logger.warn("Length of the link {} is zero. No emissions will be estimated for this link. Make sure that this is intentional.", linkId); logger.warn(Gbl.ONLYONCE); zeroLinkLengthWarnCnt++; } @@ -211,8 +209,7 @@ private void handleNullVehicle(Id vehicleId) { + " Aborting..."); } else if (this.warmEmissionAnalysisModule.getEcg().getNonScenarioVehicles().equals(NonScenarioVehicles.ignore)) { if (noVehWarnCnt < 10) { - logger.warn( - "No vehicle defined for id " + vehicleId + ". The vehicle will be ignored."); + logger.warn("No vehicle defined for id {}. The vehicle will be ignored.", vehicleId); noVehWarnCnt++; if (noVehWarnCnt == 10) logger.warn(Gbl.FUTURE_SUPPRESSED); } diff --git a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/analysis/EmissionGridAnalyzer.java b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/analysis/EmissionGridAnalyzer.java index 1454c799a48..42003c91ffb 100644 --- a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/analysis/EmissionGridAnalyzer.java +++ b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/analysis/EmissionGridAnalyzer.java @@ -57,7 +57,7 @@ /** * This class may be used to collect emission events of some events file and assign those emissions to a grid structure. - * Additionally those emissions are divided into time bins + * Additionally, those emissions are divided into time bins */ public class EmissionGridAnalyzer { @@ -106,7 +106,7 @@ public TimeBinMap>> process(String eventsFile) { logger.info("Starting grid computation..."); for (var bin : timeBinsWithEmissions.getTimeBins()) { - logger.info("creating grid for time bin with start time: " + bin.getStartTime()); + logger.info("creating grid for time bin with start time: {}", bin.getStartTime()); Grid> grid = writeAllLinksToGrid(bin.getValue()); result.getTimeBin(bin.getStartTime()).setValue(grid); } @@ -153,7 +153,7 @@ public Tuple processNextTimeBin() { if (!this.timeBins.hasNext()) throw new RuntimeException("processNextTimeBin() was called too many times"); TimeBinMap.TimeBin, EmissionsByPollutant>> nextBin = this.timeBins.next(); - logger.info("creating grid for time bin with start time: " + nextBin.getStartTime()); + logger.info("creating grid for time bin with start time: {}", nextBin.getStartTime()); Grid> grid = writeAllLinksToGrid(nextBin.getValue()); @@ -224,7 +224,7 @@ private Grid> writeAllLinksToGrid(Map, Emissions .forEach(entry -> { var count = counter.incrementAndGet(); if (count % 10000 == 0) - logger.info("processing: " + count * 100 / linksWithEmissions.keySet().size() + "% done"); + logger.info("processing: {}% done", count * 100 / linksWithEmissions.keySet().size()); if (network.getLinks().containsKey(entry.getKey()) && isWithinBounds(network.getLinks().get(entry.getKey()))) { processLink(network.getLinks().get(entry.getKey()), entry.getValue(), grid); @@ -316,7 +316,7 @@ public Builder withTimeBinSize(double size) { /** * Sets the used grid type. Default is Square * - * @param type The grid type. Currently either Square or Hexagonal + * @param type The grid type. Currently, either Square or Hexagonal * @return {@link org.matsim.contrib.emissions.analysis.EmissionGridAnalyzer.Builder} */ public Builder withGridType(GridType type) { diff --git a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/analysis/EmissionsByPollutant.java b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/analysis/EmissionsByPollutant.java index 6b1eda64b73..167bc09caf8 100644 --- a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/analysis/EmissionsByPollutant.java +++ b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/analysis/EmissionsByPollutant.java @@ -24,7 +24,6 @@ import org.matsim.contrib.emissions.Pollutant; -import java.util.HashMap; import java.util.Map; /** diff --git a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/analysis/FastEmissionGridAnalyzer.java b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/analysis/FastEmissionGridAnalyzer.java index b036c3d9f72..347fe2bb3eb 100644 --- a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/analysis/FastEmissionGridAnalyzer.java +++ b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/analysis/FastEmissionGridAnalyzer.java @@ -54,13 +54,13 @@ public abstract class FastEmissionGridAnalyzer { * 2. The aggregated emissions for each link are rastered onto all the raster-cells covered by the link. * 3. In the smoothing step the emissions are blurred onto the surrounding raster-cells. *

- * The blurring algorithm is a gaussian blur https://en.wikipedia.org/wiki/Gaussian_blur + * The blurring algorithm is a gaussian blur ... *

* If only a certain area of the scenario is of interest for the analysis. The supplied network must be filtered beforehand. * The resulting raster's size depends on the bounding box of the supplied network. *

- * Note: The algorithm is not accurate at the edges of the raster. The kernel is cut of a the edges meaning that emissions - * are underestimated at the edges of the raster. I didn't bother to implement this correctly. Otherwise the overall + * Note: The algorithm is not accurate at the edges of the raster. The kernel is cut of the edges meaning that emissions + * are underestimated at the edges of the raster. I didn't bother to implement this correctly. Otherwise, the overall * amount of emissions doesn't change. * * @param eventsFile The events file which contains the emission events @@ -92,7 +92,7 @@ public static Map processEventsFile(final String eventsFile, logger.info("Start smoothing pollution."); return linkEmissionsByPollutant.entrySet().stream() .map(entry -> { - logger.info("Smoothing of: " + entry.getKey()); + logger.info("Smoothing of: {}", entry.getKey()); return Tuple.of(entry.getKey(), processLinkEmissions(entry.getValue(), network, cellSize, radius)); }) .collect(Collectors.toMap(Tuple::getFirst, Tuple::getSecond)); @@ -116,7 +116,7 @@ public static Map processHandlerEmissions(Map, Map

{ - logger.info("Smoothing of: " + entry.getKey()); + logger.info("Smoothing of: {}", entry.getKey()); return Tuple.of(entry.getKey(), processLinkEmissions(entry.getValue(), network, cellSize, radius)); }) .collect(Collectors.toMap(Tuple::getFirst, Tuple::getSecond)); @@ -192,7 +192,7 @@ public static Raster processLinkEmissions(final Map, Double> emissions, static Raster blur(Raster raster, int radius) { - logger.info("Creating Kernel with " + (radius * 2 + 1) + " taps"); + logger.info("Creating Kernel with {} taps", radius * 2 + 1); var kernel = createKernel(radius * 2 + 1); var result = new Raster(raster.getBounds(), raster.getCellSize()); @@ -279,7 +279,7 @@ static Raster rasterizeNetwork(Network network, Map, Double> emissions, * Rasterizes links into squares. Uses Bresenham's line drawing algorithm, which is supposed to be fast * Maybe the result is too chunky, but it'll do as a first try * - * @param link Matsim network link + * @param link MATSim network link * @return number of cells the link is rastered to */ private static int rasterizeLink(Link link, double value, Raster raster) { diff --git a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/analysis/RawEmissionEventsReader.java b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/analysis/RawEmissionEventsReader.java index ff962f67cff..811c3d49181 100644 --- a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/analysis/RawEmissionEventsReader.java +++ b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/analysis/RawEmissionEventsReader.java @@ -57,7 +57,7 @@ class RawEmissionEventsReader extends MatsimXmlParser { RawEmissionEventsReader(HandleEmissionEvent handler) { super(ValidationType.NO_VALIDATION); this.handler = handler; - // events don't have dtd. Therefore validation is not possible + // events don't have dtd. Therefore, validation is not possible this.setValidating(false); } @@ -103,7 +103,7 @@ private void handleEmissionEvent(Attributes atts) { // give some feedback about progress var currentCount = eventsCounter.incrementAndGet(); if (currentCount % 500000 == 0) { - logger.info("Emission Event # " + numberFormat.format(currentCount)); + logger.info("Emission Event # {}", numberFormat.format(currentCount)); } } diff --git a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/events/ColdEmissionEvent.java b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/events/ColdEmissionEvent.java index e658817da12..fe184d1ce2b 100644 --- a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/events/ColdEmissionEvent.java +++ b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/events/ColdEmissionEvent.java @@ -20,13 +20,11 @@ package org.matsim.contrib.emissions.events; import org.matsim.api.core.v01.Id; -import org.matsim.api.core.v01.events.Event; import org.matsim.api.core.v01.network.Link; import org.matsim.contrib.emissions.Pollutant; import org.matsim.vehicles.Vehicle; import java.util.Map; -import java.util.Map.Entry; /** diff --git a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/events/EmissionEvent.java b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/events/EmissionEvent.java index 32a5221e27c..ae7c9c59e2a 100644 --- a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/events/EmissionEvent.java +++ b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/events/EmissionEvent.java @@ -23,7 +23,6 @@ import org.matsim.api.core.v01.Id; import org.matsim.api.core.v01.events.Event; -import org.matsim.api.core.v01.events.HasLinkId; import org.matsim.api.core.v01.network.Link; import org.matsim.contrib.emissions.Pollutant; import org.matsim.vehicles.Vehicle; diff --git a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/events/EmissionEventsReader.java b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/events/EmissionEventsReader.java index c9c21926ef9..11f73caf526 100644 --- a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/events/EmissionEventsReader.java +++ b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/events/EmissionEventsReader.java @@ -40,7 +40,7 @@ public final class EmissionEventsReader implements MatsimReader { // leave this public so that external code can generate "standard" emission events. MATSIM-893 - private MatsimEventsReader delegate ; + private final MatsimEventsReader delegate ; public EmissionEventsReader( EventsManager events ){ this.delegate = new MatsimEventsReader(events); @@ -59,20 +59,24 @@ public EmissionEventsReader( EventsManager events ){ // the loop is necessary since we do now know which pollutants are in the event. for (Map.Entry entry : attributes.entrySet()) { - if( "time".equals( entry.getKey() ) ){ - time = Double.parseDouble( entry.getValue() ); - } else if( "type".equals( entry.getKey() ) ){ - // I don't think that we are doing anything here. kai, jan'19 - } else if( WarmEmissionEvent.ATTRIBUTE_LINK_ID.equals( entry.getKey() ) ){ - linkId = Id.createLinkId( entry.getValue() ); - } else if (WarmEmissionEvent.ATTRIBUTE_VEHICLE_ID.equals(entry.getKey())) { - vehicleId = Id.createVehicleId(entry.getValue()); - } else { - String pollutant = entry.getKey().equals("NOX") ? - "NOx" : - entry.getKey(); // the previous versions would write NOX instead of NOx - Double value = Double.parseDouble(entry.getValue()); - warmEmissions.put(Pollutant.valueOf(pollutant), value); + switch (entry.getKey()) { + case "time" -> time = Double.parseDouble(entry.getValue()); + case "type" -> { + // I don't think that we are doing anything here. kai, jan'19 + } + case WarmEmissionEvent.ATTRIBUTE_LINK_ID -> linkId = Id.createLinkId(entry.getValue()); + case WarmEmissionEvent.ATTRIBUTE_VEHICLE_ID -> vehicleId = Id.createVehicleId(entry.getValue()); + case null, default -> { + String pollutant = null; // the previous versions would write NOX instead of NOx + if (entry.getKey() != null) { + pollutant = entry.getKey().equals("NOX") ? + "NOx" : + entry.getKey(); + } + + Double value = Double.parseDouble(entry.getValue()); + warmEmissions.put(Pollutant.valueOf(pollutant), value); + } } } @@ -91,20 +95,24 @@ public EmissionEventsReader( EventsManager events ){ // the loop is necessary since we do now know which pollutants are in the event. for (Map.Entry entry : attributes.entrySet()) { - if( "time".equals( entry.getKey() ) ){ - time = Double.parseDouble( entry.getValue() ); - } else if( "type".equals( entry.getKey() ) ){ - // do nothing - } else if( ColdEmissionEvent.ATTRIBUTE_LINK_ID.equals( entry.getKey() ) ){ - linkId = Id.createLinkId( entry.getValue() ); - } else if (ColdEmissionEvent.ATTRIBUTE_VEHICLE_ID.equals(entry.getKey())) { - vehicleId = Id.createVehicleId(entry.getValue()); - } else { - String pollutant = entry.getKey().equals("NOX") ? - "NOx" : - entry.getKey(); // the previous versions would write NOX instead of NOx - Double value = Double.parseDouble(entry.getValue()); - coldEmissions.put(Pollutant.valueOf(pollutant), value); + switch (entry.getKey()) { + case "time" -> time = Double.parseDouble(entry.getValue()); + case "type" -> { + // do nothing + } + case ColdEmissionEvent.ATTRIBUTE_LINK_ID -> linkId = Id.createLinkId(entry.getValue()); + case ColdEmissionEvent.ATTRIBUTE_VEHICLE_ID -> vehicleId = Id.createVehicleId(entry.getValue()); + case null, default -> { + String pollutant = null; // the previous versions would write NOX instead of NOx + if (entry.getKey() != null) { + pollutant = entry.getKey().equals("NOX") ? + "NOx" : + entry.getKey(); + } + + Double value = Double.parseDouble(entry.getValue()); + coldEmissions.put(Pollutant.valueOf(pollutant), value); + } } } return new ColdEmissionEvent(time, linkId, vehicleId, coldEmissions); diff --git a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/events/WarmEmissionEvent.java b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/events/WarmEmissionEvent.java index b0504f880ed..02eeb1daaf5 100644 --- a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/events/WarmEmissionEvent.java +++ b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/events/WarmEmissionEvent.java @@ -20,13 +20,11 @@ package org.matsim.contrib.emissions.events; import org.matsim.api.core.v01.Id; -import org.matsim.api.core.v01.events.Event; import org.matsim.api.core.v01.network.Link; import org.matsim.contrib.emissions.Pollutant; import org.matsim.vehicles.Vehicle; import java.util.Map; -import java.util.Map.Entry; /** diff --git a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/example/CreateEmissionConfig.java b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/example/CreateEmissionConfig.java index f50fc6a6d27..ee492e3bb25 100644 --- a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/example/CreateEmissionConfig.java +++ b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/example/CreateEmissionConfig.java @@ -32,7 +32,7 @@ * * Creates a config file * with necessary emission input files for the {@link EmissionsConfigGroup EmissionsConfigGroup}. - * + *

* This config file is used by the {@link RunDetailedEmissionToolOfflineExample OfflineExample} and * the {@link RunDetailedEmissionToolOnlineExample OnlineExample} * @@ -119,13 +119,7 @@ public static void main(String[] args) { // emission vehicles are now set in the default vehicle container config.vehicles().setVehiclesFile(emissionVehicleFile); - if ( (Boolean) false ==null ) { - ecg.setHbefaVehicleDescriptionSource( EmissionsConfigGroup.HbefaVehicleDescriptionSource.asEngineInformationAttributes ); - } else if ( false ) { - ecg.setHbefaVehicleDescriptionSource( EmissionsConfigGroup.HbefaVehicleDescriptionSource.usingVehicleTypeId ); - } else { - ecg.setHbefaVehicleDescriptionSource( EmissionsConfigGroup.HbefaVehicleDescriptionSource.fromVehicleTypeDescription ); - } + ecg.setHbefaVehicleDescriptionSource( EmissionsConfigGroup.HbefaVehicleDescriptionSource.fromVehicleTypeDescription ); ecg.setAverageWarmEmissionFactorsFile(averageFleetWarmEmissionFactorsFile); ecg.setAverageColdEmissionFactorsFile(averageFleetColdEmissionFactorsFile); diff --git a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/example/RunAverageEmissionToolOfflineExample.java b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/example/RunAverageEmissionToolOfflineExample.java index bd1af3c2a90..c1f344dc331 100644 --- a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/example/RunAverageEmissionToolOfflineExample.java +++ b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/example/RunAverageEmissionToolOfflineExample.java @@ -49,7 +49,7 @@ public final class RunAverageEmissionToolOfflineExample{ public static final String emissionEventsFilename = "emission.events.offline.xml.gz"; - // (remove dependency of one test/execution path from other. kai/ihab, nov'18) + // (remove dependency of one test/execution path from others. kai/ihab, nov'18) private Config config; @@ -60,14 +60,10 @@ public static void main (String[] args){ emissionToolOfflineExampleV2.run(); } -// public Config prepareConfig() { -// config = ConfigUtils.loadConfig(configFile, new EmissionsConfigGroup()); -// return config; -// } - public Config prepareConfig(String args){ throw new RuntimeException("execution path no longer exists"); } + public Config prepareConfig(String [] args) { config = ConfigUtils.loadConfig(args, new EmissionsConfigGroup()); EmissionsConfigGroup ecg = ConfigUtils.addOrGetModule( config, EmissionsConfigGroup.class ); @@ -96,7 +92,7 @@ public void install(){ bind( EmissionModule.class ) ; // bind( OutputDirectoryHierarchy.class ); } - };; + }; com.google.inject.Injector injector = Injector.createInjector(config, module ); diff --git a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/example/RunDetailedEmissionToolOfflineExample.java b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/example/RunDetailedEmissionToolOfflineExample.java index 191766556c2..83d4499706a 100644 --- a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/example/RunDetailedEmissionToolOfflineExample.java +++ b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/example/RunDetailedEmissionToolOfflineExample.java @@ -48,7 +48,7 @@ public final class RunDetailedEmissionToolOfflineExample{ // private static final String configFile = "./scenarios/sampleScenario/testv2_Vehv1/config_detailed.xml"; // private static final String eventsFile = "./scenarios/sampleScenario/5.events.xml.gz"; - // (remove dependency of one test/execution path from other. kai/ihab, nov'18) + // (remove dependency of one test/execution path from others. kai/ihab, nov'18) // private static final String emissionEventOutputFileName = "5.emission.events.offline.xml.gz"; private Config config; @@ -60,11 +60,6 @@ public static void main (String[] args){ emissionToolOfflineExampleV2Vehv1.run(); } -// public Config prepareConfig() { -// config = ConfigUtils.loadConfig(configFile, new EmissionsConfigGroup()); -// return config; -// } - public Config prepareConfig(String [] args) { config = ConfigUtils.loadConfig(args, new EmissionsConfigGroup()); return config; @@ -89,7 +84,7 @@ public void install(){ bind( EventsManager.class ).toInstance( eventsManager ); bind( EmissionModule.class ) ; } - };; + }; com.google.inject.Injector injector = Injector.createInjector(config, module ); diff --git a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/example/RunDetailedEmissionToolOnlineExample.java b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/example/RunDetailedEmissionToolOnlineExample.java index 32708f736ea..d0518b73dc1 100644 --- a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/example/RunDetailedEmissionToolOnlineExample.java +++ b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/example/RunDetailedEmissionToolOnlineExample.java @@ -29,8 +29,8 @@ import org.matsim.core.scenario.ScenarioUtils; /** - * - * After creating a config file with + * + * After creating a config file with * {@link CreateEmissionConfig CreateEmissionConfig} * this class runs a simulation and calculates emissions online. * Results are written into events file (including emission events) for some iterations (as specified by the config). @@ -55,23 +55,6 @@ public static Config prepareConfig( String[] args ) { return config; } - public static Scenario prepareScenario( Config config ) { - Scenario scenario = ScenarioUtils.loadScenario( config ); - - //load emissions config -// EmissionsConfigGroup emissionsConfigGroup = (EmissionsConfigGroup) config.getModules().get(EmissionsConfigGroup.GROUP_NAME); -// URL context = scenario.getConfig().getContext(); -// URL mappingFile = emissionsConfigGroup.getEmissionRoadTypeMappingFileURL(context); - - //add Hbefa mappings to the network -// HbefaRoadTypeMapping vhtm = VisumHbefaRoadTypeMapping.createVisumRoadTypeMapping(mappingFile); -// vhtm.addHbefaMappings(scenario.getNetwork()); - - // no need for the mapping file; hbefa mappings were directly written into the link attributes. ihab nov '18 - - return scenario ; - } - public static void run( Scenario scenario, AbstractModule... modules ) { Controler controler = new Controler(scenario); controler.addOverridingModule(new AbstractModule() { @@ -87,7 +70,8 @@ public void install() { } public static void main(String[] args) { Config config = prepareConfig( args ) ; - Scenario scenario = prepareScenario( config ) ; + + Scenario scenario = ScenarioUtils.loadScenario(config); run( scenario ) ; } diff --git a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/package-info.java b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/package-info.java index 95bfb7b8b85..811d521cb60 100644 --- a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/package-info.java +++ b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/package-info.java @@ -14,7 +14,7 @@ * *

Export from HBEFA 3.x

* Currently, data from the HBEFA 3.x Microsoft Access database needs to be exported manually. - * + *

* Consequently, the following steps within HBEFA 3.x need still be done manually: *

    *
  • Install and open HBEFA 3.x
  • @@ -29,11 +29,11 @@ *
  • HOT EMISSION FACTORS: Choose "Individual TrafficSituations" > "Construct your own list" > "SelectAll" > "Return"
  • *
  • COLD START EXCESS EMISSION FACTORS: Tick this option and choose "Construct your own list" > select all "patterns" with average temperature, detailed parking time (0-1h .. >12h), and detailed distance (0-1km and 1-2km) > "Return"
  • *
  • Leave everything else as default
  • - *
+ * *
  • Enter "Name of parameter set" and press "Calculate"
  • *
  • Save the two generated tables using "Results" > "Export" to the desired location
  • * - * + * * All these emission factor files need to be converted into *.txt or *.csv with ";" as delimiter. * Their column headers should automatically match the parser definition * in the respective method of the {@link org.matsim.contrib.emissions.EmissionModule}. @@ -44,9 +44,10 @@ *
  • roadTypeMappingFile: This file needs to map road types in your network to HBEFA 3.x road types. * Update (June'2018) one can now directly add HBEFA road type to link attributes using {@link org.matsim.contrib.emissions.EmissionUtils#setHbefaRoadType(org.matsim.api.core.v01.network.Link, java.lang.String)} * or see {@link org.matsim.contrib.emissions.utils.EmissionsConfigGroup} for a detailed description. - * + * *
  • emissionVehicleFile: This data type is defined in the EmissionsConfigGroup, - * see {@link org.matsim.contrib.emissions.utils.EmissionsConfigGroup}. The following information is surrounded by {@link org.matsim.contrib.emissions.EmissionUtils.EmissionSpecificationMarker}. It is described as "definition of a vehicle + * see {@link org.matsim.contrib.emissions.utils.EmissionsConfigGroup}. + * The following information is surrounded by {@link org.matsim.contrib.emissions.EmissionUtils.EmissionSpecificationMarker}. It is described as "definition of a vehicle * for every person (who is allowed to choose a vehicle in the simulation): *
      *
    • REQUIRED: Vehicle description must start with the respective HbefaVehicleCategory followed by ";" @@ -61,7 +62,7 @@ *
        * *

        Model description

        - * + * *

        Emissions

        * The main package contains classes and methods to handle the emission input data and create * maps to associate the emissions with corresponding vehicle types, speed, parking time, ...
        @@ -86,7 +87,7 @@ * a distance, which is driven after parking and, again, vehicle attributes. * The cold/warm emission factor keys are mapped to the values of cold/warm emissions, the cold/warm emission factors. *

        - * + * * @author benjamin, julia */ diff --git a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/utils/EmissionWriter.java b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/utils/EmissionWriter.java index 7a5e1a1ada1..ce87ab17cb0 100644 --- a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/utils/EmissionWriter.java +++ b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/utils/EmissionWriter.java @@ -42,39 +42,39 @@ public final class EmissionWriter { // is this useful as a publicly available class? kai, jan'19 private static final Logger logger = LogManager.getLogger(EmissionWriter.class); - + public EmissionWriter(){ } - + public void writeHomeLocation2TotalEmissions( Population population, Map, SortedMap> totalEmissions, Collection pollutants, String outFile) { try{ - FileWriter fstream = new FileWriter(outFile); + FileWriter fstream = new FileWriter(outFile); BufferedWriter out = new BufferedWriter(fstream); out.append("personId \t xHome \t yHome \t"); for (String pollutant : pollutants){ - out.append(pollutant + "[g] \t"); + out.append(pollutant).append("[g] \t"); } out.append("\n"); for(Person person: population.getPersons().values()){ Id personId = person.getId(); Plan plan = person.getSelectedPlan(); - Activity homeAct = (Activity) plan.getPlanElements().get(0); + Activity homeAct = (Activity) plan.getPlanElements().getFirst(); Coord homeCoord = homeAct.getCoord(); Double xHome = homeCoord.getX(); Double yHome = homeCoord.getY(); - out.append(personId + "\t" + xHome + "\t" + yHome + "\t"); + out.append(String.valueOf(personId)).append("\t").append(String.valueOf(xHome)).append("\t").append(String.valueOf(yHome)).append("\t"); Map emissionType2Value = totalEmissions.get(personId); for(String pollutant : pollutants){ if(emissionType2Value.get(pollutant) != null){ - out.append(emissionType2Value.get(pollutant) + "\t"); + out.append(String.valueOf(emissionType2Value.get(pollutant))).append("\t"); } else{ out.append("0.0" + "\t"); // TODO: do I still need this? } @@ -83,7 +83,7 @@ public void writeHomeLocation2TotalEmissions( } //Close the output stream out.close(); - logger.info("Finished writing output to " + outFile); + logger.info("Finished writing output to {}", outFile); } catch (Exception e){ throw new RuntimeException(e); } diff --git a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/utils/EmissionsConfigGroup.java b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/utils/EmissionsConfigGroup.java index f7107ece5f0..cc958dc1a04 100644 --- a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/utils/EmissionsConfigGroup.java +++ b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/utils/EmissionsConfigGroup.java @@ -82,7 +82,7 @@ public enum HbefaTableConsistencyCheckingLevel { allCombinations, consistent, no private static final String EMISSION_FACTORS_COLD_FILE_DETAILED_CMT = "file with HBEFA detailed cold emission factors"; private static final String HBEFA_TABLE_CONSISTENCY_CHECKING_LEVEL_CMT = "Define on which level the entries in the provided hbefa tables are checked for consistency" + "\n\t\t\t" + HbefaTableConsistencyCheckingLevel.allCombinations.name() + " : check if entries for all combinations of HbefaTrafficSituation, HbefaVehicleCategory, HbefaVehicleAttributes, HbefaComponent. " + - "are available in the table. It only checks for paramters that are available in the table (e.g. if there is no HGV in the table, it can also pass. \n\t\t\t" + + "are available in the table. It only checks for parameters that are available in the table (e.g. if there is no HGV in the table, it can also pass. \n\t\t\t" + HbefaTableConsistencyCheckingLevel.consistent.name() + " : check if the entries for the two HbefaTrafficSituations 'StopAndGo' and 'FreeFlow' (nov 2020, may be subject to change) are consistently available in the table. \n\t\t\t" + //TODO HbefaTableConsistencyCheckingLevel.none.name() + " : There is no consistency check. This option is NOT recommended and only for backward capability to inputs from before spring 2020 . \n\t\t\t" + "Default is " + HbefaTableConsistencyCheckingLevel.allCombinations.name(); @@ -187,7 +187,6 @@ public DetailedVsAverageLookupBehavior getDetailedVsAverageLookupBehavior() { // =============== /** * @param hbefaTableConsistencyCheckingLevel -- {@value #HBEFA_TABLE_CONSISTENCY_CHECKING_LEVEL} - * @noinspection JavadocReference */ @StringSetter(HBEFA_TABLE_CONSISTENCY_CHECKING_LEVEL) public void setHbefaTableConsistencyCheckingLevel(HbefaTableConsistencyCheckingLevel hbefaTableConsistencyCheckingLevel) { @@ -318,12 +317,8 @@ public void setEmissionsComputationMethod(EmissionsComputationMethod emissionsCo @Override protected final void checkConsistency(Config config){ switch( this.emissionsComputationMethod ){ - case StopAndGoFraction -> log.info( "Please note that with setting of emissionsComputationMethod " + EmissionsComputationMethod.StopAndGoFraction + "" + - " the emission factors for both freeFlow and StopAndGo fractions are looked up independently and are " + - "therefore following the fallback behaviour set in " + DETAILED_VS_AVERAGE_LOOKUP_BEHAVIOR + - " independently. --> Depending on the input, it may be that e.g. for ff the detailed value is taken, while for the stopAndGo part " + - "a less detailed value is used, because the value with the same level of detail is missing." ); - case AverageSpeed -> log.warn( "This setting of emissionsComputationMethod. " + EmissionsComputationMethod.AverageSpeed + " is not covered by many test cases." ); + case StopAndGoFraction -> log.info("Please note that with setting of emissionsComputationMethod {} the emission factors for both freeFlow and StopAndGo fractions are looked up independently and are therefore following the fallback behaviour set in " + DETAILED_VS_AVERAGE_LOOKUP_BEHAVIOR + " independently. --> Depending on the input, it may be that e.g. for ff the detailed value is taken, while for the stopAndGo part a less detailed value is used, because the value with the same level of detail is missing.", EmissionsComputationMethod.StopAndGoFraction); + case AverageSpeed -> log.warn("This setting of emissionsComputationMethod. {} is not covered by many test cases.", EmissionsComputationMethod.AverageSpeed); default -> throw new IllegalStateException( "Unexpected value: " + this.emissionsComputationMethod ); } } diff --git a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/OsmHbefaMappingTest.java b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/OsmHbefaMappingTest.java index 195fc6e6fcb..10aff1cbe2a 100644 --- a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/OsmHbefaMappingTest.java +++ b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/OsmHbefaMappingTest.java @@ -16,7 +16,7 @@ void testRegularMapping() { var mapping = OsmHbefaMapping.build(); var link = getTestLink("primary", 70 / 3.6); - var hbefaType = mapping.determineHebfaType(link); + var hbefaType = mapping.determineHbefaType(link); assertEquals("URB/Trunk-City/70", hbefaType); } @@ -27,7 +27,7 @@ void testMergedLinkTypeMapping() { var mapping = OsmHbefaMapping.build(); var link = getTestLink("primary|railway.tram", 70 / 3.6); - var hbefaType = mapping.determineHebfaType(link); + var hbefaType = mapping.determineHbefaType(link); assertEquals("URB/Trunk-City/70", hbefaType); } @@ -39,7 +39,7 @@ void testUnknownType() { var mapping = OsmHbefaMapping.build(); var link = getTestLink("unknown-tag", 100 / 3.6); - mapping.determineHebfaType(link); + mapping.determineHbefaType(link); fail("Expected Runtime Exception."); }); @@ -51,7 +51,7 @@ void testFastMotorway() { var mapping = OsmHbefaMapping.build(); var link = getTestLink("motorway", 100 / 3.6); - var hbefaType = mapping.determineHebfaType(link); + var hbefaType = mapping.determineHbefaType(link); assertEquals("URB/MW-Nat./100", hbefaType); } @@ -62,11 +62,11 @@ void testMotorwayWithNoExactSpeedTag() { var mapping = OsmHbefaMapping.build(); var link = getTestLink("motorway", 100.11 / 3.6); - var hbefaType = mapping.determineHebfaType(link); + var hbefaType = mapping.determineHbefaType(link); assertEquals("URB/MW-Nat./100", hbefaType); link = getTestLink("motorway", 86.11 / 3.6); - hbefaType = mapping.determineHebfaType(link); + hbefaType = mapping.determineHbefaType(link); assertEquals("URB/MW-Nat./90", hbefaType); } @@ -77,7 +77,7 @@ void testFastMotorwayLink() { var mapping = OsmHbefaMapping.build(); var link = getTestLink("motorway_link", 100 / 3.6); - var hbefaType = mapping.determineHebfaType(link); + var hbefaType = mapping.determineHbefaType(link); assertEquals("URB/MW-Nat./100", hbefaType); } @@ -87,7 +87,7 @@ void testLivingStreet() { var mapping = OsmHbefaMapping.build(); var link = getTestLink("living_street", 50 / 3.6); - var hbefaType = mapping.determineHebfaType(link); + var hbefaType = mapping.determineHbefaType(link); assertEquals("URB/Access/50", hbefaType); } @@ -98,7 +98,7 @@ void testUnclassified() { var mapping = OsmHbefaMapping.build(); var link = getTestLink("unclassified", 50 / 3.6); - var hbefaType = mapping.determineHebfaType(link); + var hbefaType = mapping.determineHbefaType(link); assertEquals("URB/Access/50", hbefaType); } @@ -109,7 +109,7 @@ void testNoHighwayType() { var mapping = OsmHbefaMapping.build(); var link = getTestLink(" ", 60 / 3.6); - var hbefaType = mapping.determineHebfaType(link); + var hbefaType = mapping.determineHbefaType(link); assertEquals("URB/Local/60", hbefaType); } @@ -121,7 +121,7 @@ void testNoAllowedSpeedTag() { var link = getTestLink("residential", 40 / 3.6); link.getAttributes().removeAttribute(NetworkUtils.ALLOWED_SPEED); - var hbefaType = mapping.determineHebfaType(link); + var hbefaType = mapping.determineHbefaType(link); assertEquals("URB/Access/40", hbefaType); } diff --git a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestColdEmissionAnalysisModule.java b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestColdEmissionAnalysisModule.java index d5d32b96239..aa01f57e02d 100644 --- a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestColdEmissionAnalysisModule.java +++ b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestColdEmissionAnalysisModule.java @@ -20,7 +20,6 @@ package org.matsim.contrib.emissions; -import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.matsim.api.core.v01.Id; @@ -88,7 +87,7 @@ public class TestColdEmissionAnalysisModule { private static final String geq2l_sizeClass = ">=2L"; private static final String PC_D_Euro_3_emConcept = "PC-D-Euro-3"; - // emission factors for tables - no dublicates! + // emission factors for tables - no duplicates! private static final Double detailedPetrolFactor = 100.; private static final Double detailedDieselFactor = 10.; private static final Double averageAverageFactor = .1; diff --git a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestColdEmissionAnalysisModuleCase1.java b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestColdEmissionAnalysisModuleCase1.java index 690ee4ed802..57aae0aee49 100644 --- a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestColdEmissionAnalysisModuleCase1.java +++ b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestColdEmissionAnalysisModuleCase1.java @@ -92,7 +92,7 @@ public class TestColdEmissionAnalysisModuleCase1 { private static final String geq2l_sizeClass = ">=2L"; private static final String PC_D_Euro_3_emConcept = "PC-D-Euro-3"; - // emission factors for tables - no dublicates! + // emission factors for tables - no duplicates! private static final Double detailedPetrolFactor = 100.; private static final Double detailedDieselFactor = 10.; private static final Double averageAverageFactor = .1; @@ -107,18 +107,18 @@ void calculateColdEmissionsAndThrowEventTest_completeData() { // first case: complete data // corresponding entry in average table Collections.addAll(testCase1, "PASSENGER_CAR", petrol_technology, none_sizeClass, none_emConcept, averagePetrolFactor); - logger.info("Running testcase:" + testCase1.toString()); + logger.info("Running testcase:{}", testCase1); Id linkId = Id.create("linkId" + testCase1, Link.class); Id vehicleId = Id.create("vehicleId" + testCase1, Vehicle.class); Id vehicleTypeId = Id.create(testCase1.get(0) + ";" + testCase1.get(1) + ";" + testCase1.get(2) + ";" + testCase1.get(3), VehicleType.class); Vehicle vehicle = VehicleUtils.getFactory().createVehicle(vehicleId, VehicleUtils.getFactory().createVehicleType(vehicleTypeId)); - logger.info("VehicleId: " + vehicle.getId().toString()); - logger.info("VehicleTypeId: " + vehicle.getType().getId()); + logger.info("VehicleId: {}", vehicle.getId().toString()); + logger.info("VehicleTypeId: {}", vehicle.getType().getId()); final Map calculatedPollutants = coldEmissionAnalysisModule.checkVehicleInfoAndCalculateWColdEmissions(vehicle.getType(), vehicle.getId(), linkId, 0.0, parkingDuration, tableAccDistance); double sumOfEmissions = calculatedPollutants.values().stream().mapToDouble(Double::doubleValue).sum(); - String message = "The expected emissions for " + testCase1.toString() + " are " + pollutants.size() * (Double) testCase1.get(4) + " but were " + sumOfEmissions; + String message = "The expected emissions for " + testCase1 + " are " + pollutants.size() * (Double) testCase1.get(4) + " but were " + sumOfEmissions; Assertions.assertEquals(pollutants.size() * (Double) testCase1.get(4), sumOfEmissions, MatsimTestUtils.EPSILON, message); } @@ -135,7 +135,7 @@ private static ColdEmissionAnalysisModule setUp() { // This represents the previous behavior, which fallbacks to the average table, // if values are not found in the detailed table, kmt apr'20 - // This test seems to refer to an direct lookup in average table + // This test seems to refer to a direct lookup in average table ecg.setDetailedVsAverageLookupBehavior(EmissionsConfigGroup.DetailedVsAverageLookupBehavior.tryDetailedThenTechnologyAverageThenAverageTable); return new ColdEmissionAnalysisModule(avgHbefaColdTable, detailedHbefaColdTable, ecg, pollutants, emissionEventManager); } @@ -227,5 +227,5 @@ private static void putIntoHbefaColdTable( detailedHbefaColdTable.put(detColdKey, detColdFactor); } } - + } diff --git a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestColdEmissionAnalysisModuleCase2.java b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestColdEmissionAnalysisModuleCase2.java index c97de7d7ecd..eba88366726 100644 --- a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestColdEmissionAnalysisModuleCase2.java +++ b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestColdEmissionAnalysisModuleCase2.java @@ -70,7 +70,7 @@ public class TestColdEmissionAnalysisModuleCase2 { // The material below was confused in the way that strings like "petrol" or "diesel" were given for the // size classes, and "<1,4L" or ">=2L" for the emissions concept. Tried to make it consistent, // but I don't know if it is still testing the original functionality. kai, jul'18 - + // first case: complete data - corresponding entry in average table private static final String petrol_technology = "petrol"; private static final String none_sizeClass = "average"; @@ -84,7 +84,7 @@ public class TestColdEmissionAnalysisModuleCase2 { private static final String geq2l_sizeClass = ">=2L"; private static final String PC_D_Euro_3_emConcept = "PC-D-Euro-3"; - // emission factors for tables - no dublicates! + // emission factors for tables - no duplicates! private static final Double detailedPetrolFactor = 100.; private static final Double detailedDieselFactor = 10.; private static final Double averageAverageFactor = .1; @@ -105,13 +105,13 @@ void calculateColdEmissionsAndThrowEventTest_completeData() { Id vehicleId = Id.create( "vehicleId" + testCase2 , Vehicle.class ); Id vehicleTypeId = Id.create( testCase2.get( 0 ) + ";" + testCase2.get( 1 ) + ";" + testCase2.get( 2 ) + ";" + testCase2.get( 3 ), VehicleType.class ); Vehicle vehicle = VehicleUtils.getFactory().createVehicle( vehicleId, VehicleUtils.getFactory().createVehicleType( vehicleTypeId ) ); - logger.info("VehicleId: " + vehicle.getId().toString()); - logger.info("VehicleTypeId: " + vehicle.getType().getId()); + logger.info("VehicleId: {}", vehicle.getId().toString()); + logger.info("VehicleTypeId: {}", vehicle.getType().getId()); Map calculatedPollutants = coldEmissionAnalysisModule.checkVehicleInfoAndCalculateWColdEmissions(vehicle.getType(), vehicle.getId(), linkId, 0.0, parkingDuration, tableAccDistance); double sumOfEmissions = calculatedPollutants.values().stream().mapToDouble(Double::doubleValue).sum(); - - String message = "The expected emissions for " + testCase2.toString() + " are " + pollutants.size() * (Double) testCase2.get( 4 ) + " but were " + sumOfEmissions; + + String message = "The expected emissions for " + testCase2 + " are " + pollutants.size() * (Double) testCase2.get( 4 ) + " but were " + sumOfEmissions; Assertions.assertEquals( pollutants.size() * (Double) testCase2.get( 4 ), sumOfEmissions, MatsimTestUtils.EPSILON, message ); } @@ -120,10 +120,10 @@ void calculateColdEmissionsAndThrowEventTest_completeData() { private ColdEmissionAnalysisModule setUp() { Map avgHbefaColdTable = new HashMap<>(); Map detailedHbefaColdTable = new HashMap<>(); - + fillAveragesTable( avgHbefaColdTable ); fillDetailedTable( detailedHbefaColdTable ); - + EventsManager emissionEventManager = new HandlerToTestEmissionAnalysisModules(); EmissionsConfigGroup ecg = new EmissionsConfigGroup(); ecg.setHbefaVehicleDescriptionSource( EmissionsConfigGroup.HbefaVehicleDescriptionSource.usingVehicleTypeId ); @@ -133,7 +133,7 @@ private ColdEmissionAnalysisModule setUp() { return new ColdEmissionAnalysisModule( avgHbefaColdTable, detailedHbefaColdTable, ecg, pollutants, emissionEventManager ); } - + private static void fillDetailedTable( Map detailedHbefaColdTable ) { // create all needed and one unneeded entry for the detailed table { @@ -154,19 +154,19 @@ private static void fillDetailedTable( Map avgHbefaColdTable ) { // create all needed and one unneeded entry for the average table { // add passenger car entry "average;average;average": HbefaVehicleAttributes vehAtt = ColdEmissionAnalysisModule.createHbefaVehicleAttributes( "average", "average", "average" ) ; - + putIntoHbefaColdTable( avgHbefaColdTable, vehAtt, new HbefaColdEmissionFactor(averageAverageFactor), PASSENGER_CAR ); } { HbefaVehicleAttributes vehAtt = ColdEmissionAnalysisModule.createHbefaVehicleAttributes( petrol_technology, none_sizeClass, none_emConcept ); - + putIntoHbefaColdTable( avgHbefaColdTable, vehAtt, new HbefaColdEmissionFactor( averagePetrolFactor ), PASSENGER_CAR ); } { @@ -182,7 +182,7 @@ private static void fillAveragesTable( Map detailedHbefaColdTable, final HbefaVehicleAttributes vehAtt, final HbefaColdEmissionFactor detColdFactor, final HbefaVehicleCategory hbefaVehicleCategory ) { for ( Pollutant cp : pollutants ) { HbefaColdEmissionFactorKey detColdKey = new HbefaColdEmissionFactorKey(); @@ -194,5 +194,5 @@ private static void putIntoHbefaColdTable( final Map pollutants = new HashSet<>(Arrays.asList(Pollutant.values())); // strings for test cases - + // The material below was confused in the way that strings like "petrol" or "diesel" were given for the // size classes, and "<1,4L" or ">=2L" for the emissions concept. Tried to make it consistent, // but I don't know if it is still testing the original functionality. kai, jul'18 - + // first case: complete data - corresponding entry in average table private static final String petrol_technology = "petrol"; private static final String none_sizeClass = "average"; @@ -85,7 +85,7 @@ public class TestColdEmissionAnalysisModuleCase3 { private static final String geq2l_sizeClass = ">=2L"; private static final String PC_D_Euro_3_emConcept = "PC-D-Euro-3"; - // emission factors for tables - no dublicates! + // emission factors for tables - no duplicates! private static final Double detailedPetrolFactor = 100.; private static final Double detailedDieselFactor = 10.; private static final Double averageAverageFactor = .1; @@ -103,19 +103,19 @@ void calculateColdEmissionsAndThrowEventTest_completeData() { // error when using the average entry. Collections.addAll( testCase3, "PASSENGER_CAR", diesel_technology, geq2l_sizeClass, PC_D_Euro_3_emConcept, detailedDieselFactor ); - logger.info("Running testcase: " + testCase3.toString()); + logger.info("Running testcase: {}", testCase3); Id linkId = Id.create( "linkId" + testCase3 , Link.class ); Id vehicleId = Id.create( "vehicleId" + testCase3, Vehicle.class ); Id vehicleTypeId = Id.create( testCase3.get( 0 ) + ";" + testCase3.get( 1 ) + ";" + testCase3.get( 2 ) + ";" + testCase3.get( 3 ), VehicleType.class ); Vehicle vehicle = VehicleUtils.getFactory().createVehicle( vehicleId, VehicleUtils.getFactory().createVehicleType( vehicleTypeId ) ); - logger.info("VehicleId: " + vehicle.getId().toString()); - logger.info("VehicleTypeId: " + vehicle.getType().getId()); + logger.info("VehicleId: {}", vehicle.getId().toString()); + logger.info("VehicleTypeId: {}", vehicle.getType().getId()); Map calculatedPollutants = coldEmissionAnalysisModule.checkVehicleInfoAndCalculateWColdEmissions(vehicle.getType(), vehicle.getId(), linkId, 0.0, parkingDuration, tableAccDistance); double sumOfEmissions = calculatedPollutants.values().stream().mapToDouble(Double::doubleValue).sum(); - String message = "The expected emissions for " + testCase3.toString() + " are " + pollutants.size() * (Double) testCase3.get( 4 ) + " but were " + sumOfEmissions; + String message = "The expected emissions for " + testCase3 + " are " + pollutants.size() * (Double) testCase3.get( 4 ) + " but were " + sumOfEmissions; Assertions.assertEquals( pollutants.size() * (Double) testCase3.get( 4 ), sumOfEmissions, MatsimTestUtils.EPSILON, message ); @@ -124,10 +124,10 @@ void calculateColdEmissionsAndThrowEventTest_completeData() { private ColdEmissionAnalysisModule setUp() { Map avgHbefaColdTable = new HashMap<>(); Map detailedHbefaColdTable = new HashMap<>(); - + fillAveragesTable( avgHbefaColdTable ); fillDetailedTable( detailedHbefaColdTable ); - + EventsManager emissionEventManager = new HandlerToTestEmissionAnalysisModules(); EmissionsConfigGroup ecg = new EmissionsConfigGroup(); ecg.setHbefaVehicleDescriptionSource( EmissionsConfigGroup.HbefaVehicleDescriptionSource.usingVehicleTypeId ); @@ -136,12 +136,12 @@ private ColdEmissionAnalysisModule setUp() { ecg.setDetailedVsAverageLookupBehavior(EmissionsConfigGroup.DetailedVsAverageLookupBehavior.tryDetailedThenTechnologyAverageThenAverageTable); // return new ColdEmissionAnalysisModule( avgHbefaColdTable, detailedHbefaColdTable, ecg, pollutants, emissionEventManager ); - + } - + private static void fillDetailedTable( Map detailedHbefaColdTable ) { // create all needed and one unneeded entry for the detailed table - + { // add passenger car entry "petrol;<=1.4L;PC-P-Euro-1": HbefaVehicleAttributes vehAtt = ColdEmissionAnalysisModule.createHbefaVehicleAttributes( petrol_technology2, leq14l_sizeClass, PC_P_Euro_1_emConcept ); @@ -151,19 +151,19 @@ private static void fillDetailedTable( Map=2L;PC-D-Euro-3": HbefaVehicleAttributes vehAtt = ColdEmissionAnalysisModule.createHbefaVehicleAttributes( diesel_technology, geq2l_sizeClass, PC_D_Euro_3_emConcept ); - + putIntoHbefaColdTable( detailedHbefaColdTable, vehAtt, new HbefaColdEmissionFactor( detailedDieselFactor ), PASSENGER_CAR ); } { // add heavy goods vehicle entry "petrol;none;none": //(pre-existing comment: HEAVY_GOODS_VEHICLE;PC petrol;petrol;none should not be used --???) HbefaVehicleAttributes vehAtt = ColdEmissionAnalysisModule.createHbefaVehicleAttributes( petrol_technology, none_sizeClass, none_emConcept ); - + putIntoHbefaColdTable( detailedHbefaColdTable, vehAtt, new HbefaColdEmissionFactor( fakeFactor ), HEAVY_GOODS_VEHICLE ); } } - + private static void fillAveragesTable( Map avgHbefaColdTable ) { // create all needed and one unneeded entry for the average table @@ -171,30 +171,30 @@ private static void fillAveragesTable( Map detailedHbefaColdTable, final HbefaVehicleAttributes vehAtt, final HbefaColdEmissionFactor detColdFactor, final HbefaVehicleCategory hbefaVehicleCategory ) { for ( Pollutant cp : pollutants ) { HbefaColdEmissionFactorKey detColdKey = new HbefaColdEmissionFactorKey(); @@ -206,5 +206,5 @@ private static void putIntoHbefaColdTable( final Map pollutants = new HashSet<>(Arrays.asList(Pollutant.values())); // strings for test cases - + // The material below was confused in the way that strings like "petrol" or "diesel" were given for the // size classes, and "<1,4L" or ">=2L" for the emissions concept. Tried to make it consistent, // but I don't know if it is still testing the original functionality. kai, jul'18 - + // first case: complete data - corresponding entry in average table private static final String petrol_technology = "petrol"; private static final String none_sizeClass = "average"; @@ -84,12 +84,12 @@ public class TestColdEmissionAnalysisModuleCase4 { private static final String diesel_technology = "diesel"; private static final String geq2l_sizeClass = ">=2L"; private static final String PC_D_Euro_3_emConcept = "PC-D-Euro-3"; - + // fifth case: cold emission factor not set // private static final String nullcase_emConcept = "nullCase"; - // this testcase does not exist any more. kai, jul'18 + // this testcase does not exist anymore. kai, jul'18 - // emission factors for tables - no dublicates! + // emission factors for tables - no duplicates! private static final Double detailedPetrolFactor = 100.; private static final Double detailedDieselFactor = 10.; private static final Double averageAverageFactor = .1; @@ -113,30 +113,30 @@ void calculateColdEmissionsAndThrowEventTest_completeData() { Collections.addAll( testCase4, "PASSENGER_CAR", "", "", "", averageAverageFactor ); - logger.info("Running testcase: " + testCase4.indexOf( 0 ) + " " + testCase4.toString()); + logger.info("Running testcase: {} {}", testCase4.indexOf(0), testCase4); Id linkId = Id.create( "linkId" + testCase4.indexOf( 0 ), Link.class ); Id vehicleId = Id.create( "vehicleId" + testCase4.indexOf( 0 ), Vehicle.class ); Id vehicleTypeId = Id.create( testCase4.get( 0 ) + ";" + testCase4.get( 1 ) + ";" + testCase4.get( 2 ) + ";" + testCase4.get( 3 ), VehicleType.class ); - + Vehicle vehicle = VehicleUtils.getFactory().createVehicle( vehicleId, VehicleUtils.getFactory().createVehicleType( vehicleTypeId ) ); - logger.info("VehicleId: " + vehicle.getId().toString()); - logger.info("VehicleTypeId: " + vehicle.getType().getId()); + logger.info("VehicleId: {}", vehicle.getId().toString()); + logger.info("VehicleTypeId: {}", vehicle.getType().getId()); Map calculatedPollutants = coldEmissionAnalysisModule.checkVehicleInfoAndCalculateWColdEmissions(vehicle.getType(), vehicle.getId(), linkId, 0.0, parkingDuration, tableAccDistance); double sumOfEmissions = calculatedPollutants.values().stream().mapToDouble(Double::doubleValue).sum(); - String message = "The expected emissions for " + testCase4.toString() + " are " + pollutants.size() * (Double) testCase4.get( 4 ) + " but were " + sumOfEmissions; + String message = "The expected emissions for " + testCase4 + " are " + pollutants.size() * (Double) testCase4.get( 4 ) + " but were " + sumOfEmissions; Assertions.assertEquals( pollutants.size() * (Double) testCase4.get( 4 ), sumOfEmissions, MatsimTestUtils.EPSILON, message ); - + } - + private ColdEmissionAnalysisModule setUp() { Map avgHbefaColdTable = new HashMap<>(); Map detailedHbefaColdTable = new HashMap<>(); - + fillAveragesTable( avgHbefaColdTable ); fillDetailedTable( detailedHbefaColdTable ); - + EventsManager emissionEventManager = new HandlerToTestEmissionAnalysisModules(); EmissionsConfigGroup ecg = new EmissionsConfigGroup(); @@ -146,10 +146,10 @@ private ColdEmissionAnalysisModule setUp() { ecg.setDetailedVsAverageLookupBehavior(EmissionsConfigGroup.DetailedVsAverageLookupBehavior.tryDetailedThenTechnologyAverageThenAverageTable); return new ColdEmissionAnalysisModule( avgHbefaColdTable, detailedHbefaColdTable, ecg, pollutants, emissionEventManager ); } - + private static void fillDetailedTable( Map detailedHbefaColdTable ) { // create all needed and one unneeded entry for the detailed table - + { // add passenger car entry "petrol;<=1.4L;PC-P-Euro-1": HbefaVehicleAttributes vehAtt = ColdEmissionAnalysisModule.createHbefaVehicleAttributes( petrol_technology2, leq14l_sizeClass, PC_P_Euro_1_emConcept ); @@ -167,7 +167,7 @@ private static void fillDetailedTable( Map avgHbefaColdTable ) { // create all needed and one unneeded entry for the average table @@ -194,7 +194,7 @@ private static void fillAveragesTable( Map detailedHbefaColdTable, final HbefaVehicleAttributes vehAtt, final HbefaColdEmissionFactor detColdFactor, final HbefaVehicleCategory hbefaVehicleCategory ) { for ( Pollutant cp : pollutants ) { HbefaColdEmissionFactorKey detColdKey = new HbefaColdEmissionFactorKey(); @@ -206,5 +206,5 @@ private static void putIntoHbefaColdTable( final Map pollutants = new HashSet<>(Arrays.asList(Pollutant.values())); // strings for test cases - + // The material below was confused in the way that strings like "petrol" or "diesel" were given for the // size classes, and "<1,4L" or ">=2L" for the emissions concept. Tried to make it consistent, // but I don't know if it is still testing the original functionality. kai, jul'18 - + // case: complete data - corresponding entry in average table private static final String petrol_technology = "petrol"; private static final String none_sizeClass = "average"; @@ -82,8 +82,8 @@ public class TestColdEmissionAnalysisModuleCase6 { private static final String geq2l_sizeClass = ">=2L"; private static final String PC_D_Euro_3_emConcept = "PC-D-Euro-3"; - - // emission factors for tables - no dublicates! + + // emission factors for tables - no duplicates! private static final Double detailedPetrolFactor = 100.; private static final Double detailedDieselFactor = 10.; private static final Double averageAverageFactor = .1; @@ -105,39 +105,39 @@ void calculateColdEmissionsAndThrowEventTest_completeData() { // sixth case: heavy goods vehicle // -> throw warning -> use detailed or average table for passenger cars - String heavygoodsvehicle = "HEAVY_GOODS_VEHICLE"; - Collections.addAll( testCase6, heavygoodsvehicle, petrol_technology, none_sizeClass, none_emConcept, heavyGoodsFactor); + String heavyGoodsVehicle = "HEAVY_GOODS_VEHICLE"; + Collections.addAll( testCase6, heavyGoodsVehicle, petrol_technology, none_sizeClass, none_emConcept, heavyGoodsFactor); - logger.info("Running testcase: " + testCase6 + " " +testCase6.toString()); + logger.info("Running testcase: {} {}", testCase6, testCase6); Id linkId = Id.create( "linkId" + testCase6, Link.class ); Id vehicleId = Id.create( "vehicleId" + testCase6, Vehicle.class ); Id vehicleTypeId = Id.create( testCase6.get( 0 ) + ";" + testCase6.get( 1 ) + ";" + testCase6.get( 2 ) + ";" + testCase6.get( 3 ), VehicleType.class ); - + Vehicle vehicle = VehicleUtils.getFactory().createVehicle( vehicleId, VehicleUtils.getFactory().createVehicleType( vehicleTypeId ) ); - logger.info("VehicleId: " + vehicle.getId().toString()); - logger.info("VehicleTypeId: " + vehicle.getType().getId()); + logger.info("VehicleId: {}", vehicle.getId().toString()); + logger.info("VehicleTypeId: {}", vehicle.getType().getId()); Map calculatedPollutants = coldEmissionAnalysisModule.checkVehicleInfoAndCalculateWColdEmissions(vehicle.getType(), vehicle.getId(), linkId, 0.0, parkingDuration, tableAccDistance); double sumOfEmissions = calculatedPollutants.values().stream().mapToDouble(Double::doubleValue).sum(); - String message = "The expected emissions for " + testCase6.toString() + " are " + pollutants.size() * (Double) testCase6.get( 4 ) + " but were " + sumOfEmissions; + String message = "The expected emissions for " + testCase6 + " are " + pollutants.size() * (Double) testCase6.get( 4 ) + " but were " + sumOfEmissions; Assertions.assertEquals( pollutants.size() * (Double) testCase6.get( 4 ), sumOfEmissions, MatsimTestUtils.EPSILON, message ); } - + private ColdEmissionAnalysisModule setUp() { Map avgHbefaColdTable = new HashMap<>(); Map detailedHbefaColdTable = new HashMap<>(); - + fillAveragesTable( avgHbefaColdTable ); fillDetailedTable( detailedHbefaColdTable ); - + EventsManager emissionEventManager = new HandlerToTestEmissionAnalysisModules(); EmissionsConfigGroup ecg = new EmissionsConfigGroup(); ecg.setHbefaVehicleDescriptionSource( EmissionsConfigGroup.HbefaVehicleDescriptionSource.usingVehicleTypeId ); return new ColdEmissionAnalysisModule( avgHbefaColdTable, detailedHbefaColdTable, ecg, pollutants, emissionEventManager ); } - + private static void fillDetailedTable( Map detailedHbefaColdTable ) { // create all needed and one unneeded entry for the detailed table { @@ -147,7 +147,7 @@ private static void fillDetailedTable( Map Should be used, since HGV shpuld be supported and not fallback to average any more, kmt apr'20. + //(pre-existing comment: HEAVY_GOODS_VEHICLE;PC petrol;petrol; --> Should be used, since HGV should be supported and not fallback to average anymore, kmt apr'20.) HbefaVehicleAttributes vehAtt = ColdEmissionAnalysisModule.createHbefaVehicleAttributes( petrol_technology, none_sizeClass, none_emConcept ); putIntoHbefaColdTable( detailedHbefaColdTable, vehAtt, new HbefaColdEmissionFactor(heavyGoodsFactor), HEAVY_GOODS_VEHICLE ); } @@ -160,7 +160,7 @@ private static void fillDetailedTable( Map avgHbefaColdTable ) { // create all needed and one unneeded entry for the average table @@ -184,11 +184,11 @@ private static void fillAveragesTable( Map detailedHbefaColdTable, final HbefaVehicleAttributes vehAtt, final HbefaColdEmissionFactor detColdFactor, final HbefaVehicleCategory hbefaVehicleCategory ) { for ( Pollutant cp : pollutants ) { HbefaColdEmissionFactorKey detColdKey = new HbefaColdEmissionFactorKey(); @@ -200,5 +200,5 @@ private static void putIntoHbefaColdTable( final Map * LookupBehavior: onlyTryDetailedElseAbort - * + *

        * -> should calculate value */ @Test @@ -86,7 +86,7 @@ void testColdDetailedValueOnlyDetailed() { EmissionModule emissionModule = setUpScenario( DetailedVsAverageLookupBehavior.onlyTryDetailedElseAbort ); Map coldEmissions = emissionModule.getColdEmissionAnalysisModule() - .checkVehicleInfoAndCalculateWColdEmissions(vehicleFull.getType(), vehicleFull.getId(), link.getId(), + .checkVehicleInfoAndCalculateWColdEmissions(vehicleFull.getType(), vehicleFull.getId(), link.getId(), startTime, parkingDuration, distance); Assertions.assertEquals(emissionsFactorInGrammPerKilometer_Detailed, coldEmissions.get(Pollutant.CO2_TOTAL ), MatsimTestUtils.EPSILON ); @@ -97,7 +97,7 @@ void testColdDetailedValueOnlyDetailed() { * * vehicles information is complete but fully specified entry is NOT available in detailed table * LookupBehavior: onlyTryDetailedElseAbort - * + *

        * -> should abort --> RuntimeException */ @Test @@ -114,9 +114,9 @@ void testCold_DetailedElseAbort_ShouldAbort1() { /** * vehicles information is complete but fully specified entry is NOT available in detailed table * HbefaTechnology is also not in detailed table -> fall back to technology average is NOT possible as well. - * + *

        * LookupBehavior: onlyTryDetailedElseAbort - * + *

        * -> should abort --> RuntimeException */ @Test @@ -135,7 +135,7 @@ void testCold_DetailedElseAbort_ShouldAbort2() { /** * vehicles information is complete * LookupBehavior: tryDetailedThenTechnologyAverageElseAbort - * + *

        * -> do NOT fall back to technology average * ---> should calculate value from detailed value */ @@ -144,7 +144,7 @@ void testCold_DetailedThenTechnologyAverageElseAbort_FallbackNotNeeded() { EmissionModule emissionModule = setUpScenario( DetailedVsAverageLookupBehavior.tryDetailedThenTechnologyAverageElseAbort ); Map coldEmissions = emissionModule.getColdEmissionAnalysisModule() - .checkVehicleInfoAndCalculateWColdEmissions(vehicleFull.getType(), vehicleFull.getId(), link.getId(), + .checkVehicleInfoAndCalculateWColdEmissions(vehicleFull.getType(), vehicleFull.getId(), link.getId(), startTime, parkingDuration, distance); Assertions.assertEquals(emissionsFactorInGrammPerKilometer_Detailed, coldEmissions.get(Pollutant.CO2_TOTAL ), MatsimTestUtils.EPSILON ); @@ -154,7 +154,7 @@ void testCold_DetailedThenTechnologyAverageElseAbort_FallbackNotNeeded() { /** * vehicles information is complete but fully specified entry is NOT available in detailed table * LookupBehavior: tryDetailedThenTechnologyAverageElseAbort - * + *

        * -> do fall back to technology average * ---> should calculate value from technology average */ @@ -173,9 +173,9 @@ void testCold_DetailedThenTechnologyAverageElseAbort_FallbackToTechnologyAverage /** * vehicles information is complete but fully specified entry is NOT available in detailed table * HbefaTechnology is also not in detailed table -> fall back to technology average is NOT possible as well. - * + *

        * LookupBehavior: onlyTryDetailedElseAbort - * + *

        * -> should abort --> RuntimeException */ @Test @@ -193,7 +193,7 @@ void testCold_DetailedThenTechnologyAverageElseAbort_ShouldAbort() { /** * vehicles information is complete * LookupBehavior: tryDetailedThenTechnologyAverageElseAbort - * + *

        * -> do NOT fall back to technology average or average table * ---> should calculate value from detailed value */ @@ -212,7 +212,7 @@ void testCold_DetailedThenTechnologyAverageThenAverageTable_FallbackNotNeeded() /** * vehicles information is complete but fully specified entry is NOT available in detailed table * LookupBehavior: tryDetailedThenTechnologyAverageElseAbort - * + *

        * -> do fall back to technology average; do NOT fall back to average table * ---> should calculate value from technology average */ @@ -230,9 +230,9 @@ void testCold_DetailedThenTechnologyAverageThenAverageTable_FallbackToTechnology /** * vehicles information is complete but fully specified entry is NOT available in detailed table * HbefaTechnology is also not in detailed table -> fall back to technology average is NOT possible as well. - * + *

        * LookupBehavior: tryDetailedThenTechnologyAverageThenAverageTable - * + *

        * -> do fall back to average table * ---> should calculate value from average table */ diff --git a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestHbefaColdEmissionFactorKey.java b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestHbefaColdEmissionFactorKey.java index 13efc7bf890..810c11e8d2c 100644 --- a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestHbefaColdEmissionFactorKey.java +++ b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestHbefaColdEmissionFactorKey.java @@ -43,7 +43,6 @@ public class TestHbefaColdEmissionFactorKey { private Pollutant coldPollutant; private HbefaVehicleAttributes hbefaVehicleAttributes; private HbefaVehicleCategory hbefaVehCategory; - private boolean equalErr; private HbefaColdEmissionFactorKey normal; private void setUp(){ @@ -56,7 +55,6 @@ private void setUp(){ parkingTime = 5; coldPollutant = FC; hbefaVehCategory = HbefaVehicleCategory.PASSENGER_CAR; - equalErr = false; } @@ -82,7 +80,7 @@ final void testEqualsForCompleteKeys() { compare.setVehicleAttributes(attForCompare); compare.setVehicleCategory(hbefaVehCategory); - String message = "these two objects should be the same but are not: " + normal.toString() + " and " + compare.toString(); + String message = "these two objects should be the same but are not: " + normal + " and " + compare; Assertions.assertEquals(normal, compare, message); Assertions.assertEquals(compare, normal, message); } @@ -100,13 +98,13 @@ final void testEqualsForCompleteKeys() { different.setVehicleAttributes(attForDifferent); different.setVehicleCategory(HbefaVehicleCategory.HEAVY_GOODS_VEHICLE); - String message = "these two objects should not be the same: " + normal.toString() + " and " + different.toString(); + String message = "these two objects should not be the same: " + normal + " and " + different; assertNotEquals(normal, different, message); assertNotEquals(different, normal, message); } } - // the following tests each compare a incomplete key to a complete key + // the following tests each compare an incomplete key to a complete key // wanted result: // completeData.equals(partialData) -> return false // uncompleteData.equals(completeData) -> throw nullpointer @@ -127,8 +125,8 @@ final void testEqualsForIncompleteKeys_vehicleCategory(){ noVehCat.setParkingTime(parkingTime); noVehCat.setVehicleAttributes(hbefaVehicleAttributes); - String message = "these two HbefaColdEmissionFactorKeys should not be the same: " + normal.toString() + " and " + noVehCat.toString(); - assertFalse(noVehCat.equals(normal), message); + String message = "these two HbefaColdEmissionFactorKeys should not be the same: " + normal + " and " + noVehCat; + assertNotEquals(noVehCat, normal, message); } @Test @@ -146,8 +144,8 @@ final void testEqualsForIncompleteKeys_pollutant(){ noColdPollutant.setVehicleCategory(hbefaVehCategory); noColdPollutant.setVehicleAttributes(hbefaVehicleAttributes); - String message = "these two HbefaColdEmissionFactorKeys should not be the same: " + normal.toString() + " and " + noColdPollutant.toString(); - assertFalse(noColdPollutant.equals(normal), message); + String message = "these two HbefaColdEmissionFactorKeys should not be the same: " + normal.toString() + " and " + noColdPollutant; + assertNotEquals(noColdPollutant, normal, message); } @Test @@ -165,8 +163,8 @@ final void testEqualsForIncompleteKeys_parkingTime() { noParkingTime.setVehicleCategory(hbefaVehCategory); noParkingTime.setVehicleAttributes(hbefaVehicleAttributes); - String message = "these two HbefaColdEmissionFactorKeys should not be the same: " + normal.toString() + " and " + noParkingTime.toString(); - assertFalse(noParkingTime.equals(normal), message); + String message = "these two HbefaColdEmissionFactorKeys should not be the same: " + normal.toString() + " and " + noParkingTime; + assertNotEquals(noParkingTime, normal, message); } @Test @@ -184,8 +182,8 @@ final void testEqualsForIncompleteKeys_distance() { noDistance.setVehicleCategory(hbefaVehCategory); noDistance.setVehicleAttributes(hbefaVehicleAttributes); - String message = "these two HbefaColdEmissionFactorKeys should not be the same: " + normal.toString() + " and " + noDistance.toString(); - assertFalse(noDistance.equals(normal), message); + String message = "these two HbefaColdEmissionFactorKeys should not be the same: " + normal.toString() + " and " + noDistance; + assertNotEquals(noDistance, normal, message); } @Test @@ -199,8 +197,8 @@ final void testEqualsForIncompleteKeys_emptyKey() { //empty HbefaColdEmissionFactorKey HbefaColdEmissionFactorKey emptyKey = new HbefaColdEmissionFactorKey(); - String message = "these two HbefaColdEmissionFactorKeys should not be the same: " + normal.toString() + " and " + emptyKey.toString(); - assertFalse(emptyKey.equals(normal), message); + String message = "these two HbefaColdEmissionFactorKeys should not be the same: " + normal.toString() + " and " + emptyKey; + assertNotEquals(emptyKey, normal, message); } @Test @@ -226,8 +224,8 @@ final void testEqualsForIncompleteKeys_VehicleAttributes(){ noVehAtt.setParkingTime(parkingTime); noVehAtt.setVehicleCategory(hbefaVehCategory); - String message = "these two HbefaColdEmissionFactorKeys should not be the same: " + normal.toString() + " and " + noVehAtt.toString(); - assertFalse(noVehAtt.equals(normal), message); + String message = "these two HbefaColdEmissionFactorKeys should not be the same: " + normal + " and " + noVehAtt; + assertNotEquals(noVehAtt, normal, message); //set the vehicle attributes of the normal hbefaColdWmissionFactorKey to 'average' @@ -239,7 +237,7 @@ final void testEqualsForIncompleteKeys_VehicleAttributes(){ hbefaVehicleAttributesAverage.setHbefaTechnology("average"); normal.setVehicleAttributes(hbefaVehicleAttributesAverage); - Assertions.assertTrue(noVehAtt.equals(normal), message); + assertEquals(noVehAtt, normal, message); } } diff --git a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestHbefaVehicleAttributes.java b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestHbefaVehicleAttributes.java index bb8743783d9..4cf37da4feb 100644 --- a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestHbefaVehicleAttributes.java +++ b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestHbefaVehicleAttributes.java @@ -53,7 +53,7 @@ final void testEqualsForCompleteAttributes(){ compare.setHbefaEmConcept(concept); String assertErrorMessage = "These hbefa vehicle attribute objects should have been the same: "; - assertErrorMessage += normal.toString() + " and " + compare.toString(); + assertErrorMessage += normal.toString() + " and " + compare; Assertions.assertEquals(normal, compare, assertErrorMessage); Assertions.assertEquals(compare, normal, assertErrorMessage); @@ -73,7 +73,7 @@ final void testEqualsForCompleteAttributes_emConcept(){ differentValues.setHbefaSizeClass(sizeClass); differentValues.setHbefaTechnology(technology); assertErrorMessage = "These hbefa vehicle attribute objects should not have been the same: "; - assertErrorMessage += normal.toString() + " and " + differentValues.toString(); + assertErrorMessage += normal.toString() + " and " + differentValues; Assertions.assertNotEquals(normal, differentValues, assertErrorMessage); Assertions.assertNotEquals(differentValues, normal, assertErrorMessage); } @@ -91,7 +91,7 @@ final void testEqualsForCompleteAttributes_sizeClass(){ differentValues.setHbefaSizeClass("small size"); differentValues.setHbefaTechnology(technology); assertErrorMessage = "These hbefa vehicle attribute objects should not have been the same: "; - assertErrorMessage += normal.toString() + " and " + differentValues.toString(); + assertErrorMessage += normal.toString() + " and " + differentValues; Assertions.assertNotEquals(normal, differentValues, assertErrorMessage); Assertions.assertNotEquals(differentValues, normal, assertErrorMessage); @@ -110,7 +110,7 @@ final void testEqualsForCompleteAttributes_technologies(){ differentValues.setHbefaSizeClass(sizeClass); differentValues.setHbefaTechnology("other technology"); assertErrorMessage = "These hbefa vehicle attribute objects should not have been the same: "; - assertErrorMessage += normal.toString() + " and " + differentValues.toString(); + assertErrorMessage += normal.toString() + " and " + differentValues; Assertions.assertNotEquals(normal, differentValues, assertErrorMessage); Assertions.assertNotEquals(differentValues, normal, assertErrorMessage); @@ -195,7 +195,7 @@ private void setToNormal(HbefaVehicleAttributes normal) { } } - - + + diff --git a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestHbefaWarmEmissionFactorKey.java b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestHbefaWarmEmissionFactorKey.java index 2ff96fb02bd..df5cf8fd2d7 100644 --- a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestHbefaWarmEmissionFactorKey.java +++ b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestHbefaWarmEmissionFactorKey.java @@ -26,6 +26,7 @@ import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.matsim.contrib.emissions.Pollutant.CO; import static org.matsim.contrib.emissions.Pollutant.FC; @@ -37,10 +38,10 @@ public class TestHbefaWarmEmissionFactorKey{ * test for playground.vsp.emissions.types.HbefaWarmEmissionFactorKey * 1 test equals method for complete input: two equal hbefaWarmEmissionFactorKey objects, two unequal objects * 2 test equals method for incomplete input: one complete hbefaWarmEmissionFactorKey against one with a missing argument - * + * * @author julia */ - + private HbefaVehicleAttributes hbefaVehicleAttributes; private String hbefaRoadCategory; private HbefaTrafficSituation hbefaTrafficSituation; @@ -56,22 +57,22 @@ private void setUp(){ hbefaVehicleAttributes.setHbefaEmConcept("concept"); hbefaVehicleAttributes.setHbefaSizeClass("size class"); hbefaVehicleAttributes.setHbefaTechnology("technology"); - hbefaRoadCategory = "road type"; + hbefaRoadCategory = "road type"; hbefaTrafficSituation = HbefaTrafficSituation.FREEFLOW; hbefaVehicleCategory = HbefaVehicleCategory.PASSENGER_CAR; warmPollutant = FC; - + } @Test final void testEqualsForCompleteKeys(){ - // generate a complete HbefaWarmEmissionFactorKey: 'normal' + // generate a complete HbefaWarmEmissionFactorKey: 'normal' // and set some parameters setUp(); setToNormal(normal); - // generate a warm emission factor key equal to 'normal' + // generate a warm emission factor key equal to 'normal' HbefaWarmEmissionFactorKey compare = new HbefaWarmEmissionFactorKey(); compare.setComponent(FC); compare.setRoadCategory(hbefaRoadCategory); @@ -79,9 +80,9 @@ final void testEqualsForCompleteKeys(){ compare.setVehicleAttributes(hbefaVehicleAttributes); compare.setVehicleCategory(hbefaVehicleCategory); - String message = "these two objects should be the same but are not: " + normal.toString() + " and " + compare.toString(); - Assertions.assertTrue(normal.equals(compare), message); - Assertions.assertTrue(compare.equals(normal), message); + String message = "these two objects should be the same but are not: " + normal.toString() + " and " + compare; + Assertions.assertEquals(normal, compare, message); + Assertions.assertEquals(compare, normal, message); //two unequal but complete objects HbefaWarmEmissionFactorKey different = new HbefaWarmEmissionFactorKey(); @@ -95,18 +96,18 @@ final void testEqualsForCompleteKeys(){ different.setVehicleAttributes(attrForDifferent); different.setVehicleCategory(HbefaVehicleCategory.HEAVY_GOODS_VEHICLE); - message = "these two objects should not be the same: " + normal.toString() + " and " + different.toString(); + message = "these two objects should not be the same: " + normal.toString() + " and " + different; - assertFalse(different.equals(normal), message); - assertFalse(normal.equals(different), message); + assertNotEquals(different, normal, message); + assertNotEquals(normal, different, message); } - // the following tests each compare a incomplete key to a complete key + // the following tests each compare an incomplete key to a complete key // wanted result: // completeData.equals(partialData) -> return false // uncompleteData.equals(completeData) -> throw nullpointer // exception: if the vehicleAttributes are set to 'average' by default - + @Test final void testEqualsForIncompleteKeys_vehicleCategory() { // generate a complete HbefaWarmEmissionFactorKey: 'normal' @@ -121,8 +122,8 @@ final void testEqualsForIncompleteKeys_vehicleCategory() { noVehCat.setTrafficSituation(hbefaTrafficSituation); noVehCat.setVehicleAttributes(hbefaVehicleAttributes); - log.warn("normal=" + normal); - log.warn("noVehCat=" + noVehCat); + log.warn("normal={}", normal); + log.warn("noVehCat={}", noVehCat); var result = noVehCat.equals(normal); @@ -167,10 +168,10 @@ final void testEqualsForIncompleteKeys_roadCategory() { equalErr = true; } - String message = "these two HbefaWarmEmissionFactorKeys should not be the same: " + normal.toString() + " and " + noRoadCat.toString(); + String message = "these two HbefaWarmEmissionFactorKeys should not be the same: " + normal.toString() + " and " + noRoadCat; String message2 = "this key should not be comparable since no road category is set"; Assertions.assertTrue(equalErr, message2); - assertFalse(normal.equals(noRoadCat), message); + assertNotEquals(normal, noRoadCat, message); } @Test @@ -213,7 +214,7 @@ final void testEqualsForIncompleteKeys_vehicleAttributes(){ // if no vehicle attributes are set manually they are set to 'average' by default // thus, the equals method should not throw nullpointer exceptions but return false or respectively true - // generate a complete HbefaWarmEmissionFactorKey: 'normal' + // generate a complete HbefaWarmEmissionFactorKey: 'normal' // and set some parameters setUp(); setToNormal(normal); @@ -232,12 +233,12 @@ final void testEqualsForIncompleteKeys_vehicleAttributes(){ equalErr = true; } - String message = "these two HbefaWarmEmissionFactorKeys should not be the same: " + normal.toString() + " and " + noVehAtt.toString(); - assertFalse(noVehAtt.equals(normal), message); + String message = "these two HbefaWarmEmissionFactorKeys should not be the same: " + normal.toString() + " and " + noVehAtt; + assertNotEquals(noVehAtt, normal, message); assertFalse(equalErr); // veh attributes are allowed to be not initiated // therefore this should not throw a nullpointer but return false - assertFalse(normal.equals(noVehAtt), message); + assertNotEquals(normal, noVehAtt, message); //set the vehicle attributes of the normal hbefacoldemissionfactorkey to 'average' //then noVehAtt is equal to normal @@ -247,13 +248,13 @@ final void testEqualsForIncompleteKeys_vehicleAttributes(){ hbefaVehicleAttributesAverage.setHbefaTechnology("average"); normal.setVehicleAttributes(hbefaVehicleAttributesAverage); - message = "these two HbefaWarmEmissionFactorKeys should be the same: " + normal.toString() + " and " + noVehAtt.toString(); - Assertions.assertTrue(normal.equals(noVehAtt), message); - Assertions.assertTrue(noVehAtt.equals(normal), message); + message = "these two HbefaWarmEmissionFactorKeys should be the same: " + normal.toString() + " and " + noVehAtt; + Assertions.assertEquals(normal, noVehAtt, message); + Assertions.assertEquals(noVehAtt, normal, message); } - + private void setToNormal(HbefaWarmEmissionFactorKey normal) { normal.setComponent(warmPollutant); normal.setRoadCategory(hbefaRoadCategory); @@ -261,10 +262,10 @@ private void setToNormal(HbefaWarmEmissionFactorKey normal) { normal.setVehicleAttributes(hbefaVehicleAttributes); normal.setVehicleCategory(hbefaVehicleCategory); } - - + + } - - + + diff --git a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestWarmEmissionAnalysisModule.java b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestWarmEmissionAnalysisModule.java index 30b456f1455..05ac81e5bce 100644 --- a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestWarmEmissionAnalysisModule.java +++ b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestWarmEmissionAnalysisModule.java @@ -20,10 +20,8 @@ package org.matsim.contrib.emissions; -import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import org.matsim.api.core.v01.Id; import org.matsim.api.core.v01.network.Link; @@ -49,7 +47,7 @@ /* * test for playground.vsp.emissions.WarmEmissionAnalysisModule - * + *

        * WarmEmissionAnalysisModule (weam) * public methods and corresponding tests: * weamParameter - testWarmEmissionAnalysisParameter @@ -57,17 +55,17 @@ * check vehicle info and calculate warm emissions -testCheckVehicleInfoAndCalculateWarmEmissions_and_throwWarmEmissionEvent*, testCheckVehicleInfoAndCalculateWarmEmissions_and_throwWarmEmissionEvent_Exceptions * get free flow occurences - testCounters*() * get fraction occurences - testCounters*() - * get stop go occurences - testCounters*() + * get stop-go occurences - testCounters*() * get km counter - testCounters*() * get free flow km counter - testCounters*() * get top go km couter - testCounters*() * get warm emission event counter - testCounters*() - * + *

        * private methods and corresponding tests: * rescale warm emissions - rescaleWarmEmissionsTest() * calculate warm emissions - implicitly tested * convert string 2 tuple - implicitly tested - * + *

        * in all cases the needed tables are created manually by the setUp() method * see test methods for details on the particular test cases **/ @@ -104,8 +102,8 @@ public class TestWarmEmissionAnalysisModule { private final Double noeFreeSpeed = AVG_PASSENGER_CAR_SPEED_FF_KMH; - // case 6 - data in detailed table, stop go speed = free flow speed - private final String sgffRoadCatgory = "URB_case7"; + // case 6 - data in detailed table, stop-go speed = free flow speed + private final String sgffRoadCategory = "URB_case7"; private final String sgffTechnology = "sg ff technology"; private final String sgffConcept = "sg ff concept"; private final String sgffSizeClass = "sg ff size class"; @@ -126,7 +124,7 @@ void testCheckVehicleInfoAndCalculateWarmEmissions_and_throwWarmEmissionEvent6(E Id sgffVehicleId = Id.create("vehicle sg equals ff", Vehicle.class); double sgffLinklength = 4000.; Link sgflink = createMockLink("link sgf", sgffLinklength, AVG_PASSENGER_CAR_SPEED_FF_KMH / 3.6); - EmissionUtils.setHbefaRoadType(sgflink, sgffRoadCatgory); + EmissionUtils.setHbefaRoadType(sgflink, sgffRoadCategory); Id sgffVehicleTypeId = Id.create( PASSENGER_CAR + ";" + sgffTechnology + ";"+ sgffSizeClass + ";"+sgffConcept, VehicleType.class ); VehiclesFactory vehFac = VehicleUtils.getFactory(); @@ -184,8 +182,6 @@ void testCheckVehicleInfoAndCalculateWarmEmissions_and_throwWarmEmissionEvent_Ex excep = true; } Assertions.assertFalse(excep); - - excep=false; } @ParameterizedTest @@ -211,7 +207,7 @@ void testCheckVehicleInfoAndCalculateWarmEmissions_and_throwWarmEmissionEvent_Ex }catch(Exception e){ excep = true; } - Assertions.assertTrue(excep); excep=false; + Assertions.assertTrue(excep); } @ParameterizedTest @@ -236,7 +232,7 @@ void testCheckVehicleInfoAndCalculateWarmEmissions_and_throwWarmEmissionEvent_Ex }catch(Exception e){ excep = true; } - Assertions.assertTrue(excep); excep=false; + Assertions.assertTrue(excep); } @ParameterizedTest @@ -259,7 +255,7 @@ void testCheckVehicleInfoAndCalculateWarmEmissions_and_throwWarmEmissionEvent_Ex }catch(Exception e){ excep = true; } - Assertions.assertTrue(excep); excep=false; + Assertions.assertTrue(excep); } @@ -269,7 +265,7 @@ void testCounters7(EmissionsConfigGroup.EmissionsComputationMethod emissionsComp setUp(emissionsComputationMethod); emissionsModule.reset(); - // case 10 - data in detailed table, stop go speed > free flow speed + // case 10 - data in detailed table, stop-go speed > free flow speed Id tableVehicleId = Id.create("vehicle 8", Vehicle.class); double tableLinkLength= 30.*1000; Id tableVehicleTypeId = Id.create( @@ -348,7 +344,7 @@ private void fillDetailedTable( Map avgHbefaWarmTable ) { // entries for first case "petrol" should not be used since there are entries in the detailed table - // there should only average vehicle attributes in the avgHebfWarmTable jm oct'18 + // there should only average vehicle attributes in the avgHbefaWarmTable jm oct'18 HbefaVehicleAttributes vehAtt = new HbefaVehicleAttributes(); diff --git a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestWarmEmissionAnalysisModuleCase1.java b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestWarmEmissionAnalysisModuleCase1.java index 2bc080b1bc3..2a0382250ae 100644 --- a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestWarmEmissionAnalysisModuleCase1.java +++ b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestWarmEmissionAnalysisModuleCase1.java @@ -21,11 +21,8 @@ package org.matsim.contrib.emissions; import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.EnumSource; -import org.junit.jupiter.params.provider.MethodSource; import org.matsim.api.core.v01.Id; import org.matsim.api.core.v01.network.Link; import org.matsim.contrib.emissions.utils.EmissionsConfigGroup; @@ -38,7 +35,6 @@ import org.matsim.vehicles.VehiclesFactory; import java.util.*; -import java.util.stream.Stream; import static org.matsim.contrib.emissions.Pollutant.CO2_TOTAL; import static org.matsim.contrib.emissions.TestWarmEmissionAnalysisModule.HBEFA_ROAD_CATEGORY; @@ -63,12 +59,12 @@ * weamParameter - testWarmEmissionAnalysisParameter * throw warm EmissionEvent - testCheckVehicleInfoAndCalculateWarmEmissions_and_throwWarmEmissionEvent*, testCheckVehicleInfoAndCalculateWarmEmissions_and_throwWarmEmissionEvent_Exceptions * check vehicle info and calculate warm emissions -testCheckVehicleInfoAndCalculateWarmEmissions_and_throwWarmEmissionEvent*, testCheckVehicleInfoAndCalculateWarmEmissions_and_throwWarmEmissionEvent_Exceptions - * get free flow occurences - testCounters*() - * get fraction occurences - testCounters*() - * get stop go occurences - testCounters*() + * get free flow occurrences - testCounters*() + * get fraction occurrences - testCounters*() + * get stop-go occurrences - testCounters*() * get km counter - testCounters*() * get free flow km counter - testCounters*() - * get top go km couter - testCounters*() + * get top go km counter - testCounters*() * get warm emission event counter - testCounters*() * * private methods and corresponding tests: @@ -153,7 +149,7 @@ void testCheckVehicleInfoAndCalculateWarmEmissions_and_throwWarmEmissionEvent1(E /* * this test method creates a mock link and mock vehicle (petrol technology) with a complete vehicleTypId --> detailed values are used - * the counters for all possible combinations of avg, stop go and free flow speed are tested + * the counters for all possible combinations of avg, stop-go and free flow speed are tested * for the cases: > s&g speed, vehicleId = Id.create("vehicle 1", Vehicle.class); @@ -245,9 +241,9 @@ void testCounters1(EmissionsConfigGroup.EmissionsComputationMethod emissionsComp /* - * this test method creates a incoff mock link and incoff mock vehicle (petrol technology) with a complete vehicleTypId --> detailed values are used - * for the computationMethod "Stop and Go" and "averageSpeed" the free flow occurences are tested - * the counters (StopGoOccurences, KmCounter, WarmEmissionEventCounter) are tested + * this test method creates an incoff mock link and incoff mock vehicle (petrol technology) with a complete vehicleTypId --> detailed values are used + * for the computationMethod "Stop and Go" and "averageSpeed" the free flow occurrences are tested + * the counters (StopGoOccurrences, KmCounter, WarmEmissionEventCounter) are tested * for the case average speed equals wrong free flow speed the counters are tested */ @@ -309,7 +305,7 @@ void testCounters1fractional(EmissionsConfigGroup.EmissionsComputationMethod emi // yyyyyy !!!!!! /* - * using the same case as above - case 1 and check the counters for all possible combinations of avg, stop go and free flow speed + * using the same case as above - case 1 and check the counters for all possible combinations of avg, stop-go and free flow speed */ Id vehicleId = Id.create("vehicle 1", Vehicle.class); @@ -380,7 +376,7 @@ void testCounters1fractional(EmissionsConfigGroup.EmissionsComputationMethod emi emissionsModule.reset(); emissionsModule.getEcg().setEmissionsComputationMethod(AverageSpeed ); - //@KMT it seems to me that copying the counters from above and chaning the expected values?? + //@KMT it seems to me that copying the counters from above and changing the expected values?? // yyyyyy !!!!!! } diff --git a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestWarmEmissionAnalysisModuleCase2.java b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestWarmEmissionAnalysisModuleCase2.java index 8fb143e1821..bb7beab4140 100644 --- a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestWarmEmissionAnalysisModuleCase2.java +++ b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestWarmEmissionAnalysisModuleCase2.java @@ -21,10 +21,8 @@ package org.matsim.contrib.emissions; import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.EnumSource; -import org.junit.jupiter.params.provider.MethodSource; import org.matsim.api.core.v01.Id; import org.matsim.api.core.v01.network.Link; import org.matsim.contrib.emissions.utils.EmissionsConfigGroup; @@ -37,7 +35,6 @@ import org.matsim.vehicles.VehiclesFactory; import java.util.*; -import java.util.stream.Stream; import static org.matsim.contrib.emissions.Pollutant.NMHC; import static org.matsim.contrib.emissions.TestWarmEmissionAnalysisModule.fillAverageTable; @@ -47,7 +44,7 @@ * / /* - * Case 2 - free flow entry in both tables, stop go entry in average table -> use average + * Case 2 - free flow entry in both tables, stop-go entry in average table -> use average * see (*) below. kai, jan'20 */ @@ -59,12 +56,12 @@ * weamParameter - testWarmEmissionAnalysisParameter * throw warm EmissionEvent - testCheckVehicleInfoAndCalculateWarmEmissions_and_throwWarmEmissionEvent*, testCheckVehicleInfoAndCalculateWarmEmissions_and_throwWarmEmissionEvent_Exceptions * check vehicle info and calculate warm emissions -testCheckVehicleInfoAndCalculateWarmEmissions_and_throwWarmEmissionEvent*, testCheckVehicleInfoAndCalculateWarmEmissions_and_throwWarmEmissionEvent_Exceptions - * get free flow occurences - testCounters*() - * get fraction occurences - testCounters*() - * get stop go occurences - testCounters*() + * get free flow occurrences - testCounters*() + * get fraction occurrences - testCounters*() + * get stop-go occurrences - testCounters*() * get km counter - testCounters*() * get free flow km counter - testCounters*() - * get top go km couter - testCounters*() + * get top go km counter - testCounters*() * get warm emission event counter - testCounters*() * * private methods and corresponding tests: @@ -98,7 +95,7 @@ public class TestWarmEmissionAnalysisModuleCase2{ // vehicle information for regular test cases - // case 2 - free flow entry in both tables, stop go entry in average table -> use average (now fail) + // case 2 - free flow entry in both tables, stop-go entry in average table -> use average (now fail) private static final String PC_TECHNOLOGY = "PC petrol <1,4L lookUpBehaviour: tryDetailedThenTechnologyAverageThenAverageTable - * for two speed cases: avg speed = free flow speed & avg speed = stop go speed the NMHC warm emissions and emissions sum are computed using the two emissionsComputationMethods StopAndGoFraction & AverageSpeed + * for two speed cases: avg speed = free flow speed & avg speed = stop-go speed the NMHC warm emissions and emissions sum are computed using the two emissionsComputationMethods StopAndGoFraction & AverageSpeed */ @ParameterizedTest @@ -118,7 +115,7 @@ void testCheckVehicleInfoAndCalculateWarmEmissions_and_throwWarmEmissionEvent2(E WarmEmissionAnalysisModule emissionsModule = setUp(emissionsComputationMethod); - // case 2 - free flow entry in both tables, stop go entry in average table -> use average + // case 2 - free flow entry in both tables, stop-go entry in average table -> use average // see (*) below. kai, jan'20 // create a link: @@ -131,7 +128,7 @@ void testCheckVehicleInfoAndCalculateWarmEmissions_and_throwWarmEmissionEvent2(E VehiclesFactory vehFac = VehicleUtils.getFactory(); Vehicle pcVehicle = vehFac.createVehicle(pcVehicleId, vehFac.createVehicleType(pcVehicleTypeId)); - // sub case avg speed = free flow speed + // subcase avg speed = free flow speed { // compute warm emissions with travel time coming from free flow: warmEmissions = emissionsModule.checkVehicleInfoAndCalculateWarmEmissions( pcVehicle, pclink, pclinkLength / PC_FREE_VELOCITY_KMH * 3.6 ); @@ -140,8 +137,8 @@ void testCheckVehicleInfoAndCalculateWarmEmissions_and_throwWarmEmissionEvent2(E // - DETAILED FreeFlow value is available in the table (1.0E-4 g/km); StopAndGo value is NOT available in the table // - AVERAGE FreeFlow value is available in the table (1.0 g/km) ; StopAndGo value is NOT available in the table ( 10.0 g/km) // --> It seems like it was intended (or only implemented) in a way, that if one of the detailed values is missing (FreeFlow or StopGo) there is a fallback to average. So the result of this would be 1.0 g/km * 0.1 km = 0.1 g/km - // --> Now, after implementing the new fallback behaviour, it is looking up both values (FreeFlow or StopGo) ways independently from each other. Therefore the result comes from the detailed table (1.0E-4 g/km) * * 0.1 km = 1.0E-5 g/km - // -----> We need a decision here, if we want allow that inconsistent(?) lookup of FreeFlow and Detailed values with different grade of detail or not. + // --> Now, after implementing the new fallback behaviour, it is looking up both values (FreeFlow or StopGo) ways independently of each other. Therefore, the result comes from the detailed table (1.0E-4 g/km) * * 0.1 km = 1.0E-5 g/km + // -----> We need a decision here, if we want to allow that inconsistent(?) lookup of FreeFlow and Detailed values with different grade of detail or not. // After discussion with Kai N. we decided to let it as it is for the time being. I will add a log.info in the consistency checker. KMT Jul'20 //results should be equal here, because in both cases only the freeflow value is relevant (100% freeflow, 0% stop&go). @@ -155,7 +152,7 @@ void testCheckVehicleInfoAndCalculateWarmEmissions_and_throwWarmEmissionEvent2(E warmEmissions.clear(); } - // sub case avg speed = stop go speed + // subcase avg speed = stop-go speed { warmEmissions = emissionsModule.checkVehicleInfoAndCalculateWarmEmissions( pcVehicle, pclink, pclinkLength / PCSG_VELOCITY_KMH * 3.6 ); Assertions.assertEquals( AVG_PC_FACTOR_SG * pclinkLength / 1000., warmEmissions.get( NMHC ), MatsimTestUtils.EPSILON ); @@ -169,7 +166,7 @@ void testCheckVehicleInfoAndCalculateWarmEmissions_and_throwWarmEmissionEvent2(E /* * this test method creates a vehicle and mock link - * for three cases: "current speed equals free flow speed" & "current speed equals stop go speed" & "current speed equals stop go speed" the counters are tested + * for three cases: "current speed equals free flow speed" & "current speed equals stop-go speed" & "current speed equals stop-go speed" the counters are tested * average values are used */ @ParameterizedTest @@ -178,7 +175,7 @@ void testCounters3(EmissionsConfigGroup.EmissionsComputationMethod emissionsComp WarmEmissionAnalysisModule emissionsModule = setUp(emissionsComputationMethod); - // case 2 - free flow entry in both tables, stop go entry in average table -> use average + // case 2 - free flow entry in both tables, stop-go entry in average table -> use average Id pcVehicleId = Id.create("vehicle 2", Vehicle.class); double pclinkLength= 20.*1000; Id pcVehicleTypeId = Id.create( PASSENGER_CAR + ";"+ PC_TECHNOLOGY + ";"+ PC_SIZE_CLASS +";"+ PC_CONCEPT, VehicleType.class ); @@ -186,7 +183,7 @@ void testCounters3(EmissionsConfigGroup.EmissionsComputationMethod emissionsComp Vehicle pcVehicle = vehFac.createVehicle(pcVehicleId, vehFac.createVehicleType(pcVehicleTypeId)); Link pclink = TestWarmEmissionAnalysisModule.createMockLink("link 2", pclinkLength, PC_FREE_VELOCITY_KMH / 3.6 ); - // sub case: current speed equals free flow speed + // subcase: current speed equals free flow speed warmEmissions = emissionsModule.checkVehicleInfoAndCalculateWarmEmissions(pcVehicle,pclink, pclinkLength/ PC_FREE_VELOCITY_KMH *3.6 ); Assertions.assertEquals(0, emissionsModule.getFractionOccurences() ); Assertions.assertEquals(pclinkLength/1000, emissionsModule.getFreeFlowKmCounter(), MatsimTestUtils.EPSILON ); @@ -197,7 +194,7 @@ void testCounters3(EmissionsConfigGroup.EmissionsComputationMethod emissionsComp Assertions.assertEquals(1, emissionsModule.getWarmEmissionEventCounter() ); emissionsModule.reset(); - // sub case: current speed equals stop go speed + // subcase: current speed equals stop-go speed warmEmissions = emissionsModule.checkVehicleInfoAndCalculateWarmEmissions(pcVehicle, pclink, pclinkLength/ PCSG_VELOCITY_KMH *3.6 ); Assertions.assertEquals(0, emissionsModule.getFractionOccurences() ); Assertions.assertEquals(0., emissionsModule.getFreeFlowKmCounter(), MatsimTestUtils.EPSILON ); diff --git a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestWarmEmissionAnalysisModuleCase3.java b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestWarmEmissionAnalysisModuleCase3.java index b9df5a7e9bf..c0741ed1ced 100644 --- a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestWarmEmissionAnalysisModuleCase3.java +++ b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestWarmEmissionAnalysisModuleCase3.java @@ -22,9 +22,7 @@ import org.junit.jupiter.api.Assertions; import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.EnumSource; -import org.junit.jupiter.params.provider.MethodSource; import org.matsim.api.core.v01.Id; import org.matsim.api.core.v01.network.Link; import org.matsim.contrib.emissions.utils.EmissionsConfigGroup; @@ -37,7 +35,6 @@ import org.matsim.vehicles.VehiclesFactory; import java.util.*; -import java.util.stream.Stream; import static org.matsim.contrib.emissions.Pollutant.PM; @@ -57,9 +54,9 @@ * weamParameter - testWarmEmissionAnalysisParameter * throw warm EmissionEvent - testCheckVehicleInfoAndCalculateWarmEmissions_and_throwWarmEmissionEvent*, testCheckVehicleInfoAndCalculateWarmEmissions_and_throwWarmEmissionEvent_Exceptions * check vehicle info and calculate warm emissions -testCheckVehicleInfoAndCalculateWarmEmissions_and_throwWarmEmissionEvent*, testCheckVehicleInfoAndCalculateWarmEmissions_and_throwWarmEmissionEvent_Exceptions - * get free flow occurences - testCounters*() - * get fraction occurences - testCounters*() - * get stop go occurences - testCounters*() + * get free flow occurrences - testCounters*() + * get fraction occurrences - testCounters*() + * get stop-go occurrences - testCounters*() * get km counter - testCounters*() * get free flow km counter - testCounters*() * get top go km counter - testCounters*() @@ -94,14 +91,14 @@ public class TestWarmEmissionAnalysisModuleCase3{ private static final Double AVG_PC_FACTOR_FF = 1.; private static final Double AVG_PC_FACTOR_SG = 10.; - // case 3 - stop go entry in both tables, free flow entry in average table -> use average (now fail) + // case 3 - stop-go entry in both tables, free flow entry in average table -> use average (now fail) private final String dieselTechnology = "PC diesel"; private final String dieselSizeClass = "diesel"; private final String dieselConcept = ">=2L"; /* * this test method creates a diesel vehicle and mock link - * for two cases: "avg speed = free flow speed" & "avg speed = stop go speed" the average values are used to calculate the PM warm emissions + * for two cases: "avg speed = free flow speed" & "avg speed = stop-go speed" the average values are used to calculate the PM warm emissions */ @ParameterizedTest @EnumSource(EmissionsConfigGroup.EmissionsComputationMethod.class) @@ -110,7 +107,7 @@ void testCheckVehicleInfoAndCalculateWarmEmissions_and_throwWarmEmissionEvent3(E //-- set up tables, event handler, parameters, module WarmEmissionAnalysisModule emissionsModule = setUp(emissionsComputationMethod); - // case 3 - stop go entry in both tables, free flow entry in average table -> use average + // case 3 - stop-go entry in both tables, free flow entry in average table -> use average Id dieselVehicleId = Id.create("veh 3", Vehicle.class); double dieselLinkLength= 20.; Link diesellink = TestWarmEmissionAnalysisModule.createMockLink("link 3", dieselLinkLength, TestWarmEmissionAnalysisModule.AVG_PASSENGER_CAR_SPEED_FF_KMH / 3.6 ); @@ -120,7 +117,7 @@ void testCheckVehicleInfoAndCalculateWarmEmissions_and_throwWarmEmissionEvent3(E VehiclesFactory vehFac = VehicleUtils.getFactory(); Vehicle dieselVehicle = vehFac.createVehicle(dieselVehicleId, vehFac.createVehicleType(dieselVehicleTypeId)); - // sub case avg speed = free flow speed + // subcase avg speed = free flow speed warmEmissions = emissionsModule.checkVehicleInfoAndCalculateWarmEmissions(dieselVehicle, diesellink, dieselLinkLength/ TestWarmEmissionAnalysisModule.AVG_PASSENGER_CAR_SPEED_FF_KMH *3.6 ); Assertions.assertEquals( AVG_PC_FACTOR_FF *dieselLinkLength/1000., warmEmissions.get(PM ), MatsimTestUtils.EPSILON ); emissionEventManager.reset(); @@ -129,7 +126,7 @@ void testCheckVehicleInfoAndCalculateWarmEmissions_and_throwWarmEmissionEvent3(E emissionEventManager.reset(); warmEmissions.clear(); - // sub case avg speed = stop go speed + // subcase avg speed = stop-go speed warmEmissions = emissionsModule.checkVehicleInfoAndCalculateWarmEmissions(dieselVehicle, diesellink, dieselLinkLength/ TestWarmEmissionAnalysisModule.AVG_PASSENGER_CAR_SPEED_SG_KMH *3.6 ); Assertions.assertEquals( AVG_PC_FACTOR_SG *dieselLinkLength/1000., warmEmissions.get(PM ), MatsimTestUtils.EPSILON ); emissionEventManager.reset(); @@ -141,7 +138,7 @@ void testCheckVehicleInfoAndCalculateWarmEmissions_and_throwWarmEmissionEvent3(E /* * this test method creates a diesel vehicle and mock link - * for two cases: "current speed equals free flow speed" & "current speed equals stop go speed" the counters are tested + * for two cases: "current speed equals free flow speed" & "current speed equals stop-go speed" the counters are tested */ @ParameterizedTest @EnumSource(EmissionsConfigGroup.EmissionsComputationMethod.class) @@ -149,7 +146,7 @@ void testCounters4(EmissionsConfigGroup.EmissionsComputationMethod emissionsComp WarmEmissionAnalysisModule emissionsModule = setUp(emissionsComputationMethod); - // case 3 - stop go entry in both tables, free flow entry in average table -> use average + // case 3 - stop-go entry in both tables, free flow entry in average table -> use average Id dieselVehicleId = Id.create("vehicle 3", Vehicle.class); double dieselLinkLength= 200.*1000; Id dieselVehicleTypeId = Id.create( @@ -158,7 +155,7 @@ void testCounters4(EmissionsConfigGroup.EmissionsComputationMethod emissionsComp Vehicle dieselVehicle = vehFac.createVehicle(dieselVehicleId, vehFac.createVehicleType(dieselVehicleTypeId)); Link diesellink = TestWarmEmissionAnalysisModule.createMockLink("link 3", dieselLinkLength, TestWarmEmissionAnalysisModule.AVG_PASSENGER_CAR_SPEED_FF_KMH / 3.6 ); - // sub case: current speed equals free flow speed + // subcase: current speed equals free flow speed warmEmissions = emissionsModule.checkVehicleInfoAndCalculateWarmEmissions(dieselVehicle, diesellink, dieselLinkLength/ TestWarmEmissionAnalysisModule.AVG_PASSENGER_CAR_SPEED_FF_KMH *3.6 ); Assertions.assertEquals(0, emissionsModule.getFractionOccurences() ); Assertions.assertEquals(dieselLinkLength/1000., emissionsModule.getFreeFlowKmCounter(), MatsimTestUtils.EPSILON ); @@ -169,7 +166,7 @@ void testCounters4(EmissionsConfigGroup.EmissionsComputationMethod emissionsComp Assertions.assertEquals(1, emissionsModule.getWarmEmissionEventCounter() ); emissionsModule.reset(); - // sub case: current speed equals stop go speed + // subcase: current speed equals stop-go speed warmEmissions = emissionsModule.checkVehicleInfoAndCalculateWarmEmissions(dieselVehicle, diesellink, dieselLinkLength/ TestWarmEmissionAnalysisModule.AVG_PASSENGER_CAR_SPEED_SG_KMH *3.6 ); Assertions.assertEquals(0, emissionsModule.getFractionOccurences() ); Assertions.assertEquals(0., emissionsModule.getFreeFlowKmCounter(), MatsimTestUtils.EPSILON ); diff --git a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestWarmEmissionAnalysisModuleCase4.java b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestWarmEmissionAnalysisModuleCase4.java index 838573a0e35..7f085baf2fb 100644 --- a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestWarmEmissionAnalysisModuleCase4.java +++ b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestWarmEmissionAnalysisModuleCase4.java @@ -23,7 +23,6 @@ import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.EnumSource; import org.matsim.api.core.v01.Id; @@ -57,12 +56,12 @@ * weamParameter - testWarmEmissionAnalysisParameter * throw warm EmissionEvent - testCheckVehicleInfoAndCalculateWarmEmissions_and_throwWarmEmissionEvent*, testCheckVehicleInfoAndCalculateWarmEmissions_and_throwWarmEmissionEvent_Exceptions * check vehicle info and calculate warm emissions -testCheckVehicleInfoAndCalculateWarmEmissions_and_throwWarmEmissionEvent*, testCheckVehicleInfoAndCalculateWarmEmissions_and_throwWarmEmissionEvent_Exceptions - * get free flow occurences - testCounters*() - * get fraction occurences - testCounters*() - * get stop go occurences - testCounters*() + * get free flow occurrences - testCounters*() + * get fraction occurrences - testCounters*() + * get stop-go occurrences - testCounters*() * get km counter - testCounters*() * get free flow km counter - testCounters*() - * get top go km couter - testCounters*() + * get top go km counter - testCounters*() * get warm emission event counter - testCounters*() * * private methods and corresponding tests: @@ -105,7 +104,7 @@ public class TestWarmEmissionAnalysisModuleCase4{ /* * this test method creates a vehicle (lpg properties) and a mock link - * for two cases: "avg speed = stop go speed" & "avg speed = free flow speed" the PM warm Emissions and the Emissions "sum" are tested + * for two cases: "avg speed = stop-go speed" & "avg speed = free flow speed" the PM warm Emissions and the Emissions "sum" are tested * average values are used */ @ParameterizedTest @@ -123,7 +122,7 @@ void testCheckVehicleInfoAndCalculateWarmEmissions_and_throwWarmEmissionEvent4(E VehiclesFactory vehFac = VehicleUtils.getFactory(); Vehicle lpgVehicle = vehFac.createVehicle(lpgVehicleId, vehFac.createVehicleType(lpgVehicleTypeId)); - // sub case avg speed = stop go speed + // subcase avg speed = stop-go speed warmEmissions = emissionsModule.checkVehicleInfoAndCalculateWarmEmissions(lpgVehicle, lpglink, lpgLinkLength/ SPEED_SG *3.6 ); Assertions.assertEquals( AVG_PC_FACTOR_SG *lpgLinkLength/1000., warmEmissions.get(PM), MatsimTestUtils.EPSILON ); emissionEventManager.reset(); @@ -132,7 +131,7 @@ void testCheckVehicleInfoAndCalculateWarmEmissions_and_throwWarmEmissionEvent4(E emissionEventManager.reset(); warmEmissions.clear(); - // sub case avg speed = free flow speed + // subcase avg speed = free flow speed warmEmissions = emissionsModule.checkVehicleInfoAndCalculateWarmEmissions(lpgVehicle, lpglink, lpgLinkLength/ SPEED_FF *3.6 ); Assertions.assertEquals( AVG_PC_FACTOR_FF *lpgLinkLength/1000., warmEmissions.get(PM ), MatsimTestUtils.EPSILON ); emissionEventManager.reset(); @@ -144,7 +143,7 @@ void testCheckVehicleInfoAndCalculateWarmEmissions_and_throwWarmEmissionEvent4(E /* * this test method creates a vehicle and mock link - * for two cases: "avg speed = stop go speed" & "avg speed = free flow speed" the PM warm Emissions are tested + * for two cases: "avg speed = stop-go speed" & "avg speed = free flow speed" the PM warm Emissions are tested * average values are used */ @ParameterizedTest @@ -161,7 +160,7 @@ void testCounters2(EmissionsConfigGroup.EmissionsComputationMethod emissionsComp Link lpgLink = TestWarmEmissionAnalysisModule.createMockLink("link zero", lpgLinkLength, SPEED_FF / 3.6 ); - // sub case: current speed equals free flow speed + // subcase: current speed equals free flow speed warmEmissions = emissionsModule.checkVehicleInfoAndCalculateWarmEmissions(vehicle, lpgLink, lpgLinkLength/ SPEED_FF *3.6 ); Assertions.assertEquals(0, emissionsModule.getFractionOccurences() ); Assertions.assertEquals(lpgLinkLength/1000, emissionsModule.getFreeFlowKmCounter(), MatsimTestUtils.EPSILON ); @@ -172,7 +171,7 @@ void testCounters2(EmissionsConfigGroup.EmissionsComputationMethod emissionsComp Assertions.assertEquals(1, emissionsModule.getWarmEmissionEventCounter() ); emissionsModule.reset(); - // sub case: current speed equals free flow speed + // subcase: current speed equals free flow speed warmEmissions = emissionsModule.checkVehicleInfoAndCalculateWarmEmissions(vehicle, lpgLink, lpgLinkLength/ SPEED_SG *3.6 ); Assertions.assertEquals(0, emissionsModule.getFractionOccurences() ); Assertions.assertEquals(0., emissionsModule.getFreeFlowKmCounter(), MatsimTestUtils.EPSILON ); diff --git a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestWarmEmissionAnalysisModuleCase5.java b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestWarmEmissionAnalysisModuleCase5.java index c1ba590dcfa..a792d37d620 100644 --- a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestWarmEmissionAnalysisModuleCase5.java +++ b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestWarmEmissionAnalysisModuleCase5.java @@ -22,9 +22,7 @@ import org.junit.jupiter.api.Assertions; import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.EnumSource; -import org.junit.jupiter.params.provider.MethodSource; import org.matsim.api.core.v01.Id; import org.matsim.api.core.v01.network.Link; import org.matsim.contrib.emissions.utils.EmissionsConfigGroup; @@ -37,7 +35,6 @@ import org.matsim.vehicles.VehiclesFactory; import java.util.*; -import java.util.stream.Stream; import static org.matsim.contrib.emissions.Pollutant.PM; @@ -46,7 +43,7 @@ */ /* - * Case 5 - data in detailed table, stop go speed zero + * Case 5 - data in detailed table, stop-go speed zero */ @@ -60,12 +57,12 @@ * testCheckVehicleInfoAndCalculateWarmEmissions_and_throwWarmEmissionEvent_Exceptions * check vehicle info and calculate warm emissions -testCheckVehicleInfoAndCalculateWarmEmissions_and_throwWarmEmissionEvent*, * testCheckVehicleInfoAndCalculateWarmEmissions_and_throwWarmEmissionEvent_Exceptions - * get free flow occurences - testCounters*() - * get fraction occurences - testCounters*() - * get stop go occurences - testCounters*() + * get free flow occurrences - testCounters*() + * get fraction occurrences - testCounters*() + * get stop-go occurrences - testCounters*() * get km counter - testCounters*() * get free flow km counter - testCounters*() - * get top go km couter - testCounters*() + * get top go km counter - testCounters*() * get warm emission event counter - testCounters*() * * private methods and corresponding tests: @@ -93,7 +90,7 @@ public class TestWarmEmissionAnalysisModuleCase5 { private final HandlerToTestEmissionAnalysisModules emissionEventManager = new HandlerToTestEmissionAnalysisModules(); // vehicle information for regular test cases - // case 5 - data in detailed table, stop go speed zero + // case 5 - data in detailed table, stop-go speed zero private final String zeroRoadCategory = "URB_case6"; private final String zeroTechnology = "zero technology"; private final String zeroConcept = "zero concept"; diff --git a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestWarmEmissionAnalysisModuleTrafficSituations.java b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestWarmEmissionAnalysisModuleTrafficSituations.java index 3289f013639..6d65c3ea4f6 100644 --- a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestWarmEmissionAnalysisModuleTrafficSituations.java +++ b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestWarmEmissionAnalysisModuleTrafficSituations.java @@ -19,12 +19,8 @@ * *********************************************************************** */ import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.EnumSource; -import org.junit.jupiter.params.provider.MethodSource; import org.matsim.api.core.v01.Id; import org.matsim.api.core.v01.network.Link; import org.matsim.api.core.v01.network.Node; @@ -39,7 +35,6 @@ import org.matsim.vehicles.VehiclesFactory; import java.util.*; -import java.util.stream.Stream; import static org.matsim.contrib.emissions.HbefaTrafficSituation.*; import static org.matsim.contrib.emissions.Pollutant.NOx; @@ -79,7 +74,7 @@ public class TestWarmEmissionAnalysisModuleTrafficSituations { private static final String petrolConcept ="<1,4L"; private static final double[] detailedPetrolFactor = {10, 100, 1000, 10000, 100000}; - // case 2 - free flow entry in both tables, stop go entry in average table -> use average + // case 2 - free flow entry in both tables, stop-go entry in average table -> use average private static final String pcTechnology = "PC petrol <1,4L * LookupBehavior: onlyTryDetailedElseAbort - * + *

        * -> should calculate value */ @Test void testWarmDetailedValueOnlyDetailed() { EmissionModule emissionModule = setUpScenario(EmissionsConfigGroup.DetailedVsAverageLookupBehavior.onlyTryDetailedElseAbort); - double travelTimeOnLink = 21; //sec. approx freeSpeed of link12 is : (200 m) / (9.72.. m/s) approx 20.57 s + double travelTimeOnLink = 21; //sec. approx freeSpeed of link12 is : (200 m) / (9.72... m/s) approx 20.57 s Map warmEmissions = emissionModule.getWarmEmissionAnalysisModule().checkVehicleInfoAndCalculateWarmEmissions(vehicleFull, link, travelTimeOnLink); double expectedValue = 30.34984742; // = 200m * 151.7492371 g/km @@ -84,7 +84,7 @@ void testWarmDetailedValueOnlyDetailed() { * * vehicles information is complete but fully specified entry is NOT available in detailed table * LookupBehavior: onlyTryDetailedElseAbort - * + *

        * -> should abort --> RuntimeException */ @Test @@ -92,7 +92,7 @@ void testWarm_DetailedElseAbort_ShouldAbort1() { assertThrows(RuntimeException.class, () -> { EmissionModule emissionModule = setUpScenario(EmissionsConfigGroup.DetailedVsAverageLookupBehavior.onlyTryDetailedElseAbort); - double travelTimeOnLink = 21; //sec. approx freeSpeed of link12 is : (200 m) / (9.72.. m/s) approx 20.57 s + double travelTimeOnLink = 21; //sec. approx freeSpeed of link12 is : (200 m) / (9.72... m/s) approx 20.57 s emissionModule.getWarmEmissionAnalysisModule().checkVehicleInfoAndCalculateWarmEmissions(vehicleFallbackToTechnologyAverage, link, travelTimeOnLink); }); } @@ -100,9 +100,9 @@ void testWarm_DetailedElseAbort_ShouldAbort1() { /** * vehicles information is complete but fully specified entry is NOT available in detailed table * HbefaTechnology is also not in detailed table -> fall back to technology average is NOT possible as well. - * + *

        * LookupBehavior: onlyTryDetailedElseAbort - * + *

        * -> should abort --> RuntimeException */ @Test @@ -110,17 +110,17 @@ void testWarm_DetailedElseAbort_ShouldAbort2() { assertThrows(RuntimeException.class, () -> { EmissionModule emissionModule = setUpScenario(EmissionsConfigGroup.DetailedVsAverageLookupBehavior.onlyTryDetailedElseAbort); - double travelTimeOnLink = 21; //sec. approx freeSpeed of link12 is : (200 m) / (9.72.. m/s) approx 20.57 s + double travelTimeOnLink = 21; //sec. approx freeSpeed of link12 is : (200 m) / (9.72... m/s) approx 20.57 s emissionModule.getWarmEmissionAnalysisModule().checkVehicleInfoAndCalculateWarmEmissions(vehicleFallbackToAverageTable, link, travelTimeOnLink); }); } -// --------- DetailedVsAverageLookupBehavior.tryDetailedThenTechnologyAverageElseAbort) ----------- +// --------- DetailedVsAverageLookupBehavior.tryDetailedThenTechnologyAverageElseAbort) ----------- /** * vehicles information is complete * LookupBehavior: tryDetailedThenTechnologyAverageElseAbort - * + *

        * -> do NOT fall back to technology average * ---> should calculate value from detailed value */ @@ -128,7 +128,7 @@ void testWarm_DetailedElseAbort_ShouldAbort2() { void testWarm_DetailedThenTechnologyAverageElseAbort_FallbackNotNeeded() { EmissionModule emissionModule = setUpScenario(EmissionsConfigGroup.DetailedVsAverageLookupBehavior.tryDetailedThenTechnologyAverageElseAbort); - double travelTimeOnLink = 21; //sec. approx freeSpeed of link12 is : (200 m) / (9.72.. m/s) approx 20.57 s + double travelTimeOnLink = 21; //sec. approx freeSpeed of link12 is : (200 m) / (9.72... m/s) approx 20.57 s Map warmEmissions = emissionModule.getWarmEmissionAnalysisModule().checkVehicleInfoAndCalculateWarmEmissions(vehicleFull, link, travelTimeOnLink); double expectedValue = 30.34984742; // = 200m * 151.7492371 g/km @@ -139,7 +139,7 @@ void testWarm_DetailedThenTechnologyAverageElseAbort_FallbackNotNeeded() { /** * vehicles information is complete but fully specified entry is NOT available in detailed table * LookupBehavior: tryDetailedThenTechnologyAverageElseAbort - * + *

        * -> do fall back to technology average * ---> should calculate value from technology average */ @@ -147,7 +147,7 @@ void testWarm_DetailedThenTechnologyAverageElseAbort_FallbackNotNeeded() { void testWarm_DetailedThenTechnologyAverageElseAbort_FallbackToTechnologyAverage() { EmissionModule emissionModule = setUpScenario(EmissionsConfigGroup.DetailedVsAverageLookupBehavior.tryDetailedThenTechnologyAverageElseAbort); - double travelTimeOnLink = 21; //sec. approx freeSpeed of link12 is : (200 m) / (9.72.. m/s) approx 20.57 s + double travelTimeOnLink = 21; //sec. approx freeSpeed of link12 is : (200 m) / (9.72... m/s) approx 20.57 s Map warmEmissions = emissionModule.getWarmEmissionAnalysisModule().checkVehicleInfoAndCalculateWarmEmissions(vehicleFallbackToTechnologyAverage, link, travelTimeOnLink); double expectedValue = 31.53711548; // = 200m * 157.6855774 g/km @@ -157,9 +157,9 @@ void testWarm_DetailedThenTechnologyAverageElseAbort_FallbackToTechnologyAverage /** * vehicles information is complete but fully specified entry is NOT available in detailed table * HbefaTechnology is also not in detailed table -> fall back to technology average is NOT possible as well. - * + *

        * LookupBehavior: onlyTryDetailedElseAbort - * + *

        * -> should abort --> RuntimeException */ @Test @@ -167,16 +167,16 @@ void testWarm_DetailedThenTechnologyAverageElseAbort_ShouldAbort() { assertThrows(RuntimeException.class, () -> { EmissionModule emissionModule = setUpScenario(EmissionsConfigGroup.DetailedVsAverageLookupBehavior.onlyTryDetailedElseAbort); - double travelTimeOnLink = 21; //sec. approx freeSpeed of link12 is : (200 m) / (9.72.. m/s) approx 20.57 s + double travelTimeOnLink = 21; //sec. approx freeSpeed of link12 is : (200 m) / (9.72... m/s) approx 20.57 s emissionModule.getWarmEmissionAnalysisModule().checkVehicleInfoAndCalculateWarmEmissions(vehicleFallbackToAverageTable, link, travelTimeOnLink); }); } -// --------- DetailedVsAverageLookupBehavior.tryDetailedThenTechnologyAverageThenAverageTable ----------- +// --------- DetailedVsAverageLookupBehavior.tryDetailedThenTechnologyAverageThenAverageTable ----------- /** * vehicles information is complete * LookupBehavior: tryDetailedThenTechnologyAverageElseAbort - * + *

        * -> do NOT fall back to technology average or average table * ---> should calculate value from detailed value */ @@ -184,7 +184,7 @@ void testWarm_DetailedThenTechnologyAverageElseAbort_ShouldAbort() { void testWarm_DetailedThenTechnologyAverageThenAverageTable_FallbackNotNeeded() { EmissionModule emissionModule = setUpScenario(EmissionsConfigGroup.DetailedVsAverageLookupBehavior.tryDetailedThenTechnologyAverageThenAverageTable); - double travelTimeOnLink = 21; //sec. approx freeSpeed of link12 is : (200 m) / (9.72.. m/s) approx 20.57 s + double travelTimeOnLink = 21; //sec. approx freeSpeed of link12 is : (200 m) / (9.72... m/s) approx 20.57 s Map warmEmissions = emissionModule.getWarmEmissionAnalysisModule().checkVehicleInfoAndCalculateWarmEmissions(vehicleFull, link, travelTimeOnLink); double expectedValue = 30.34984742; // = 200m * 151.7492371 g/km @@ -195,7 +195,7 @@ void testWarm_DetailedThenTechnologyAverageThenAverageTable_FallbackNotNeeded() /** * vehicles information is complete but fully specified entry is NOT available in detailed table * LookupBehavior: tryDetailedThenTechnologyAverageElseAbort - * + *

        * -> do fall back to technology average; do NOT fall back to average table * ---> should calculate value from technology average */ @@ -203,7 +203,7 @@ void testWarm_DetailedThenTechnologyAverageThenAverageTable_FallbackNotNeeded() void testWarm_DetailedThenTechnologyAverageThenAverageTable_FallbackToTechnology() { EmissionModule emissionModule = setUpScenario(EmissionsConfigGroup.DetailedVsAverageLookupBehavior.tryDetailedThenTechnologyAverageThenAverageTable); - double travelTimeOnLink = 21; //sec. approx freeSpeed of link12 is : (200 m) / (9.72.. m/s) approx 20.57 s + double travelTimeOnLink = 21; //sec. approx freeSpeed of link12 is : (200 m) / (9.72... m/s) approx 20.57 s Map warmEmissions = emissionModule.getWarmEmissionAnalysisModule().checkVehicleInfoAndCalculateWarmEmissions(vehicleFallbackToTechnologyAverage, link, travelTimeOnLink); double expectedValue = 31.53711548; // = 200m * 157.6855774 g/km @@ -213,9 +213,9 @@ void testWarm_DetailedThenTechnologyAverageThenAverageTable_FallbackToTechnology /** * vehicles information is complete but fully specified entry is NOT available in detailed table * HbefaTechnology is also not in detailed table -> fall back to technology average is NOT possible as well. - * + *

        * LookupBehavior: tryDetailedThenTechnologyAverageThenAverageTable - * + *

        * -> do fall back to average table * ---> should calculate value from average table */ @@ -223,7 +223,7 @@ void testWarm_DetailedThenTechnologyAverageThenAverageTable_FallbackToTechnology void testWarm_DetailedThenTechnologyAverageThenAverageTable_FallbackToAverageTable() { EmissionModule emissionModule = setUpScenario(EmissionsConfigGroup.DetailedVsAverageLookupBehavior.tryDetailedThenTechnologyAverageThenAverageTable); - double travelTimeOnLink = 21; //sec. approx freeSpeed of link12 is : (200 m) / (9.72.. m/s) approx 20.57 s + double travelTimeOnLink = 21; //sec. approx freeSpeed of link12 is : (200 m) / (9.72... m/s) approx 20.57 s Map warmEmissions = emissionModule.getWarmEmissionAnalysisModule().checkVehicleInfoAndCalculateWarmEmissions(vehicleFallbackToAverageTable, link, travelTimeOnLink); double expectedValue = 31.1947174; // = 200m * 155.973587 g/km @@ -233,7 +233,7 @@ void testWarm_DetailedThenTechnologyAverageThenAverageTable_FallbackToAverageTab -// ---------- setup and helper methods ------------- +// ---------- setup and helper methods ------------- /** * load and prepare the scenario, create the emissionsModule diff --git a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/VspHbefaRoadTypeMappingTest.java b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/VspHbefaRoadTypeMappingTest.java index f0164d11e86..fb906ac6f63 100644 --- a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/VspHbefaRoadTypeMappingTest.java +++ b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/VspHbefaRoadTypeMappingTest.java @@ -16,7 +16,7 @@ void testSimpleMapping() { var mapper = new VspHbefaRoadTypeMapping(); var link = getTestLink("", 70 / 3.6); - var result = mapper.determineHebfaType(link); + var result = mapper.determineHbefaType(link); assertEquals("URB/MW-Nat./80", result); } @@ -36,4 +36,4 @@ private static Link getTestLink(String osmRoadType, double allowedSpeed) { return link; } -} \ No newline at end of file +} diff --git a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/analysis/EmissionGridAnalyzerTest.java b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/analysis/EmissionGridAnalyzerTest.java index d9614bd3dea..ef291d8d788 100644 --- a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/analysis/EmissionGridAnalyzerTest.java +++ b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/analysis/EmissionGridAnalyzerTest.java @@ -69,7 +69,7 @@ void process() { final Pollutant pollutant = HC; final double pollutionPerEvent = 1; - Path eventsFile = Paths.get(testUtils.getOutputDirectory()).resolve(UUID.randomUUID().toString() + ".xml"); + Path eventsFile = Paths.get(testUtils.getOutputDirectory()).resolve(UUID.randomUUID() + ".xml"); Network network = TestUtils.createRandomNetwork(100, 1000, 1000); TestUtils.writeWarmEventsToFile(eventsFile, network, pollutant, pollutionPerEvent, 1, 99); @@ -95,7 +95,7 @@ void process_singleLinkWithOneEvent() { final Pollutant pollutant = CO; final double pollutionPerEvent = 1000; final int time = 1; - final Path eventsFile = Paths.get(testUtils.getOutputDirectory()).resolve(UUID.randomUUID().toString() + ".xml"); + final Path eventsFile = Paths.get(testUtils.getOutputDirectory()).resolve(UUID.randomUUID() + ".xml"); final Network network = NetworkUtils.createNetwork(); Node from = network.getFactory().createNode(Id.createNodeId("from"), new Coord(5, 5)); network.addNode(from); @@ -134,7 +134,7 @@ void process_singleLinkWithTwoEvents() { final Pollutant pollutant = CO; final double pollutionPerEvent = 1000; final int time = 1; - final Path eventsFile = Paths.get(testUtils.getOutputDirectory()).resolve(UUID.randomUUID().toString() + ".xml"); + final Path eventsFile = Paths.get(testUtils.getOutputDirectory()).resolve(UUID.randomUUID() + ".xml"); final Network network = NetworkUtils.createNetwork(); Node from = network.getFactory().createNode(Id.createNodeId("from"), new Coord(5, 5)); network.addNode(from); @@ -173,7 +173,7 @@ void process_twoLinksWithOneEventEach() { final Pollutant pollutant = CO; final double pollutionPerEvent = 1000; final int time = 1; - final Path eventsFile = Paths.get(testUtils.getOutputDirectory()).resolve(UUID.randomUUID().toString() + ".xml"); + final Path eventsFile = Paths.get(testUtils.getOutputDirectory()).resolve(UUID.randomUUID() + ".xml"); final Network network = NetworkUtils.createNetwork(); Node from = network.getFactory().createNode(Id.createNodeId("from"), new Coord(5, 5)); network.addNode(from); @@ -215,7 +215,7 @@ void process_twoLinksWithTwoEventsEach() { final Pollutant pollutant = NOx; final double pollutionPerEvent = 1000; final int time = 1; - final Path eventsFile = Paths.get(testUtils.getOutputDirectory()).resolve(UUID.randomUUID().toString() + ".xml"); + final Path eventsFile = Paths.get(testUtils.getOutputDirectory()).resolve(UUID.randomUUID() + ".xml"); final Network network = NetworkUtils.createNetwork(); Node from = network.getFactory().createNode(Id.createNodeId("from"), new Coord(5, 5)); network.addNode(from); @@ -255,7 +255,7 @@ void process_twoLinksWithTwoEventsEach() { void process_withBoundaries() { final double pollutionPerEvent = 1; - Path eventsFile = Paths.get(testUtils.getOutputDirectory()).resolve(UUID.randomUUID().toString() + ".xml"); + Path eventsFile = Paths.get(testUtils.getOutputDirectory()).resolve(UUID.randomUUID() + ".xml"); Network network = TestUtils.createRandomNetwork(100, 1000, 1000); TestUtils.writeWarmEventsToFile(eventsFile, network, NOx, pollutionPerEvent, 1, 99); @@ -281,7 +281,7 @@ void processToJson() { final double pollutionPerEvent = 1; final int time = 1; - final Path eventsFile = Paths.get(testUtils.getOutputDirectory()).resolve(UUID.randomUUID().toString() + ".xml"); + final Path eventsFile = Paths.get(testUtils.getOutputDirectory()).resolve(UUID.randomUUID() + ".xml"); final Network network = TestUtils.createRandomNetwork(1, 1000, 1000); TestUtils.writeWarmEventsToFile(eventsFile, network, NO2, pollutionPerEvent, time, time + 3); @@ -302,8 +302,8 @@ void processToJsonFile() throws IOException { final double pollutionPerEvent = 1; final int time = 1; - final Path eventsFile = Paths.get(testUtils.getOutputDirectory()).resolve(UUID.randomUUID().toString() + ".xml"); - final Path jsonFile = Paths.get(testUtils.getOutputDirectory()).resolve(UUID.randomUUID().toString() + ".json"); + final Path eventsFile = Paths.get(testUtils.getOutputDirectory()).resolve(UUID.randomUUID() + ".xml"); + final Path jsonFile = Paths.get(testUtils.getOutputDirectory()).resolve(UUID.randomUUID() + ".json"); final Network network = TestUtils.createRandomNetwork(1, 1000, 1000); TestUtils.writeWarmEventsToFile(eventsFile, network, NO2, pollutionPerEvent, time, time + 3); @@ -386,9 +386,9 @@ private void writeGridToCSV(TimeBinMap>> bins, Strin } } - private void assertCsvValuesAreSame(Path expected, Path acutal) throws IOException { + private void assertCsvValuesAreSame(Path expected, Path actual) throws IOException { - try (FileReader expectedReader = new FileReader(expected.toString()); var actualReader = new FileReader(acutal.toString())) { + try (FileReader expectedReader = new FileReader(expected.toString()); var actualReader = new FileReader(actual.toString())) { var actualIterator = CSVFormat.TDF.withFirstRecordAsHeader().parse(actualReader).iterator(); diff --git a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/analysis/EmissionsByPollutantTest.java b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/analysis/EmissionsByPollutantTest.java index 635affd8832..52ed3393a4f 100644 --- a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/analysis/EmissionsByPollutantTest.java +++ b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/analysis/EmissionsByPollutantTest.java @@ -17,7 +17,7 @@ public class EmissionsByPollutantTest { // The EmissionsByPollutant potentially adds up the same emissions coming from cold and warm. Thus, this cannot be combined into the enum approach // without some thinking. kai, jan'20 - // Quite possibly, should just combine them into an enum "pollutant"?! There is, anyways, the JM map of those emissions that are actually present in the + // Quite possibly, should just combine them into an enum "pollutant"?! There is, anyway, the JM map of those emissions that are actually present in the // input file. kai, jan'20 @Test @@ -25,8 +25,7 @@ void initialize() { Map emissions = EmissionUtilsTest.createEmissions(); - Map map = new LinkedHashMap<>(); - emissions.forEach( map::put ) ; + Map map = new LinkedHashMap<>(emissions); EmissionsByPollutant linkEmissions = new EmissionsByPollutant( map ) ; @@ -46,8 +45,7 @@ void addEmission() { final Pollutant pollutant = CO; final double expectedValue = emissions.get(pollutant) + valueToAdd; - Map map = new LinkedHashMap<>(); - emissions.forEach( map::put ) ; + Map map = new LinkedHashMap<>(emissions); EmissionsByPollutant emissionsByPollutant = new EmissionsByPollutant(map); @@ -79,13 +77,11 @@ void addEmissions() { Map emissions = EmissionUtilsTest.createEmissions(); - Map map = new LinkedHashMap<>(); - emissions.forEach( map::put ) ; + Map map = new LinkedHashMap<>(emissions); EmissionsByPollutant linkEmissions = new EmissionsByPollutant(map); - Map map2 = new LinkedHashMap<>(); - emissions.forEach( map2::put ) ; + Map map2 = new LinkedHashMap<>(emissions); linkEmissions.addEmissions(map2); diff --git a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/analysis/RawEmissionEventsReaderTest.java b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/analysis/RawEmissionEventsReaderTest.java index 4592d26ec17..955c1d4313d 100644 --- a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/analysis/RawEmissionEventsReaderTest.java +++ b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/analysis/RawEmissionEventsReaderTest.java @@ -22,7 +22,7 @@ public class RawEmissionEventsReaderTest { @Test void handleNonEventNode() { - // read in an xml file which doesn't have events. It will parse the whole file but will not handle any of the + // read in a xml file which doesn't have events. It will parse the whole file but will not handle any of the // parsed nodes var networkUrl = IOUtils.extendUrl(ExamplesUtils.getTestScenarioURL("equil"), "network.xml"); new RawEmissionEventsReader((time, linkId, vehicleId, pollutant, value) -> { @@ -36,7 +36,7 @@ void handleNonEventNode() { @Test void handleNonEmissionEvent() { - // read in events file wihtout emission events. Those events should be ignored + // read in events file without emission events. Those events should be ignored var eventsUrl = IOUtils.extendUrl(ExamplesUtils.getTestScenarioURL("equil"), "output_events.xml.gz"); new RawEmissionEventsReader((time, linkId, vehicleId, pollutant, value) -> { // this method should not be called diff --git a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/events/TestColdEmissionEventImpl.java b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/events/TestColdEmissionEventImpl.java index 022265df9f0..9a3af2d8601 100644 --- a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/events/TestColdEmissionEventImpl.java +++ b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/events/TestColdEmissionEventImpl.java @@ -62,7 +62,7 @@ final void testGetAttributesForCompleteEmissionMaps(){ Map coldEmissionsMap = new HashMap<>(); setColdEmissions(coldEmissionsMap); ColdEmissionEvent ce = new ColdEmissionEvent(0.0, linkId, vehicleId, coldEmissionsMap); - + Map ceg = ce.getAttributes(); Assertions.assertEquals(Double.parseDouble(ceg.get(CO.name())), co, MatsimTestUtils.EPSILON, "the CO value of this cold emission event was "+ Double.parseDouble(ceg.get(CO.name()))+ "but should have been "+ co); Assertions.assertEquals(Double.parseDouble(ceg.get(FC.name())), fc, MatsimTestUtils.EPSILON, "the FC value of this cold emission event was "+ Double.parseDouble(ceg.get(FC.name()))+ "but should have been "+ fc); @@ -71,7 +71,7 @@ final void testGetAttributesForCompleteEmissionMaps(){ Assertions.assertEquals(Double.parseDouble(ceg.get(NO2.name())), n2, MatsimTestUtils.EPSILON, "the NO2 value of this cold emission event was "+ Double.parseDouble(ceg.get(NO2.name()))+ "but should have been "+ n2); Assertions.assertEquals(Double.parseDouble(ceg.get(NOx.name())), nx, MatsimTestUtils.EPSILON, "the NOx value of this cold emission event was "+ Double.parseDouble(ceg.get(NOx.name()))+ "but should have been "+ nx); Assertions.assertEquals(Double.parseDouble(ceg.get(PM.name())), pm, MatsimTestUtils.EPSILON, "the PM value of this cold emission event was "+ Double.parseDouble(ceg.get(PM.name()))+ "but should have been "+ pm); - + } private void setColdEmissions( Map coldEmissionsMap ) { @@ -90,12 +90,12 @@ final void testGetAttributesForIncompleteMaps(){ //the getAttributesMethod should // - return null if the emission map is empty // - throw NullPointerExceptions if the emission values are not set - // - throw NullPointerExceptions if no emission map is assigned - + // - throw NullPointerExceptions if no emission map is assigned + //empty map Map emptyMap = new HashMap<>(); ColdEmissionEvent emptyMapEvent = new ColdEmissionEvent(22., linkId, vehicleId, emptyMap); - + //values not set Map valuesNotSet = new HashMap<>(); valuesNotSet.put(CO, null); @@ -106,30 +106,30 @@ final void testGetAttributesForIncompleteMaps(){ valuesNotSet.put(NOx, null); valuesNotSet.put(PM, null); ColdEmissionEvent valuesNotSetEvent = new ColdEmissionEvent(44., linkId, vehicleId, valuesNotSet); - + //no map ColdEmissionEvent noMap = new ColdEmissionEvent(50., linkId, vehicleId, null); - + int numberOfColdPollutants = coldPollutants.size(); int valNullPointers = 0, noMapNullPointers=0; - + for(Pollutant cp : coldPollutants){ //empty map - Assertions.assertNull(emptyMapEvent.getAttributes().get(cp)); - + Assertions.assertNull(emptyMapEvent.getAttributes().get(cp.name())); + //values not set try{ - valuesNotSetEvent.getAttributes().get(cp); + valuesNotSetEvent.getAttributes().get(cp.name()); } catch(NullPointerException e){ valNullPointers ++; } - + //no map try{ - noMap.getAttributes().get(cp); + noMap.getAttributes().get(cp.name()); } catch(NullPointerException e){ noMapNullPointers++; @@ -138,5 +138,5 @@ final void testGetAttributesForIncompleteMaps(){ Assertions.assertEquals(numberOfColdPollutants, valNullPointers); Assertions.assertEquals(numberOfColdPollutants, noMapNullPointers); } - + } diff --git a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/events/TestWarmEmissionEventImpl.java b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/events/TestWarmEmissionEventImpl.java index 62691c3670f..b203c8792ce 100644 --- a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/events/TestWarmEmissionEventImpl.java +++ b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/events/TestWarmEmissionEventImpl.java @@ -42,55 +42,52 @@ public class TestWarmEmissionEventImpl { - + private final Id vehicleId = Id.create("veh 1", Vehicle.class); private final Id linkId = Id.create("link 1", Link.class); - private final Double co = 20.; - private final Double c2 = 8.; - private final Double fc = 30.; - private final Double hc=4.; - private final Double nm=5.; - private final Double n2=6.; - private final Double nx=7.; - private final Double pm=8.; - private final Double so=1.6; -// private final Set pollutants = new HashSet<>(Arrays.asList(CO, CO2_TOTAL, FC, HC, NMHC, NOx, NO2,PM, SO2)); + private final Double co_value = 20.; + private final Double co2total_value = 8.; + private final Double fc_value = 30.; + private final Double hc_value =4.; + private final Double nmhc_value =5.; + private final Double no2_value =6.; + private final Double nox_value =7.; + private final Double pm_value =8.; + private final Double so2_value =1.6; private final Set pollutants = new HashSet<>( Arrays.asList( Pollutant.values() ) ); @Test final void testGetAttributesForCompleteEmissionMaps(){ //test normal functionality - + //create a normal event impl Map warmEmissionsMap = new HashMap<>(); - warmEmissionsMap.put(CO, co ); - warmEmissionsMap.put(CO2_TOTAL, c2 ); - warmEmissionsMap.put(FC, fc ); - warmEmissionsMap.put(HC, hc ); - warmEmissionsMap.put(NMHC, nm ); - warmEmissionsMap.put(NO2, n2 ); - warmEmissionsMap.put(NOx, nx ); - warmEmissionsMap.put(PM, pm ); - warmEmissionsMap.put(SO2, so ); + warmEmissionsMap.put(CO, co_value); + warmEmissionsMap.put(CO2_TOTAL, co2total_value); + warmEmissionsMap.put(FC, fc_value); + warmEmissionsMap.put(HC, hc_value); + warmEmissionsMap.put(NMHC, nmhc_value); + warmEmissionsMap.put(NO2, no2_value); + warmEmissionsMap.put(NOx, nox_value); + warmEmissionsMap.put(PM, pm_value); + warmEmissionsMap.put(SO2, so2_value); - Map map = new LinkedHashMap<>(); - warmEmissionsMap.forEach( (key,value) -> map.put( key, value ) ); - // (this could be made more direct) + Map map = new LinkedHashMap<>(warmEmissionsMap); WarmEmissionEvent we = new WarmEmissionEvent(0.0, linkId, vehicleId, map); - + Map weg = we.getAttributes(); - Assertions.assertEquals(Double.parseDouble(weg.get(CO.name())), co, MatsimTestUtils.EPSILON, "the CO value of this warm emission event was "+ Double.parseDouble(weg.get(CO.name()))+ "but should have been "+ co); - Assertions.assertEquals(Double.parseDouble(weg.get(CO2_TOTAL.name())), c2, MatsimTestUtils.EPSILON, "the CO2 value of this warm emission event was "+ Double.parseDouble(weg.get(CO2_TOTAL.name()))+ "but should have been "+ c2); - Assertions.assertEquals(Double.parseDouble(weg.get(FC.name())), fc, MatsimTestUtils.EPSILON, "the FC value of this warm emission event was "+ Double.parseDouble(weg.get(FC.name()))+ "but should have been "+ fc); - Assertions.assertEquals(Double.parseDouble(weg.get(HC.name())), hc, MatsimTestUtils.EPSILON, "the HC value of this warm emission event was "+ Double.parseDouble(weg.get(HC.name()))+ "but should have been "+ hc); - Assertions.assertEquals(Double.parseDouble(weg.get(NMHC.name())), nm, MatsimTestUtils.EPSILON, "the NMHC value of this warm emission event was "+ Double.parseDouble(weg.get(NMHC.name()))+ "but should have been "+ nm); - Assertions.assertEquals(Double.parseDouble(weg.get(NO2.name())), n2, MatsimTestUtils.EPSILON, "the NO2 value of this warm emission event was "+ Double.parseDouble(weg.get(NO2.name()))+ "but should have been "+ n2); - Assertions.assertEquals(Double.parseDouble(weg.get(NOx.name())), nx, MatsimTestUtils.EPSILON, "the NOx value of this warm emission event was "+ Double.parseDouble(weg.get(NOx.name()))+ "but should have been "+ nx); - Assertions.assertEquals(Double.parseDouble(weg.get(PM.name())), pm, MatsimTestUtils.EPSILON, "the PM value of this warm emission event was "+ Double.parseDouble(weg.get(PM.name()))+ "but should have been "+ pm); - Assertions.assertEquals(Double.parseDouble(weg.get(SO2.name())), so, MatsimTestUtils.EPSILON, "the SO2 value of this warm emission event was "+ Double.parseDouble(weg.get(SO2.name()))+ "but should have been "+ so); + Assertions.assertEquals(Double.parseDouble(weg.get(CO.name())), co_value, MatsimTestUtils.EPSILON, "the CO value of this warm emission event was "+ Double.parseDouble(weg.get(CO.name()))+ "but should have been "+ co_value); + Assertions.assertEquals(Double.parseDouble(weg.get(CO2_TOTAL.name())), co2total_value, MatsimTestUtils.EPSILON, "the CO2 value of this warm emission event was "+ Double.parseDouble(weg.get(CO2_TOTAL.name()))+ "but should have been "+ co2total_value); + Assertions.assertEquals(Double.parseDouble(weg.get(FC.name())), fc_value, MatsimTestUtils.EPSILON, "the FC value of this warm emission event was "+ Double.parseDouble(weg.get(FC.name()))+ "but should have been "+ fc_value); + Assertions.assertEquals(Double.parseDouble(weg.get(HC.name())), hc_value, MatsimTestUtils.EPSILON, "the HC value of this warm emission event was "+ Double.parseDouble(weg.get(HC.name()))+ "but should have been "+ hc_value); + Assertions.assertEquals(Double.parseDouble(weg.get(NMHC.name())), nmhc_value, MatsimTestUtils.EPSILON, "the NMHC value of this warm emission event was "+ Double.parseDouble(weg.get(NMHC.name()))+ "but should have been "+ nmhc_value); + Assertions.assertEquals(Double.parseDouble(weg.get(NO2.name())), no2_value, MatsimTestUtils.EPSILON, "the NO2 value of this warm emission event was "+ Double.parseDouble(weg.get(NO2.name()))+ "but should have been "+ no2_value); + Assertions.assertEquals(Double.parseDouble(weg.get(NOx.name())), nox_value, MatsimTestUtils.EPSILON, "the NOx value of this warm emission event was "+ Double.parseDouble(weg.get(NOx.name()))+ "but should have been "+ nox_value); + Assertions.assertEquals(Double.parseDouble(weg.get(PM.name())), pm_value, MatsimTestUtils.EPSILON, "the PM value of this warm emission event was "+ Double.parseDouble(weg.get(PM.name()))+ "but should have been "+ pm_value); + Assertions.assertEquals(Double.parseDouble(weg.get(SO2.name())), so2_value, MatsimTestUtils.EPSILON, "the SO2 value of this warm emission event was "+ Double.parseDouble(weg.get(SO2.name()))+ "but should have been "+ so2_value); } @Test @@ -98,12 +95,12 @@ final void testGetAttributesForIncompleteMaps(){ //the getAttributesMethod should // - return null if the emission map is empty // - throw NullPointerExceptions if the emission values are not set - // - throw NullPointerExceptions if no emission map is assigned - + // - throw NullPointerExceptions if no emission map is assigned + //empty map Map emptyMap = new HashMap<>(); WarmEmissionEvent emptyMapEvent = new WarmEmissionEvent(22., linkId, vehicleId, emptyMap); - + //values not set Map valuesNotSet = new HashMap<>(); valuesNotSet.put(CO, null); @@ -114,25 +111,23 @@ final void testGetAttributesForIncompleteMaps(){ valuesNotSet.put(NOx, null); valuesNotSet.put(PM, null); - Map map = new LinkedHashMap<>(); - valuesNotSet.forEach( (key,value) -> map.put( key, value ) ); - // (this could be made more direct) + Map map = new LinkedHashMap<>(valuesNotSet); WarmEmissionEvent valuesNotSetEvent = new WarmEmissionEvent(44., linkId, vehicleId, map); - + //no map WarmEmissionEvent noMap = new WarmEmissionEvent(23, linkId, vehicleId, null); - + int numberOfWarmPollutants = pollutants.size(); int valuesNotSetNullPointers =0, noMapNullPointers=0; - + for( Pollutant wpEnum : pollutants){ String wp=wpEnum.name(); //empty map Assertions.assertNull(emptyMapEvent.getAttributes().get(wp)); - + //values not set try{ valuesNotSetEvent.getAttributes().get(wp); @@ -140,7 +135,7 @@ final void testGetAttributesForIncompleteMaps(){ catch(NullPointerException e){ valuesNotSetNullPointers++; } - + //no map try{ noMap.getAttributes().get(wp); diff --git a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/example/RunDetailedEmissionToolOfflineExampleIT.java b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/example/RunDetailedEmissionToolOfflineExampleIT.java index e2ed6c54bba..09d0e9bc5b0 100644 --- a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/example/RunDetailedEmissionToolOfflineExampleIT.java +++ b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/example/RunDetailedEmissionToolOfflineExampleIT.java @@ -42,7 +42,7 @@ public class RunDetailedEmissionToolOfflineExampleIT { * * */ - // Expecting RuntimeException, because requested values are only in average file. Without fallback it has to fail! + // Expecting RuntimeException, because requested values are only in average file. Without fallback, it has to fail! // @Test(expected=RuntimeException.class) @Test final void testDetailed_vehTypeV1() { @@ -67,7 +67,7 @@ final void testDetailed_vehTypeV1() { Assertions.assertTrue( gotAnException ); } - // Expecting RuntimeException, because requested values are only in average file. Without fallback it has to fail! + // Expecting RuntimeException, because requested values are only in average file. Without fallback, it has to fail! // @Test(expected=RuntimeException.class) @Test final void testDetailed_vehTypeV2() { @@ -91,7 +91,7 @@ final void testDetailed_vehTypeV2() { Assertions.assertTrue( gotAnException ); } - // Expecting RuntimeException, because requested values are only in average file. Without fallback it has to fail! + // Expecting RuntimeException, because requested values are only in average file. Without fallback, it has to fail! // @Test(expected=RuntimeException.class) @Test final void testDetailed_vehTypeV2_HBEFA4() { diff --git a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/example/RunDetailedEmissionToolOnlineExampleIT_vehTypeV1.java b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/example/RunDetailedEmissionToolOnlineExampleIT_vehTypeV1.java index 1c16db00fa9..892803c548e 100644 --- a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/example/RunDetailedEmissionToolOnlineExampleIT_vehTypeV1.java +++ b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/example/RunDetailedEmissionToolOnlineExampleIT_vehTypeV1.java @@ -26,6 +26,7 @@ import org.matsim.contrib.emissions.utils.EmissionsConfigGroup; import org.matsim.core.config.Config; import org.matsim.core.config.ConfigUtils; +import org.matsim.core.scenario.ScenarioUtils; import org.matsim.testcases.MatsimTestUtils; /** @@ -45,21 +46,21 @@ public class RunDetailedEmissionToolOnlineExampleIT_vehTypeV1 { * This is by now (feb'20) the default. Setting it here for the tests explicitly * * */ -// @Test(expected=RuntimeException.class) // Expecting RuntimeException, because requested values are only in average file. Without fallback it has to fail! - @Disabled //Ignore this test, because the thrown exception during events handling does not always leads to an abort of the Simulation ->> Maybe a problem in @link{ParallelEventsManagerImpl.class}? +// @Test(expected=RuntimeException.class) // Expecting RuntimeException, because requested values are only in average file. Without fallback, it has to fail! + @Disabled //Ignore this test, because the thrown exception during events handling does not always lead to an abort of the Simulation ->> Maybe a problem in @link{ParallelEventsManagerImpl.class}? @Test final void testDetailed_vehTypeV1() { boolean gotAnException = false ; try { - RunDetailedEmissionToolOnlineExample onlineExample = new RunDetailedEmissionToolOnlineExample(); - Config config = onlineExample.prepareConfig( new String[]{"./scenarios/sampleScenario/testv2_Vehv1/config_detailed.xml"} ) ; + Config config = RunDetailedEmissionToolOnlineExample.prepareConfig( new String[]{"./scenarios/sampleScenario/testv2_Vehv1/config_detailed.xml"} ) ; config.controller().setOutputDirectory( utils.getOutputDirectory() ); config.controller().setLastIteration( 1 ); EmissionsConfigGroup emissionsConfig = ConfigUtils.addOrGetModule( config, EmissionsConfigGroup.class ); emissionsConfig.setHbefaVehicleDescriptionSource( EmissionsConfigGroup.HbefaVehicleDescriptionSource.fromVehicleTypeDescription ); emissionsConfig.setDetailedVsAverageLookupBehavior( EmissionsConfigGroup.DetailedVsAverageLookupBehavior.onlyTryDetailedElseAbort ); - Scenario scenario = onlineExample.prepareScenario( config ) ; - onlineExample.run( scenario ) ; + + Scenario scenario = ScenarioUtils.loadScenario(config); + RunDetailedEmissionToolOnlineExample.run( scenario ) ; } catch (Exception ee ) { gotAnException = true ; } diff --git a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/example/RunDetailedEmissionToolOnlineExampleIT_vehTypeV1FallbackToAverage.java b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/example/RunDetailedEmissionToolOnlineExampleIT_vehTypeV1FallbackToAverage.java index 8715b4525ed..21f6baf1404 100644 --- a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/example/RunDetailedEmissionToolOnlineExampleIT_vehTypeV1FallbackToAverage.java +++ b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/example/RunDetailedEmissionToolOnlineExampleIT_vehTypeV1FallbackToAverage.java @@ -26,6 +26,7 @@ import org.matsim.contrib.emissions.utils.EmissionsConfigGroup; import org.matsim.core.config.Config; import org.matsim.core.config.ConfigUtils; +import org.matsim.core.scenario.ScenarioUtils; import org.matsim.core.utils.io.IOUtils; import org.matsim.examples.ExamplesUtils; import org.matsim.testcases.MatsimTestUtils; @@ -65,7 +66,7 @@ final void testDetailed_vehTypeV1_FallbackToAverage() { emissionsConfig.setAverageWarmEmissionFactorsFile( "../sample_41_EFA_HOT_vehcat_2020average.csv" ); emissionsConfig.setHbefaTableConsistencyCheckingLevel( EmissionsConfigGroup.HbefaTableConsistencyCheckingLevel.consistent ); - Scenario scenario = RunDetailedEmissionToolOnlineExample.prepareScenario( config ) ; + Scenario scenario = ScenarioUtils.loadScenario(config); RunDetailedEmissionToolOnlineExample.run( scenario ) ; } catch ( Exception ee ) { ee.printStackTrace(); diff --git a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/example/RunDetailedEmissionToolOnlineExampleIT_vehTypeV2.java b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/example/RunDetailedEmissionToolOnlineExampleIT_vehTypeV2.java index 95cbc87199b..d6e33fc37f1 100644 --- a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/example/RunDetailedEmissionToolOnlineExampleIT_vehTypeV2.java +++ b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/example/RunDetailedEmissionToolOnlineExampleIT_vehTypeV2.java @@ -26,6 +26,7 @@ import org.matsim.contrib.emissions.utils.EmissionsConfigGroup; import org.matsim.core.config.Config; import org.matsim.core.config.ConfigUtils; +import org.matsim.core.scenario.ScenarioUtils; import org.matsim.testcases.MatsimTestUtils; /** @@ -39,20 +40,20 @@ public class RunDetailedEmissionToolOnlineExampleIT_vehTypeV2 { * Test method for {@link RunDetailedEmissionToolOnlineExample#main(String[])}. */ -// @Test(expected=RuntimeException.class) // Expecting RuntimeException, because requested values are only in average file. Without fallback it has to fail! - @Disabled //Ignore this test, because the thrown exception during events handling does not always leads to an abort of the Simulation ->> Maybe a problem in @link{ParallelEventsManagerImpl.class}? +// @Test(expected=RuntimeException.class) // Expecting RuntimeException, because requested values are only in average file. Without fallback, it has to fail! + @Disabled //Ignore this test, because the thrown exception during events handling does not always lead to an abort of the Simulation ->> Maybe a problem in @link{ParallelEventsManagerImpl.class}? @Test final void testDetailed_vehTypeV2() { boolean gotAnException = false ; try { - RunDetailedEmissionToolOnlineExample onlineExample = new RunDetailedEmissionToolOnlineExample(); - Config config = onlineExample.prepareConfig( new String[]{"./scenarios/sampleScenario/testv2_Vehv2/config_detailed.xml"} ) ; + Config config = RunDetailedEmissionToolOnlineExample.prepareConfig( new String[]{"./scenarios/sampleScenario/testv2_Vehv2/config_detailed.xml"} ) ; config.controller().setOutputDirectory( utils.getOutputDirectory() ); config.controller().setLastIteration( 1 ); EmissionsConfigGroup emissionsConfig = ConfigUtils.addOrGetModule( config, EmissionsConfigGroup.class ); emissionsConfig.setDetailedVsAverageLookupBehavior( EmissionsConfigGroup.DetailedVsAverageLookupBehavior.onlyTryDetailedElseAbort ); - Scenario scenario = onlineExample.prepareScenario( config ) ; - onlineExample.run( scenario ) ; + + Scenario scenario = ScenarioUtils.loadScenario(config); + RunDetailedEmissionToolOnlineExample.run( scenario ) ; } catch (Exception ee ) { gotAnException = true ; } diff --git a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/example/RunDetailedEmissionToolOnlineExampleIT_vehTypeV2FallbackToAverage.java b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/example/RunDetailedEmissionToolOnlineExampleIT_vehTypeV2FallbackToAverage.java index ef667425698..2c89b956450 100644 --- a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/example/RunDetailedEmissionToolOnlineExampleIT_vehTypeV2FallbackToAverage.java +++ b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/example/RunDetailedEmissionToolOnlineExampleIT_vehTypeV2FallbackToAverage.java @@ -27,6 +27,7 @@ import org.matsim.contrib.emissions.utils.EmissionsConfigGroup.DetailedVsAverageLookupBehavior; import org.matsim.core.config.Config; import org.matsim.core.config.ConfigUtils; +import org.matsim.core.scenario.ScenarioUtils; import org.matsim.core.utils.io.IOUtils; import org.matsim.examples.ExamplesUtils; import org.matsim.testcases.MatsimTestUtils; @@ -44,9 +45,6 @@ public class RunDetailedEmissionToolOnlineExampleIT_vehTypeV2FallbackToAverage { @Test final void testDetailed_vehTypeV2_FallbackToAverage() { try { -// RunDetailedEmissionToolOnlineExample onlineExample = new RunDetailedEmissionToolOnlineExample(); - -// Config config = onlineExample.prepareConfig( new String[]{"./scenarios/sampleScenario/testv2_Vehv2/config_detailed.xml"} ) ; var scenarioUrl = ExamplesUtils.getTestScenarioURL( "emissions-sampleScenario/testv2_Vehv2" ); var configUrl = IOUtils.extendUrl( scenarioUrl, "config_detailed.xml" ); Config config = RunDetailedEmissionToolOnlineExample.prepareConfig( new String [] { configUrl.toString() } ); @@ -60,7 +58,7 @@ final void testDetailed_vehTypeV2_FallbackToAverage() { emissionsConfig.setAverageWarmEmissionFactorsFile( "../sample_41_EFA_HOT_vehcat_2020average.csv" ); emissionsConfig.setHbefaTableConsistencyCheckingLevel( EmissionsConfigGroup.HbefaTableConsistencyCheckingLevel.consistent ); - Scenario scenario = RunDetailedEmissionToolOnlineExample.prepareScenario( config ) ; + Scenario scenario = ScenarioUtils.loadScenario(config); RunDetailedEmissionToolOnlineExample.run( scenario ) ; } catch ( Exception ee ) { ee.printStackTrace(); diff --git a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/utils/EmissionUtilsTest.java b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/utils/EmissionUtilsTest.java index 4f20dfbf78f..f71692faa5e 100644 --- a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/utils/EmissionUtilsTest.java +++ b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/utils/EmissionUtilsTest.java @@ -52,8 +52,8 @@ * missing data is not tested here * negative emission values are allowed * 1 test constructor - * 2 test sumUpEmissions - * 3 test sumUpEmissionPerId + * 2 test sumUpEmissions + * 3 test sumUpEmissionPerId * 4 test getTotalEmissions * 5 test SetNonCalculatedEmissionsForPopulation * - correct input - population does not match map of emissions - empty map of emissions @@ -74,8 +74,6 @@ public class EmissionUtilsTest { private boolean nullPointerEx; public static Map createUntypedEmissions() { -// return Arrays.asList("co2", CO, NOx, "NO", NO2, HC).stream() -// .collect(Collectors.toMap(p -> p, p -> Math.random())); return Stream.of(CO2_TOTAL, CO, NOx, NO2, HC) .collect(Collectors.toMap(p -> p, p -> Math.random())); } @@ -292,7 +290,7 @@ final void testGetTotalEmissions_completeData() { //put some content into the list // no incorrect/incomplete input data here - // warm and cold emissions are already sumed up -> sumUpEmissionsPerId is tested seperatly + // warm and cold emissions are already summed up -> sumUpEmissionsPerId is tested separately //person1 SortedMap allEmissionsP1 = new TreeMap<>(); @@ -430,7 +428,7 @@ final void testSetNonCalculatedEmissionsForPopulation_completeData(){ //check: all values for person 1 and 2 are not null or zero // and of type double for(Object id : finalMap.keySet()) { - Assertions.assertTrue(id instanceof Id); + Assertions.assertInstanceOf(Id.class, id); for (Object pollutant : finalMap.get(id).values()) { Assertions.assertSame(pollutant.getClass(), Double.class); Assertions.assertNotSame(0.0, pollutant); @@ -442,7 +440,7 @@ final void testSetNonCalculatedEmissionsForPopulation_completeData(){ } //nothing else in the list int numOfPolls = pollsFromEU.size(); - Assertions.assertEquals(numOfPolls, finalMap.get(id).keySet().size(), "the number of pullutants is " + finalMap.get(id).keySet().size() + " but should be" + numOfPolls); + Assertions.assertEquals(numOfPolls, finalMap.get(id).keySet().size(), "the number of pollutants is " + finalMap.get(id).keySet().size() + " but should be" + numOfPolls); } //check: values for all emissions are correct -person 1 @@ -486,11 +484,11 @@ final void testSetNonCalculatedEmissionsForPopulation_missingMap() { message = "the calculated map should contain " + pop.getPersons().size() + " person(s) but contains " + finalMap.keySet().size() + "person(s)."; Assertions.assertEquals(pop.getPersons().keySet().size(), finalMap.keySet().size(), message); - //check: all values for the this person are zero and of type double - for (Object pollutant : finalMap.get(idp3).values()) { - Assertions.assertSame(pollutant.getClass(), Double.class); - Assertions.assertEquals(0.0, (Double) pollutant, MatsimTestUtils.EPSILON); - Assertions.assertNotNull(pollutant); + //check: all values for this person are zero and of type double + for (Double pollutantValues : finalMap.get(idp3).values()) { + Assertions.assertSame(pollutantValues.getClass(), Double.class); + Assertions.assertEquals(0.0, pollutantValues, MatsimTestUtils.EPSILON); + Assertions.assertNotNull(pollutantValues); } //check: all types of emissions appear for (Pollutant emission : pollsFromEU) { @@ -498,7 +496,7 @@ final void testSetNonCalculatedEmissionsForPopulation_missingMap() { } //nothing else in the list int numOfPolls = pollsFromEU.size(); - message = "the number of pullutants is " + finalMap.get(idp3).keySet().size() + " but should be" + numOfPolls; + message = "the number of pollutants is " + finalMap.get(idp3).keySet().size() + " but should be" + numOfPolls; Assertions.assertEquals(numOfPolls, finalMap.get(idp3).keySet().size(), message); } @@ -553,7 +551,7 @@ final void testSetNonCalculatedEmissionsForPopulation_nullEmissions(){ //test setNonCalculatedEmissionsForPopulation with 'null' // throw nullpointer exception setUpForNonCaculatedEmissions(); - + Id idp5 = Id.create("p5", Person.class); Person p5 = populationFactory.createPerson(idp5); pop.addPerson(p5); @@ -576,7 +574,7 @@ final void testSetNonCalculatedEmissionsForPopulation_emptyPopulation(){ // empty list should be returned setUpForNonCaculatedEmissions(); - //person 7 in totalEmissions but not in population + //person 7 in totalEmissions but not in population SortedMap p7Emissions = new TreeMap<>(); //complete list of all pollutants - missing data is not tested here p7Emissions.put( CO, .0 ); @@ -625,9 +623,9 @@ final void testSetNonCalculatedEmissionsForPopulation_emptyEmissionMap() { //check: all values for all persons are zero and of type double for (Id id : finalMap.keySet()) { - for (Object pollutant : finalMap.get(id).values()) { + for (Double pollutant : finalMap.get(id).values()) { Assertions.assertSame(pollutant.getClass(), Double.class); - Assertions.assertEquals(0.0, (Double) pollutant, MatsimTestUtils.EPSILON, "map of pollutants was missing. Therefore all values should be set to zero."); + Assertions.assertEquals(0.0, pollutant, MatsimTestUtils.EPSILON, "map of pollutants was missing. Therefore all values should be set to zero."); Assertions.assertNotNull(pollutant); } //check: alle types of emissions appear @@ -793,10 +791,6 @@ public static Map createEmissions() { return Arrays.stream( Pollutant.values() ).collect( Collectors.toMap( p -> p, p -> Math.random() ) ) ; } -// public static Map createEmissionsWithFixedValue(double value) { -// return Arrays.asList("co2", CO, NOx, "NO", NO2, HC).stream() -// .collect(Collectors.toMap(p -> p, p -> value)); -// } public static Map createEmissionsWithFixedValue( double value ) { return Arrays.stream( Pollutant.values() ).collect( Collectors.toMap( p -> p, p -> value ) ) ; } @@ -815,6 +809,6 @@ private void addLinksToNetwork(Scenario sc) { NetworkUtils.createAndAddLink(network, Id.create("link24", Link.class), node2, node4, 1000., 20., 3600, 2); NetworkUtils.createAndAddLink(network, Id.create("link34", Link.class), node3, node4, 1000., 20., 3600, 2); //w/o orig id and type } - + } - +