Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Geopandas #9

Closed
wants to merge 14 commits into from
Closed

Geopandas #9

wants to merge 14 commits into from

Conversation

Kanahiro
Copy link
Member

Close #0

Description(変更内容)

  • ...

Manual Testing(手動テスト)

Not required / 不要

Copy link

coderabbitai bot commented Apr 30, 2024

Important

Auto Review Skipped

Review was skipped due to path filters

Files ignored due to path filters (2)
  • poetry.lock is excluded by !**/*.lock, !**/*.lock
  • pyproject.toml is excluded by !**/*.toml

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

ウォークスルー

プロジェクト全体の変更は、GTFSクラスをGTFSFactoryに改名し、データフレームの取り扱いを強化しました。これにより、地理データ処理が向上し、新しいテスト機能が追加されました。

変更点

ファイル 変更内容
.../__main__.py GTFSクラスをGTFSFactoryに改名。インスタンス作成方法変更。
.../aggregate.py GTFSのインポートパスを修正。
.../gtfs.py GTFSクラスをGTFSFactoryに改名、データ型の変更、新しいデータロード方法の導入。
.../parse.py GTFSのインポートパスを修正、新しいライブラリのインポート。
tests/test_parser.py 新しいテスト関数の追加。

🐰✨
変更の風、新たな道
コードの森を駆け巡る
データの海、広がりを知る
テストの光、確かな足跡を残す
うさぎも跳ねる、新しい春🌸
🌟📊


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

Share
Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (invoked as PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger a review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai help to get help.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

CodeRabbit Configration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

codecov bot commented Apr 30, 2024

Codecov Report

Attention: Patch coverage is 84.00000% with 12 lines in your changes are missing coverage. Please review.

Project coverage is 81.35%. Comparing base (c7ac530) to head (123c0dd).
Report is 1 commits behind head on main.

Files Patch % Lines
gtfs_parser/parse.py 80.48% 8 Missing ⚠️
gtfs_parser/gtfs.py 86.66% 4 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main       #9      +/-   ##
==========================================
- Coverage   82.50%   81.35%   -1.15%     
==========================================
  Files           8        8              
  Lines         280      295      +15     
==========================================
+ Hits          231      240       +9     
- Misses         49       55       +6     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

Copy link
Contributor

@takohei takohei left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please leave the exception.

    if len(tables) == 0:
        raise FileNotFoundError(
            "txt files must reside at the root level directly, not in a sub folder."
        )

This is so popular error. MIERUNE/GTFS-GO#75
It is difficult for users to determine the cause from the message of missing table.

Copy link
Contributor

@takohei takohei left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

GeoDataFrame.dissolve() is very slow and it is a method for different purposes.

Please generate a LineString for each stop_id pattern, not for each trip_id.
This process was 13 times faster than dissolve for GTFS of Saga Bus.
f4100001_佐賀県の路線バス情報のデータ.zip

Even the process for GTFS of Toei Bus takes only 4 seconds. (dissolve() take some minutes)

    if gtfs.shapes is None or ignore_shapes:
        sorted_stop_times = gtfs.stop_times.sort_values(["trip_id", "stop_sequence"])

        trip_stop_pattern = sorted_stop_times.groupby("trip_id")["stop_id"].apply(tuple)

        route_trip_stop_pattern = pd.merge(
            trip_stop_pattern,
            gtfs.trips[["trip_id", "route_id"]],
            on='trip_id'
        )
        route_stop_patterns = route_trip_stop_pattern[["route_id", "stop_id"]].drop_duplicates()

        route_stop_patterns["stop_pattern"] =  route_stop_patterns["stop_id"]
        route_stop_ids = route_stop_patterns.explode("stop_id")
        route_stop_geoms = pd.merge(
            route_stop_ids,
            gtfs.stops[["stop_id", "geometry"]],
            on="stop_id"
        )

        # Point -> LineString: group by route_id and trip_id
        line_df = route_stop_geoms.groupby(["route_id", "stop_pattern"])["geometry"].apply(
            lambda x: shapely.geometry.LineString(x)
        )

        # group by route_id into MultiLineString
        multilines = line_df.groupby(['route_id']).apply(
            lambda x: shapely.geometry.MultiLineString(x.to_list())
        )

        # join route_id and route_name
        multiline_df = pd.merge(
            gpd.GeoSeries(multilines),
            gtfs.routes[["route_id", "route_long_name", "route_short_name"]],
            on="route_id",
        )
        # # trip-route-merge:A
        # trips_routes = pd.merge(
        #     gtfs.trips[["trip_id", "route_id"]],
        #     gtfs.routes[["route_id", "route_long_name", "route_short_name"]],
        #     on="route_id",
        # )
        # 
        # # stop_times-stops-merge:B
        # stop_times_stop = pd.merge(
        #     gtfs.stop_times[["stop_id", "trip_id", "stop_sequence"]],
        #     gtfs.stops[["stop_id", "geometry"]],
        #     on="stop_id",
        # )
        # 
        # # A-B-merge
        # merged = pd.merge(stop_times_stop, trips_routes, on="trip_id")
        # # sort by route_id, trip_id, stop_sequence
        # merged.sort_values(["route_id", "trip_id", "stop_sequence"], inplace=True)
        # 
        # # Point -> LineString: group by route_id and trip_id
        # line_df = merged.groupby(["route_id", "trip_id"])["geometry"].apply(
        #     lambda x: shapely.geometry.LineString(x)
        # )
        # line_df = line_df.reset_index()
        # 
        # # group by route_id into MultiLineString
        # multiline_df = gpd.GeoDataFrame(line_df).dissolve(by="route_id")
        # multiline_df.reset_index(inplace=True)
        # 
        # # join route_id and route_name
        # multiline_df = pd.merge(
        #    multiline_df[["route_id", "geometry"]],
        #    gtfs.routes[["route_id", "route_long_name", "route_short_name"]],
        #    on="route_id",
        # )

        multiline_df["route_name"] = multiline_df["route_long_name"].fillna(
            ""
        ) + multiline_df["route_short_name"].fillna("")

        # to GeoJSON-Feature
        features = list(
            multiline_df[["geometry", "route_id", "route_name"]].iterfeatures()
        )
        return features

@Kanahiro
Copy link
Member Author

Kanahiro commented May 1, 2024

いただいたロジック、確かに速いのでdissolve使わない方針にしていきます。
ただ、見た目が直感的でなくて、処理が正しいかちょっと判断つかなかったです。shapesを見ると、なんとなくdissolveでやってる結果は直感的に合ってそうに見えるのですが、「停車パターン」を全て考慮するといただいたロジックの結果になるとしたら、(dissolveの結果が)間違っていることになりそうです。

shapes

Screenshot 2024-05-01 at 14 54 56

dissolve

Screenshot 2024-05-01 at 14 54 39

いただいたロジック

Screenshot 2024-05-01 at 14 54 14

@takohei
Copy link
Contributor

takohei commented May 1, 2024

@Kanahiro
手元では、tuppleを使った処理で問題無く出力されています。
image

見た感じ、ソートがおかしい気がします。
sorted_stop_times = gtfs.stop_times.sort_values(["trip_id", "stop_sequence"])
の処理が抜けていたりしませんか?

参考に、手元のparse.pyを添付します。(.pyを添付できなかったので、拡張子をtxtにしています)
parse.py.txt

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

Out of diff range and nitpick comments (1)
gtfs_parser/aggregate.py (1)

Line range hint 110-110: 型の比較には isinstance() を使用してください。

- val if type(val) == str else val.stop_name
+ val if isinstance(val, str) else val.stop_name

@Kanahiro
Copy link
Member Author

Kanahiro commented May 2, 2024

すぐに解決しなさそうだったので、単にdissolveを使わない実装にしました。
改善の余地があれば、別のコミットで、ということで

@Kanahiro Kanahiro marked this pull request as ready for review May 2, 2024 07:10
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

# rename column: route_id -> route_ids
route_stop.rename(columns={"route_id": "route_ids"}, inplace=True)
# fill na with empty list
route_stop["route_ids"] = route_stop["route_ids"].fillna("").apply(list)
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

空のリストの処理を簡素化することを提案します。

- route_stop["route_ids"] = route_stop["route_ids"].fillna("").apply(list)
+ route_stop["route_ids"] = route_stop["route_ids"].apply(lambda x: x if isinstance(x, list) else [])

Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation.

Suggested change
route_stop["route_ids"] = route_stop["route_ids"].fillna("").apply(list)
route_stop["route_ids"] = route_stop["route_ids"].apply(lambda x: x if isinstance(x, list) else [])

Comment on lines 159 to 178
unloaded_shapes = unloaded_shapes.groupby("shape_id")["geometry"].apply(
lambda x: shapely.geometry.LineString(x)
)
unloaded_shapes = unloaded_shapes.reset_index()

return features
# group by route_id into MultiLineString
unloaded_shapes = unloaded_shapes.groupby(["shape_id"])["geometry"].apply(
lambda x: shapely.geometry.MultiLineString(x.to_list())
)
unloaded_shapes = unloaded_shapes.reset_index()

# fill id, name with shape_id
unloaded_shapes["route_id"] = None
unloaded_shapes["route_name"] = unloaded_shapes["shape_id"]

# to GeoJSON-Feature
unloaded_features = list(
gpd.GeoDataFrame(unloaded_shapes.reset_index()).iterfeatures()
)
features.extend(unloaded_features)
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

テストによってカバーされていない行がいくつかあります。これらの行のテストを追加することをお勧めします。

@Kanahiro
Copy link
Member Author

Kanahiro commented May 2, 2024

QGISだとエラーになるコードがあるので調査中

@Kanahiro
Copy link
Member Author

Kanahiro commented May 2, 2024

おそらくGeoPandasじゃなくてshapely側の問題

@Kanahiro
Copy link
Member Author

Kanahiro commented May 2, 2024

たぶんgroupbyで各行のpointの配列は、ndarrayになるはず
しかしQGISに入っているバージョンのshapelyはlistを食わせなければならない、ということで.tolist()を使う

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 7


if len(unloaded_shapes) > 0:
# group by shape_id into LineString
unloaded_shapes = unloaded_shapes.groupby("shape_id")["geometry"].apply(
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

テストによってカバーされていない行があります。これらの行のテストを追加することをお勧めします。

)
unloaded_shapes = unloaded_shapes.reset_index()
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

テストによってカバーされていない行があります。これらの行のテストを追加することをお勧めします。


return features
# group by route_id into MultiLineString
unloaded_shapes = unloaded_shapes.groupby(["shape_id"])["geometry"].apply(
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

テストによってカバーされていない行があります。これらの行のテストを追加することをお勧めします。

unloaded_shapes = unloaded_shapes.groupby(["shape_id"])["geometry"].apply(
lambda x: shapely.geometry.MultiLineString(x.to_list())
)
unloaded_shapes = unloaded_shapes.reset_index()
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

テストによってカバーされていない行があります。これらの行のテストを追加することをお勧めします。

Comment on lines +171 to +172
unloaded_shapes["route_id"] = None
unloaded_shapes["route_name"] = unloaded_shapes["shape_id"]
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

テストによってカバーされていない行があります。これらの行のテストを追加することをお勧めします。

unloaded_shapes["route_name"] = unloaded_shapes["shape_id"]

# to GeoJSON-Feature
unloaded_features = list(
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

テストによってカバーされていない行があります。これらの行のテストを追加することをお勧めします。

unloaded_features = list(
gpd.GeoDataFrame(unloaded_shapes.reset_index()).iterfeatures()
)
features.extend(unloaded_features)
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

テストによってカバーされていない行があります。これらの行のテストを追加することをお勧めします。

@Kanahiro
Copy link
Member Author

Kanahiro commented May 2, 2024

QGISで動作はOK
ただしMacbook Air M2 で動作させていると、信じられないくらい遅い
amd/armの差を吸収する何かが原因な気が、する

Shapelyは内部的にGEOSに依存していて、それが遅いのではないだろうか

Screenshot 2024-05-02 at 17 03 31

@Kanahiro
Copy link
Member Author

Kanahiro commented May 2, 2024

Windowsだと正常な速度(都営バス、no-shapes, 10秒程度)で処理が完了したので、macOSだけが異常に遅くなるようだ

@Kanahiro
Copy link
Member Author

Kanahiro commented May 2, 2024

#10 にて同一の処理をgeopandasなしに置き換えましたので、クローズ
(なんとgeopandas無しの方が速い)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants