#Set working directory  "Ctrl + shift +H"
#getwd()

##INSTALL NEED PACKAGES 
#install.packages("gtfstools")
#install.packages("leaflet")
#install.packages("gtfsio")
#install.packages("shiny")
#install.packages("rsconnect")
#install.packages("dplyr")
#CALL REQUIRED PACKAGES 
library(gtfstools)
library(leaflet)
library(gtfsio)
library(shiny)
library(rsconnect)
## 
## Attaching package: 'rsconnect'
## The following object is masked from 'package:shiny':
## 
##     serverInfo
library(shiny)
library(dplyr)
## 
## Attaching package: 'dplyr'
## The following objects are masked from 'package:stats':
## 
##     filter, lag
## The following objects are masked from 'package:base':
## 
##     intersect, setdiff, setequal, union
##Set the working directory file to the location of the zip file
## don't forget to include the file extension in the code



Sakay_ph <- file.path("gtfs-master.zip")

read_gtfs(Sakay_ph)
## $agency
##                      agency_id                           agency_name
##                         <char>                                <char>
## 1:                        LRTA   Manila Light Rail Transit Authority
## 2:                       LTFRB                                 LTFRB
## 3:                        MRTC Manila Metro Rail Transit Corporation
## 4: Maritime Industry Authority                                MARINA
## 5:                         PNR          Philippine National Railways
## 6:                        FORT                          The Fort Bus
##                  agency_url agency_timezone agency_lang agency_phone
##                      <char>          <char>      <char>       <char>
## 1:  http://www.lrta.gov.ph/     Asia/Manila                         
## 2: http://www.ltfrb.gov.ph/     Asia/Manila                         
## 3:   http://dotcmrt3.gov.ph     Asia/Manila                         
## 4: http://www.marina.gov.ph     Asia/Manila                         
## 5:   http://www.pnr.gov.ph/     Asia/Manila                         
## 6:       http://bgcbus.com/     Asia/Manila                         
## 
## $calendar
##     service_id monday tuesday wednesday thursday friday saturday sunday
##         <char>  <int>   <int>     <int>    <int>  <int>    <int>  <int>
##  1:     881614      0       0         0        0      0        0      1
##  2:     880893      1       1         1        1      1        1      0
##  3:     881744      0       0         0        0      0        0      1
##  4:     882006      0       0         0        0      0        0      1
##  5:     882002      1       1         1        1      1        1      0
##  6:     880772      1       1         1        1      1        0      0
##  7:     880774      0       0         0        0      0        1      1
##  8:     881444      0       0         0        0      0        0      1
##  9:     881445      0       0         0        0      0        0      1
## 10:     881397      0       0         0        0      0        1      0
## 11:     881408      1       1         1        1      1        0      0
## 12:     881411      1       1         1        1      1        0      0
## 13:     880851      1       1         1        1      1        0      0
## 14:     880853      0       0         0        0      0        1      0
## 15:     881502      0       0         0        0      0        0      1
## 16:     881578      0       0         0        0      0        1      1
## 17:     724594      1       1         1        1      1        1      1
## 18:     881579      0       0         0        0      0        1      1
## 19:   WEEKDAYS      1       1         1        1      1        0      0
## 20:      DAILY      1       1         1        1      1        1      1
##     service_id monday tuesday wednesday thursday friday saturday sunday
##     start_date   end_date
##         <Date>     <Date>
##  1: 2013-06-17 2020-06-30
##  2: 2013-06-17 2020-06-30
##  3: 2013-06-17 2020-06-30
##  4: 2013-06-17 2020-06-30
##  5: 2013-06-17 2020-06-30
##  6: 2013-06-17 2020-06-30
##  7: 2013-06-17 2020-06-30
##  8: 2013-06-17 2020-06-30
##  9: 2013-06-17 2020-06-30
## 10: 2013-06-17 2020-06-30
## 11: 2013-06-17 2020-06-30
## 12: 2013-06-17 2020-06-30
## 13: 2013-06-17 2020-06-30
## 14: 2013-06-17 2020-06-30
## 15: 2013-06-17 2020-06-30
## 16: 2013-06-17 2020-06-30
## 17: 2013-06-17 2020-06-30
## 18: 2013-06-17 2020-06-30
## 19: 2013-06-17 2020-06-30
## 20: 2013-06-17 2020-06-30
##     start_date   end_date
## 
## $feed_info
##    feed_publisher_name feed_publisher_url feed_lang
##                 <char>             <char>    <char>
## 1:            Sakay.ph    http://sakay.ph        en
## 
## $frequencies
##           trip_id start_time end_time headway_secs exact_times
##            <char>     <char>   <char>        <int>       <int>
##    1:      882005   05:37:00 07:37:00         3600           0
##    2:      882007   09:37:00 14:37:00         3600           0
##    3:      882008   07:37:00 09:37:00         1800           0
##    4:      882009   14:37:00 19:07:00         1800           0
##    5:      882110   16:00:00 19:30:00         1800           0
##   ---                                                         
## 1860:      724965   06:00:00 23:00:00           60           0
## 1861:      724960   06:00:00 23:00:00           60           0
## 1862:      724967   06:00:00 23:00:00           60           0
## 1863: FORT_CENT_1   06:00:00 22:00:00           60           0
## 1864: FORT_WEST_1   10:00:00 17:00:00           60           0
## 
## $routes
##       agency_id route_short_name          route_long_name
##          <char>           <char>                   <char>
##    1:      LRTA            LRT 1     Baclaran - Roosevelt
##    2:      LRTA            LRT 2         Recto - Santolan
##    3:     LTFRB                  Alabang (Starmall) Lagro
##    4:     LTFRB                  Alabang (Starmall) Lagro
##    5:     LTFRB                          Alabang Fairview
##   ---                                                    
## 1713:     LTFRB                    Dampalit Hulo Palengke
## 1714:      MRTC            MRT-3     Taft Ave - North Ave
## 1715:       PNR           PNR MC           Metro Commuter
## 1716:      FORT                              Fort Central
## 1717:      FORT                                 Fort West
##                                                                                                                                       route_desc
##                                                                                                                                           <char>
##    1:                                                                       Urban railway line serving 20 stations between Balaran and Roosevelt
##    2:                                                                             Light rail line serving 11 stations between Recto and Santolan
##    3: South Luzon Expressway / Montillano St Intersection, Muntinlupa City, Manila - Quirino Highway / La Mesa Road Intersection, Calcoocan City
##    4:   Quirino Highway / La Mesa Road Intersection, Calcoocan City - Starmall Footbridge, Starmall Starmall Service Rd, Muntinlupa City, Manila
##    5: South Luzon Expressway / Montillano St Intersection, Muntinlupa City, Manila - SM Public Transport Terminal, Regalado Highway, Quezon City
##   ---                                                                                                                                           
## 1713:            Sto Rosario Parish, Don Bastilio Bautista Boulevard, Malabon City - Kamias Rd / Kasing-Kasing Intersection, Quezon City, Manila
## 1714:                                                                                                 MRT3 line from Taft Avenue to North Avenue
## 1715:                                                               PNT Metro South Commuter connects the cities of Manila, Pasay and Muntinlupa
## 1716:                                                                                                                                           
## 1717:                                                                                                                                           
##       route_type                                            route_url
##            <int>                                               <char>
##    1:          2 http://www.lrta.gov.ph/train_operating_schedules.php
##    2:          2 http://www.lrta.gov.ph/train_operating_schedules.php
##    3:          3                                                     
##    4:          3                                                     
##    5:          3                                                     
##   ---                                                                
## 1713:          3                                                     
## 1714:          2                              http://dotcmrt3.gov.ph/
## 1715:          2             http://www.pnr.gov.ph/metro_commuter.htm
## 1716:          3                                                     
## 1717:          3                                                     
##       route_color route_text_color      route_id
##            <char>           <char>        <char>
##    1:      fdff00                   ROUTE_880747
##    2:      a520a1                   ROUTE_880801
##    3:                              LTFRB_PUB1001
##    4:                              LTFRB_PUB1002
##    5:                              LTFRB_PUB1003
##   ---                                           
## 1713:                              LTFRB_PUJ2618
## 1714:      ffd80a                   ROUTE_880854
## 1715:      e58e11                   ROUTE_880872
## 1716:                                  FORT_CENT
## 1717:                                  FORT_WEST
## 
## $shapes
##      shape_id shape_pt_sequence shape_dist_traveled shape_pt_lat shape_pt_lon
##        <char>             <int>               <num>        <num>        <num>
##   1:   880814                 0                  NA     14.60350     120.9830
##   2:   880814                 1                  NA     14.60240     120.9871
##   3:   880814                 2                  NA     14.60049     120.9908
##   4:   880814                 3                  NA     14.60052     120.9915
##   5:   880814                 4                  NA     14.60072     120.9920
##  ---                                                                         
## 516:   882086                95                  NA     14.33087     121.0815
## 517:   882086                96                  NA     14.33087     121.0815
## 518:   882086                97                  NA     14.33087     121.0815
## 519:   882086                98                  NA     14.33087     121.0815
## 520:   882086                99                  NA     14.33087     121.0815
## 
## $stop_times
##            trip_id stop_sequence    stop_id arrival_time departure_time
##             <char>         <int>     <char>       <char>         <char>
##     1:      880815             1 LTFRB_4977     00:00:00       00:00:00
##     2:      880815             2 LTFRB_4978     00:02:30       00:03:00
##     3:      880815             3 LTFRB_4979     00:06:30       00:07:00
##     4:      880815             4 LTFRB_4980     00:10:00       00:10:30
##     5:      880815             5 LTFRB_4981     00:13:30       00:14:00
##    ---                                                                 
## 79410: FORT_WEST_1             4     FORT_3     00:16:00       00:16:30
## 79411: FORT_WEST_1             5     FORT_4     00:18:30       00:19:00
## 79412: FORT_WEST_1             6     FORT_5     00:20:00       00:20:30
## 79413: FORT_WEST_1             7    FORT_11     00:25:30       00:26:00
## 79414: FORT_WEST_1             8 LTFRB_4974     00:36:00       00:36:30
##        stop_headsign pickup_type drop_off_type shape_dist_traveled
##               <char>       <int>         <int>               <num>
##     1:                         0             0                  NA
##     2:                         0             0                  NA
##     3:                         0             0                  NA
##     4:                         0             0                  NA
##     5:                         0             0                  NA
##    ---                                                            
## 79410:                         0             0                  NA
## 79411:                         0             0                  NA
## 79412:                         0             0                  NA
## 79413:                         0             0                  NA
## 79414:                         0             0                  NA
## 
## $stops
##          stop_id stop_code                       stop_name stop_desc stop_lat
##           <char>    <char>                          <char>    <char>    <num>
##    1: LTFRB_4944                              Baclaran LRT           14.53390
##    2: LTFRB_4945                                  EDSA LRT           14.53810
##    3: LTFRB_4946                              Libertad LRT           14.54790
##    4: LTFRB_4947                             Gil Puyat LRT           14.55430
##    5: LTFRB_4948                             Vito Cruz LRT           14.56360
##   ---                                                                        
## 4854:     FORT_7                   Track 30th, Taguig City           14.55184
## 4855:     FORT_8           University Parkway, Taguig City           14.55154
## 4856:     FORT_9              Market! Market!, Taguig City           14.54712
## 4857:    FORT_10                  One Parkade, Taguig City           14.54974
## 4858:    FORT_11                Fort Victoria, Taguig City           14.54766
##       stop_lon zone_id stop_url location_type parent_station
##          <num>  <char>   <char>         <int>         <char>
##    1: 120.9980                              0               
##    2: 121.0010                              0               
##    3: 120.9990                              0               
##    4: 120.9970                              0               
##    5: 120.9950                              0               
##   ---                                                       
## 4854: 121.0509                              0               
## 4855: 121.0568                              0               
## 4856: 121.0553                              0               
## 4857: 121.0501                              0               
## 4858: 121.0460                              0               
##       wheelchair_boarding
##                     <int>
##    1:                   0
##    2:                   0
##    3:                   0
##    4:                   0
##    5:                   0
##   ---                    
## 4854:                   0
## 4855:                   0
## 4856:                   0
## 4857:                   0
## 4858:                   0
## 
## $trips
##           route_id service_id trip_short_name trip_headsign direction_id
##             <char>     <char>          <char>        <char>        <int>
##    1: ROUTE_880801     880772                                         NA
##    2: ROUTE_880801     880772                                         NA
##    3: ROUTE_880801     880772                                         NA
##    4: ROUTE_880801     880772                                         NA
##    5: ROUTE_880801     880772                                         NA
##   ---                                                                   
## 1860: ROUTE_880872     882002                                         NA
## 1861: ROUTE_880872     882006                                         NA
## 1862: ROUTE_880872     882006                                         NA
## 1863:    FORT_CENT      DAILY                                         NA
## 1864:    FORT_WEST      DAILY                                         NA
##       block_id shape_id     trip_id
##         <char>   <char>      <char>
##    1:            880814      880815
##    2:            880814      882129
##    3:            880814      882130
##    4:            880814      882131
##    5:            880814      882132
##   ---                              
## 1860:            882086      882112
## 1861:            882086      882113
## 1862:            882086      882114
## 1863:                   FORT_CENT_1
## 1864:                   FORT_WEST_1
# CALL THE GTFS FILE AND ASSIGN VARIABLE 
SakayPH <- read_gtfs(Sakay_ph)

# CHECK THE CONTENT OF THE GTFS FILE
names(SakayPH)
## [1] "agency"      "calendar"    "feed_info"   "frequencies" "routes"     
## [6] "shapes"      "stop_times"  "stops"       "trips"
#It will show all the files in the GTFS zip file, make sure that all of the required file is present in the GTFS zip file 

# CREATE DF SHOWING STOPS AND TRIPS ONLY
#make sure that GTFS file were properly zipped, usual error occure if the required texts files are in folder within folder
SakayPH_stops<- read_gtfs(path = Sakay_ph, files = c("stops", "trips"))
names(SakayPH_stops)
## [1] "stops" "trips"
##ANALYZE THE FEED 
trip_geom <- get_trip_geometry(SakayPH, file = "shapes")
plot(trip_geom$geometry)

## Create Leaflet map with OSM basemap
leaflet() %>%
  addTiles() %>%
  addPolylines(data = trip_geom$geometry,
               color = "blue",
               weight = 3)
#Create Leaflet map with OSM basemap now with Markers 
## Plot  first the stops location
stop_location <- SakayPH$stops

leaflet() %>%
  addTiles() %>%
  addMarkers(data = stop_location, 
             lat = ~stop_lat, 
             lng = ~stop_lon, 
             popup = ~stop_name)
#TRY TO PLOT 1 STOP ONLY 
names(stop_location)
##  [1] "stop_id"             "stop_code"           "stop_name"          
##  [4] "stop_desc"           "stop_lat"            "stop_lon"           
##  [7] "zone_id"             "stop_url"            "location_type"      
## [10] "parent_station"      "wheelchair_boarding"
head(stop_location)
##       stop_id stop_code       stop_name stop_desc stop_lat stop_lon zone_id
##        <char>    <char>          <char>    <char>    <num>    <num>  <char>
## 1: LTFRB_4944              Baclaran LRT            14.5339  120.998        
## 2: LTFRB_4945                  EDSA LRT            14.5381  121.001        
## 3: LTFRB_4946              Libertad LRT            14.5479  120.999        
## 4: LTFRB_4947             Gil Puyat LRT            14.5543  120.997        
## 5: LTFRB_4948             Vito Cruz LRT            14.5636  120.995        
## 6: LTFRB_4949           Quirino Ave LRT            14.5703  120.992        
##    stop_url location_type parent_station wheelchair_boarding
##      <char>         <int>         <char>               <int>
## 1:                      0                                  0
## 2:                      0                                  0
## 3:                      0                                  0
## 4:                      0                                  0
## 5:                      0                                  0
## 6:                      0                                  0
# lets try stop id LTFRB_4944

# Filter the stop_location data frame to include only the stop you want to plot
# For example, if you want to plot the stop with stop_id == 1
stop_to_plot <- stop_location[stop_location$stop_id ==  "LTFRB_4944" , ]

leaflet() %>%
  addTiles() %>%
  addMarkers(data = stop_to_plot, 
             lat = ~stop_lat, 
             lng = ~stop_lon, 
             popup = ~stop_name)
#LETS TRY PLOTTING MULTIPLE STOPS 
stop_location <- SakayPH$stops

# Filter the stop_location data frame to include multiple stops
stops_to_plot <- stop_location[stop_location$stop_id %in% c("LTFRB_4948" , "LTFRB_4946" ,"LTFRB_4944"), ]

leaflet() %>%
  addTiles() %>%
  addMarkers(data = stops_to_plot, 
             lat = ~stop_lat, 
             lng = ~stop_lon, 
             popup = ~stop_name)
# Single Trip, UPDATE THIS WITH EXPLANATION
single_trip <- SakayPH$trips$trip_id[1]
single_trip
## [1] "880815"
# This shall print Trip Id 880815

# 'file' argument defaults to c("shapes", "stop_times")
both_geom <- get_trip_geometry(SakayPH, trip_id = single_trip)
plot(both_geom["origin_file"])

# Get Trip duration
trip_durtn <- get_trip_duration(SakayPH, unit = "s") # in seconds

## See first few data
head(trip_durtn)
## Key: <trip_id>
##    trip_id duration
##     <char>    <int>
## 1:  724597     7673
## 2:  724598     6079
## 3:  724599     1213
## 4:  724600     1524
## 5:  724601     2489
## 6:  724602     2470
# 'unit' argument defaults to "min"
single_durtn <- get_trip_duration(SakayPH, trip_id = single_trip)
single_durtn
## Key: <trip_id>
##    trip_id duration
##     <char>    <num>
## 1:  880815     33.5
# Trip Segment Duration, (route structure) 
trip_seg_durtn <- get_trip_segment_duration(SakayPH, unit = "s")
head(trip_seg_durtn)
##    trip_id segment duration
##     <char>   <int>    <int>
## 1:  880815       1      150
## 2:  880815       2      210
## 3:  880815       3      180
## 4:  880815       4      180
## 5:  880815       5      120
## 6:  880815       6      150
# In Minutes
single_seg_durtn <- get_trip_segment_duration(SakayPH, trip_id = single_trip)
head(single_seg_durtn)
##    trip_id segment duration
##     <char>   <int>    <num>
## 1:  880815       1      2.5
## 2:  880815       2      3.5
## 3:  880815       3      3.0
## 4:  880815       4      3.0
## 5:  880815       5      2.0
## 6:  880815       6      2.5
## Trip Speed, THIS WILL GENERATE TRIP SPEED IN DESIRED UNIT 
trip_speed <- get_trip_speed(SakayPH, unit = "m/s")
head(trip_speed)
##    trip_id origin_file     speed
##     <char>      <char>     <num>
## 1:  724968      shapes  3.478441
## 2:  725383      shapes  3.308112
## 3:  880815      shapes  6.310990
## 4:  881478      shapes 10.117919
## 5:  881479      shapes 10.117919
## 6:  881480      shapes 10.117919
# 'unit' argument defaults to "km/h"
#THIS WILL GENERATE TRIP SPEED IN DEFAULT UNIT 
single_trip_speed <- get_trip_speed(SakayPH, trip_id = single_trip)
single_trip_speed
##    trip_id origin_file    speed
##     <char>      <char>    <num>
## 1:  880815      shapes 22.71956
### MANIPULATE THE FEEDS, PROVIDE EXPLANATION

old_headway_secs <- SakayPH$frequencies$headway_secs

SakayPH$frequencies[, headway_secs := NULL]
head(SakayPH$frequencies)
##    trip_id start_time end_time exact_times
##     <char>     <char>   <char>       <int>
## 1:  882005   05:37:00 07:37:00           0
## 2:  882007   09:37:00 14:37:00           0
## 3:  882008   07:37:00 09:37:00           0
## 4:  882009   14:37:00 19:07:00           0
## 5:  882110   16:00:00 19:30:00           0
## 6:  882111   09:00:00 11:00:00           0
SakayPH$frequencies[, headway_secs := old_headway_secs]
head(SakayPH$frequencies)
##    trip_id start_time end_time exact_times headway_secs
##     <char>     <char>   <char>       <int>        <int>
## 1:  882005   05:37:00 07:37:00           0         3600
## 2:  882007   09:37:00 14:37:00           0         3600
## 3:  882008   07:37:00 09:37:00           0         1800
## 4:  882009   14:37:00 19:07:00           0         1800
## 5:  882110   16:00:00 19:30:00           0         1800
## 6:  882111   09:00:00 11:00:00           0         1800
## MANIPULATE 
# (1)Set trip speed
## We will observe two (2) trips, 882005 AND 882009

#CHECK SAMPLE TRIP
selected_trips <- c("882005", "882009")
get_trip_speed(SakayPH, selected_trips, unit = "km/h")
##    trip_id origin_file    speed
##     <char>      <char>    <num>
## 1:  882005      shapes 23.71936
## 2:  882009      shapes 23.71936
# 'speed' is recycled to all trips if only a single value is given
new_speed_gtfs <- set_trip_speed(SakayPH, selected_trips, 50)
get_trip_speed(new_speed_gtfs, selected_trips)
##    trip_id origin_file    speed
##     <char>      <char>    <num>
## 1:  882005      shapes 50.00567
## 2:  882009      shapes 50.00567
#THIS WILL SHOW NEW DF WITH A SPEED OF 50.000 KM/H

# but you can also specify different speeds for each trip
new_speed_gtfs <- set_trip_speed(SakayPH, selected_trips, c(35, 45))
get_trip_speed(new_speed_gtfs, selected_trips)
##    trip_id origin_file    speed
##     <char>      <char>    <num>
## 1:  882005      shapes 35.00151
## 2:  882009      shapes 45.00827
#with this we were able to change the speed of the selected trips to 35 and 45 respectively 


#Lets try to rewrite this GTFS with new speed of selected trips 

### WRITING FEEDS
# tried reinstallting gtfsio but did not work 

temp_dir <- file.path(tempdir(), "gttools_vig1")
dir.create(temp_dir)
list.files(temp_dir)
## character(0)
# Name it
filename <- file.path(temp_dir, "SakayPh_GTFS.zip")

write_gtfs(SakayPH, filename)
list.files(temp_dir)
## [1] "SakayPh_GTFS.zip"
# Read as a zip file
zip::zip_list(filename)$filename
## [1] "agency.txt"      "calendar.txt"    "feed_info.txt"   "frequencies.txt"
## [5] "routes.txt"      "shapes.txt"      "stop_times.txt"  "stops.txt"      
## [9] "trips.txt"
# Write your last manipulated data to this nwe gtfs
write_gtfs(SakayPH, filename, files = c("stop_times", "trips", "calendar"))
zip::zip_list(filename)$filename
## [1] "stop_times.txt" "trips.txt"      "calendar.txt"