Meowmob
generateOD(trip_df, shape, active_day_df, hldf, adult_population, output_dir, org_loc_cols=('org_lng', 'org_lat'), dest_loc_cols=('dest_lng', 'dest_lat'), cpu_cores=max(1, cpu_count() // 2), save_drived_products=True, od_type=['type3'])
¶
Generate weighted Origin-Destination (OD) matrices from trip-level data, using spatial joins, demographic weights, and user activity data. This function leverages multiprocessing to handle large datasets efficiently and can produce multiple types of OD matrices in a single pass.
Key Steps:
1. Shape File Preparation:
- Ensures the provided shape
GeoDataFrame uses EPSG:4326.
- Pre-builds a spatial index for quicker joins.
- Spatial Joins:
- Splits
trip_df
into load-balanced buckets (viagetLoadBalancedBuckets
) for parallel processing. -
Spatially joins origins and destinations against the
shape
to label each trip with "origin_geo_code" and "destination_geo_code". -
Filtering:
- Removes trips longer than 24 hours and stay durations over 3600 minutes.
-
Drops records without valid origin or destination geo-codes.
-
Disclosure Analysis:
- Aggregates trip counts by origin-destination pairs and user IDs to help identify any potential risk of user-level data disclosure.
-
Saves results in "disclosure_analysis_.csv".
-
Trip ID & Metrics:
- Assigns incremental
trip_id
s per user. -
Computes total trips per user and merges with
active_day_df
to calculate "trips per active day" (TPAD). -
Adding Demographic Data:
- Merges each record with user-level IMD quintiles and council info
from
hldf
. -
Adds placeholder columns for travel mode if needed.
-
Optional Saving of Intermediate Products (if
save_drived_products=True
): -
Saves non-aggregated flows, aggregated flows, stay points, and trip points in separate CSV files for further analysis.
-
Final OD Matrix Generation:
- Filters out infrequent or low-activity users based on active days and TPAD.
- For each OD type in
od_type
(e.g., "type1", "type2", "type3", "type4"), selects trips matching the time-of-day/week criteria. - Applies weighting (
getWeights
) to scale user trip counts to population-level estimates. - Aggregates trips, then calculates weighted trips with different weighting factors (activity, council, IMD) for each origin-destination pair.
- Saves the resulting OD matrix as a CSV (e.g., "type3_od.csv") and collects it in a list of OD DataFrames to be returned.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
trip_df
|
DataFrame
|
The main trip-level DataFrame. Must contain columns indicating user IDs,
timestamps (arrivals/departures), plus the origin/destination lat-lng
pairs (specified by |
required |
shape
|
GeoDataFrame
|
A GeoDataFrame containing the geographic boundaries (e.g., MSOA or LSOA). Must have a valid geometry column. This is used for spatial joins. |
required |
active_day_df
|
DataFrame
|
DataFrame with columns ["uid", "total_active_days"], representing how many days each user was active. |
required |
hldf
|
DataFrame
|
DataFrame mapping user IDs to home council and IMD quintile info. |
required |
adult_population
|
DataFrame
|
Contains population counts broken down by council and IMD quintile. |
required |
output_dir
|
str
|
Directory path where all output files will be saved. |
required |
org_loc_cols
|
Tuple[str, str]
|
Column names for the origin's (longitude, latitude). Defaults to ("org_lng", "org_lat"). |
('org_lng', 'org_lat')
|
dest_loc_cols
|
Tuple[str, str]
|
Column names for the destination's (longitude, latitude). Defaults to ("dest_lng", "dest_lat"). |
('dest_lng', 'dest_lat')
|
cpu_cores
|
int
|
Number of CPU cores to use for parallel processing. Defaults to half of available cores (at least 1). |
max(1, cpu_count() // 2)
|
save_drived_products
|
bool
|
Whether to save intermediate or "derived" datasets (e.g., stay points). Defaults to True. |
True
|
od_type
|
List[str]
|
Which OD matrix types to produce. Recognized values: - "type1": AM Peak Weekdays (7am–10am) - "type2": PM Peak Weekdays (4pm–7pm) - "type3": All Trips (default) - "type4": All Trips excluding type1 + type2 Passing multiple values produces multiple OD DataFrames. Defaults to ["type3"]. |
['type3']
|
Returns:
Type | Description |
---|---|
List[DataFrame]
|
List[pd.DataFrame]:
A list of OD matrix DataFrames, one for each type listed in |
Example
from meowmotion.meowmob import generateOD od_matrices = generateOD( trip_df=trip_data, shape=lsoa_shapes, active_day_df=active_days, hldf=home_locations, adult_population=population_stats, org_loc_cols=('org_lng', 'org_lat'), dest_loc_cols=('dest_lng', 'dest_lat'), output_dir='./output', cpu_cores=4, od_type=["type3", "type1"] ) print(od_matrices[0].head()) # OD matrix for "type3"
Source code in meowmotion/meowmob.py
308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 |
|
getActivityStats(df, output_dir, cpu_cores=max(1, int(cpu_count() / 2)))
¶
Compute per-month user activity (number of active days) in parallel and save to disk.
This function partitions the input DataFrame into load-balanced buckets (based on unique users), processes each bucket in parallel, and then combines the results. Each row in the returned DataFrame corresponds to a specific user and month, with a column indicating how many days that user was active during that month.
Key Points:
- Requires at least the columns "uid" and "datetime" in the input DataFrame.
- Uses multiprocessing to handle large datasets efficiently, controlled by cpu_cores
.
- Saves the final aggregated statistics to "activity_stats.csv" in the provided output directory.
- The returned DataFrame has columns:
* "uid"
* "month"
* "total_active_days" (number of unique days in that month with at least one record)
- Designed to produce monthly-level stats from typically yearly data. If you need
a yearly total, aggregate "total_active_days" across all months per user before
using these stats in any further steps (like OD generation).
Parameters:
Name | Type | Description | Default |
---|---|---|---|
df
|
DataFrame
|
The input DataFrame containing at least the columns "uid" and "datetime". |
required |
output_dir
|
str
|
Path where the resulting "activity_stats.csv" file will be saved. |
required |
cpu_cores
|
int
|
Number of CPU cores to use for multiprocessing. Defaults to half of the available cores (at least 1). |
max(1, int(cpu_count() / 2))
|
Returns:
Type | Description |
---|---|
DataFrame
|
pd.DataFrame: A DataFrame of monthly user activity counts, with columns ["uid", "month", "total_active_days"]. |
Example
from meowmotion.meowmob import getActivityStats
Suppose df has columns: uid, datetime, lat, lng, etc.¶
activity_df = getActivityStats(df, output_dir="./stats", cpu_cores=4) activity_df.head() uid month total_active_days 0 1 1 10 1 1 2 12 2 2 1 8
Source code in meowmotion/meowmob.py
229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 |
|
getStopNodes(tdf, time_th=5, radius=500, cpu_cores=max(1, int(cpu_count() / 2)))
¶
Detect stop nodes from trajectory data in parallel using scikit-mobility's stay_locations.
This function splits the input TrajDataFrame across multiple CPU cores (via getLoadBalancedBuckets), detects stops on each chunk using the stay_locations function, then merges the results back together. After detection, latitude and longitude columns are renamed to "org_lat" and "org_lng" in the final returned DataFrame.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
tdf
|
TrajDataFrame
|
Input trajectory data with columns at least ["uid", "datetime", "lat", "lng"]. |
required |
time_th
|
int
|
Time threshold (in minutes) used by stay_locations to detect a stop. Defaults to 5. |
5
|
radius
|
int
|
Spatial radius (in meters) within which points are considered part of the same stop. Defaults to 500. |
500
|
cpu_cores
|
int
|
Number of CPU cores to use for parallel processing. Defaults to half the available cores (at least 1). |
max(1, int(cpu_count() / 2))
|
Returns:
Type | Description |
---|---|
DataFrame
|
pd.DataFrame: A DataFrame representing the detected stop nodes. The main columns include: "uid", "org_lat", "org_lng", "datetime" (representing arrival time), "leaving_datetime", and any additional columns returned by stay_locations. |
Example
from meowmotion.meowmob import getStopNodes stops_df = getStopNodes(tdf, time_th=10, radius=1000, cpu_cores=4) print(stops_df.head())
Source code in meowmotion/meowmob.py
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 |
|
getWeights(geo_df, hldf, adult_population, origin_col, destination_col, active_day_df)
¶
Computes activity-based, IMD-level, and council-level weights for users to scale observed trips to population-level estimates.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
geo_df
|
DataFrame
|
Geo-tagged trip DataFrame containing user ID and trip counts. |
required |
hldf
|
DataFrame
|
Home location and demographic info including IMD and council. |
required |
adult_population
|
DataFrame
|
Population statistics broken down by IMD and council. |
required |
origin_col
|
str
|
Name of the column containing origin geo code. |
required |
destination_col
|
str
|
Name of the column containing destination geo code. |
required |
active_day_df
|
DataFrame
|
DataFrame with total number of active days per user. |
required |
Returns:
Type | Description |
---|---|
DataFrame
|
pd.DataFrame: DataFrame with user-level weights including:
- |
Example
weighted_df = getWeights( geo_df=geo_enriched_data, hldf=home_locations, adult_population=population_stats, origin_col="origin_geo_code", destination_col="destination_geo_code", active_day_df=active_days ) print(weighted_df[['uid', 'activity_weight', 'imd_weight']].head())
Source code in meowmotion/meowmob.py
955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 |
|
processFlowGeneration(stdf, raw_df, cpu_cores=max(1, int(cpu_count() / 2)))
¶
Generate flow data from stop nodes using parallel processing.
This function takes two data sources
stdf
: A DataFrame of stop nodes, which must contain columns such as "uid", "datetime", "org_lat", "org_lng", and the "dest_*" fields added here.raw_df
: The underlying trajectory data (with columns like "uid", "datetime", "lat", "lng") from which the detailed trip segments and stay points are extracted.
The function first prepares stdf
by assigning "dest_at", "dest_lat", and "dest_lng"
(the next stop in sequence for each user), then uses getLoadBalancedBuckets
to split
the DataFrame for multiprocessing. For each split/bucket, it calls flowGenration(...)
in parallel to build the trip segments and stay details from the raw data. Finally,
it concatenates the partial results and returns a single DataFrame of flow data.
Columns in the final flow DataFrame typically include
- "uid"
- "org_lat", "org_lng", "org_arival_time", "org_leaving_time"
- "dest_lat", "dest_lng", "dest_arival_time"
- "stay_points", "trip_points"
- "trip_time", "stay_duration", "observed_stay_duration"
(and any other columns you choose to include in
flowGenration
)
Parameters:
Name | Type | Description | Default |
---|---|---|---|
stdf
|
DataFrame
|
DataFrame containing stop nodes. Must have columns such as "uid", "datetime", "org_lat", "org_lng". Additional columns will be created or renamed (e.g., "dest_lat", "dest_lng", "dest_at"). |
required |
raw_df
|
DataFrame
|
The raw trajectory data with columns like "uid", "datetime", "lat", "lng". Used to extract trip details. |
required |
cpu_cores
|
int
|
Number of CPU cores for multiprocessing. Defaults to half of available cores, at minimum 1. |
max(1, int(cpu_count() / 2))
|
Returns:
Type | Description |
---|---|
DataFrame
|
pd.DataFrame: A concatenation of all flows generated in parallel. |
DataFrame
|
Each row represents a trip between one stop node and the next. |
Example
from meowmotion.meowmob import getStopNodes, processFlowGeneration stop_nodes_df = getStopNodes(traj_df) flow_data = processFlowGeneration(stop_nodes_df, raw_df, cpu_cores=4) print(flow_data.head())
Source code in meowmotion/meowmob.py
77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 |
|