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

fix: update in_clinvar flag in smallvariants (#2222) #2224

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

stolpeo
Copy link
Contributor

@stolpeo stolpeo commented Feb 7, 2025

Summary by CodeRabbit

  • New Features
    • Introduced a new command-line tool for synchronizing variant data with an external reference source.
    • Offers a detailed update mode for comprehensive case-level processing and a streamlined mode for project-wide updates.
    • Provides a summary report of the update results to ensure data remains consistent.

@stolpeo stolpeo linked an issue Feb 7, 2025 that may be closed by this pull request
Copy link
Contributor

coderabbitai bot commented Feb 7, 2025

Walkthrough

A new Django management command file "in_clinvar.py" has been introduced. This command updates the "in_clinvar" field in the SmallVariant model by comparing variant coordinates with entries from the Clinvar database. It supports two update modes – a full update for a specific case and a light update at the project level. The command parses arguments (project UUID and update mode flag) and aggregates update results accordingly.

Changes

File(s) Change Summary
backend/clinvar/.../in_clinvar.py Added a Django management command with:
- update_in_clinvar_full(case)
- update_in_clinvar_light(project, printer=lambda x: None)
- run(*args, **options)
- Command class with add_arguments(parser) and handle(*args, **options)

Sequence Diagram(s)

sequenceDiagram
    participant User as CLI User
    participant CMD as Command.handle()
    participant RUN as run()
    participant FULL as update_in_clinvar_full()
    participant LIGHT as update_in_clinvar_light()
    
    User->>CMD: Invoke command with options
    CMD->>RUN: Call run(*args, **options)
    alt Full update option provided
        RUN->>FULL: Call update_in_clinvar_full(case)
        FULL-->>RUN: Return detailed update summary
    else Light update
        RUN->>LIGHT: Call update_in_clinvar_light(project)
        LIGHT-->>RUN: Return light update count
    end
    RUN-->>CMD: Aggregate update summaries
    CMD-->>User: Output final summary and logs
Loading

Poem

Hi, I'm a happy little rabbit,
Hopping through code so neat and rapid.
I munch on updates with a joyful heart,
New commands dancing like modern art.
With Clinvar fields now fresh and true,
I celebrate these changes – woohoo! 🥕🐇

✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

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 generate docstrings to generate docstrings for this PR. (Beta)
  • @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

github-actions bot commented Feb 7, 2025

deps-report 🔍

Commit scanned: a8a38cc
ℹ️ Python version 3.10 is used by your project but the latest version is 3.13.

Vulnerable dependencies

3 dependencies have vulnerabilities 😱
Dependency Advisory Versions impacted
djangorestframework (transitive) Affected versions of the package djangorestframework are vulnerable to Cross-site Scripting (XSS) via the break_long_headers template filter due to improper input sanitization before splitting and joining with
tags.
<3.15.2
setuptools (transitive) Affected versions of Setuptools allow for remote code execution via its download functions. These functions, which are used to download packages from URLs provided by users or retrieved from package index servers, are susceptible to code injection. If these functions are exposed to user-controlled inputs, such as package URLs, they can execute arbitrary commands on the system. <70.0.0
sqlalchemy Sqlalchemy 2.0.0b1 avoids leaking cleartext passwords to the open for careless uses of str(engine.URL()) in logs and prints. sqlalchemy/sqlalchemy#8563 <2.0.0b1

Outdated dependencies

83 outdated dependencies found (including 33 outdated major versions)😢
Dependency Installed version Latest version
alabaster (transitive) 0.7.16 1.0.0
aldjemy 2.6 3.2
argon2-cffi (transitive) 21.3.0 23.1.0
asttokens (dev,transitive) 2.4.1 3.0.0
attrs 24.3.0 25.1.0
billiard (transitive) 3.6.4.0 4.2.1
black 24.10.0 25.1.0
certifi (transitive) 2024.8.30 2025.1.31
crispy-bootstrap4 (transitive) 2022.1 2024.10
cryptography (transitive) 43.0.1 44.0.0
django 3.2.25 5.1.6
django-debug-toolbar 4.3.0 5.0.1
django-model-utils (transitive) 4.3.1 5.0.0
django-rest-knox (transitive) 4.2.0 5.0.2
django-sodar-core 0.13.4 1.0.4
drf-spectacular-sidecar (transitive) 2024.7.1 2025.2.1
et-xmlfile (dev,transitive) 1.1.0 2.0.0
fsspec (transitive) 2024.12.0 2025.2.0
isort (dev) 5.13.2 6.0.0
mistune (transitive) 2.0.5 3.1.1
packaging (transitive) 23.2 24.2
pillow (transitive) 10.4.0 11.1.0
protobuf 3.20.3 5.29.3
pyopenssl (transitive) 24.2.1 25.0.0
pytz (transitive) 2024.2 2025.1
s3fs 2024.12.0 2025.2.0
setuptools (transitive) 67.6.1 75.8.0
sphinx (transitive) 6.2.1 8.1.3
sphinx-rtd-theme (transitive) 1.2.2 3.0.2
sqlalchemy 1.4.54 2.0.38
tzdata (transitive) 2024.2 2025.1
unidecode (transitive) 0.4.21 1.3.8
xmlschema (transitive) 2.5.1 3.4.3
Dependency Installed version Latest version
aiobotocore (transitive) 2.16.0 2.19.0
aiohttp (transitive) 3.11.11 3.11.12
amqp (transitive) 5.2.0 5.3.1
anyio (transitive) 4.6.2.post1 4.8.0
babel (transitive) 2.16.0 2.17.0
beautifulsoup4 4.12.3 4.13.3
botocore (transitive) 1.35.81 1.36.15
celery (transitive) 5.2.7 5.4.0
charset-normalizer (transitive) 3.3.2 3.4.1
coverage (dev,transitive) 7.6.1 7.6.10
django-autocomplete-light (transitive) 3.9.4 3.11.0
django-crispy-forms (transitive) 2.0 2.3
django-db-file-storage (transitive) 0.5.5 0.5.6.1
django-dirtyfields (transitive) 1.9.3 1.9.6
django-environ (transitive) 0.10.0 0.12.0
django-iconify (transitive) 0.1.1 0.4.1
django-modelcluster 6.3 6.4
django-plugins-bihealth 0.4.0 0.5.2
django-postgres-copy 2.3.7 2.7.6
django-pydantic-field 0.3.10 0.3.12
djangorestframework (transitive) 3.14.0 3.15.2
docutils (transitive) 0.18.1 0.21.2
drf-keyed-list-bihealth 0.1.1 0.2.1
elementpath (transitive) 4.5.0 4.7.0
executing (dev,transitive) 2.1.0 2.2.0
factory-boy (dev) 3.3.1 3.3.3
faker 35.0.0 35.2.0
httpcore (transitive) 1.0.6 1.0.7
httpx (transitive) 0.27.2 0.28.1
ipython (dev,transitive) 8.28.0 8.32.0
markdown (transitive) 3.4.1 3.7
mypy-protobuf (dev) 3.3.0 3.6.0
prettytable 3.13.0 3.14.0
prompt-toolkit (transitive) 3.0.48 3.0.50
psycopg2 (transitive) 2.9.9 2.9.10
psycopg2-binary (transitive) 2.9.9 2.9.10
pydantic 2.9.2 2.10.6
pydantic-core (transitive) 2.23.4 2.28.0
pygments (transitive) 2.18.0 2.19.1
pysam 0.22.1 0.23.0
referencing (transitive) 0.35.1 0.36.2
regex (transitive) 2024.9.11 2024.11.6
requests-http-signature 0.2.0 0.7.1
rules (transitive) 3.3 3.5
sentry-sdk 2.19.2 2.20.0
typer (transitive) 0.12.5 0.15.1
types-psycopg2 (dev,transitive) 2.9.21.20241019 2.9.21.20250121
versioneer (transitive) 0.28 0.29
wheel (transitive) 0.40.0 0.45.1
xlsxwriter 3.2.0 3.2.2

Logs

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: 1

🧹 Nitpick comments (3)
backend/clinvar/management/commands/in_clinvar.py (3)

11-33: Consider using bulk operations for better performance.

The current implementation updates and saves each variant individually, which could be inefficient for large datasets. Consider using Django's bulk update operations.

Here's an example implementation using bulk updates:

 def update_in_clinvar_full(case):
     """Update the in_clinvar field in SmallVariant with information from Clinvar database."""
     variants = SmallVariant.objects.filter(case_id=case.id)
     result = {
         "true": 0,
         "false": 0,
         "total": 0,
     }
+    to_update = []
     for var in variants:
         coords = {
             "release": var.release,
             "chromosome": var.chromosome,
             "start": var.start,
             "end": var.end,
             "reference": var.reference,
             "alternative": var.alternative,
         }
         var.in_clinvar = Clinvar.objects.filter(**coords).exists()
-        var.save()
+        to_update.append(var)
         result["true" if var.in_clinvar else "false"] += 1
         result["total"] += 1
+    
+    # Perform bulk update in batches of 1000
+    batch_size = 1000
+    for i in range(0, len(to_update), batch_size):
+        batch = to_update[i:i + batch_size]
+        SmallVariant.objects.bulk_update(batch, ['in_clinvar'])
     return result

97-97: Remove commented out code.

The commented out argument --all should be removed if it's not being used. If it's planned for future implementation, consider tracking it in an issue instead.


99-106: Fix f-string usage and enhance logging.

The f-strings on lines 103 and 106 don't contain any placeholders.

Apply this diff to fix the issues and enhance the logging:

     def handle(self, *args, **options):
         self.stdout.write("Call options:")
         self.stdout.write(f"- {options['project_uuid']=}")
         self.stdout.write(f"- {options['full']=}")
-        self.stdout.write(f"Performing ...")
+        self.stdout.write("Performing update...")
         updates = run(*args, **options)
         self.stdout.write(f"{updates=}")
-        self.stdout.write(f"Done.")
+        self.stdout.write("Done.")
🧰 Tools
🪛 Ruff (0.8.2)

103-103: f-string without any placeholders

Remove extraneous f prefix

(F541)


106-106: f-string without any placeholders

Remove extraneous f prefix

(F541)

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 1e80ed3 and a8a38cc.

📒 Files selected for processing (1)
  • backend/clinvar/management/commands/in_clinvar.py (1 hunks)
🧰 Additional context used
🪛 Ruff (0.8.2)
backend/clinvar/management/commands/in_clinvar.py

103-103: f-string without any placeholders

Remove extraneous f prefix

(F541)


106-106: f-string without any placeholders

Remove extraneous f prefix

(F541)

⏰ Context from checks skipped due to timeout of 90000ms (5)
  • GitHub Check: Python-Test
  • GitHub Check: Python-Lint
  • GitHub Check: Analyze (python)
  • GitHub Check: Analyze (javascript)
  • GitHub Check: build-and-push-image
🔇 Additional comments (1)
backend/clinvar/management/commands/in_clinvar.py (1)

56-77: LGTM! Good use of transaction management.

The function is well-structured with proper transaction handling using @transaction.atomic and clear result aggregation.

Comment on lines +35 to +54
def update_in_clinvar_light(project, printer=lambda x: None):
result = 0
for cv in Clinvar.objects.all():
coords = {
"release": cv.release,
"chromosome": cv.chromosome,
"start": cv.start,
"end": cv.end,
"reference": cv.reference,
"alternative": cv.alternative,
}
for case in project.case_set.all():
for var in SmallVariant.objects.filter(case_id=case.id, **coords):
if var.in_clinvar:
continue
var.in_clinvar = True
var.save()
result += 1
return result

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

Optimize database queries and remove unused parameter.

The function has performance and code quality issues:

  1. Triple nested loops with database queries could be inefficient.
  2. The printer parameter is unused.

Consider this optimized implementation:

-def update_in_clinvar_light(project, printer=lambda x: None):
+def update_in_clinvar_light(project):
     result = 0
+    batch_size = 1000
+    to_update = []
     for cv in Clinvar.objects.all():
         coords = {
             "release": cv.release,
             "chromosome": cv.chromosome,
             "start": cv.start,
             "end": cv.end,
             "reference": cv.reference,
             "alternative": cv.alternative,
         }
-        for case in project.case_set.all():
-            for var in SmallVariant.objects.filter(case_id=case.id, **coords):
-                if var.in_clinvar:
-                    continue
-                var.in_clinvar = True
-                var.save()
-                result += 1
+        # Get all cases in one query
+        case_ids = project.case_set.values_list('id', flat=True)
+        # Update variants in bulk
+        variants = SmallVariant.objects.filter(
+            case_id__in=case_ids,
+            in_clinvar=False,
+            **coords
+        )
+        to_update.extend(variants)
+        result += variants.count()
+        
+        # Perform bulk update when batch size is reached
+        if len(to_update) >= batch_size:
+            SmallVariant.objects.bulk_update(to_update, ['in_clinvar'])
+            to_update = []
+    
+    # Update remaining variants
+    if to_update:
+        SmallVariant.objects.bulk_update(to_update, ['in_clinvar'])
     return result

Committable suggestion skipped: line range outside the PR's diff.

Copy link

codecov bot commented Feb 7, 2025

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 91%. Comparing base (1e80ed3) to head (a8a38cc).

Additional details and impacted files
@@          Coverage Diff          @@
##            main   #2224   +/-   ##
=====================================
  Coverage     91%     91%           
=====================================
  Files        678     678           
  Lines      38537   38537           
=====================================
  Hits       35140   35140           
  Misses      3397    3397           

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.

update in_clinvar flag in SmallVariants
1 participant