

\section{Material and Methods}

\subsubsection*{Traffic data}
 
 Traffic simulations usually include morning peak flow for light duty vehicles (LDV) and heavy duty vehicles (HDV) at morning peak hour. It also includes average speed, free flow speed, capacity and length of the link. These data inputs were used in a study of the implementation of VEIN for São Paulo, as shown in Figure \ref{fig:fig}a. 
 The traffic data is processed as:
    \begin{equation}
    F_{i,j,k}=Q_{i} \cdot VC_{i,j} \cdot TF_{j,k}
    \label{eq:F}
    \end{equation}
    
 In Equation \ref{eq:F}, $F_{i,j,k}$ is the vehicular flow at street link $i$ for vehicle type $j$ and hour of the week $k$.  $Q_i$ is the traffic flow at street link $i$. $VC_{i,j}$ is the vehicular composition which identifies the type of vehicle \textit{j} for street link $i$. 
 
\textit{TF} are the temporal factors used to expand the morning traffic data \textit{Q} to each hour \textit{k}.  The age of use is an important parameter because it enables annual distributions. The distribution can be obtained with traffic databases or by applying a distribution based on average age. VEIN can produce age distributions with the \textit{age*} functions or use other yearly statistics data such as sales or registrations. In the São Paulo study, Figure ??%\ref{fig:ages}
shows traffic distributed with the green curve of distribution based on data from a top-down emissions inventory report for São Paulo \citealt{CETESB2015}. This data is based on vehicles sales. Figure ??%\ref{fig:ages} 
also shows other modeled age distributions. 

 Traffic simulations are normally applied at morning peak hour, between 08:00-09:00. Traffic data can be estimated from short period traffic counts datasets then expanded to represent longer timespan, such as Annual Average Daily Traffic (AADT) \citep{wang2009forecasting, lam2000estimation}. In order to expand traffic to other hours, \textit{TF} matrices must be normalized to the hour which represents the traffic data. It means that \textit{TF} values at morning peak hour must be 1 and the respective proportion must be assigned to the other hours. For example, \textit{TF} values can be obtained from automatic traffic count stations. In the São Paulo study, traffic counts were sourced from toll stations near the western part of São Paulo City. For the São Paulo case, \textit{TF} was calculated with hourly data of toll stations from the supplied by the Transport Agency of São Paulo State \cite{artesp}, shown in Figure ???%\ref{fig:tf}.
 
 Once the vehicular flow is identified for each hour, it is also important to identify the average speed for each hour. This was accomplished by employing curves from the Bureau of Public Roads (BPR) \cite{bpr}, as shown in Equation \ref{eq:bpr}. The process involved calculating speed by dividing the length of road by the time. The time was calculated using the traffic $Q_{i,k}$ expanded to each hour $k$, as shown in Equation \ref{eq:F}. 
 
 \begin{equation}
   T_{i,k} = To_i \cdot \left(1 +\alpha \cdot \left(\dfrac{Q_{i,k}}{C_i}\right)^\beta \right)
       \label{eq:bpr}
  \end{equation}
 
where $T_i$ is the travel time per street link $i$ at each hour of the week $k$, $To_i$ is the travel time under free flow conditions where maximums speed was used, $Q_{i,k}$ is the traffic flow at peak hour for each street link $i$ and hour of the week $k$, $C_i$ is the capacity of vehicles on street link $i$, and $\alpha$ and $\beta$ are parameters for adjustment, taken as 0.15 and 4 respectively. These values come from recommendations by BPR. However, the user can use other values. When there is no available information for curves (BPR for example), it is possible to apply a simple average between peak and free flow speeds, in order to obtain the average speeds at different hours.

VEIN estimates the following types of vehicular emissions:  hot exhaust, cold start, evaporative, wear, resuspension and performs speciation. In order to describe the VEIN methods in a concise way, this paper only outlines the estimation of hot exhaust emissions. However, the process to estimate other types of emissions is very similar in VEIN.

    \subsubsection*{Emission methods}
    
	A emissions factor is the amount of pollutant released by the vehicle per distance traveled under specific driving conditions. The VEIN process of emissions estimation is shown in Equation \ref{eq:emi}. VEIN includes includes three options for emissions factors. One option is to use speed functions from Copert \cite{copert}, which are stored internally in the model. Another option is to use emission factors from local sources. For demonstration purposes, VEIN is loaded with Brazilian emission factors \cite{CETESB2015}, which are constant speed values. This database is called \textit{fe2015}, as shown in Table \ref{ta:ta1}. The third option is to scale the local emission factors with COPERT in order to incorporate speed variation for local factors, as shown in Equation \ref{eq:scale}. 
    %In Europe, vehicle emission factors are available as speed functions \cite{copert}, resulting from regressions of several emissions driving tests. 
    %In Brazil, emissions factors are available as average speed recordings measured from driving cycles \citep{CETESB2015}. 
    Figure ??%\ref{fig:efldv}
shows the annual emission factors of CO $g \cdot km^{-1}$ of new and deteriorated Passenger Cars using Gasoline. 
    
    The next section discusses the correct format of emission factors used to estimate the emissions.  VEIN include deterioration factors from Copert\citep{copert}. However, it is possible to include other sources \cite{corvalan2003experimental}. 
    
Emissions per street link, vehicle type, hour of week, and pollutant are obtained by
 \begin{equation}
 E_{i,j,k,l} =F_{i,j,k} \cdot L_i \cdot EF(V_{i,k})_{j,l} \cdot DF_{j}
        \label{eq:emi}
  \end{equation}
    
    where  $E_{i,j,k,l}$ are the emissions of the pollutant $l$ at each street link $i$, due to the vehicle type $j$ and for the hour of week $k$, where $F_{i,j,k}$ is the vehicular flow calculated in Equation 1. $L_i$ is the length of the road link $i$. $EF(V_{i,k})_{j,l}$ is the emission factor of each pollutant $l$ for vehicle type $j$ depending on the average speed $V$ at street link $i$ and hour $k$. $DF_j$ is the deterioration factor for vehicle of type $j$. 
    
    %VEIN includes a dataset of averaged annual recordings of emission factors from the Environmental Agency of São Paulo \cite{CETESB2015}. This dataset covers several types of vehicles for years between 1981 and 2015. This database is named in VEIN as \textit{fe2015} (see Table \ref{ta:ta1}). The user could also use its own emission factors dataset.
    
   When the user intends to scale local emission factors with Copert, it is necessary to match vehicular categories beforehand. The scaling process is shown in Equation \ref{eq:scale}.
    
    \begin{equation}
    EF_{\mbox{scaled}}(V_{i,k})_{j,l} = EF(V_{i,k})_{j,l} \cdot \dfrac{EFlocal_j}{EF(Vdc_{i,k})_{j,l}}
        \label{eq:scale}
    \end{equation}
    
 where $EF_{\mbox{scaled}}(V_{i,k})_{j,l}$ is the scaled emission factor and $EF(V_{i,k})_{j,l}$ is the Copert emission factor. $EFlocal_j$ represents the constant emission factor (not speed functions).  $EF(Vdc_{i,k})_{j,l}$ are COPERT emission factors with average speed value of the respective driving cycle for the vehicular category \textit{j}. The São Paulo emission factors data include recordings of FTP-75 driving cycle for LDV with an average speed of 34.12 $km \cdot h^{-1}$, as shown by in a report of driving cycles\cite{barlow2009} . 
    
%    \subsubsection*{Cold start exhaust emissions}
    
    During engine startup, if the engine and/or catalytic converter system are slow in reaching their normal operational temperature, emissions will be higher than in normal engine operation, regardless of whether the catalyst has reached its optimum temperature for functioning \citep{cold}. These are the cold start emissions. Moreover, if the atmospheric temperature decreases, cold start emissions will increase. The VEIN model caters to these emissions by using the approach outlined in Copert \citep{copert}, as shown in Equation \ref{eq:cold}.
    
    \begin{equation}
    E_{i,j,k} =\beta_{j} \cdot F_{i,j,k} \cdot L_i \cdot EF(V_{i,k})_{j} \cdot DF_{j} \cdot \left(EF_{\mbox{cold}}(ta_m,V_{i,k})_{j,l}-1\right)
        \label{eq:cold}
    \end{equation}
    
    This approach adds two terms to Equation 3. The first term $EF_{\mbox{cold}}(ta_m,V_{i,k})_{j,l}-1$ is the emission factors for cold start conditions. It depends on monthly average temperature and average speed at each street link \textit{i} and hour \textit{k}. It varies with each type of vehicle \textit{j} and each pollutant \textit{l}. The second term $\beta$ is defined as the fraction of mileage driven with a cold engine/catalyst \cite{copert}. The VEIN model incorporates a dataset of cold starts recorded during the application of the International Vehicle Emissions (IVE) model \citep{davis2005part} in São Paulo \citep{ivesp}.% In this experimental campaign, the vehicular start patterns were registered and the results showed that, on average, LDV starts were 6.1 times per day with half of the starts in the morning hour, after the cars had rested for 12 hours \citep{ivesp}. Cold start patterns were obtained for only a typical work day. %Therefore, we expanded $\beta$ to each day of the week by: 1) assuming $\beta$ represents a Monday, and 2) multiplying $\beta$ with the proportion for the daily sum expansion factors to each day and for morning as  $TF_{j,day}/TF_{j,Monday}$ from Equation \ref{eq:F}. These values normalized so that $\beta$ values sum 1 at each day of the week. %figure \ref{fig:beta} shows patterns of cold start for Passenger Cars (PC) used in this study and \ref{fig:temp} the monthly temperature values for a meteorological station on São Paulo.  
    
%    \subsubsection*{Evaporative emissions}
    
    Evaporative emissions are important sources of hydrocarbons and these emissions are produced due to differences in atmospheric and gasoline temperature \citep{evap}. There are mainly three types of evaporative emissions: \textit{diurnal} emissions due to increases in atmospheric temperature which lead to thermal expansion of vapor fuel inside the tank; \textit{running losses} is fuel evaporated inside the tank due to normal operation of vehicle; and \textit{hot soak} emissions are generated when the hot engine is turned off. These methods implemented in VEIN were sourced from the evaporative emissions methods of Copert \cite{evap}. This approach is shown in Equation \ref{eq:ev1}, \ref{eq:ev2} and \ref{eq:ev3}.

    \begin{equation}
E_{j} =\sum_{s}D_{s} \cdot \sum_{j}F_{j} \cdot (HS_j+de_j+RL_j) 
        \label{eq:ev1}
\end{equation}

where $E_{j,k}$ are the VOC evaporative emissions due to each type of vehicle \textit{j}.  
$D_s$ are the number of days when the mean monthly temperature is within a determined range:  [-5$^{\circ}$,10$^{\circ}$],  [0$^{\circ}$,  15$^{\circ}$], [10$^{\circ}$, 25$^{\circ}$] and [20$^{\circ}$, 35$^{\circ}$].  %In the São Paulo study, monthly temperature data was obtained from the Air Quality Information System from \cite{CETESB2017}. %and figure \ref{fig:temp} shows the averaged monthly Celcius temperature for the station "Pinheiros" located at downtown. 
F$_j$ is the number of vehicles according to vehicle type \textit{j}. $HS_j$, $de_j$ and $RL_j$ are average hot/warm soak, diurnal and running losses evaporative emissions $g \cdot day^{-1}$, respectively. $HS_j$ and $RL_j$ are obtained using equations also sourced from \cite{evap}:

\begin{equation}
\centering
HS_{j} = x_j \cdot (c \cdot (p \cdot e_{shc}+(1-p) \cdot e_{swc})+(1-c) \cdot e_{shfi} )
        \label{eq:ev2}
\end{equation}
\begin{equation}
RL_{j} = x_j \cdot (c \cdot (p \cdot e_{rhc}+(1-p) \cdot e_{rwc})+(1-c) \cdot e_{rhfi} )
        \label{eq:ev3}
\end{equation}

where x are the number of trips per day for the vehicular category \textit{j}, c is the fraction of vehicles with fuel return systems,  p is the fraction of trips finished with hot engine, $e_{shc}$ and  $e_{swc}$ are average hot-soak and warm-soak emission factors for gasoline vehicles with carburettor or fuel return systems $g \cdot parking^{-1}$, $e_{shfi}$  are average hot-soak emission factors for gasoline vehicles equipped with fuel injection and non-return fuel systems $g \cdot parking^{-1}$. 
$e_{rhc}$ and  $e_{rwc}$ are average hot and warm running losses emission factors for gasoline vehicles with carburettor or fuel return systems $g \cdot trip^{-1}$ and $e_{rhfi}$  are average hot running losses emission factors for gasoline vehicles equipped with fuel injection and non-return fuel systems $g \cdot trip^{-1}$.
It is recommended to estimate the number of trips per day\cite{evap}, x, as the division between the mileage and 365 times the length of trip: $ x = \dfrac{mileage_j}{(365 \cdot ltrip)}$. However, the mileage of a vehicle is not constant over the years. Therefore, VEIN incorporates a dataset of equations to estimate mileage of different type of vehicles by age of use \cite{bruni2013curvas}. %Therefore, the number of trips was obtained with the mileage of vehicles by age of use and \textit{ltrip} = 9km.

\begin{figure*}
  \centering
  \includegraphics[trim=1.3cm 0cm 0cm 1cm,clip=true,width=.9\linewidth]{figures/Figura1.png}
\caption{Data used to estimate vehicular emissions with VEIN Model. 
  (a) LDV at morning rush hour ($veh \cdot km^{-1}$), (b) Age distributions for LDV from \citeauthor{CETESB2015} (green) and estimated (red and blue), (c) Temporal factors for expanding morning rush traffic, (d) Emission factors CO ($g \cdot km^{-1}$) for Passenger Cars  from \citeauthor{CETESB2015}}
\label{fig:fig}
\end{figure*}

%The following sections provide a description of the VEIN model and how it incorporated the methods into the R package.

%	\subsection*{The R project}
	

	\subsection*{VEIN functions - General Overview}

	R is a programming language and environment for statistical computing and graphics \citep{R}. R is free open source software and the R language itself was developed primarily for analyzing data. However, since its capabilities have grown over time, R has become a flexible language with many different areas of application. R has elements of Lisp and syntax of S, as described by \cite{leiner1997past}.  
	
	The VEIN R package depends on the package \textbf{sp} \citep{sp1}, as it uses several of its classes. VEIN imports some functions from the package \textbf{rgeos} \citep{rgeos}, which is an interface for the Geometry Open Source GEOS library (https://trac.osgeo.org/geos/). It also imports from \textbf{rgdal} \citep{rgdal}, which provides bindings to the GDAL (http://www.gdal.org/) library. This means that these R packages must be installed prior to using the VEIN package. There are plans to migrate spatial dependencies into the Simple Features \textbf{sf} package\cite{sf}.% which is a package that implements several functions of the mentioned packages \textbf{sp}, \textbf{rgdal} and \textbf{rgeos} into one package.

VEIN started between 2014 and 2016 as a collection of several R scripts, initially named REMI, ordered in folders \citep{remitap}, which later evolved into an R package. It was developed in R due to the free open source advantages. VEIN is open to scrutiny from its community of users, thus allowing opportunities for user feedback and improvements. This facilitates widespread use of the model and identifying any software bugs/errors with potential for adding new capabilities. VEIN has its own functions, but it also incorporates other data and functions such as emission factors and mileage.

	The following sections present the most important functions of VEIN, each one with different options. This paper describes the functions for estimating emissions of Light Duty Vehicles (LDV) in a sequential order. VEIN uses objects of class 'Spatial' \citep{sp2}, including {\tt SpatialLinesDataFrame} to represent road segments. In order to install and run VEIN's demo, use the following scripts:
    
    \begin{verbatim}
    install.packages("vein")
    library(vein)
    demo(VEIN)
    \end{verbatim}

	VEIN incorporates S3 classes which are objects with specific characteristics that aim to help the user. There are 8 classes in VEIN  and each one includes the following methods: 'print', 'summary' and 'plot', which means that when the user runs any of these functions in any VEIN class, it will return a specific result. Table \ref{ta:class} shows VEIN classes.  Another important characteristic of each class is that they include explicit units, in an effort to reduce human errors and improve the usability. Therefore, VEIN imports some functions of the package \textbf{units} \citep{units},  which is an interface on the C library 'udunits' from University Corporation for Atmospheric Research (UCAR). This means that this library must be installed on the system prior to using VEIN. %Each function in VEIN automatically returns any class when corresponds. 
	
%\texttt{\textbackslash textsuperscript} and
%\texttt{\textbackslash emph} macros, as illustrated (Table~\ref{tbl:notes}).
\begin{table}
		\caption{Summary of vein classes.}
		\label{ta:class}
		\begin{tabular}{@{}llrrrrrrrrrr@{}}
%			\toprule
			Class  & Methods  & Units  \\ %\midrule
			{\tt Vehicles} &	print, plot, summary &	 $h^{-1}$   \\
			{\tt EmissionFactors} &	print, plot, summary  &	 $g \cdot km^{-1}$    \\
			{\tt EmissionFactorsList}$^a$ &	print, plot, summary  &	 $g \cdot km^{-1}$   \\
			{\tt Emissions} &	print, plot, summary  &	 $g \cdot h^{-1}$    \\
			{\tt EmissionsArray}$^a$ &	print, plot, summary  &	 $g \cdot h^{-1}$    \\
			{\tt EmissionsList} &	print, plot, summary  &	 $g \cdot h^{-1}$    \\
			{\tt Evaporative} &	print, plot, summary  &	 $g \cdot d^{-1}$ \\
			{\tt Speed} &	print, plot, summary  & $km \cdot h^{-1}$   \\ %\midrule
		\end{tabular}

  \textsuperscript{\emph{a}} {\tt EmissionFactorsList} and {\tt EmissionsArray} do not show their units explicitly.
%  \textsuperscript{\emph{b}} \textbf{Some more text}.
\end{table}

	 The classes mentioned in Table \ref{ta:class} are also constructor functions, which means that they can create VEIN classes and add the respective units. For example, the following chunk of code transforms a
	 data-frame of vehicles into an object with class {\tt Vehicles}. The returning 
	 object has two classes, "Vehicles" and "data.frame",  which means that it has all the
	 characteristics of a data-frame, but also adding the units to each element. When
	 the construction function is applied to a numeric element, the construction just
	 adds the units and the resulting object has class 'units'.
	 
%	\begin{verbatim}
%df <- data.frame(a = 1:30, b = 1:30)
%dfv <- Vehicles(df)
%class(dfv)
%\end{verbatim}

    
    The São Paulo study example included a traffic simulation for morning rush hour. 
    The traffic data is Light Duty Vehicles (LDV) consisting in Passenger Cars (PC) plus Light Commercial Vehicles (LCV). However, they were treated as PC in this estimation for example purposes. Future estimations must consider vehicles accordingly. This traffic data is then extrapolated 24 hours of the day, seven days of the week, with a profile in a data-frame built by the user. VEIN includes a 24/7 profile and Brazilian hot emission factors. Deterioration effect was added with the function \textit{emis\_det}. Then, the resulting factors were scaled to account for speed with the function \textit{ef\_ldv\_scaled}. 
    VEIN also incorporates functions to estimate emissions of cold start, evaporative, wear, resuspension processes and performs speciation.     

The function \textit{emis} estimates the emissions for each hour of the day, and day of the week. The function \textit{emis\_post} produces an emissions database by vehicle category or by street. All emission estimate outputs are given in $g \cdot h^{-1}$. The function \textit{make\_grid} creates a rectangular grid used to allocate emissions spatially with the function \textit{emis\_grid}. Table \ref{ta:ta1} shows most of the functions and data incorporated into the VEIN model. The addition of more features can be expected in the near future. 

\small
\begin{table*}{tbp}
\caption{Summary of vein functions/data.} 
\label{ta:ta1}
\centering
\scalebox{0.91}{	
		
        \begin{tabular}{@{}llrrrrrrrrrrrr@{}}
        
			%\toprule
	Function  & Description & Type & Reference \\ %\midrule
	age\_hdv &	Distribution of HDV according age of use &	 function &	 \citep{MMA}  \\
	age\_ldv  &	Distribution of LDV according age of use  &	 function   &	 \citep{MMA}  \\
	age\_moto  & Distribution of Motorcycle according age of use  & function   &	 \citep{MMA}  \\
	ef\_evap  &	Evaporative emission factors[2]&	 function  &	 \citep{evap}  \\
	ef\_hdv\_scaled  &	List of HDV emission factors by age of use[1] &	function  &	 \citep{copert} \\
	ef\_hdv\_speed  & HDV Emission factors [2] &	function   &	 \citep{copert}\\
	ef\_ldv\_cold  & LDV cold start emission factors &	function[2]   &	 \citep{copert}\\
	ef\_ldv\_cold\_list &	List of LDV cold start emission factors &	function   &	 \citep{copert}\\
	ef\_ldv\_scaled  &	List of LDV emission factors by age of use[1] & function  &	 \citep{copert}\\
	ef\_ldv\_speed  &	LDV Emission factors[3] &	function    &	 \citep{copert}\\
	ef\_wear  &	Tyre and break wear, and road abrassion &	function    &	 \citep{wear}\\
	EmissionFactors  &	Constructor for class "EmissionFactors" &	function    \\
	EmissionFactorsList  &	Constructor for class "EmissionFactorsList" &	function    \\
	Emissions  &	Constructor for class "Emissions" &	function    \\
	EmissionsArray  &	Constructor for class "EmissionsArray" &	function    \\
	EmissionsList  &	Constructor for class "EmissionsList" &	function    \\
	emis  &	Emission estimation to hour and day of the week &	function    \\
	emis\_cold  &	Cold start emission estimation &	function   &	\citep{copert}  \\
	emis\_det  &	Deterioration factors &	function   &	 \citep{copert}\\
emis\_evap  &	Evaporative emission estimation &	 function   &	 \citep{evap}\\
	emis\_grid  &	Allocation of emissions on rectangular grid &	function   &	  \\
	emis\_paved  &	Resuspenssion emissions/ of paved roads&	function   &	 \citep{paved}\\
	emis\_post  &	Post processing of emissions &	function  &	 \\
	emis\_wear  &	Estimation of wear emissions &	function   &	 \citep{wear}\\
	emis\_wrf  &	Exporting emissions data-frame to WRF-Chem &	function   &	 \citep{Angel2015}\\
	Evaporative  &	Constructor for class "Evaporative" &	function    \\
	hot\_soak  &	Hot soak evaporative emissions[2] &	function   &	 \citep{evap}\\
	make\_grid  &	Rectangular grid[4] &	function &	  \\
	my\_age  &	Distribution of vehicles according age of use &	function &	  \\
	netspeed  &	Estimate average speed[3] &	function &	  \\
	running\_losses  &	Evaporative emissions estimation &	function &	 \citep{evap}\\
	speciate  &	Split of emissions by species &	function &	 \cite{copert}, \\ \cite{evap}, \\\citep{sameh}\\ %%%BOTEI   \cite{evap} para baixo para a tabela caber na pagina
	Speed  &	Constructor for class "Speed" &	function    \\
	temp\_fact  &	Expand hourly traffic &	function &	 \\
	Vehicles  &	Constructor for class "Vehicles" &	function    \\
	vkm  &	Determination of vehicle-kilometers &	function &	  \\
	fe2015  &	CETESB emission factors of pc &	data  &	 \citep{CETESB2015}\\
    pc\_profile  &	Normalized temporal factors \textit{TF} of equation \ref{eq:F} &	data  &	 \citep{artesp} \\
    pc\_cold  &	Vehicle start pattern &	data  &	 \citep{ivesp} \\
	fkm  &	Mileage functions by vehicle  &	data &	 \citep{bruni2013curvas}\\
	net  &	Traffic simulation of west side of São Paulo &	data &	 \citep{CET} \\ %\midrule

	\end{tabular}
	}
%\begin{tablenotes} %AR tirei table notes pq saiu o pacote e nao compilava sem ele
\end{table*}

\begin{itemize}
\small
\item Notes: [1]: The length of the list depends on the age distribution.
[2]: hese functions access and match the selected parameters with an internal look-up table of emission factors \cite{copert}' \cite{evap}
[3]: The streets are {\tt SpatialLinesDataFrame} of the western part of São Paulo.
[4]: It returns a {\tt SpatialPolygonsDataFrame} or a {\tt SpatialGridDataFrame}.
%\end{tablenotes}
\end{itemize}	
	
	The process of estimating emissions is shown in Figure \ref{fig:diagrama} where green circles indicate data and blue boxes indicate functions.  In Figure 2, VEIN starts at the green circle traffic which is the morning rush hour traffic data for each street link. There are no functions for reading spatial data in VEIN because there are several packages providing these functions, such as rgdal \citep{rgdal} or maptools \citep{maptools}. The user can use any of these functions to read their geospatial data. The main requirement is that the resulting R object must be a {\tt SpatialLinesDataFrame}, class of 'sp' \citep{sp2}. All the functions and data in VEIN are shown in Table \ref{ta:ta1}.

\begin{figure*}
\centering
\includegraphics[width=15cm]{figures/diavein.png}
\caption[Flow chart of VEIN model]{Boxes are functions and circles are data.}
\label{fig:diagrama}
\end{figure*}
    
%	\subsubsection*{Traffic data and spatial allocation}

	 
		
As previously mentioned, traffic simulations usually count with peak and free flow speed, along with capacity and traffic flow. After the traffic flow was expanded to each hour in the São Paulo study, it was possible to calculate new speeds with BPR curves, as shown in Equation \ref{eq:bpr}. The function \textit{netspeed} calculates average speeds with Equation \ref{eq:bpr}. The resulting speeds can be observed in Figure \ref{fig:mapspeed}, which shows two speed maps for hour 08:00 and 23:00 local time (LT). Figure \ref{fig:speed168} also shows the average speed by type of street being Arterial, Collector, Local and Motorway.  Lower speeds are obtained for morning and evening rush hours and maximum average speeds for each type of road are on Sundays and at night hours of Figure \ref{fig:speed168}. The following chunk of code shows the function \textit{netspeed} where the logical argument \textit{isList} indicates if the result should be returned as a data-frame or as a list of 7 lists. Each list represents a day of the week and each one contains 24 data-frames of speeds at each street link. The following code shows the expansion of traffic data with the function \textit{temp\_fact}. The function \textit{netspeed} then estimates the speeds.
\\


	\begin{verbatim}
data(net)
data(pc_profile)
pcw <- temp_fact(net$ldv+net$hdv, 
pc_profile)
df <- netspeed(pcw, net$ps, 
  net$ffs, net$capacity, net$lkm, alpha = 1,
  isList = TRUE)
	\end{verbatim}


	\begin{figure*}
		\centering
		\includegraphics[width=18cm]{figures/speed1.png}
		\caption{Speeds for 08:00 and 23:00 Local Time (km/h).}
		\label{fig:mapspeed}
	\end{figure*}

	\begin{figure}
		\centering
		\includegraphics[width=15cm]{figures/speed2.png}
		\caption{Average speed of traffic by type of street.}
		\label{fig:speed168}
	\end{figure}

%	\subsubsection*{Age distribution}
	
    The \textit{age*} functions distribute the traffic data by age of vehicle use. These functions return a data-frame with the number of rows matching the number of streets, columns representing the amount of vehicles by age of use, and a message indicating the average age of the fleet. In any of these functions there is an argument \textit{k} to multiply the resulting data-frame. The \textit{age*} functions play the role of \textit{VC} in Equation \ref{eq:F} by splitting the vehicular flow \textit{Q} for any type of vehicle \textit{j}. These functions include \textit{age\_ldv}, \textit{age\_hdv} and \textit{age\_moto}, which are based on the survival equations presented in the Brazilian emissions inventory report \cite{MMA} and parameterized for the VEIN model. These functions allow the use of different coefficients to obtain different age distributions. Furthermore, there is the function \textit{my\_age}, which distributes the traffic from an existing dataset, e.g. yearly vehicle licensing. New options will be added into \textit{age*} functions.
    
    The following code shows three uses of age functions. The first \textit{my\_age} uses yearly traffic data from the report of the emissions inventory of São Paulo\cite{CETESB2015} expressed as CETESB\_PC, based on vehicle sales as preciusly mentioned. The second \textit{age\_ldv} uses default parameters and the third \textit{age\_ldv} uses b=-0.14. 
    
		\begin{verbatim}
pc1 <- my_age(net$ldv,CETESB_PC, "PC")
pc2 <- age_ldv(net$ldv, "PC", 41)
pc3 <- age_ldv(net$ldv, "PC", b=-0.14, 41)
		\end{verbatim}
		
		%This is particularly useful for estimating vehicular emissions in cities with the same emissions standard, but with different average income. This is due to the fact that cities with lower income are expected to have an older fleet with higher emissions of pollutants. This idea was justified by the development of a vehicular emissions inventory for 58 urban centers in South America, assuming that countries with lower GDP have older fleets \citep{ibarra2015}. 
        Figure \ref{fig:ages} shows three age distributions, each one sums to 1,946,955 $veh \cdot h^{-1}$, but with different average age. The graph represents LDV vehicles with an estimated average age of 11.09 years (red line) and 15.53 years (blue line), and includes a green line of 15.17 years as explained before. There are more newer vehicles than older ones. %The amount of vehicles is observed to be higher at newer age of vehicle use and lower at older age of vehicle use.% In most cases, the higher amount of newer vehicles could be due to a higher average income in the city. 

Age functions also include a logical option named \textit{bystreet}, with default value equal to FALSE. When this value is TRUE, \textit{age*} expects that the coefficients \textit{b} and \textit{b1} of the age functions are numeric vectors, with length matching the number of streets. This allows different age distributions within the same road network and is particularly useful for areas inside a city restrictions based on age of use. 

 %   \subsubsection*{Emission Factors}
%	The main requisite of the emission factors in VEIN is that they must be functions depending on speed and they need to be stored in a list with a length that is equal to the age distribution of the specific vehicular category. For example, if a vehicle category has 41 years distribution, the length for the list of emission factors will be 41, one for each year.  Moreover, the class of each element in the list must be a function dependent on speed.
    
   For the São Paulo case, emission factors are not dependent on speed \cite{CETESB2015}. The VEIN package includes a database titled \textit{fe2015} with emission factors for Passenger Cars and Light Trucks. The pollutants are CH$_4$, CO, CO$_2$, HC, N$_2$O, NMHC, NO$_X$, and PM. 
   This data includes national and equivalent Euro Emission Standards by year and age. The equivalence between Brazilian \cite{PROCONVE}, \cite{Promot}, \cite{Promo} and Euro \cite{euro} was added into this database in order to choose the corresponding matching vehicle and emissions standard. The equivalence can be seen in Table \ref{tab:euro}.
    
    \begin{table}[tbp]
\centering
\caption{Proposed equivalence of emission standards used in São Paulo study.}
\label{tab:euro}
\begin{tabular}{@{}lcll@{}}
%\toprule
Vehicle         & Brazilian Standard & Euro Standard & Year \\ \hline %\midrule
\multirow{6}{*}{LDV} & L - 1       & Pre ECE &  1988 - 1991 \\
                     & L - 2       & Euro 1   & 1992 - 1996 \\
                     & L - 3       & Euro 2   & 1997 - 2004 \\
                     & L - 4       & Euro 3   & 2005 - 2011 \\
                     & L - 5       & Euro 4   & 2012 - 2013 \\
                     & L - 6       & Euro 5   & 2014 \\ %\midrule
\multirow{7}{*}{HDV} & P - 1       & Pre Euro & 1990 - 1992 \\
                     & P - 2       & Pre Euro & 1993 \\
                     & P - 3       & Euro 1   & 1994 - 1997 \\
                     & P - 4       & Euro 2   & 1998 - 2003 \\
                     & P - 5       & Euro 3   & 2004 - 2011 \\
                     & P - 6       & Euro 4   & -    \\
                     & P - 7       & Euro 5   & 2012 \\ %\midrule
\multirow{3}{*}{M}   & M - 1       & Euro 1 &  2003 - 2005 \\
                     & M - 2       & Euro 2   & 2006 - 2008 \\
                     & M - 3       & Euro 3   & 2009 \\ %\midrule

\end{tabular}

  \textsuperscript{Based on http://transportpolicy.net/index.php?title=Category:Brazil}
\end{table}


	
    The deterioration factor function \textit{emis\_det} has the arguments: pollutant, size of engine, Euro Standard and mileage in km. VEIN includes a Brazilian database of mileage functions named \textit{fkm}, which is a list of functions with each element of the list corresponding to vehicle type. These functions depend on age of vehicle use and they originate from the odometer readings of more than 1.6*10$^6$ vehicles \cite{bruni2013curvas}. %Since the function \textit{emis\_det} depends on mileage, the mileage database can also be used with this function.%  The following lines of code show the use of \textit{emis\_det}.
    
Emission factors for passenger cars, light commercial vehicles, motorcycles are called with the function \textit{ef\_ldv\_speed} and for trucks and buses \textit{ef\_hdv\_speed}. %These functions behave as a look-up table. 
    The arguments are filters for an internal database of emission factors which include several parameters such as fuel, Euro Standard, volume of engine and load, among others. These functions also include a multiplication factor with a default value of 1. Exact spelling is required when using the arguments. If the argument names are entered incorrectly, VEIN will not return the emission factor functions.	
    
    \begin{verbatim}
data(fe2015)
data(pc_profile)
data(fkm)
pckm <- fkm[[1]](1:24)
pckma <- cumsum(pckm)
cod1 <- emis_det(po = "CO", cc = 1000, 
eu = "III", km = pckma[1:11])
cod2 <- emis_det(po = "CO", cc = 1000, 
eu = "I", km = pckma[12:24])
co1 <- fe2015[fe2015$Pollutant=="CO", ]
cod <- c(co1$PC_G[1:24] * c(cod1,cod2),
  co1$PC_G[25:nrow(co1)])
	\end{verbatim}

Once it was added the deterioration into the Brazilian emission factors \cite{CETESB2015}, they were scaled to account for speed with the function \textit{ef\_ldv\_scaled}. %This function returns a list of emission factors. %This function was created to accommodate specific databases, e.g. the Brazilian databases used in the São Paulo study. 
This function is used to multiply emission factors from \textit{ef\_ldv\_speed} with a constant.% so that the resulting emission factor is a function of speed and has the same original value.

The new emission factor (dependent on speed) has the same value as the local emission factor, which is evaluated at the reference speed of the measurement 34.12 kmh$^{-1}$ for FTP-75. %Therefore, the functions \textit{ef\_ldv\_scaled} and \textit{ef\_hdv\_scaled} have the same arguments as \textit{ef\_ldv\_speed} and \textit{ef\_hdv\_speed}. 
        %The function  \textit{ef\_ldv\_speed} requires a numeric vector for local emission factors by age of use and the average speed of driving cycle. 
    The default speed value is 34.12 kmh$^{-1}$, but this value must change correspondingly to the speed of the driving conditions. To use this function, it is necessary to scale emission standards of local emission factors with Euro Standards. In the following code, \textit{Euro\_LDV} is a vector indicating Euro Standard by age of use.
	
	\begin{verbatim}
lef <- ef_ldv_scaled(co1, cod, v = "PC", 
  t = "ALL", cc = "ALL", 
  f = "G", p = "CO", eu=co1$Euro_LDV)
	\end{verbatim}
	

