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

enhance(apps/analytics): add scripts for the computation of aggregated analytics #4385

Merged
merged 2 commits into from
Dec 4, 2024

Conversation

sjschlapbach
Copy link
Member

@sjschlapbach sjschlapbach commented Dec 3, 2024

IMPORTANT: In order to compute the aggregated analytics with this script, the participant analytics need to be computed and stored in the corresponding database table using the script, which has already been merged into the v3-analytics branch

Summary by CodeRabbit

  • New Features
    • Introduced new functions for computing and saving aggregated analytics, enhancing data analysis capabilities.
    • Added a Jupyter Notebook for computing aggregated analytics over various time spans (daily, weekly, monthly).
  • Bug Fixes
    • Improved error handling and logging in data retrieval processes.
  • Documentation
    • Updated documentation to reflect new functionalities and usage instructions.

Copy link

aviator-app bot commented Dec 3, 2024

Current Aviator status

Aviator will automatically update this comment as the status of the PR changes.
Comment /aviator refresh to force Aviator to re-examine your PR (or learn about other /aviator commands).

This PR was merged manually (without Aviator). Merging manually can negatively impact the performance of the queue. Consider using Aviator next time.


See the real-time status of this PR on the Aviator webapp.
Use the Aviator Chrome Extension to see the status of your PR within GitHub.

Copy link

gitguardian bot commented Dec 3, 2024

️✅ There are no secrets present in this pull request anymore.

If these secrets were true positive and are still valid, we highly recommend you to revoke them.
Once a secret has been leaked into a git repository, you should consider it compromised, even if it was deleted immediately.
Find here more information about risks.


🦉 GitGuardian detects secrets in your source code to help developers and security teams secure the modern development process. You are seeing this because you or someone else with access to this repository has authorized GitGuardian to scan your pull request.

@sjschlapbach sjschlapbach changed the base branch from v3 to v3-analytics December 3, 2024 16:38
Copy link

coderabbitai bot commented Dec 3, 2024

📝 Walkthrough

Walkthrough

The pull request introduces several new functions and modules to enhance the analytics capabilities within the application. Key additions include the compute_aggregated_analytics, aggregate_participant_analytics, load_participant_analytics, and save_aggregated_analytics functions, which facilitate data retrieval, aggregation, and storage. The changes also include updates to the __init__.py files to expose these new functionalities at the package level, making them readily accessible. Additionally, a Jupyter Notebook is added to provide an interactive environment for computing aggregated analytics over various time spans.

Changes

File Path Change Summary
apps/analytics/src/modules/init.py Added import for compute_aggregated_analytics from aggregated_analytics.
apps/analytics/src/modules/aggregated_analytics/init.py Added imports for compute_aggregated_analytics, load_participant_analytics, aggregate_participant_analytics, and save_aggregated_analytics.
apps/analytics/src/modules/aggregated_analytics/aggregate_participant_analytics.py Introduced aggregate_participant_analytics function for aggregating participant data.
apps/analytics/src/modules/aggregated_analytics/compute_aggregated_analytics.py Introduced compute_aggregated_analytics function for loading, aggregating, and saving analytics data.
apps/analytics/src/modules/aggregated_analytics/load_participant_analytics.py Introduced convert_to_df and load_participant_analytics functions for data retrieval and conversion.
apps/analytics/src/modules/aggregated_analytics/save_aggregated_analytics.py Introduced save_aggregated_analytics function for storing aggregated analytics data in the database.
apps/analytics/src/notebooks/aggregated_analytics.ipynb Added a Jupyter Notebook for computing aggregated analytics across various time spans.

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>, 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 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

sonarqubecloud bot commented Dec 3, 2024

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

🧹 Outside diff range and nitpick comments (8)
apps/analytics/src/modules/aggregated_analytics/save_aggregated_analytics.py (1)

61-73: Optimize calculation of totalElementsAvailable

The calculation of totalElementsAvailable involves nested loops over practiceQuizzes and microLearnings, their stacks, and elements. This can be inefficient for courses with large datasets.

Consider optimizing this calculation by using database aggregation functions or modifying the query to compute totalElementsAvailable directly in the database. This approach would reduce processing time and resource usage in Python.

apps/analytics/src/modules/__init__.py (1)

2-2: Add compute_aggregated_analytics to __all__ to define the public API

The static analysis tool reports that compute_aggregated_analytics is imported but unused. Since you're importing it in __init__.py to expose it at the package level, consider adding it to the __all__ list to explicitly declare it as part of the public API.

Apply this diff:

+__all__ = [
+    'compute_correctness',
+    'get_participant_responses',
+    'compute_aggregated_analytics',
+]
🧰 Tools
🪛 Ruff (0.8.0)

2-2: .aggregated_analytics.compute_aggregated_analytics imported but unused; consider removing, adding to __all__, or using a redundant alias

(F401)

apps/analytics/src/modules/aggregated_analytics/__init__.py (1)

1-4: Add imported functions to __all__ to define the public API

The static analysis tool reports that the imported functions are unused. Since you're importing these functions to make them available at the module level, consider adding them to the __all__ list to explicitly define the public API.

Apply this diff:

+__all__ = [
+    'compute_aggregated_analytics',
+    'load_participant_analytics',
+    'aggregate_participant_analytics',
+    'save_aggregated_analytics',
+]
🧰 Tools
🪛 Ruff (0.8.0)

1-1: .compute_aggregated_analytics.compute_aggregated_analytics imported but unused; consider removing, adding to __all__, or using a redundant alias

(F401)


2-2: .load_participant_analytics.load_participant_analytics imported but unused; consider removing, adding to __all__, or using a redundant alias

(F401)


3-3: .aggregate_participant_analytics.aggregate_participant_analytics imported but unused; consider removing, adding to __all__, or using a redundant alias

(F401)


4-4: .save_aggregated_analytics.save_aggregated_analytics imported but unused; consider removing, adding to __all__, or using a redundant alias

(F401)

apps/analytics/src/modules/aggregated_analytics/aggregate_participant_analytics.py (1)

9-9: Fix typo in comment

There's a typo in the comment. "aggreagte" should be spelled "aggregate".

Apply this diff:

-    # aggreagte all participant analytics for the specified time range and separate courses
+    # aggregate all participant analytics for the specified time range and separate courses
apps/analytics/src/modules/aggregated_analytics/compute_aggregated_analytics.py (3)

6-8: Consider adding type hints and docstring

The function signature would benefit from type hints and a docstring describing the parameters and return value.

 def compute_aggregated_analytics(
-    db, start_date, end_date, timestamp, analytics_type="DAILY", verbose=False
+    db: Prisma,
+    start_date: str,
+    end_date: str,
+    timestamp: str,
+    analytics_type: str = "DAILY",
+    verbose: bool = False
 ):
+    """Compute aggregated analytics for the given time range.
+
+    Args:
+        db: Prisma database connection
+        start_date: Start date in ISO format
+        end_date: End date in ISO format
+        timestamp: Timestamp for analytics computation
+        analytics_type: Type of analytics (DAILY, WEEKLY, MONTHLY, COURSE)
+        verbose: Enable verbose output
+
+    Returns:
+        None
+    """

20-21: Use f-strings for string formatting

String concatenation with + is less readable than f-strings.

-        print("Aggregated analytics for time range:" + start_date + " to " + end_date)
+        print(f"Aggregated analytics for time range: {start_date} to {end_date}")

23-28: Use f-strings for string formatting

Similar to above, use f-strings for better readability.

-        print(
-            "No aggregated analytics to compute for time range:"
-            + start_date
-            + " to "
-            + end_date
-        )
+        print(f"No aggregated analytics to compute for time range: {start_date} to {end_date}")
apps/analytics/src/notebooks/aggregated_analytics.ipynb (1)

67-71: Consider parameterizing date ranges

The start date is hardcoded to "2021-01-01". Consider making this configurable.

+# Configuration
+DEFAULT_START_DATE = "2021-01-01"
+start_date = os.getenv("ANALYTICS_START_DATE", DEFAULT_START_DATE)
-start_date = "2021-01-01"
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 4ca93c7 and 7113565.

📒 Files selected for processing (7)
  • apps/analytics/src/modules/__init__.py (1 hunks)
  • apps/analytics/src/modules/aggregated_analytics/__init__.py (1 hunks)
  • apps/analytics/src/modules/aggregated_analytics/aggregate_participant_analytics.py (1 hunks)
  • apps/analytics/src/modules/aggregated_analytics/compute_aggregated_analytics.py (1 hunks)
  • apps/analytics/src/modules/aggregated_analytics/load_participant_analytics.py (1 hunks)
  • apps/analytics/src/modules/aggregated_analytics/save_aggregated_analytics.py (1 hunks)
  • apps/analytics/src/notebooks/aggregated_analytics.ipynb (1 hunks)
🧰 Additional context used
🪛 Ruff (0.8.0)
apps/analytics/src/modules/__init__.py

2-2: .aggregated_analytics.compute_aggregated_analytics imported but unused; consider removing, adding to __all__, or using a redundant alias

(F401)

apps/analytics/src/modules/aggregated_analytics/load_participant_analytics.py

22-22: Undefined name start_date

(F821)


22-22: Undefined name end_date

(F821)

apps/analytics/src/modules/aggregated_analytics/__init__.py

1-1: .compute_aggregated_analytics.compute_aggregated_analytics imported but unused; consider removing, adding to __all__, or using a redundant alias

(F401)


2-2: .load_participant_analytics.load_participant_analytics imported but unused; consider removing, adding to __all__, or using a redundant alias

(F401)


3-3: .aggregate_participant_analytics.aggregate_participant_analytics imported but unused; consider removing, adding to __all__, or using a redundant alias

(F401)


4-4: .save_aggregated_analytics.save_aggregated_analytics imported but unused; consider removing, adding to __all__, or using a redundant alias

(F401)

🔇 Additional comments (2)
apps/analytics/src/modules/aggregated_analytics/compute_aggregated_analytics.py (1)

1-4: LGTM: Clean imports structure

The imports are well-organized and follow a clear pattern of importing related functionality from sibling modules.

apps/analytics/src/notebooks/aggregated_analytics.ipynb (1)

133-136: Verify timestamp usage for course-wide analytics

Using a constant timestamp from 1970 seems like a workaround. Consider if this could cause issues with data querying or historical tracking.

✅ Verification successful

Let me gather more context about the timestamp usage and analytics computation.


Let me check the actual implementation of the analytics computation to understand how these timestamps are used.


Let me check how the timestamp is used in the analytics computation.


Let me check the participant analytics computation to understand the timestamp usage pattern.


Based on the code analysis, I can now provide a final response:

Using epoch timestamp (1970) is intentional and valid for course-wide analytics

The constant timestamp "1970-01-01T00:00:00.000Z" is used as a special marker for course-wide analytics, which is different from daily/weekly/monthly analytics. This is a valid design pattern because:

  1. The code explicitly handles different analytics types ("DAILY", "WEEKLY", "MONTHLY", "COURSE")
  2. Course-wide analytics represent aggregate data across all time periods, making the epoch timestamp a logical choice
  3. The timestamp is consistently used across participant and aggregated analytics modules
  4. The database schema supports this through unique indices on timestamp fields
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check if there are any other timestamp usages that might conflict
rg -A 2 "1970-01-01T00:00:00.000Z"

# Check for any timestamp-related queries in the database access layer
ast-grep --pattern 'timestamp = $value' 

Length of output: 800


Script:

#!/bin/bash
# Check the implementation of compute_aggregated_analytics to understand timestamp usage
ast-grep --pattern 'def compute_aggregated_analytics($$$)'

# Look for other timestamp-related database queries
rg -A 5 "timestamp.*db\." 

# Check for any date/time related database operations
rg -A 3 "datetime.*db\."

Length of output: 1241


Script:

#!/bin/bash
# Find the analytics computation implementation
rg -A 10 "def compute_aggregated_analytics"

# Check for any timestamp-related filtering or querying in analytics
rg -A 5 "timestamp.*where|where.*timestamp"

# Look for any database queries with date ranges
rg -A 5 "between.*date|date.*between"

Length of output: 67644


Script:

#!/bin/bash
# Check the implementation of load_participant_analytics to understand timestamp usage
rg -A 10 "def load_participant_analytics"

# Look for any timestamp-related database queries in participant analytics
rg -A 5 "timestamp.*participant"

# Check for any timestamp-related constants or defaults
rg -A 3 "timestamp.*const|DEFAULT_TIMESTAMP"

Length of output: 69860


Script:

#!/bin/bash
# Check the participant analytics computation implementation
rg -A 10 "def compute_participant_analytics"

# Look for any timestamp-related database queries in analytics computation
rg -A 5 "timestamp.*analytics"

# Check for any timestamp-related constants or defaults in analytics
rg -A 3 "DEFAULT_TIMESTAMP|EPOCH_TIMESTAMP"

Length of output: 7037

Copy link

cypress bot commented Dec 3, 2024

klicker-uzh    Run #3760

Run Properties:  status check passed Passed #3760  •  git commit cfe3c1606b ℹ️: Merge 7113565689c06665aa5b8888b6951f87bace49c3 into 51bbba935c90b70aecdbb887dc56...
Project klicker-uzh
Branch Review aggregated-analytics
Run status status check passed Passed #3760
Run duration 12m 04s
Commit git commit cfe3c1606b ℹ️: Merge 7113565689c06665aa5b8888b6951f87bace49c3 into 51bbba935c90b70aecdbb887dc56...
Committer Julius Schlapbach
View all properties for this run ↗︎

Test results
Tests that failed  Failures 0
Tests that were flaky  Flaky 0
Tests that did not run due to a developer annotating a test with .skip  Pending 0
Tests that did not run due to a failure in a mocha hook  Skipped 0
Tests that passed  Passing 148
View all changes introduced in this branch ↗︎

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

Successfully merging this pull request may close these issues.

1 participant