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

Update/calculate hourly airqualitydata using bigqdata #4524

Conversation

NicholasTurner23
Copy link
Contributor

@NicholasTurner23 NicholasTurner23 commented Mar 5, 2025

Description

  1. Make calibration more modular
  2. Clean up empty values

Summary by CodeRabbit

  • New Features

    • Integrated enhancements in data retrieval and sensor calibration processes to deliver more accurate and reliable air quality measurements.
  • Refactor

    • Streamlined data processing workflows with improved filtering and timestamp handling for better data quality.
    • Removed legacy measurement procedures to consolidate and simplify operations.

Copy link
Contributor

coderabbitai bot commented Mar 5, 2025

Warning

Rate limit exceeded

@NicholasTurner23 has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 15 minutes and 25 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between f10ed8a and b4941b4.

📒 Files selected for processing (3)
  • src/workflows/airqo_etl_utils/airnow_utils.py (2 hunks)
  • src/workflows/airqo_etl_utils/airqo_utils.py (7 hunks)
  • src/workflows/airqo_etl_utils/datautils.py (6 hunks)
📝 Walkthrough

Walkthrough

This pull request updates several utility modules for air quality data processing. In particular, it modifies device retrieval logic for BAM network data in the extraction routines and refines the data calibration process. The changes in the data utility module improve type conversion, filtering, and handling of API data, while two DAG and utility files related to KCCA measurements have been removed. Error handling and method signatures remain consistent with previous behavior.

Changes

File(s) Change Summary
src/.../airnow_utils.py Updated extract_bam_data: Added import of DataUtils and retrieval of devices via DataUtils.get_devices along with existing call to AirQoApi().get_devices_by_network; error handling for missing devices remains intact.
src/.../airqo_utils.py Modified calibrate_data and _airqo_calibrate: Added detailed docstring, reworked merging of calibrated data, updated condition checking in the network column, and integrated model predictions for PM values; streamlined calculations and data processing.
src/.../datautils.py Enhanced get_devices by updating missing value handling and applying type conversion; improved extract_devices_data by filtering out fully NaN rows; updated timestamp conversion in aggregate_low_cost_sensors_data; added private methods for transforming Clarity API data and retrieving site/device details.
src/.../kcca_utils.py Removed entire file containing KccaUtils with its suite of utility methods for querying and processing air quality data.
src/.../dags/kcca_measurements.py Removed DAG definitions for kcca_hourly_measurements and kcca_historical_hourly_measurements, which previously managed data extraction, transformation, and loading routines for KCCA measurement data.

Sequence Diagram(s)

sequenceDiagram
    participant U as User
    participant AN as AirnowDataUtils
    participant AQ as AirQoApi
    participant DU as DataUtils

    U->>AN: Call extract_bam_data(start_date_time, end_date_time)
    AN->>AQ: get_devices_by_network()
    AN->>DU: get_devices(device_category, network)
    DU-->>AN: Return device list
    AQ-->>AN: Return device list
    AN->>AN: Merge and process devices
    AN-->>U: Return DataFrame or raise ValueError if no devices found
Loading
sequenceDiagram
    participant U as User
    participant AD as AirQoDataUtils
    participant M as CalibrationModel

    U->>AD: Call calibrate_data(data, groupby)
    AD->>AD: Filter and prepare input DataFrame
    AD->>M: Request model predictions for PM values
    M-->>AD: Return pm2_5_calibrated and pm10_calibrated values
    AD->>AD: Merge predictions to form calibrated_data
    AD-->>U: Return calibrated_data DataFrame
Loading

Possibly related PRs

Suggested reviewers

  • Baalmart
  • BenjaminSsempala

Poem

In the realm of air and code so bright,
We merge and transform data with might.
New flows of logic, paths redefined,
Utility tweaks leave bugs behind.
🚀 Cheers to progress in every line!
Happy coding through day and night!


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ 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>, please review it.
    • 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 gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @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.
    • @coderabbitai help me debug CodeRabbit configuration file.

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 using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration 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
Contributor

@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

🧹 Nitpick comments (1)
src/workflows/airqo_etl_utils/airqo_utils.py (1)

699-736: Optimize repeated model downloads.
Each grouped calibration retrieves models from GCS, potentially causing performance overhead for large datasets. Consider caching downloaded models the first time they are needed, then reuse them for subsequent groups.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 71f26f2 and f10ed8a.

📒 Files selected for processing (5)
  • src/workflows/airqo_etl_utils/airnow_utils.py (2 hunks)
  • src/workflows/airqo_etl_utils/airqo_utils.py (4 hunks)
  • src/workflows/airqo_etl_utils/datautils.py (4 hunks)
  • src/workflows/airqo_etl_utils/kcca_utils.py (0 hunks)
  • src/workflows/dags/kcca_measurements.py (0 hunks)
💤 Files with no reviewable changes (2)
  • src/workflows/dags/kcca_measurements.py
  • src/workflows/airqo_etl_utils/kcca_utils.py
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Analyze (python)
  • GitHub Check: Analyze (javascript)
🔇 Additional comments (6)
src/workflows/airqo_etl_utils/airnow_utils.py (1)

11-11: No concerns with this new import.
It cleanly references DataUtils without introducing side effects.

src/workflows/airqo_etl_utils/airqo_utils.py (1)

611-622: Confirm the need to drop calibration columns.
Dropping columns like avg_pm2_5, avg_pm10, and others may limit post-calibration analysis. If long-term traceability or further debug is required, consider preserving them.

src/workflows/airqo_etl_utils/datautils.py (4)

211-214: Recheck strict filtering on PM columns.
Dropping rows where all PM columns are null may discard records containing valid data in other columns (e.g., temperature). Confirm that losing such rows is acceptable.


1030-1121: Confirm robust coordinate parsing and device lookup logic.

  • _flatten_location_coordinates_clarity logs stack traces on invalid coordinates; consider downgrading to logger.error if these are frequent user input errors.
  • _add_site_and_device_details depends on devices.name existing. Verify that the column matches the local device naming convention.

811-811:

❓ Verification inconclusive

Ensure 'format="mixed"' is supported in your pandas environment.
This parameter may require a recent pandas version. Double check your environment's compatibility to prevent runtime errors.


🌐 Web query:

Is "format='mixed'" supported in pandas 1.x?

💡 Result:

The format='mixed' option in pandas' date parsing functions like pd.to_datetime() was introduced in pandas 2.0.0 (April 2023) and is not supported in pandas 1.x [9][10].

Key points:

  • Purpose: Allows parsing date strings with inconsistent formats by inferring the format for each element individually.
  • Pandas 1.x Limitation: In pandas 1.x, users had to either:
    • Specify a single format for all elements (format="%Y-%m-%d")
    • Use infer_datetime_format=True (less flexible)
    • Process dates iteratively with custom logic
  • New in 2.0.0: Explicit support for mixed-format dates via format="mixed" was added to handle real-world datasets with irregular date formatting [9][10].

Example of the new syntax (only works in ≥2.0.0):

pd.to_datetime(["2020-01-01", "01/02/2023"], format="mixed")

For pandas 1.x users, alternatives include:

  1. Preprocessing data to standardize formats
  2. Using errors='coerce' with pd.to_datetime()
  3. Applying custom parsing logic row-wise with apply()

Citations:


Ensure Compatibility with Pandas 2.0.0 or Later for format="mixed"

The pd.to_datetime(..., format="mixed") call will only work if you're running pandas 2.0.0 or newer—pandas 1.x does not support this parameter. Please verify that your runtime environment meets this requirement. If not, consider either upgrading pandas or revising the date parsing strategy (e.g., using infer_datetime_format=True or custom parsing logic).

  • Location: src/workflows/airqo_etl_utils/datautils.py at line 811
  • Code Snippet:
            data["timestamp"] = pd.to_datetime(data["timestamp"], format="mixed")

69-89:

❓ Verification inconclusive

Validate potential non-integer device numbers.
Casting device_number to int after filling with -1 is fine for missing values, but ensure no rows have non-numeric entries (e.g., string codes) that would raise errors outside the try block.


🏁 Script executed:

#!/bin/bash
# Confirm only integer-like device_number values exist before type casting
rg '\"device_number\":' -A5

Length of output: 114


Attention: Re-check Device Number Casting for Non-Numeric Values

The initial verification command failed due to an escape sequence error. This means the original check didn’t yield any useful results. While filling missing values with –1 and casting to int is acceptable for missing entries, please manually verify that no non-numeric entries (e.g., string codes) exist in the "device_number" column. For a more precise inspection, consider running a revised shell script such as:

#!/bin/bash
# Search for the usage of device_number assignment and conversion in the code
rg 'devices\["device_number"\]' -n src/workflows/airqo_etl_utils/datautils.py

This should provide context on how “device_number” is handled in the file and help confirm that there isn’t unexpected non-numeric data leading to potential errors.

Comment on lines 74 to 76
devices, _ = DataUtils.get_devices(
device_category=DeviceCategory.BAM, device_network=DeviceNetwork.METONE
)
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consolidate or remove the redundant device retrieval call.
Currently, the result from AirQoApi().get_devices_by_network(...) gets overshadowed by the subsequent DataUtils.get_devices(...). Consider removing one of these calls or merging their results to avoid confusion and ensure consistency.

-        devices = AirQoApi().get_devices_by_network(
-            device_network=DeviceNetwork.METONE, device_category=DeviceCategory.BAM
-        )
         devices, _ = DataUtils.get_devices(
             device_category=DeviceCategory.BAM, device_network=DeviceNetwork.METONE
         )
📝 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. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
devices, _ = DataUtils.get_devices(
device_category=DeviceCategory.BAM, device_network=DeviceNetwork.METONE
)
devices, _ = DataUtils.get_devices(
device_category=DeviceCategory.BAM, device_network=DeviceNetwork.METONE
)


data["timestamp"] = pd.to_datetime(data["timestamp"])

to_calibrate = data["network"] == "xxxx"
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Network check seems to be a placeholder.
Using "xxxx" as the network condition might be unintentional. Verify if a production network name should be used instead, or if this logic is still under development.

- to_calibrate = data["network"] == "xxxx"
+ # Example correction:
+ to_calibrate = data["network"] == "airqo"  # or whichever name is intended
📝 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. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
to_calibrate = data["network"] == "xxxx"
# Example correction:
to_calibrate = data["network"] == "airqo" # or whichever name is intended

Copy link

codecov bot commented Mar 5, 2025

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 11.47%. Comparing base (71f26f2) to head (0146412).

Additional details and impacted files

Impacted file tree graph

@@             Coverage Diff             @@
##           staging    #4524      +/-   ##
===========================================
- Coverage    11.51%   11.47%   -0.04%     
===========================================
  Files          155       63      -92     
  Lines        18709     6237   -12472     
  Branches       549      549              
===========================================
- Hits          2154      716    -1438     
+ Misses       16551     5517   -11034     
  Partials         4        4              

see 92 files with indirect coverage changes

@Baalmart Baalmart merged commit 281249c into airqo-platform:staging Mar 5, 2025
46 checks passed
@Baalmart Baalmart mentioned this pull request Mar 5, 2025
1 task
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