Transit Planner  1.0
An experiment on transfer patterns robustness
src/TransitNetwork.h
00001 // Copyright 2011: Eugen Sawin, Philip Stahl, Jonas Sternisko
00002 #ifndef SRC_TRANSITNETWORK_H_
00003 #define SRC_TRANSITNETWORK_H_
00004 
00005 #include <boost/archive/binary_iarchive.hpp>
00006 #include <boost/archive/binary_oarchive.hpp>
00007 #include <boost/serialization/vector.hpp>
00008 #include <google/dense_hash_map>
00009 #include <kdtree++/kdtree.hpp>
00010 #include <ostream>
00011 #include <vector>
00012 #include <string>
00013 #include <functional>
00014 #include <queue>
00015 #include "gtest/gtest_prod.h"  // Needed for FRIEND_TEST in this case.
00016 #include "./StopTree.h"
00017 #include "./GeoInfo.h"
00018 
00019 // #define CREATE_WALKWAY_STATISTICS
00020 
00021 using std::vector;
00022 using std::string;
00023 using std::pair;
00024 using std::make_pair;
00025 using google::dense_hash_map;
00026 
00027 
00028 // Represents a Node in a transit network.
00029 class Node {
00030  public:
00031   enum Type {
00032     NONE = 0,
00033     ARRIVAL,
00034     TRANSFER,
00035     DEPARTURE,
00036   };
00037 
00038   // Constructor
00039   Node(const int stopIndex, const Node::Type& type, int time)
00040     : _stop(stopIndex), _type(type), _time(time) {}
00041   // Node comparison
00042   bool operator==(const Node& other) const;
00043   int stop() const { return _stop; }
00044   Type type() const { return _type; }
00045   int time() const { return _time; }
00046   // Returns a string representation of the node for debug purposes.
00047 //   string debugString() const;
00048 
00049  private:
00050   // Constructor
00051   Node()
00052     : _stop(-1), _type(NONE), _time(-1) {}
00053   // serialization / deserialization
00054   template<class Archive>
00055   void serialize(Archive& ar, const unsigned int version) {  //NOLINT
00056     ar & _stop;
00057     ar & _time;
00058     ar & _type;
00059   }
00060   friend class boost::serialization::access;
00061 
00062   // stop index
00063   int _stop;
00064   Type _type;
00065   int _time;
00066 };
00067 
00068 
00069 // Converts an enum type to a string.
00070 string type2Str(const Node::Type type);
00071 
00072 
00073 // A functor to compare nodes[a] and nodes[b] for sorting, sorts ascending by
00074 // time and transfer nodes before departure nodes. This sophisticated structure
00075 // is used here, because a standard static comparison function cannot access the
00076 // non-static _nodes array.
00077 class CompareNodesByTime : std::binary_function<int, int, bool> {
00078  public:
00079   explicit CompareNodesByTime(const vector<Node>* nodes) : _nodes(nodes) {}
00080   bool operator() (const int& a, const int& b);
00081   const vector<Node>* _nodes;
00082 };
00083 
00084 
00085 // An arc to a destination node specified by its id with a certain cost.
00086 class Arc {
00087  public:
00088   Arc(const int dest, const unsigned int cost, const unsigned char penalty)
00089     : _dest(dest), _cost(cost), _penalty(penalty) {}
00090 
00091   bool operator==(const Arc& rhs) const {
00092     return _dest == rhs._dest && _cost == rhs._cost && _penalty == rhs._penalty;
00093   }
00094 
00095   int destination() const { return _dest; }
00096   unsigned int cost() const { return _cost; }
00097   unsigned char penalty() const { return _penalty; }
00098 
00099  private:
00100   Arc() {}
00101   // serialization / deserialization
00102   template<class Archive>
00103   void serialize(Archive& ar, const unsigned int version) {  // NOLINT
00104     ar & _dest;
00105     ar & _cost;
00106     ar & _penalty;
00107   }
00108   friend class boost::serialization::access;
00109 
00110   int _dest;
00111   unsigned int _cost;
00112   unsigned char _penalty;
00113 };
00114 
00115 
00116 // The TransitNetwork class. It's a graph.
00117 class TransitNetwork {
00118  public:
00119   // The time needed to get off a vehicle and to board another.
00120   static const int TRANSFER_BUFFER;
00121   // The farthest distance between stops that can be walked.
00122   static const float MAX_WALKWAY_DIST;
00123 
00124   // Constructor
00125   explicit TransitNetwork();
00126 
00127   // Destructor
00128   ~TransitNetwork();
00129 
00130   // Copy Constructor
00131   TransitNetwork(const TransitNetwork& other);
00132 
00133   // Assignment Operator
00134   TransitNetwork& operator=(const TransitNetwork& other);
00135 
00136   // Resets the TransitNetwork, clearing all data.
00137   void reset();
00138 
00139   // A Validity check for the graph. Asserts on error.
00140   void validate() const;
00141 
00142   // Performs all actions that have to be done after both parsing and loading
00143   // a network. I.e. construct stuff that cannot be serialized.
00144   void preprocess();
00145 
00146   // Creates a compressed, i.e. time independent version of the network: For
00147   // each stop it has one node and between two nodes there is an arc with cost
00148   // as the cost of the fastest connection between two arrival and departure of
00149   // the  corresponding stops in the original network.
00150   TransitNetwork createTimeCompressedNetwork() const;
00151   FRIEND_TEST(DijkstraTest, compressedNetwork);
00152 
00153   // Creates a mirrored version of the network: For each arc, there is an arc of
00154   // opposite direction and equal cost. Used to determine connected components.
00155   const TransitNetwork mirrored() const;
00156 
00157   // Returns the largest connected component if we consider the network as bi-
00158   // directional graph. NOTE(jonas): Right now, the component has the same arcs
00159   // and nodes as the original network. Just the stops are filtered.
00160   const TransitNetwork largestConnectedComponent() const;
00161   FRIEND_TEST(TransitNetworkTest, largestConnectedComponent);
00162 
00163   // Sets the network name.
00164   void name(const string& name);
00165 
00166   // Returns the network name;
00167   string name() const;
00168 
00169   // Returns the number of nodes.
00170   size_t numNodes() const;
00171 
00172   // Returns the number of Arcs.
00173   size_t numArcs() const;
00174 
00175   // Returns the number of stops.
00176   size_t numStops() const;
00177 
00178   // Returns node reference for given node index.
00179   inline const Node& node(const size_t node) const { return _nodes.at(node); }
00180 
00181   // Returns a reference to the vector of adjacency lists.
00182   const vector<vector<Arc> >& adjacencyLists() const;
00183 
00184   // Returns a reference to the adjacency list of given node.
00185   const vector<Arc>& adjacencyList(const size_t node) const;
00186 
00187   // Returns stop reference for given stop index.
00188   const Stop& stop(const size_t stop) const;
00189 
00190   // Returns stop reference for given stop index.  TODO(sawine): unsafe.
00191   Stop& stop(const size_t stop);
00192 
00193   // Returns a reference to the i-th walkwayList of the walking graph. Its
00194   // elements are the arcs starting at stop i.
00195   const vector<Arc>& walkwayList(const int i) const;
00196 
00197   // Get the walking arc between two stops. Result is empty, when there is no
00198   // such arc and contains the single arc otherwise.
00199   vector<Arc> walkway(const int stopFrom, const int stopTo) const;
00200 
00201   // Returns a reference to the KDTree of stops.
00202   const StopTree& stopTree() const;
00203 
00204   // Adds a new node, returns its index in the _nodes vector.
00205   int addTransitNode(const int stopIndex, const Node::Type& type,
00206                      int time);
00207 
00208   // Adds a stop to the network.
00209   void addStop(Stop& stop);  // NOLINT
00210 
00211   // Adds an arc to target with cost to the adjacency list of source. Handicap
00212   // is set to 0 if not specified.
00213   void addArc(int source, int target, int cost);
00214   void addArc(int source, int target, int cost, int penalty);
00215 
00216   // Returns the nearest stop to the given coordinates.
00217   // Returns NULL if no suitable stop could be found.
00218   const Stop* findNearestStop(const float lat, const float lon) const;
00219 
00220   // Returns suitable start nodes for given stop and time.
00221   vector<int> findStartNodeSequence(const Stop& stop, const int ptime) const;
00222 
00223   // Returns all dep Nodes of the given stop
00224   const vector<int> getDepNodes(const int stopIndex) const;
00225 
00226   // Returns the index of stop given by stop id.
00227   // Returns -1 if stop id is not known.
00228   int stopIndex(const string& id) const;
00229 
00230   const GeoInfo& geoInfo() const;
00231 
00232   // Returns a string representation for debug purposes.
00233   string debugString() const;
00234   // Returns a string representation of the walking graph for debug purposes.
00235   string debugStringOfWalkingGraph() const;
00236 
00237  private:
00238   // For a certain STOP returns the position in stop.nodeIndices i for the first
00239   // node after TIME.
00240   int findFirstNode(const Stop& stop, const int time) const;
00241   FRIEND_TEST(TransitNetworkTest, findFirstNode);
00242 
00243   // Constructs the kdtree from the vector of stops.
00244   void buildKdtreeFromStops();
00245 
00246   // Constructs the graph of walking arcs between stops. Retrieves the neighbors
00247   // within a certain distance (in meters) for all stops and adds arcs to those
00248   // with costs according to the manhattan distance.
00249   void buildWalkingGraph(const float dist);
00250   FRIEND_TEST(GtfsParserTest, walkingGraphConstruction);
00251   FRIEND_TEST(GtfsParserTest, walkingGraphNonReflexive);
00252 
00253   // Computes geometric information about the network: center, min, max
00254   void computeGeoInfo();
00255   FRIEND_TEST(TransitNetworkTest, computeGeoInfo);
00256 
00257   // Performs breadth first search remembering visited nodes. Used on mirrored
00258   // time-compressed networks to determine connected components.
00259   vector<size_t> connectedComponentNodes(size_t startNode) const;
00260 
00261   vector<Node> _nodes;
00262   vector<vector<Arc> > _adjacencyLists;
00263   size_t _numArcs;
00264 
00265   vector<Stop> _stops;
00266   // Walking arcs between stops.
00267   vector<vector<Arc> > _walkwayLists;
00268   // A (2-)Kdtree to locate the nearest stop to a certain lat-lon-coordinate.
00269   StopTree _mapOfStops;
00270   // Geometric information on the network.
00271   GeoInfo _geoInfo;
00272 
00273   dense_hash_map<string, int> _stopId2indexMap;
00274   string _name;
00275 
00276   // serialization / deserialization: add new members to the archive using '&'
00277   // cannot serialize the kd tree, reconstruct it after deserialization
00278   template<class Archive>
00279   void serialize(Archive& ar, const unsigned int version) {  // NOLINT
00280     ar & _nodes;
00281     ar & _adjacencyLists;
00282     ar & _numArcs;
00283     ar & _stops;
00284     ar & _walkwayLists;
00285 //     ar & _stopId2indexMap;  // <-- not serializeable
00286     ar & _name;
00287   }
00288   FRIEND_TEST(GtfsParserTest, serialization);
00289   friend class boost::serialization::access;
00290   friend class GtfsParser;
00291 };
00292 
00293 
00294 #endif  // SRC_TRANSITNETWORK_H_
 All Classes