require 'yaml' require 'json' csv_data = [] File.open('tube_data_2006-07-26.csv','r').readlines[1..-1].each {|line| csv_data << line.split(',')} tube_data_hash = Hash.new {|key,value| key[value] = {}} csv_data.each do |line,direction,from_station,to_station,distance,unimpeded_time,peak_time,off_peak_time| tube_data_hash["#{from_station.gsub(/ \(.*\)/,'')}_#{line}"]["#{to_station.gsub(/ \(.*\)/,'')}_#{line}"] = {'line' => line, 'direction' => direction, 'distance' => distance.to_f, 'unimpeded_time' => unimpeded_time.to_f, 'peak_time' => peak_time.to_f, 'off_peak_time' => off_peak_time.to_f} end tube_data_hash.keys.each do |from_station| stations = tube_data_hash.find_all {|f_stat,t_stats| f_stat.split('_')[0] == from_station.split('_')[0] } if stations.size == 1 tube_data_hash[from_station.gsub(/_.*/,'')] = tube_data_hash.delete(from_station) to_stations = tube_data_hash[from_station.gsub(/_.*/,'')] to_stations.keys.each {|station| to_stations[station.gsub(/_.*/,'')] = to_stations.delete(station)} else stations.each do |f_stat,t_stats| tube_data_hash[from_station].merge! t_stats end end end change_stations = tube_data_hash.find_all {|f_stat,t_stats| f_stat.match /_/ }.map {|f_stat,t_stats| f_stat} change_stations.each do |from_station| to_stations = tube_data_hash[from_station] to_stations.keys.each {|station| to_stations[station.gsub(/_.*/,'')] = to_stations.delete(station) unless change_stations.include?(station)} tube_data_hash[from_station][from_station.gsub(/_.*/,'')] = {'line' => from_station.split('_')[1], 'direction' => nil, 'distance' => 0.01, 'unimpeded_time' => 0.01, 'peak_time' => 0.01, 'off_peak_time' => 0.01} tube_data_hash[from_station].each do |to_station,data| tube_data_hash[from_station.gsub(/_.*/,'')][from_station] = {'line' => from_station.split('_')[1], 'direction' => nil, 'distance' => 0.01, 'unimpeded_time' => 0.01, 'peak_time' => 0.01, 'off_peak_time' => 0.01} end end File.new('graph.yaml', 'w') << tube_data_hash.to_yaml File.new('graph.json', 'w') << tube_data_hash.to_json