API¶
Truck Input Parameter¶
-
class carculator_truck.truck_input_parameters.TruckInputParameters(parameters: str | Path | list =
None, extra: str | Path | list =None)¶
Array¶
-
carculator_utils.array.fill_xarray_from_input_parameters(input_parameters, sensitivity=
False, scope=None)¶ Build a labelled vehicle array from static or sampled input parameters.
- Parameters:¶
- input_parameters¶
A
VehicleInputParameterssubclass afterstatic()orstochastic()has populated its values.- sensitivity=
False¶ Produce a reference and one-at-a-time 10% perturbations. Requires static inputs.
- scope=
None¶ Optional size, powertrain and native-year selections. The supplied dictionary is not mutated; required PHEV modes are added locally.
- Returns:¶
(mappings, array). Mappings are ordered as size, powertrain, parameter and year. The array dimensions aresize,powertrain,parameter,yearandvalue.
Missing static cells retain the legacy zero convention and overlapping records retain first-entry precedence. Build bracketing native years before using
array.interp(year=...)for annual interpolation.
Driving cycle¶
- carculator_truck.driving_cycles.get_driving_cycle(size: list, name: str) ndarray¶
Get driving cycle.
- carculator_truck.driving_cycles.get_road_gradient(size: list, name: str) ndarray¶
Get road gradient data.
Energy consumption¶
energy_consumption.py contains the class EnergyConsumption Model which exposes two methods: one for calculating the auxiliary energy needs, and another one for calculating the motive energy needs.
-
class carculator_utils.energy_consumption.EnergyConsumptionModel(vehicle_type: str, vehicle_size: list[str], powertrains: list[str], cycle: str | ndarray, gradient: str | ndarray, rho_air: float =
1.204, country: str ='CH', ambient_temperature: float | ndarray =None, indoor_temperature: float | ndarray =20)¶ Calculate energy consumption of a vehicle for a given driving_cycles and vehicle parameters.
Based on a selected driving_cycles, this class calculates the acceleration needed and provides two methods:
aux_energy_per_km()calculates the energy needed to power auxiliary servicesmotive_energy_per_km()calculates the energy needed to move the vehicle over 1 km
Acceleration is calculated as the difference between velocity at t_2 and velocity at t_0, divided by 2. See for example: http://www.unece.org/fileadmin/DAM/trans/doc/2012/wp29grpe/WLTP-DHC-12-07e.xls
- Parameters:¶
- cycle : str or numpy.ndarray¶
Named cycle or array of second-by-second speeds (km/h). Every custom-array sample is an operating second, including terminal stops. Trim storage padding before supplying a custom array.
- rho_air : float¶
Air density, default 1.204 kg/m3 at 23 degrees Celsius.
- gradient : numpy.ndarray¶
User-supplied road gradient per second, in degrees, overriding the gradient of either a named or custom cycle. None by default. A numeric array must match the cycle length.
- ambient_temperature: float | ndarray =
None¶ Celsius scalar or twelve monthly temperatures; None uses the selected country’s bundled series for HVAC.
- indoor_temperature: float | ndarray =
20¶ Fixed cabin assumption: 20 degrees Celsius, either as a scalar or twelve identical monthly values. Other settings raise ValueError because cabin-setpoint sensitivity is not modelled.
velocityis the speed time series in m/s.accelerationis its one-second centred difference in m/s2; both are calculated attributes.-
aux_energy_per_km(aux_power: DataArray | array, efficiency: DataArray | array, hvac_power: DataArray | array =
None, battery_cooling_unit: DataArray | array =None, battery_heating_unit: DataArray | array =None, heat_pump_cop_cooling: DataArray | array =None, heat_pump_cop_heating: DataArray | array =None, cooling_consumption: DataArray | array =None, heating_consumption: DataArray | array =None) tuple[Any, Any, Any, Any, Any] | Any¶ Calculate energy used other than motive energy per km driven.
- Parameters:¶
- aux_power: DataArray | array¶
Total power needed for auxiliaries, heating, and cooling (W)
- efficiency: DataArray | array¶
Efficiency of electricity generation (dimensionless, between 0.0 and 1.0). Battery electric vehicles should have efficiencies of one here, as we account for battery efficiencies elsewhere.
- Returns:¶
total auxiliary energy in kJ/km
- find_last_driving_second() ndarray¶
Find the last second of the driving_cycles that is not zero.
-
motive_energy_per_km(driving_mass: DataArray | array, rr_coef: DataArray | array, drag_coef: DataArray | array, frontal_area: DataArray | array, electric_motor_power: DataArray | array, engine_power: DataArray | array, recuperation_efficiency: DataArray | array, aux_power: DataArray | array, battery_charge_eff: DataArray | array, battery_discharge_eff: DataArray | array, engine_efficiency: DataArray | array | None =
None, transmission_efficiency: DataArray | array | None =None, fuel_cell_system_efficiency: DataArray | array =None, hvac_power: DataArray | array =None, battery_cooling_unit: DataArray | array =None, battery_heating_unit: DataArray | array =None, heat_pump_cop_cooling: DataArray | array =None, heat_pump_cop_heating: DataArray | array =None, cooling_consumption: DataArray | array =None, heating_consumption: DataArray | array =None, electric_motor_efficiency: DataArray | array | float =0.9, combustion_engine_power: DataArray | array | None =None, engine_efficiency_factor: DataArray | array | float =1.0, combustion_controls: dict =None) DataArray¶ Calculate energy used and recuperated for a given vehicle per km driven.
- Parameters:¶
- driving_mass: DataArray | array¶
Mass of vehicle (kg)
- rr_coef: DataArray | array¶
Rolling resistance coefficient (dimensionless, between 0.0 and 1.0)
- drag_coef: DataArray | array¶
Aerodynamic drag coefficient (dimensionless, between 0.0 and 1.0)
- frontal_area: DataArray | array¶
Frontal area of vehicle (m2)
- electric_motor_power: DataArray | array¶
Electric motor power (watts). Optional.
- engine_efficiency_factor: DataArray | array | float =
1.0¶ Multiplicative map correction in (0, 1].
- combustion_controls: dict =
None¶ Optional conventional petrol-car operating controls keyed by (powertrain, size, year). Control fuel is returned separately as
combustion control energy(kJ per sample). Applies before fuel conversion; explicit efficiency overrides take precedence.
- Returns:¶
Labelled per-second energy components and operating traces. Energy components are kJ per one-second sample; the vehicle model integrates them to obtain consumption per kilometre.
Power to overcome rolling resistance is calculated by:
\[g v M C_{r}\]where \(g\) is 9.81 (m/s2), \(v\) is velocity (m/s), \(M\) is mass (kg), and \(C_{r}\) is the rolling resistance coefficient (dimensionless).
Power to overcome air resistance is calculated by:
\[\frac{1}{2} \rho_{air} v^{3} A C_{d}\]where \(\rho_{air}\) is 1.225 (kg/m3), \(v\) is velocity (m/s), \(A\) is frontal area (m2), and \(C_{d}\) is the aerodynamic drag coefficient (dimensionless).
- carculator_utils.energy_consumption.efficiency_override(value, shape)¶
Broadcast fixed efficiencies; masked cells retain load-map behaviour.
- carculator_utils.energy_consumption.get_country_temperature(country: str) ndarray¶
Read January–December temperatures in degrees Celsius.
Use the first bundled city row for the requested country code. Missing countries require explicit ambient temperatures; a different country’s climate is never silently substituted. These city proxies are not national driving-weighted climate observations.
- carculator_utils.energy_consumption.get_default_driving_cycle_name(vehicle_type) str¶
Get the default driving_cycles name
- carculator_utils.energy_consumption.validate_hvac_indoor_temperature(value: float | ndarray)¶
Retain the empirical HVAC model’s fixed 20-degree cabin assumption.
Accept a scalar or twelve monthly values, all equal to 20 degrees Celsius. Return a scalar or private array; other cabin settings are not modelled.
Truck Model¶
-
class carculator_truck.model.TruckModel(array, *args, cost_overrides=
None, hybrid_battery=None, fuel_cell_battery=None, **kwargs)¶ This class represents the entirety of the vehicles considered, with useful attributes, such as an array that stores all the vehicles parameters.
arrayis the labelled parameter array.ecmis the energy-consumption model created for the selected driving cycle during a completed run.-
calculate_cost_impacts(sensitivity=
False, scope=None)¶ This method returns an array with cost values per vehicle-km, subdivided into the following groups:
Purchase
Maintenance
Component replacement
Energy
Total cost of ownership
- calculate_hybrid_buffer()¶
Size and cycle the HEV pack on the current mass-dependent trace.
- calculate_ttw_energy()¶
This method calculates the energy required to operate auxiliary services as well as to move the vehicle. The sum is stored under the parameter label “TtW energy” in
self.array.
- check_fuel_cell_battery_power()¶
Reject an undersized supplied pack after the mass iteration converges.
- create_PHEV()¶
Combine driving modes while retaining the actual depot charger specs.
- fuel_cell_battery_capacity_requirement()¶
Check cycle discharge at the DC bus, retaining unmet speed-trace demand.
- override_range()¶
Set storage size or range for each powertrain.
This method sets the energy consumption of vehicles that are not available to zero.
-
set_all(electric_utility_factor: float =
None)¶ This method runs a series of other methods to obtain the tank-to-wheel energy requirement, efficiency of the vehicle, costs, etc.
set_component_masses(),set_vehicle_masses()andset_power_parameters()andset_energy_stored_properties()relate to one another. powertrain_mass depends on power, curb_mass is affected by changes in powertrain_mass, combustion engine mass, electric engine mass. energy battery mass is influencedby the curb mass but also by the target range the truck has. power is also varying with curb_mass.Sizing converges driving mass, available payload, battery mass, fuel mass and TtW energy together to a relative tolerance of 1e-6 per active vehicle, year and sample. Payload limits are applied within the loop. The final energy trace uses the final driving mass. Iterations are bounded; nonconvergence raises rather than returning a partial vehicle. Numerical convergence does not establish real-world duty feasibility.
- set_battery_chemistry()¶
Extension hook for downstream battery chemistry defaults.
Subclasses can populate
self.energy_storagebefore battery preferences are applied. The base implementation intentionally does nothing.
- set_battery_fuel_cell_replacements()¶
Calculate battery and fuel-cell replacement demand.
After sizing, each zero supplied battery replacement input requests a calculation from final lifetime energy throughput and chemistry-specific cycle life, clipped to 0–3 for charger-equipped vehicles. Nonzero supplied inputs are retained per vehicle, year and sample. The factor is not rounded up and there is no mandatory replacement battery. Production is allocated to this vehicle without a second-life credit. Fuel cells use a separate lifetime-hours calculation, rounded up.
PHEV lifetime energy is weighted by electric driving share BEFORE subtracting the initial pack and clipping. The resulting physical count belongs to both modes. Nonzero PHEV count inputs are whole-vehicle counts; conflicting values for the same pack are rejected rather than averaged. This retains the net stored-energy approximation, nominal-capacity EFC convention and absence of a separate truck calendar-age limit.
- set_battery_preferences()¶
Apply high-power cell density to the default HEV LFP pack.
Other explicit chemistries retain their density and cycle life; the electrical envelope is a transfer assumption unless the caller also supplies a matching
hybrid_batteryprofile.
- set_cargo_mass_and_annual_mileage()¶
Set the cargo mass and annual mileage of the vehicles.
- set_costs()¶
Calculate the different cost types. :return:
-
set_depot_infrastructure_costs(charger_power_kw, charger_life_years, infra_wacc, capex_per_kw, install_per_kw, connection_per_kw, fixed_om_share, capacity_charge_per_kw_year, trucks_per_charger, annual_km_per_truck, consumption_kwh_per_km_at_plug, availability=
0.98, efficiency=0.94)¶ Returns a DataArray of depot infra surcharge in €/kWh with full xarray broadcasting. All inputs can be scalars or DataArrays aligned/broadcastable to your model dims.
-
set_electric_utility_factor(uf: float =
None) None¶ The electric utility factor is the share of km driven in battery-depleting mode over the required range autonomy. Scania’s PHEV tractor can drive 60 km in electric mode
- set_energy_stored_properties()¶
First, fuel mass is defined. It is dependent on the range required. Then batteries are sized, depending on the range required and the energy consumption.
- set_fuel_cell_mass()¶
Size the stack without replacing the truck’s final energy-sized pack.
- set_power_battery_properties()¶
Keep the HEV starter separate from its lithium-ion traction pack.
- set_power_parameters()¶
Use a declared shaft rating where supplied, then caller overrides.
Zero or absent
rated powerretains mass-based sizing. Keeping a documented rating independent of curb mass avoids shrinking a motor when storage or other components become lighter. Values are in kW.
Apply the finite HEV buffer to the inherited brake-wear credit.
-
calculate_cost_impacts(sensitivity=
Noise Model¶
noise_emissions.py contains NoiseEmissionsModel which calculates noise emissions, in joules, given a driving_cycles and a powertrain type.
- class carculator_utils.noise_emissions.NoiseEmissionsModel(velocity: DataArray, vehicle_type: str)¶
Calculate propulsion and rolling noise emissions for combustion, hybrid and electric vehicles, based on CNOSSOS model.
- Parameters:¶
- velocity : pandas.Series¶
Driving cycle. Pandas Series of second-by-second speeds (km/h) or name (str) of cycle e.g., “WLTC”,”WLTC 3.1”,”WLTC 3.2”,”WLTC 3.3”,”WLTC 3.4”,”CADC Urban”,”CADC Road”, “CADC Motorway”,”CADC Motorway 130”,”CADC”,”NEDC”.
- get_sound_power_per_compartment() ndarray¶
Calculate sound energy (in J/s) over the driving_cycles duration from sound power (in dB). The sound energy sums are further divided into geographical compartments: urban, suburban and rural, based on the profile of the driving_cycles.
- propulsion_noise() ndarray¶
Calculate noise from propulsion engine and gearbox. Model from CNOSSOS-EU project (http://publications.jrc.ec.europa.eu/repository/bitstream/JRC72550/cnossos-eu%20jrc%20reference%20report_final_on%20line%20version_10%20august%202012.pdf)
For electric cars, special coefficients are applied from (Pallas et al. 2016 )
Also, for electric cars, a warning signal of 56 dB is added when the car drives at 20 km/h or lower.
- rolling_noise() ndarray¶
Calculate noise from rolling friction. Model from CNOSSOS-EU project (http://publications.jrc.ec.europa.eu/repository/bitstream/JRC72550/cnossos-eu%20jrc%20reference%20report_final_on%20line%20version_10%20august%202012.pdf)
- carculator_utils.noise_emissions.get_noise_coefficients(filepath: Path) None | DataArray¶
Noise coefficients extracted for vehicles from CNOSSOS-EU 2018 detailed by size, powertrain and EURO class for each octave.
Hot pollutants emissions¶
hot_emissions.py contains HotEmissionModel which calculates fuel-related exhaust emissions.
- class carculator_utils.hot_emissions.HotEmissionsModel(powertrains: array, sizes: array, velocity: ndarray, cycle_name: str, vehicle_type: str)¶
Calculate hot pollutants emissions from the bundled HBEFA-derived tables, function of fuel consumption for vehicles with a combustion engine.
- Parameters:¶
- get_hot_emissions(euro_class: list[int], lifetime_km: DataArray, energy_consumption: DataArray, yearly_km: DataArray) DataArray¶
Calculate hot pollutants emissions given a powertrain type (i.e., diesel, petrol, CNG) and a EURO pollution class, per air sub-compartment (i.e., urban, suburban and rural). Note that Nh3 and N2O emissions do not depend on the speed level. For those, average values observed across different traffic situations are used instead. Also includes cold start emissions. Cold start emissions are also given by HBEFA 4.1 and expressed in given in g/start. Cold start emissions are divided by the average trip length in Europe (20 km), to normalize them per km.
The emission sums are further divided into air compartments: urban, suburban and rural.
urban: from 0 to 50 km/k
suburban: from 51 km/h to 80 km/h
rural: above 80 km/h
- Parameters:¶
- lifetime_km: DataArray¶
Lifetime distance by vehicle and sample (km).
- euro_class: list[int]¶
integer, corresponding to the EURO pollution class
- energy_consumption: DataArray¶
tank-to-wheel energy consumption for each second of the driving_cycles
- yearly_km: DataArray¶
annual mileage, to calculate cold start emissions
- Returns:¶
Pollutants emission per km driven, per air compartment.
- carculator_utils.hot_emissions.get_emission_factors(filepath) [Any, None]¶
Load shipped emission coefficients; the exact HBEFA version is unverified. detailed by size, powertrain and EURO class for each substance.
- carculator_utils.hot_emissions.get_mileage_degradation_factor(lifetime_km: DataArray, euro_class: list[int], powertrains: list[str], vehicle_type: str) [<class 'xarray.core.dataarray.DataArray'>, None]¶
Catalyst degrade overtime, leading to increased emissions of CO, HC and NOX. We apply a correction factor from HBEFA 4.1 to reflect this. :return:
Inventory calculation¶
inventory.py contains Inventory which provides all methods to solve inventories.
-
class carculator_truck.inventory.InventoryTruck(vm, background_configuration: dict =
None, scenario: str ='SSP2-NPi', method: str ='recipe', indicator: str ='midpoint', functional_unit: str ='vkm')¶ Build and solve the inventory for results characterization and inventory export
- add_depot_chargers()¶
Allocate the 200-kW charger reference over lifetime grid throughput.
- fill_in_A_matrix()¶
Fill-in the A matrix. Does not return anything. Modifies in place. Shape of the A matrix (values, products, activities).
arrayfromCarModelclass
Temporal lifecycle policy¶
Inventory export¶
export.py contains the class Export, which offers methods to export the inventories in different formats.
-
class carculator_utils.export.ExportInventory(array, vehicle_model, indices, db_name=
'carculator_utils export')¶ Export the inventory to various formats
- format_data_for_lci_for_simapro(data: list[dict], ei_version: str) list[list]¶
Return Brightpath-rendered SimaPro rows (before file encoding).
- rename_vehicles() None¶
Rename powertrain acronyms to full length descriptive terms
-
write_bw2_lci(ecoinvent_version, directory=
None, filename=None, export_format='file')¶ Export Brightway Excel files/bytes or unlinked bw2io importers.
- write_lci(ecoinvent_version: str, year: int) list[dict]¶
Return activities and exchanges for a single retained value sample.
Select one sample before constructing the vehicle model and inventory. Its label may be numeric or a sensitivity parameter name.
-
write_openlca_lci(ecoinvent_version, directory=
None, filename=None, export_format='file', method_mapping=None)¶ Export a foreground-only openLCA JSON-LD ZIP as a file or bytes.
-
write_simapro_lci(ecoinvent_version, directory=
None, filename=None, export_format='file')¶ Export Latin-1 SimaPro CSV files or their decoded contents.
- carculator_utils.export.load_mapping(filename) dict[tuple[str, str, str, str], tuple[str, str, str, str]]¶
Load mapping dictionary between two versions of ecoinvent.
- carculator_utils.export.load_references() dict¶
Load LCIs to fetch metadata from.
- carculator_utils.export.rename_mapping(filename: str) dict[str, str]¶
Load the file rename_powertrains.yaml and return a dictionary
- carculator_utils.export.safe_filename(name: str) str¶
Return a filename-safe string without requiring bw2io at import time.
Background systems¶
background_systems.py contains BackgroundSystem, which contains different arrays relating to the evolution of fuel blends, sulfur content in fuels, and electricity mixes in different countries over time.
-
class carculator_utils.background_systems.BackgroundSystemModel(electricity_scenario: str =
'geco-2025-reference')¶ Retrieve and build dictionaries that contain important information to model in the background system:
historical electricity generation and explicit country/regional projections through 2070.
cumulative electricity transformation/transmission/distribution losses from high voltage to medium and low voltage.
share of biomass-derived fuel in the total consumption of liquid fuel in the transport sector. Source: REMIND.
share of bioethanol, biodiesel and biomethane, for each country, for different years.
share of sulfur in gasoline and diesel, for different countries and years.
- define_fuel_blends(powertrains: list[str], country: str, years: list[int]) dict¶
This function defines fuel blends from what is passed in fuel_blend. It populates a dictionary self.fuel_blends that contains the respective shares, lower heating values and CO2 emission factors of the fuels used.
Source for LHV: https://www.bafu.admin.ch/bafu/en/home/topics/climate/state/data/climate-reporting/references.html
- Returns:¶
Find fuel shares for a country and ordered model years.
Default hydrogen uses the configured primary route at 100% in every country and year (currently natural-gas steam methane reforming). This is a fallback assumption, independent of the biofuel tables. Explicit model fuel-blend overrides are validated separately.
Interpolate bundled country biofuel shares in the requested year order.
Retain supplied shares above 30%, including pure biofuel. Linear extrapolation uses the physical fraction bounds [0, 1]. The source arrays are unchanged; a single requested year retains scalar output.
- carculator_utils.background_systems.data_to_dict(csv_list: list) dict¶
Returns a dictionary from a sequence of items. :param csv_list: list :return: dict
Biodiesel shares in the fuel blend, by country and year.
- carculator_utils.background_systems.get_default_fuels() dict¶
Import default fuels from default_fuels.yaml
- carculator_utils.background_systems.get_electricity_losses() dict[str, float]¶
Retrieve cumulative electricity losses from high to medium and low voltage. Source: ecoinvent v.3.6.
-
carculator_utils.background_systems.get_electricity_mix(scenario: str =
'geco-2025-reference') DataArray¶ Retrieve validated Ember/GECO generation shares, or the legacy dataset.
- carculator_utils.background_systems.get_fuels_specs() dict¶
Import fuel specifications from fuel_specs.yaml Contains names, LHV, CO2 emission factors.
- carculator_utils.background_systems.get_sulfur_content_in_fuel() DataArray¶
Retrieve sulfur content per kg of petrol and diesel. For CH, DE, FR, AU and SE, the concentration values come from HBEFA 4.1, from 1909 to 2020 (extrapolated to 2050).
For the other countries, values come from Miller, J. D., & Jin, L. (2019). Global progress toward soot-free diesel vehicles in 2019. International Council on Clean Transportation. https://www.theicct.org/publications/global-progress-toward-soot-free-diesel-vehicles-2019
There is an assumption made: countries that have high-sulfur content fuels (above 50 ppm in 2019) are assumed to improve over time to reach 50 ppm by 2050.
Return known unsupported fuel labels and explicit reasons, without fallback.