### Install pfaedle Source: https://github.com/ad-freiburg/pfaedle/blob/master/README.md Install the built pfaedle binaries. ```shell $ make install ``` -------------------------------- ### Config constructor initializes defaults Source: https://github.com/ad-freiburg/pfaedle Initializes all configuration fields with their default values in the PfaedleConfig.h constructor. Used as the starting point for all configuration options. ```cpp Config() : dbgOutputPath("."), solveMethod("global"), outputPath("gtfs-out"), dropShapes(false), useHMM(false), writeGraph(false), buildTransitGraph(false), useCaching(false), writeOverpass(false), writeOsmfilter(false), inPlace(false), writeColors(false), noFastHops(false), noAStar(false), noTrie(false), noHopCache(false), writeStats(false), parseAdditionalGTFSFields(false), gridSize(2000 / util::geo::M_PER_DEG), boxPadding(20000), gaussianNoise(0), verbosity(0) {} ``` -------------------------------- ### pfaedle CLI invocation with config file and inline MOT parameters Source: https://github.com/ad-freiburg/pfaedle Shows two example invocations of the pfaedle command-line tool. The first uses an explicit config file with the -c flag, and the second adds inline MOT parameters using -P. Both require an OSM file and a GTFS feed as positional arguments. ```bash # With an explicit config file pfaedle -c /custom/pfaedle.cfg -x region.osm.pbf feed.zip # With extra inline MOT parameters pfaedle -x region.osm.pbf feed.zip -P "routing_transition_penalty_fac: 0.01" ``` -------------------------------- ### Error-handling example (shell) Source: https://github.com/ad-freiburg/pfaedle Shows exit code 5 (RetCode::NO_OSM_INPUT) when the OSM file is missing. If OSM parse fails, exits with RetCode::OSM_PARSE_ERR (7); malformed GTFS yields RetCode::GTFS_PARSE_ERR (4). ```bash pfaedle -x missing.osm.pbf feed.zip echo $? # prints 5 == RetCode::NO_OSM_INPUT if the OSM file is missing ``` -------------------------------- ### Normalizer usage example from pfaedle.cfg station_normalize_chain (C++) Source: https://github.com/ad-freiburg/pfaedle Shows how to construct a Normalizer with a ReplRules list and normalize a string. The rules replace dots, parenthesized content, and whitespace with spaces. The example normalizes ' Hauptbahnhof Freiburg '. ```cpp trgraph::ReplRules rules = { {"\\.", " "}, {"\\(.+\\)", " "}, {"\\s+", " "}}; pfaedle::trgraph::Normalizer norm(rules); std::string n = norm.norm(" Hauptbahnhof Freiburg "); // normalized ``` -------------------------------- ### shapevl example invocation Source: https://github.com/ad-freiburg/pfaedle Example command that runs shapevl with a ground-truth GTFS file and a candidate shapes file, outputting JSON with averaged results. ```bash shapevl -g ground-truth.zip candidate-shapes.zip --json --avg ``` -------------------------------- ### Reading OSM data via OsmSource interface Source: https://github.com/ad-freiburg/pfaedle Use this example to read OSM data through the abstract OsmSource interface, selecting PBFSource or XMLSource based on file extension. The loop processes nodes and attributes, handling missing nodes by seeking or breaking when no more data is available. ```cpp #include "pfaedle/osm/source/XMLSource.h" #include "pfaedle/osm/source/PBFSource.h" // Reading via the abstract interface pfaedle::osm::source::OsmSource* src; if (path ends_with ".pbf") src = new PBFSource(path); else src = new XMLSource(path); while (src->cont()) { const auto* node = src->nextNode(); if (!node) { if (src->cont()) src->seekNodes(); else break; } // consume attributes via src->nextAttr() } delete src; ``` -------------------------------- ### Generate shapes for Freiburg GTFS dataset Source: https://github.com/ad-freiburg/pfaedle/blob/master/README.md Example workflow to download the Freiburg GTFS feed and OSM data, then run pfaedle with the -D flag to replace existing shapes. ```shell $ wget https://www.vag-freiburg.de/fileadmin/gtfs/VAGFR.zip $ wget http://download.geofabrik.de/europe/germany/baden-wuerttemberg/freiburg-regbez-latest.osm.pbf $ pfaedle -D -x freiburg-regbez-latest.osm.pbf VAGFR.zip ``` -------------------------------- ### CMake build configuration for pfaedle Source: https://github.com/ad-freiburg/pfaedle/blob/master/CMakeLists.txt Defines the CMake project for pfaedle with C++11 standard, compiler flags for various build types, optional library detection (LibZip, ZLIB, BZip2), Git revision tracking, submodule initialization, and install targets for binaries and config file. ```cmake cmake_minimum_required (VERSION 3.6) set(CMAKE_CXX_STANDARD 11) project (pfaedle) if (CMAKE_BUILD_TYPE) string(SUBSTRING ${CMAKE_BUILD_TYPE} 0 1 FIRST_CHAR) string(TOUPPER ${FIRST_CHAR} FIRST_CHAR) string(REGEX REPLACE "^.(.*)" "${FIRST_CHAR}\\1" CMAKE_BUILD_TYPE "${CMAKE_BUILD_TYPE}") endif() enable_testing() set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} "${CMAKE_SOURCE_DIR}/cmake/") set(EXECUTABLE_OUTPUT_PATH "${CMAKE_BINARY_DIR}") # set compiler flags, see http://stackoverflow.com/questions/7724569/debug-vs-release-in-cmake set(CMAKE_CXX_FLAGS "-O -fno-signed-zeros -fno-trapping-math -Wall -Wno-format-extra-args -Wextra -Wformat-nonliteral -Wformat-security -Wformat=2 -Wextra -Wno-implicit-fallthrough -pedantic -Wno-keyword-macro") set(CMAKE_CXX_FLAGS_SANITIZE "-Og -g -fsanitize=address -fsanitize=leak -fsanitize=undefined -DLOGLEVEL=3 -DPFAEDLE_DBG=1") set(CMAKE_CXX_FLAGS_PROFILE "-g -pg -DLOGLEVEL=3 -DPFAEDLE_DBG=1") set(CMAKE_CXX_FLAGS_DEBUG "-Og -g -DLOGLEVEL=3 -DPFAEDLE_DBG=1") set(CMAKE_CXX_FLAGS_MINSIZEREL "${CMAKE_CXX_FLAGS} -DLOGLEVEL=2") set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS} -DLOGLEVEL=2") set(CMAKE_CXX_FLAGS_RELWITHDEBINFO "${CMAKE_CXX_FLAGS} -g -DLOGLEVEL=3") # export compile commands to tools like clang set(CMAKE_EXPORT_COMPILE_COMMANDS ON) set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -DPFAEDLE_PRECISION=${PFAEDLE_PRECISION}") find_package(LibZip) find_package(ZLIB) find_package(BZip2) if (LIBZIP_FOUND) set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -DLIBZIP_FOUND=1") endif() if (ZLIB_FOUND) set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -DZLIB_FOUND=1") else () set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -DPFXML_NO_ZLIB=1") endif() if (BZIP2_FOUND) set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -DBZLIB_FOUND=1") else () set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -DPFXML_NO_BZLIB=1") endif() # http://brianmilco.blogspot.de/2012/11/cmake-automatically-use-git-tags-as.html include(GetGitRevisionDescription) git_get_tag(VERSION_GIT) get_git_is_dirty(VERSION_GIT_IS_DIRTY) if ("${VERSION_GIT_IS_DIRTY}" STREQUAL "") set(VERSION_GIT_FULL "${VERSION_GIT}") else() set(VERSION_GIT_FULL "${VERSION_GIT}-${VERSION_GIT_IS_DIRTY}") endif() # Download submodules if needed if(NOT EXISTS ${CMAKE_SOURCE_DIR}/src/configparser/.git OR NOT EXISTS ${CMAKE_SOURCE_DIR}/src/cppgtfs/.git OR NOT EXISTS ${CMAKE_SOURCE_DIR}/src/xml/.git) execute_process( COMMAND git submodule update --init --recursive ) endif() add_subdirectory(src) # tests add_test("utilTest" utilTest) add_test("pfaedleTest" pfaedleTest) # handles install target install( FILES pfaedle.cfg DESTINATION etc/${PROJECT_NAME} COMPONENT config PERMISSIONS OWNER_READ GROUP_READ WORLD_READ ) install( FILES ${CMAKE_BINARY_DIR}/pfaedle DESTINATION bin PERMISSIONS OWNER_EXECUTE GROUP_EXECUTE WORLD_EXECUTE COMPONENT binaries ) install( FILES ${CMAKE_BINARY_DIR}/shapevl DESTINATION bin PERMISSIONS OWNER_EXECUTE GROUP_EXECUTE WORLD_EXECUTE COMPONENT binaries ) ``` -------------------------------- ### ConfigReader::help Source: https://github.com/ad-freiburg/pfaedle Prints the full usage/help text, including the compiled version, build date, geometry precision, and the complete list of options with defaults. Used by both the `-h` branch of `read` and the Docker entrypoint. ```APIDOC ## ConfigReader::help ### Description Prints the full usage/help text, including the compiled version, build date, geometry precision (`PFDL_PREC_STR`, e.g. `double`), and the complete list of options with defaults. Used by both the `-h` branch of `read` and the Docker entrypoint. `help` itself only writes to `std::cout`. ### Method static void help(const char* bin) ### Parameters - **bin** (const char*) - Required - The binary name to display in the help text. ### Returns void ``` -------------------------------- ### ConfigReader::help signature Source: https://github.com/ad-freiburg/pfaedle Prints usage/help text including version, build date, geometry precision, and options with defaults. Used by -h branch and Docker entrypoint. ```cpp static void help(const char* bin); ``` -------------------------------- ### Clone repository with submodules Source: https://github.com/ad-freiburg/pfaedle/blob/master/README.md Fetch the pfaedle repository and initialize its submodules. ```shell $ git clone --recurse-submodules https://github.com/ad-freiburg/pfaedle ``` -------------------------------- ### Build pfaedle with CMake Source: https://github.com/ad-freiburg/pfaedle/blob/master/README.md Create a build directory, configure with CMake, and compile. ```shell $ mkdir build && cd build $ cmake .. $ make -j ``` -------------------------------- ### HopCache class declaration Source: https://github.com/ad-freiburg/pfaedle Declares the HopCache class with a get method returning a pair of uint32_t and bool, where the bool indicates whether the value was found. ```cpp class HopCache { ... std::pair get(...) const; ... }; ``` -------------------------------- ### MotConfigReader::getConfigs method signature Source: https://github.com/ad-freiburg/pfaedle Returns the parsed MotConfig list for main to iterate and match MOTs. ```cpp const std::vector& getConfigs() const; ``` -------------------------------- ### HopCache class definition in HopCache.h Source: https://github.com/ad-freiburg/pfaedle Caches known route costs between edges to avoid recomputing Dijkstra when the same hop cost is requested. setMin records a minimum bound; setEx records an exact value; get returns (value, found). ```cpp class HopCache { public: void setMin(const trgraph::Edge* a, const trgraph::Edge* b, uint32_t val); void setMin(const trgraph::Edge* a, const std::set& b, uint32_t val); void setMin(const std::set& a, const trgraph::Edge* b, uint32_t val); void setEx(const trgraph::Edge* a, const trgraph::Edge* b, uint32_t val); std::pair get(const trgraph::Edge* a, const trgraph::Edge* b) const; private: util::SparseMatrix _cache; }; ``` -------------------------------- ### Basic map-matching run (shell) Source: https://github.com/ad-freiburg/pfaedle Runs pfaedle with an OSM file and a GTFS feed. Parses one GTFS feed, builds the OSM graph, matches all MOTs, and writes the shape-ful feed to ./gtfs-out (default outputPath). ```bash pfaedle -x freiburg-regbez-latest.osm.pbf VAGFR.zip ``` -------------------------------- ### MotConfigReader::parse method signature Source: https://github.com/ad-freiburg/pfaedle Parses configuration files in order (later overriding earlier) plus an optional literal string. Throws configparser::ParseExc on malformed input. ```cpp void parse(const std::vector& paths, const std::string& literal); ``` -------------------------------- ### OsmWriter abstract class definition Source: https://github.com/ad-freiburg/pfaedle Abstract pull-driven writer for filtered OSM output. start()/finish() bracket the document; writeNode/writeNd/writeWay/writeRel write entities; getBounds reports the output bound; cont() signals whether more data can be written. ```cpp class OsmWriter { public: virtual ~OsmWriter() {}; virtual void writeNode(const OsmNode& n) = 0; virtual void writeNd(osmid nd) = 0; virtual void writeWay(const OsmWay& w) = 0; virtual void writeRel(const OsmRel& r) = 0; virtual void start() = 0; virtual void finish() = 0; virtual util::geo::Box getBounds() = 0; virtual bool cont() = 0; }; ``` -------------------------------- ### Using JaccardGeodistClassifier for station similarity Source: https://github.com/ad-freiburg/pfaedle Example usage of the JaccardGeodistClassifier. It provides two overloads: 'similar(a, b)' for name-only comparison and 'similar(a, posA, b, posB)' for name plus position. A false result for the spatial check indicates a terminus mismatch, which leads to route penalization. ```cpp #include "pfaedle/statsimi-classifier/StatsimiClassifier.h" #include "pfaedle/Def.h" pfaedle::statsimiclassifier::JaccardGeodistClassifier cls; std::string a = "freiburg hauptbahnhof"; std::string b = "freiburg hbf"; POINT posA(7.59, 47.99), posB(7.598, 47.997); bool sameName = cls.similar(a, b); // name-only bool sameSpat = cls.similar(a, posA, b, posB); // name + position if (!sameSpat) { /* terminus mismatch → route penalized */ } ``` -------------------------------- ### XMLSource constructor declaration Source: https://github.com/ad-freiburg/pfaedle Constructor for XMLSource. Opens an OSM XML file, supporting .gz and .bz2 compression when compiled with zlib/bzlib. May throw pfxml::parse_exc. ```cpp XMLSource(const std::string& path); ``` -------------------------------- ### ConfigReader::read Source: https://github.com/ad-freiburg/pfaedle Parses CLI options into a Config via POSIX getopt_long. It populates the target Config with feed paths, MOTs, and optionally prints the resulting configuration. ```APIDOC ## ConfigReader::read ### Description Parses CLI options into a `Config` via POSIX `getopt_long`. After option parsing, all remaining positional arguments are appended to `cfg->feedPaths`. The `-m` MOT value is split on `,` and each token resolved via `ad::cppgtfs::gtfs::flat::Route::getTypesFromString` and inserted into `cfg->mots`. If `-p` is passed, the resulting configuration is printed via `cfg->toString()`. ### Method static void read(Config* targetConfig, int argc, char** argv) ### Parameters - **targetConfig** (Config*) - Required - The `Config` to populate (modified in place). - **argc** (int) - Required - The standard `main` argument count. - **argv** (char**) - Required - The standard `main` argument vector. ### Returns void ``` -------------------------------- ### PBFSource constructor declaration Source: https://github.com/ad-freiburg/pfaedle Constructor for PBFSource. Opens a .pbf OSM file and decodes its header, including bbox and feature lists. Blob decoding is handled by util::protobuf::Protobuf. ```cpp PBFSource(const std::string& path); ``` -------------------------------- ### Run pfaedle via Docker Source: https://github.com/ad-freiburg/pfaedle/blob/master/README.md Mount OSM and GTFS data into the container and run pfaedle. The command pulls the latest image and mounts volumes for OSM data, GTFS data, and the output directory. The -x and -i flags specify the OSM and GTFS input files. ```shell $ docker pull ghcr.io/ad-freiburg/pfaedle:latest $ docker run -i --rm \ # mount OSM data --volume /path/to/osm/data:/osm \ # mount GTFS data --volume /path/to/gtfs/data:/gtfs \ # mount default output folder gtfs-out --volume /path/to/output-dir:/gtfs-out \ ghcr.io/ad-freiburg/pfaedle:latest \ # tell pfaedle where to find the data -x /osm/osm-data.xml.bz2 -i /gtfs/myfeed.zip ``` -------------------------------- ### getCfgPaths function declaration Source: https://github.com/ad-freiburg/pfaedle Returns config files to parse. If cfg.configPaths is non-empty (i.e., -c flag given), returns those; otherwise probes implicit locations in order and returns existing ones. Later files override earlier ones during MotConfigReader::parse. File-local to PfaedleMain.cpp. ```cpp std::vector getCfgPaths(const Config& cfg); ``` -------------------------------- ### Querying a BBoxIdx for cropping Source: https://github.com/ad-freiburg/pfaedle Shows how to construct a BBoxIdx with a padding of 20000 meters, add a box, check if a station point is contained, and retrieve the full bounding box. ```cpp pfaedle::osm::BBoxIdx box(20000); box.add(util::geo::Box(p1, p2)); if (!box.contains(stationPoint)) { /* OSM element outside crop, skip */ } auto full = box.getFullBox(); ``` -------------------------------- ### ConfigReader::read signature Source: https://github.com/ad-freiburg/pfaedle Parses CLI options into a Config via POSIX getopt_long. Appends positional arguments to feedPaths, splits -m on commas, and prints config if -p is passed. Terminates on -v, -h, missing argument, or unknown option. ```cpp static void read(Config* targetConfig, int argc, char** argv); ``` -------------------------------- ### gtfsWarnCb logging callback Source: https://github.com/ad-freiburg/pfaedle Logging callback passed to the GTFS parser as the warning handler when cfg.verbosity != 0. Defined in src/pfaedle/PfaedleMain.cpp. ```cpp void gtfsWarnCb(std::string msg) { LOG(WARN) << msg; } ``` -------------------------------- ### CMake build configuration for pfaedle executable and library Source: https://github.com/ad-freiburg/pfaedle/blob/master/src/pfaedle/CMakeLists.txt Defines the build for the pfaedle executable and its dependency library. It collects all C++ sources, excludes the main file, configures a header, and links required libraries including pb_util, configparser, and ad_cppgtfs. Optional linking for libzip and bzip2 is conditionally added, and tests are included when CMAKE_TESTING_ENABLED is set. ```cmake file(GLOB_RECURSE pfaedle_SRC *.cpp) set(pfaedle_main PfaedleMain.cpp) list(REMOVE_ITEM pfaedle_SRC ${pfaedle_main}) include_directories( ${PFAEDLE_INCLUDE_DIR} ) configure_file ( "_config.h.in" "_config.h" ) add_executable(pfaedle ${pfaedle_main}) add_library(pfaedle_dep ${pfaedle_SRC}) target_include_directories(pfaedle_dep PUBLIC ${PROJECT_SOURCE_DIR}/src/xml/include/ ${PROJECT_SOURCE_DIR}/src/cppgtfs/src) target_link_libraries(pfaedle_dep PRIVATE pb_util pb_util_geo pb_util_graph pb_util_xml pb_util_json configparser ad_cppgtfs -lpthread) target_link_libraries(pfaedle PRIVATE pfaedle_dep pb_util pb_util_geo pb_util_graph pb_util_xml pb_util_json configparser ad_cppgtfs -lpthread) if (LIBZIP_FOUND) target_link_libraries(pfaedle PRIVATE ${LIBZIP_LIBRARY}) endif( LIBZIP_FOUND ) if (BZIP2_FOUND) target_link_libraries(pfaedle PRIVATE ${BZIP2_LIBRARY}) endif( BZIP2_FOUND ) if(CMAKE_TESTING_ENABLED) add_subdirectory(tests) endif() ``` -------------------------------- ### ConfigReader class declaration Source: https://github.com/ad-freiburg/pfaedle Declares the ConfigReader class with static methods read and help. ```cpp class ConfigReader { public: static void read(Config* targetConfig, int argc, char** argv); static void help(const char* bin); }; ``` -------------------------------- ### getFileNameMotStr function declaration Source: https://github.com/ad-freiburg/pfaedle Maps a set of route MOTs to a human-readable filename suffix (e.g., bus, rail, tram-subway), falling back to numeric GTFS route-type strings. Used to name per-MOT transit-graph output. File-local to PfaedleMain.cpp. ```cpp std::string getFileNameMotStr(const MOTs& mots); ``` -------------------------------- ### Reading a configuration programmatically (application usage) Source: https://github.com/ad-freiburg/pfaedle Use this snippet to parse a configuration file programmatically in a C++ application. It creates a Config and MotConfigReader, parses the given paths, and catches a configparser::ParseExc exception, returning error code 6 (RetCode::MOT_CFG_PARSE_ERR) on failure. After parsing, it retrieves the MotConfig objects and computes the maximum maxSpeed from their osmBuildOpts. ```cpp #include "pfaedle/config/MotConfigReader.h" #include "pfaedle/config/PfaedleConfig.h" pfaedle::config::Config cfg; pfaedle::config::MotConfigReader reader; std::vector paths = {"/etc/pfaedle/pfaedle.cfg"}; try { reader.parse(paths, cfg.motCfgParam); } catch (const configparser::ParseExc& ex) { std::cerr << "parse failed: " << ex.what() << "\n"; return 6; // RetCode::MOT_CFG_PARSE_ERR } std::vector cfgs = reader.getConfigs(); double maxSpeed = 0; for (const auto& c : cfgs) maxSpeed = std::max(maxSpeed, c.osmBuildOpts.maxSpeed); ``` -------------------------------- ### Full matching run as done by main Source: https://github.com/ad-freiburg/pfaedle Complete workflow for shape matching across all trips. Requires a parsed feed, MOT configurations from MotConfigReader, and runtime config. Builds graph, classifier, and router, then calls shapeify on all trips. Deletes classifier and router after use. ```cpp #include "pfaedle/router/ShapeBuilder.h" #include "pfaedle/router/Router.h" #include "pfaedle/router/Weights.h" #include "pfaedle/router/Stats.h" #include "pfaedle/statsimi-classifier/StatsimiClassifier.h" #include "pfaedle/netgraph/Graph.h" #include "pfaedle/gtfs/Feed.h" pfaedle::gtfs::Feed feed; // parsed feed std::vector motCfgs; // from MotConfigReader config::Config cfg; // runtime config for (const auto& motCfg : motCfgs) { osm::Restrictor restr; trgraph::Graph graph; router::FeedStops fStops = router::writeMotStops(&feed, motCfg.mots, cfg.shapeTripId); osm::BBoxIdx box(cfg.boxPadding); ShapeBuilder::getGtfsBox(&feed, usedMots, cfg.shapeTripId, cfg.dropShapes, &box, motCfg.osmBuildOpts.maxSpeed, 0, cfg.verbosity); osm::OsmBuilder builder; if (fStops.size()) builder.read(cfg.osmPath, motCfg.osmBuildOpts, &graph, box, cfg.gridSize, &restr); StatsimiClassifier* cls = new JaccardGeodistClassifier(); Router* router = new RouterImpl(); ShapeBuilder shapeBuilder(&feed, usedMots, motCfg, &graph, &fStops, &restr, cls, router, cfg); netgraph::Graph ng; Stats stats = shapeBuilder.shapeify(&ng); // all trips delete cls; delete router; } ``` -------------------------------- ### Debug a single trip and drop existing shapes Source: https://github.com/ad-freiburg/pfaedle Runs pfaedle with debug flags to look up trip VAG-123. On success emits dbg/path.json as GeoJSON and exits SUCCESS. ```bash mkdir dbg pfaedle -D -T VAG-123 -d dbg -x region.osm.pbf feed.zip ``` -------------------------------- ### ShapeBuilder constructor Source: https://github.com/ad-freiburg/pfaedle Constructs a ShapeBuilder instance with the required dependencies for shape construction. ```APIDOC ## ShapeBuilder constructor ### Description Constructs a ShapeBuilder instance with the required dependencies for shape construction. ### Method Constructor ### Parameters - `feed` (pfaedle::gtfs::Feed*) - Required - Pointer to the GTFS feed. - `mots` (MOTs) - Required - Modes of transport. - `motCfg` (const config::MotConfig&) - Required - Mode configuration. - `g` (trgraph::Graph*) - Required - Pointer to the transit graph. - `stops` (router::FeedStops*) - Required - Pointer to feed stops. - `restr` (osm::Restrictor*) - Required - Pointer to the OSM restrictor. - `classifier` (const pfaedle::statsimiclassifier::StatsimiClassifier*) - Required - Pointer to the classifier. - `router` (router::Router*) - Required - Pointer to the router. - `cfg` (const config::Config&) - Required - Configuration. ### Response No return value. ``` -------------------------------- ### main function declaration Source: https://github.com/ad-freiburg/pfaedle Entry point of the pfaedle binary. Returns a process exit code corresponding to one of the RetCode values. ```cpp int main(int argc, char** argv); ``` -------------------------------- ### Populate and write netgraph with GeoGraphJsonOutput Source: https://github.com/ad-freiburg/pfaedle Shows how to fill the netgraph via ShapeBuilder::shapeify and serialize it to a JSON file using GeoGraphJsonOutput. Requires --write-trgraph to be set in main. ```cpp #include "pfaedle/netgraph/Graph.h" #include "util/geo/output/GeoGraphJsonOutput.h" pfaedle::netgraph::Graph ng; shapeBuilder.shapeify(&ng); // fill the transit network graph util::geo::output::GeoGraphJsonOutput out; std::ofstream fstr("trgraph.json"); out.print(ng, fstr); fstr.close(); ``` -------------------------------- ### Config struct definition with defaults Source: https://github.com/ad-freiburg/pfaedle Defines the Config struct capturing all runtime options for pfaedle. The constructor initializes every field to its default value, which are documented in the field table and mapped to CLI flags in configuration.md. toString() renders a human-readable dump for the -p debug flag. ```cpp struct Config { Config() : dbgOutputPath("."), solveMethod("global"), outputPath("gtfs-out"), dropShapes(false), useHMM(false), writeGraph(false), buildTransitGraph(false), useCaching(false), writeOverpass(false), writeOsmfilter(false), inPlace(false), writeColors(false), noFastHops(false), noAStar(false), noTrie(false), noHopCache(false), writeStats(false), parseAdditionalGTFSFields(false), gridSize(2000 / util::geo::M_PER_DEG), boxPadding(20000), gaussianNoise(0), verbosity(0) {} std::string dbgOutputPath; std::string solveMethod; std::string shapeTripId; std::string outputPath; std::string writeOsm; std::string osmPath; std::string motCfgParam; std::vector feedPaths; std::vector configPaths; std::set mots; bool dropShapes; bool useHMM; bool writeGraph; bool buildTransitGraph; bool useCaching; bool writeOverpass; bool writeOsmfilter; bool inPlace; bool writeColors; bool noFastHops; bool noAStar; bool noTrie; bool noHopCache; bool writeStats; bool parseAdditionalGTFSFields; double gridSize; double boxPadding; double gaussianNoise; uint8_t verbosity; std::string toString() { ... } }; ``` -------------------------------- ### Constants in Router.h Source: https://github.com/ad-freiburg/pfaedle Defines infinity sentinels for route costs, distances, predecessor indices, and the max number of route cost-doubling iterations used to grow the search bound. ```cpp constexpr static uint32_t ROUTE_INF = std::numeric_limits::max(); constexpr static double DBL_INF = std::numeric_limits::infinity(); constexpr static size_t NO_PREDE = std::numeric_limits::max(); constexpr static int MAX_ROUTE_COST_DOUBLING_STEPS = 3; ``` -------------------------------- ### RouterImpl class template declaration Source: https://github.com/ad-freiburg/pfaedle Template class implementing Router. Provides route, hops, hopsFast, connected, cacheDrop, and addNonOverflow methods. Instantiated with weight types based on transPenMethod and noAStar options. ```cpp template class RouterImpl : public Router { public: virtual std::map route( const TripTrie* trie, const EdgeCandMap& ecm, const RoutingOpts& rOpts, const osm::Restrictor& rest, HopCache* hopCache, bool noFastHops) const; private: void hops(const EdgeCandGroup& from, const EdgeCandGroup& to, CostMatrix* rCosts, CostMatrix* dists, const RoutingAttrs& rAttrs, const RoutingOpts& rOpts, const osm::Restrictor& rest, HopCache* hopCache, uint32_t maxCost) const; void hopsFast(const EdgeCandGroup& from, const EdgeCandGroup& to, const LayerCostsDAG& initCosts, CostMatrix* rCosts, const RoutingAttrs& rAttrs, const RoutingOpts& rOpts, const osm::Restrictor& rest, HopCache* hopCache, uint32_t maxCost) const; bool connected(const EdgeCand& from, const EdgeCandGroup& tos) const; bool connected(const EdgeCandGroup& froms, const EdgeCand& to) const; bool cacheDrop(HopCache* hopCache, const std::set& froms, const trgraph::Edge* to, uint32_t maxCost) const; uint32_t addNonOverflow(uint32_t a, uint32_t b) const; }; ``` -------------------------------- ### Comp.h: statSimi and lineSimi declarations Source: https://github.com/ad-freiburg/pfaedle Declarations for string similarity helpers used in station name and line short-name matching. statSimi returns true if strings are equal, one is a prefix/suffix (plus trailing space) of the other, or normalized edit distance is < 0.05 of the longer string. lineSimi uses the same prefix/suffix logic but without edit distance fallback. ```cpp inline bool statSimi(const std::string& a, const std::string& b); inline bool lineSimi(const std::string& a, const std::string& b); ``` -------------------------------- ### Catch configparser::ParseExc when parsing MOT config Source: https://github.com/ad-freiburg/pfaedle Wrap MotConfigReader::parse in a try-catch block to handle malformed MOT configuration files. The exception type is configparser::ParseExc. ```cpp try { motCfgReader.parse(paths, literal); } catch (const configparser::ParseExc& ex) { // malformed MOT config } ``` -------------------------------- ### Standalone route call with RouterImpl Source: https://github.com/ad-freiburg/pfaedle Shows a standalone routing call outside ShapeBuilder, mirroring main. Requires a TripTrie from ShapeBuilder and an EdgeCandMap of candidate edges per stop. The result maps trie nodes to EdgeListHops hop sequences. The routing method must be one of exp, distdiff, or timenorm; otherwise main logs 'Unknown routing method' and exits. ```cpp #include "pfaedle/router/Router.h" #include "pfaedle/router/Weights.h" #include "pfaedle/router/TripTrie.h" pfaedle::router::RoutingOpts rOpts; rOpts.transPenMethod = "exp"; rOpts.statsimiMethod = "jaccard-geodist"; osm::Restrictor rest; HopCache cache; Router* router = new RouterImpl(); const TripTrie* trie = /* from ShapeBuilder */; EdgeCandMap ecm; // candidate edges per stop std::map result = router->route(trie, ecm, rOpts, rest, &cache, /*noFastHops=*/false); delete router; for (const auto& kv : result) { // kv.first = trie node; kv.second = EdgeListHops hop sequence } ``` -------------------------------- ### NodePL::NodePL() Source: https://github.com/ad-freiburg/pfaedle Default constructor for NodePL. Creates an empty node payload. ```APIDOC ## NodePL::NodePL() ### Description Default constructor for NodePL. Creates an empty node payload. ### Method Constructor ### Signature `NodePL()` ### Parameters None ### Returns An empty NodePL object. ``` -------------------------------- ### BBoxIdx constructor Source: https://github.com/ad-freiburg/pfaedle Constructs a BBoxIdx with a padding amount in meters. The padding is used to expand the bounding boxes added to the index. ```APIDOC ## BBoxIdx(double padding) ### Description Constructs a BBoxIdx with a padding amount in meters. The padding is used to expand the bounding boxes added to the index. ### Parameters - `padding` (double) - Required - Padding amount in meters. ### Example ```cpp pfaedle::osm::BBoxIdx box(20000); ``` ``` -------------------------------- ### shapevl CLI usage Source: https://github.com/ad-freiburg/pfaedle Shows the command-line usage of the shapevl binary, including options for ground truth GTFS, summary output, JSON output, segment length, report folder, and MOT matching. ```text Usage: shapevl [-f ] -g [-s] -g Ground truth GTFS file -s Only output summary --json Output JSON --avg Take avg of all inputs (only for --json) --unique Only use trips with unique stop sequence --segment-length Segment length for Frechet distance (m), default 25 -f Output full reports (per feed) to -l Full report level (0 - 2), default 1 -m MOTs to match (GTFS MOT or string, default: all) ``` -------------------------------- ### Define pfaedleTest executable and link libraries Source: https://github.com/ad-freiburg/pfaedle/blob/master/src/pfaedle/tests/CMakeLists.txt Creates the pfaedleTest executable from TestMain.cpp and links it against the pfaedle_dep and pb_util libraries. ```cmake add_executable(pfaedleTest TestMain.cpp) target_link_libraries(pfaedleTest pfaedle_dep pb_util pb_util_geo pb_util_graph pb_util_xml pb_util_json) ``` -------------------------------- ### DistDiffTransWeight class Source: https://github.com/ad-freiburg/pfaedle Distance-difference transition penalty; needs distances (NEED_DIST=true), no fast route. ```cpp class DistDiffTransWeight : public ExpoTransWeight { public: static uint32_t maxCost(double tTime, const RoutingOpts& rOpts); static double weight(uint32_t c, double d, double t0, double d0, const RoutingOpts& rOpts); static uint32_t invWeight(double cost, const RoutingOpts& rOpts); static const bool ALLOWS_FAST_ROUTE = false; static const bool NEED_DIST = true; }; ``` -------------------------------- ### Accessing the parsed configuration aggregate Source: https://github.com/ad-freiburg/pfaedle Use this snippet to access and modify a parsed configuration aggregate. It creates a Config with all defaults applied, sets outputPath and dropShapes, and prints a debugging dump via toString(). Note that in shipped binaries, configuration is normally populated by ConfigReader::read as described in configuration.md. ```cpp #include "pfaedle/config/PfaedleConfig.h" pfaedle::config::Config cfg; // all defaults apply cfg.outputPath = "out-feed"; cfg.dropShapes = true; std::cout << cfg.toString() << std::endl; // debugging dump ``` -------------------------------- ### CMake build configuration for shapevl executable Source: https://github.com/ad-freiburg/pfaedle/blob/master/src/shapevl/CMakeLists.txt Defines the shapevl executable and its dependency library. Uses GLOB_RECURSE to collect all .cpp files, excludes the main file, and links required libraries including pb_util, ad_cppgtfs, and libzip. ```cmake file(GLOB_RECURSE shapevl_SRC *.cpp) set(shapevl_main ShapevlMain.cpp) list(REMOVE_ITEM shapevl_SRC ${shapevl_main}) include_directories( ${PFAEDLE_INCLUDE_DIR} SYSTEM ${LIBZIP_INCLUDE_DIR} SYSTEM ${LIBZIP_CONF_INCLUDE_DIR} ) add_executable(shapevl ${shapevl_main}) add_library(shapevl_dep ${shapevl_SRC}) include_directories(shapevl_dep PUBLIC ${PROJECT_SOURCE_DIR}/src/cppgtfs/src) target_link_libraries(shapevl shapevl_dep pb_util pb_util_geo pb_util_graph pb_util_xml pb_util_json ad_cppgtfs -lpthread ${LIBZIP_LIBRARY}) ``` -------------------------------- ### Building the routing graph (as done by main) Source: https://github.com/ad-freiburg/pfaedle Constructs the routing graph from an OSM PBF file using OsmBuilder, BBoxIdx, Restrictor, and Graph. Includes error handling that prints an error message and exits with code 7 (RetCode::OSM_PARSE_ERR) on runtime errors. ```cpp #include "pfaedle/osm/OsmBuilder.h" #include "pfaedle/osm/BBoxIdx.h" #include "pfaedle/osm/Restrictor.h" #include "pfaedle/trgraph/Graph.h" pfaedle::osm::OsmBuilder builder; pfaedle::osm::BBoxIdx box(20000); // 20 km padding pfaedle::osm::Restrictor restr; pfaedle::trgraph::Graph graph; pfaedle::osm::OsmReadOpts opts; // filled from config try { builder.read("region.osm.pbf", opts, &graph, box, 2000.0 / M_PER_DEG, &restr); } catch (const std::runtime_error& ex) { std::cerr << "OSM error: " << ex.what() << "\n"; exit(7); // RetCode::OSM_PARSE_ERR } ``` -------------------------------- ### Using the hop cache (HopCache set/get) Source: https://github.com/ad-freiburg/pfaedle Creates a HopCache, sets a cached hop cost between two edges (eA, eB) to 1500, then retrieves it with structured binding. The found flag indicates whether the cost was present in the cache. ```cpp pfaedle::router::HopCache cache; cache.setEx(eA, eB, 1500); auto [cost, found] = cache.get(eA, eB); if (found) { /* reuse cached hop cost */ } ``` -------------------------------- ### Supporting public types in OsmBuilder.h Source: https://github.com/ad-freiburg/pfaedle Defines candidate snap positions and node-search predicates used during station snapping. EqSearch accepts nodes with StatInfo::simi at least minSimi (default 0.9); BlockSearch rejects nodes with similarity below 0.5 or blockers. ```cpp struct NodeCand { double dist; Node* node; const Edge* fromEdge; int fullTurns; }; struct SearchFunc { virtual bool operator()(const Node* n, const StatInfo* si) const = 0; }; struct EqSearch : public SearchFunc { EqSearch() {} double minSimi = 0.9; bool operator()(const Node* cand, const StatInfo* si) const; }; struct BlockSearch : public SearchFunc { bool operator()(const Node* n, const StatInfo* si) const { if (n->pl().getSI() && n->pl().getSI()->simi(si) < 0.5) return true; return n->pl().isBlocker(); } }; inline bool operator<(const NodeCand& a, const NodeCand& b) { return a.fullTurns > b.fullTurns || a.dist > b.dist; } typedef std::priority_queue NodeCandPQ; ``` -------------------------------- ### RoutingOpts struct with default constructor Source: https://github.com/ad-freiburg/pfaedle Aggregate of routing options with default values for several fields. Some fields are uninitialized and filled from configuration. operator== compares all fields with float tolerance 0.01. ```cpp struct RoutingOpts { RoutingOpts() : fullTurnPunishFac(1000), fullTurnAngle(45), lineUnmatchedPunishFact(1), lineNameFromUnmatchedPunishFact(1), lineNameToUnmatchedPunishFact(1), noLinesPunishFact(1), platformUnmatchedPen(0), stationDistPenFactor(0), turnRestrCost(0), popReachEdge(true), noSelfHops(true) {} uint32_t fullTurnPunishFac; double fullTurnAngle; double lineUnmatchedPunishFact; double lineNameFromUnmatchedPunishFact; double lineNameToUnmatchedPunishFact; double noLinesPunishFact; double platformUnmatchedPen; double stationUnmatchedPen; double stationDistPenFactor; double nonStationPen; uint32_t turnRestrCost; bool popReachEdge; bool noSelfHops; bool useStations; double transitionPen; std::string transPenMethod; std::string emPenMethod; std::string statsimiMethod; }; ``` -------------------------------- ### PBFWriter Source: https://github.com/ad-freiburg/pfaedle Concrete OsmWriter that writes OSM PBF output. Construct with an output stream and a bounding box, then use inherited methods to write OSM entities. ```APIDOC ## PBFWriter ### Description Writes OSM PBF output. Inherits from OsmWriter and implements all virtual methods. ### Constructor - `PBFWriter(std::ostream* os, const util::geo::Box& bbox)` - Constructs a PBFWriter on the given output stream with the dataset bounding box. ### Methods - `virtual void writeNode(const OsmNode& n)` - Writes a node entity. - `virtual void writeNd(osmid nd)` - Writes a bare node reference inside a way. - `virtual void writeWay(const OsmWay& w)` - Writes a way entity. - `virtual void writeRel(const OsmRel& r)` - Writes a relation entity. - `virtual void start()` - Starts the output document. - `virtual void finish()` - Finishes the output document. - `virtual util::geo::Box getBounds()` - Returns the output bounds. - `virtual bool cont()` - Signals whether more data can be written. ``` -------------------------------- ### BBoxIdx::add Source: https://github.com/ad-freiburg/pfaedle Adds a box to the index. The box is padded by the padding amount specified in the constructor. ```APIDOC ## BBoxIdx::add(Box box) ### Description Adds a box to the index. The box is padded by the padding amount specified in the constructor. ### Parameters - `box` (Box) - Required - The box to add. ### Example ```cpp box.add(util::geo::Box(p1, p2)); ``` ``` -------------------------------- ### Shell script to inspect pfaedle exit code Source: https://github.com/ad-freiburg/pfaedle Shows how a shell can check the exit code of pfaedle using $? and handle different error conditions. The script prints a message for each possible exit code. ```bash pfaedle -x region.osm.pbf feed.zip rc=$? case $rc in 0) echo "ok" ;; 1) echo "no input feed" ;; ... esac ``` -------------------------------- ### OsmFilter::toString Source: https://github.com/ad-freiburg/pfaedle Returns a string representation of the filter. ```APIDOC ## [METHOD] OsmFilter::toString ### Description Returns a string representation of the filter. ### Method C++ method ### Endpoint OsmFilter::toString ### Response #### Success Response - **std::string** - A string representation of the filter ``` -------------------------------- ### BBoxIdx::getLeafs Source: https://github.com/ad-freiburg/pfaedle Returns the leaf boxes of the index. ```APIDOC ## BBoxIdx::getLeafs() const ### Description Returns the leaf boxes of the index. ### Returns - `std::vector>` - The leaf boxes. ```