Search This Blog

Showing posts with label nytrans. Show all posts
Showing posts with label nytrans. Show all posts

Monday, March 10, 2014

Generating Poisson Distributed time events with R

In this example, I would like to generate a set of values that is based on a set of discrete arrivals. Poisson distribution is ideal for generating these random values. Lets say I want to generate a set of time events for cars arriving into an on-street parking next to a strip mall at a rate of average 2 to 3 per minute. Maximum arrivals are at 9:00 am. Total number of parking available is 10. If parking is available, a car parks for a mean of 45 minutes. If not, drivers look for additional parking around.

To start with, we can start arrivals at 6 AM till 10:00 PM. That is 16 hours. Also, let us assume an average of 3 cars per minute. To make sure, we can generate sub-minute arrivals, we need to convert everything to seconds. In this first attempt, we will ignore that arrival rate is time dependent and assume a homogeneous arrival rate through out the day. We will tackle inhomogeneous time-dependent arrival rates in a future post.

To generate these numbers, we can use the following formula

rate <- 3/60
period <- 16*60*60
start <- 6*60*60
cars <- runif(rpois(1,period*rate), min=start, max=start+period)



To see, how the data is distributed over time, we can see the individual arrivals per hour as a histogram with the following command.

> hist(cars, breaks=16)




To see arrivals per minute, we can use the following command.

> hist(cars, breaks=16*4)



To see the actual data generated, we can just type cars on the prompt to see the generated vector.


We will carry on from here...





Saturday, March 8, 2014

Analyzing statistical data using R

In this post, we will examine the data that we accessed previously using R. We repeat the steps from our previous post to load the RpostgreSQL driver and to load the data. In this case, it is hourly traffic counts from New York state.

We first run a few queries to load the data.

> library(RPostgreSQL)

> drv <- dbDriver("PostgreSQL")

> con <- dbConnect(drv, user = "nydot", password = "nydot", dbname = "nydot", host = "localhost", port = 5432)

> rs <- dbGetQuery(con, "select rcstation, start_time, direction, lane, count from traffic")


> plot(rs$lane, rs$count)



Next, we are plotting the start_time with the count

> plot(rs$start_time, rs$count)

This gets us another ridiculous chart revealing that in fact our data is across many months.



To understand whether the data is collected for each station across the year, I plot the following

> plot(rs$start_time, rs$rcstation)



This shows that data is actually spread over twelve months in a year. To understand whether the data is for the entire year for each station, I applied a filter on the dataset for one rcstation (360001 in this case) and created a plot to see the data range.

In the following case, I have applied the filter and am plotting the start time.

> plot(rs[rs$rcstation==360001,]$start_time)



As, we can see from the plot below, the data is for a single station is actually spread out over one week.



Another way of looking at the data would be the total count for each day of the week. First we would like to check the range of values for the specific days.

We can use the range command to check for this...

> range(rs[rs$rcstation==360001,]$start_time)

In our case, it gave the following response.



We can plot a histogram for a single count station using the following formula

> hist(rs[rs$rcstation==360001,]$count)

This displays the following histogram.



That's it we are done for our first exploration. We will pick up more advanced stuff as we go along...



Sunday, February 23, 2014

Connecting to PostgreSQL database to do R analysis

In the previous post, we saw how to install R on Ubuntu. To perform analysis on PostgreSQL data, we need to have the RPostgreSQL library installed. Installing on Ubuntu is simple, and you need to follow the scripts listed below.

Install libpq-dev library

First step is to ensure that the libpq-dev library is installed. This can be installed by entering the following command.

$ sudo apt-get install libpq-dev




Install RPostgreSQL Library


Now that we have the library installed, we need to setup PostgreSQL library for R on our machine. To do this, we need to start R as a super user.

$ sudo R




Next step is to run the command to install additional packages. Enter the following command on the R prompt.

> install.packages()



This prompts a bunch of mirrors from where new packages can be downloaded from. Choose your location from the list.




Choose the appropriate mirror for your location and continue...

Next, we need to choose the package. Choose RPostgreSQL, as shown below



Clicking OK will start the download and installation.


Now let's see if we can connect to a database, and use the R library.

To do so, we need to load the RPostgreSQL library, load the driver for PostgreSQL and make a connection to our database with an authorized user and password.

Here are the steps to do so....
> library(RPostgreSQL)
> drv <- dbDriver("PostgreSQL")
> con <- dbConnect(drv, user = "nydot", password = "nydot", dbname = "nydot", host = "localhost", port = 5432)
This loads the library and connects to the database as shown in our terminal window.



Now that the connection is made, I can fire a query to load the data. You do so by using the command dbGetQuery as shown in the following statement.

> rs <- dbGetQuery(con, "select rcstation, start_time, direction, lane, count from traffic")

This assigns the results of the query to our object.


Just typing rs on the console will list all the data that got loaded.

> rs

Will list all contents of the object containing the results of the query. If we now wanted to check the mean count of all the data in the results we could do so as follows:

> mean(rs$count)

Here mean() is the function that we want to execute that calculates the average; rs is the object holding our results and rs$count refers to the field “count” in our resultset.



That's it.... We saw how we can calculate statistics from datasets in a PostgreSQL database.




Sunday, November 24, 2013

Download and Install SUMO - Simulation of Urban MObility on Ubuntu

SUMO is an open source, microscopic and continuous road traffic simulation package designed to handle large road networks. The advantage is that it is open source. In this post, we will follow the steps to install SUMO on Ubuntu. The version we will install is Version 0.18.

The SUMO site is at the following location:




The downloads link provides the links to download and install the software.



We will install a pre-compiled binary to get started. To install the software on Ubuntu, we need to add the repository to the apt package using the following command.

$ sudo add-apt-repository ppa:sumo/stable



Entering gives several prompts for entering the password and confirming the installation.



Next, we need to install the sumo, sumo-tools and sumo-doc packages on our machine.

$ sudo apt-get install sumo sumo-tools sumo-doc



Entering the command downloads the files and prompts to start installation on the machine.



After clicking yes, SUMO is installed on the machine.

To check, open a new terminal window or within the same window, type the following command, and we can see the results from the program.

$ sumo --help



There we go, we have installed SUMO on our machine.

Happy simulating


Wednesday, October 16, 2013

Setting the schema (search_path) in psql using command line options

The need to set schema using command line options

I was looking at ways to set the search_path in psql using command line options. The reason being that I had a bunch of auto-generated sql scripts that I wanted to run for a specific schema in Postgresql. Turns out that there is no out of the box option to set the schema from command line options. However, it is fairly straightforward to add the option.

Verifying the default schema


By default, when a user logs into psql, the search_path includes the public and $user schema. This can be verified by entering the show search_path command on the psql terminal as shown below.

=> show search_path;



To change the default schema from the psql command line, the first step is to edit the .psqlrc file on your machine.

Editing the ~/.psqlrc file


Postgresql's psql file allows users to extend the behaviour of the psql tool. Open a terminal window and type in the following commands.

$ sudo gedit ~/.psqlrc




This will open the existing (or new) ~./psqlrc file on your machine for editing.

Add the following line to the file.

SET search_path TO :schema;



This exposes search_path as a variable that can be set from the command line. Now, specifying a schema as a parameter sets the schema(search_path) to the specified value, as shown below....

In the following statement, nystaging is the name of the schema I want to set the value to.

$ psql -U nydot -d nywarehouse -v schema=nystaging



This changes the default schema to nystaging. This can be verified again by entering the show search_path command, as shown below....

=> show search_path;



To revert to the default path, you can specify the default path as a command line parameter, or comment the line in ~./psqlrc file.

That's it.


Monday, September 2, 2013

Starting a Remote Session from one Ubuntu machine on another Ubuntu machine

In this article, we look at ways to start a remote session from one Ubuntu machine on another. First to clarify, starting a remote session is not the same as Desktop sharing with tools like VNC.

What I really wanted was to let the remote machine operate using display settings of my client machine. Reason was, on my primary machines at my home, I have a dual display with 23 and 24 inch monitors, one of which is rotated by 90 degrees. Trying to access this over VNC meant that my local view consisted of this extended desktop made up of display real estate that was impossible to manipulate over my client machine that was a laptop.

This requires two steps

  1. Step 1: Connect to the machine using secure shell
  2. Step 2: Launch a remote gnome session

Here are the steps.

Step 1: Connect to the machine using a secure shell


The first step was to open a terminal windows and start a sescure shell session.

$ ssh -X user@host_machine

For example, in my case that works out to the following:



It may show a prompt similar to following (I have blanked out my ECDSA key on purpose).


Say yes to continue.

You will have to enter your password to continue.


This will start the remote X session.

Step 2: Launch a remote gnome session

Next launch a gnome session using the following command.

$gnome-session –session=gnome-classic


The new gnome session is launched as part of the primary desktop, and we can see the remote machine's desktop on our machine.




That's it, we are done.

Saturday, August 31, 2013

Creating the Time Dimension table in Pentaho Data Integration (Kettle)

In my previous post, we had seen how to create the Date Dimension table using Pentaho Data Integration (Kettle). In this post, we will see how to create a Time dimension in Kettle.

It is recommended that Time dimension be a separate dimension from the Date. In that spirit, I created the following transformation in Kettle. It contains the following 10 steps.

1. Launch Kettle
2. Generate Rows for processing and setup variables
3. Convert Date to Epoch Time
4. Create sequence for incrementing time in milliseconds
5. Create sequence for incrementing identifier
6. Increment time and identifier with newly created sequences
7. Convert time in milliseconds back to Date
8. Output contents to a text file
9. Extract time out of the incremented date

Step 1: Launch Kettle

Launch Pentaho Data Integration (Kettle or GeoKettle) on your local machine. Create a new transformation by clicking on File > New Transformation.



Step 2: Generate Rows for processing and setup variables


Make sure you are in design mode. Expand the Input section on Steps menu on the side and navigate to Generate Rows step.



Drag the Generate Rows step across to the work area as shown below, and drop it in the work area.







Right click on the Generate Rows step and enter the following information

  1. Step Name: Generate Rows
  2. Limit : 1440

In the fields column, add the following field

  1. Name: START_TIME
  2. Type: Integer
  3. Format: ####
  4. Value: 0000

Click on the row to add a second field. Add the following parameters for this field

  1. Name: REAL_TIME
  2. Type: Date
  3. Format: yyyy/MM/dd HH:mm:ss
  4. Value: 1970/01/01 00:00:00


Step 3: Convert Date to Epoch Time


Next add “Select Values” from the Transform section of the Design tab. Select Values control allows us to change and modify the datatype of any variable in the flow. After dropping the step in the workspace, connect it to the preceding step using a hop as shown in the adjacent figure.







Now Edit the step to enter the following configuration information to convert Real time to an Integer. Doing so, converts the time to its Epoch time in milliseconds. To do so, we enter the following information.

  1. Fieldname: REAL_TIME
  2. Type: Integer

Step 4: Create sequence for incrementing time in milliseconds


Next we add a Sequence to our flow, and connect it to the preceding step as shown in the screenshots below. The sequence will increment our time in milliseconds derived in the previous step, by one minute intervals.







Edit the step in the transformation to enter the following information.

  1. Step name: Millisecond Sequence
  2. Name of value: MS_Increment
  3. Use counter to calculate sequence:
  4. Start at value: 0
  5. Increment by: 60000
  6. Maximum value: 86400000


Click OK to continue.

Step 5: Create sequence for incrementing identifier


Now add another sequence to the transformation as shown below and connect it to the preceding hop as shown below.



We can enter the following configuration for the newly added sequence.
  1. Step name: Time_Since
  2. Name of value: Time_Since
  3. Use counter to calculate sequence:
  4. Start at value: 0
  5. Increment by: 1
  6. Maximum value: 1440


Step 6: Increment time and identifier with newly created sequences


Next, we need to add a calculator to the flow.






We need to configure the calculator by adding two calculations. First calculation adds the numeric sequence to our identifier, and second sequence adds Millisecond increments to our time.

For the first field, enter the following details.

New field: INC_TIME
Calculation: A+B
Field A: INC_TIME
Field B: Time_Since
Remove: N

For the next field, add the following parameters.

New field: CALC_TIME
Calculation: A+B
Field A: REAL_TIME
Field B: MS_Increment
Value type: Integer
Remove: N

Here is how the dialog box looks on my screen.





Click OK to continue.

Step 7: Convert time in milliseconds back to Date


Next step is to convert the calculated time from integer back to Date. To do this, we add another Select Values step to our transformation.



Make the following configuration changes in the newly added step.

Fieldname: CALC_TIME
Type: Date
Binary to Normal?: N
Format: yyyy/MM/dd HH:mm:ss


Click OK to continue

Step 8: Output contents to a text file


The final step is to output the contents to a text file

For this we add a “File Text Output” step to our transformation.



The Text File Output step, as the name suggests outputs the results to a text file.



Edit the “Text File Ouput” step, and make the following changes.

On the File tab, set the name of the output file. I have set it to simply “log” and the Extension to txt. This will create a file called log.txt in the output folder.



Step 9: Extract time out of the incremented date


Before clicking OK, switch to the Fields tab, and make the following entries.

Retain the following two fields.

  1. Field 1 details are as follows
    • Name: Time_Since
    • Type: Integer
    • Precision: 0

  1. Field 2 details are as follows
    • Name: CALC_TIME
    • Type: Date
    • Format: HH:mm:ss

The following screenshot shows these changes as on my screen.



Click Ok. 

Step 10: Save and Test the Transformation

Save the transformation using the floppy icon on toolbar or File > Save on drop down menu.

Now, we need to run it using the Launch button.



Clicking this button launches the following screen.


Click the Launch button and the transformation starts executing.

The Execution Results window shows the results in a bottom pane.



Opening the log file, we can see the following results.



That's it, we are done.