diff --git a/app/__init__.py b/app/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..4391f58d22e7f86c55351f7f7185db3d5fb2d076 --- /dev/null +++ b/app/__init__.py @@ -0,0 +1 @@ +"""App module init.""" diff --git a/app/api/__init__.py b/app/api/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..3396cd51ca100a581bcf418e60e6a383ef46d2f1 --- /dev/null +++ b/app/api/__init__.py @@ -0,0 +1 @@ +"""API module init.""" diff --git a/app/api/__pycache__/__init__.cpython-314.pyc b/app/api/__pycache__/__init__.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f419c098ad7cbbe05cf8fcc31e08d78aad68e137 Binary files /dev/null and b/app/api/__pycache__/__init__.cpython-314.pyc differ diff --git a/app/api/__pycache__/algorithms.cpython-314.pyc b/app/api/__pycache__/algorithms.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bd2e763381b1ff0a6423baab323e54831c1b6223 Binary files /dev/null and b/app/api/__pycache__/algorithms.cpython-314.pyc differ diff --git a/app/api/__pycache__/datasets.cpython-314.pyc b/app/api/__pycache__/datasets.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cb0902154e7c4f4152cc48b78dfcd1e8f4230871 Binary files /dev/null and b/app/api/__pycache__/datasets.cpython-314.pyc differ diff --git a/app/api/__pycache__/runs.cpython-314.pyc b/app/api/__pycache__/runs.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a6318b07f9df1cc2027aec74d6768c2d7086e657 Binary files /dev/null and b/app/api/__pycache__/runs.cpython-314.pyc differ diff --git a/app/api/algorithms.py b/app/api/algorithms.py new file mode 100644 index 0000000000000000000000000000000000000000..4ad27ff22a45f507563a82b966c96a1243ecdef5 --- /dev/null +++ b/app/api/algorithms.py @@ -0,0 +1,37 @@ +from fastapi import APIRouter +from app.registry.catalog import ALGORITHMS + +router = APIRouter(prefix="/algorithms", tags=["Algorithms"]) + + +BEELINE_ALGORITHMS = [ + "grnboost2", + "genie3", + "clr", + "aracne", + "mrnet", + "pearson", + "spearman", + "pidc", + "inferelator", + "tigress", + "pcc", + "glasso" +] + +@router.get("/") +def list_algorithms(): + """ + List all BEELINE Docker algorithms + """ + return [ + { + "name": alg, + "docker_image": f"grnbeeline/{alg}" + } + for alg in BEELINE_ALGORITHMS + ] + +@router.get("/", summary="List BEELINE algorithms") +def list_algorithms(): + return ALGORITHMS diff --git a/app/api/datasets.py b/app/api/datasets.py new file mode 100644 index 0000000000000000000000000000000000000000..0e507659fb1c7928eeed105db64a03b43260a141 --- /dev/null +++ b/app/api/datasets.py @@ -0,0 +1,157 @@ +""" +API endpoints for dataset management. +""" + +from typing import Optional +from fastapi import APIRouter, Query, HTTPException, status +from fastapi.responses import FileResponse +import logging + +from app.models.dataset import ( + DatasetCreate, + DatasetResponse, + DatasetListResponse, + DatasetPreview, + DatasetUpdate, +) +from app.services.datasets_service import dataset_service + +logger = logging.getLogger(__name__) +router = APIRouter(prefix="/datasets", tags=["datasets"]) + + +@router.post("/register", response_model=DatasetResponse, status_code=status.HTTP_201_CREATED) +async def register_dataset(dataset: DatasetCreate) -> DatasetResponse: + """Register a new dataset.""" + try: + result = await dataset_service.register_dataset( + name=dataset.name, + description=dataset.description, + source=dataset.source, + schema=dataset.schema, + species=dataset.species, + tissue=dataset.tissue, + ) + return result + except Exception as e: + logger.error(f"Failed to register dataset: {str(e)}") + raise HTTPException( + status_code=status.HTTP_400_BAD_REQUEST, + detail=f"Failed to register dataset: {str(e)}", + ) + + +@router.get("", response_model=DatasetListResponse) +async def list_datasets( + skip: int = Query(0, ge=0), + limit: int = Query(10, ge=1, le=100), +) -> DatasetListResponse: + """List all registered datasets.""" + try: + result = await dataset_service.list_datasets(skip=skip, limit=limit) + return DatasetListResponse(**result) + except Exception as e: + logger.error(f"Failed to list datasets: {str(e)}") + raise HTTPException( + status_code=status.HTTP_400_BAD_REQUEST, + detail="Failed to list datasets", + ) + + +@router.get("/{dataset_id}", response_model=DatasetResponse) +async def get_dataset(dataset_id: str) -> DatasetResponse: + """Get dataset by ID.""" + try: + dataset = await dataset_service.get_dataset(dataset_id) + if not dataset: + raise HTTPException( + status_code=status.HTTP_404_NOT_FOUND, + detail=f"Dataset {dataset_id} not found", + ) + return dataset + except HTTPException: + raise + except Exception as e: + logger.error(f"Failed to get dataset: {str(e)}") + raise HTTPException( + status_code=status.HTTP_400_BAD_REQUEST, + detail="Failed to get dataset", + ) + + +@router.get("/{dataset_id}/preview", response_model=DatasetPreview) +async def get_dataset_preview( + dataset_id: str, + num_rows: int = Query(5, ge=1, le=100), +) -> DatasetPreview: + """Get preview of dataset.""" + try: + preview = await dataset_service.get_dataset_preview( + dataset_id=dataset_id, + num_rows=num_rows, + ) + if not preview: + raise HTTPException( + status_code=status.HTTP_404_NOT_FOUND, + detail=f"Cannot preview dataset {dataset_id}", + ) + return DatasetPreview(**preview) + except HTTPException: + raise + except Exception as e: + logger.error(f"Failed to preview dataset: {str(e)}") + raise HTTPException( + status_code=status.HTTP_400_BAD_REQUEST, + detail="Failed to preview dataset", + ) + + +@router.patch("/{dataset_id}", response_model=DatasetResponse) +async def update_dataset( + dataset_id: str, + dataset_update: DatasetUpdate, +) -> DatasetResponse: + """Update dataset metadata.""" + try: + if dataset_update.metadata: + result = await dataset_service.update_dataset_metadata( + dataset_id=dataset_id, + metadata=dataset_update.metadata, + ) + return result + else: + dataset = await dataset_service.get_dataset(dataset_id) + if not dataset: + raise HTTPException( + status_code=status.HTTP_404_NOT_FOUND, + detail=f"Dataset {dataset_id} not found", + ) + return dataset + except HTTPException: + raise + except Exception as e: + logger.error(f"Failed to update dataset: {str(e)}") + raise HTTPException( + status_code=status.HTTP_400_BAD_REQUEST, + detail="Failed to update dataset", + ) + + +@router.delete("/{dataset_id}", status_code=status.HTTP_204_NO_CONTENT) +async def delete_dataset(dataset_id: str): + """Delete a dataset.""" + try: + success = await dataset_service.delete_dataset(dataset_id) + if not success: + raise HTTPException( + status_code=status.HTTP_404_NOT_FOUND, + detail=f"Dataset {dataset_id} not found", + ) + except HTTPException: + raise + except Exception as e: + logger.error(f"Failed to delete dataset: {str(e)}") + raise HTTPException( + status_code=status.HTTP_400_BAD_REQUEST, + detail="Failed to delete dataset", + ) diff --git a/app/api/docs.py b/app/api/docs.py new file mode 100644 index 0000000000000000000000000000000000000000..52b339f3e3c0704f30b36b366d47914e8e7ac24d --- /dev/null +++ b/app/api/docs.py @@ -0,0 +1,38 @@ +from fastapi import APIRouter +from app.registry.catalog import DATASETS, ALGORITHMS + +router = APIRouter(prefix="/docs", tags=["Documentation"]) + + +@router.get("/", summary="System overview and API guide") +def system_docs(): + return { + "name": "WebGenie BEELINE Platform", + "description": ( + "A web-based execution, benchmarking, and comparison platform " + "for BEELINE GRN inference algorithms." + ), + "concepts": { + "datasets": "scRNA-seq benchmark datasets hosted on Hugging Face", + "algorithms": "BEELINE GRN inference algorithms executed via Docker", + "runs": "Asynchronous benchmark executions", + "metrics": ["AUROC", "AUPRC", "F1"] + }, + "canonical_dataset_ids": "Hugging Face dataset IDs (not UI aliases)", + "example_dataset_id": DATASETS[0]["id"], + "workflow": [ + "GET /datasets", + "GET /algorithms", + "POST /runs", + "GET /runs/{run_id}", + "GET /runs/{run_id}/metrics" + ], + "example_run_payload": { + "dataset_id": DATASETS[0]["id"], + "algorithms": ["grnbeeline/genie3"], + "params": { + "num_trees": 100 + } + }, + "frontend": "https://github.com/ukanduchimeremezejames/WebGenieDark" + } diff --git a/app/api/jobs.py b/app/api/jobs.py new file mode 100644 index 0000000000000000000000000000000000000000..a21ded041613a2d70dc5e5a9ff4c8c236d24f919 --- /dev/null +++ b/app/api/jobs.py @@ -0,0 +1,144 @@ +""" +API endpoints for job management. +""" + +from typing import Optional +from fastapi import APIRouter, Query, HTTPException, status +import logging + +from app.models.job import ( + JobCreate, + JobResponse, + JobListResponse, + JobStatusEnum, + JobLogResponse, + JobCancellationResponse, +) +from app.services.jobs_service import job_service + +logger = logging.getLogger(__name__) +router = APIRouter(prefix="/jobs", tags=["jobs"]) + + +@router.post("", response_model=JobResponse, status_code=status.HTTP_201_CREATED) +async def submit_job(job: JobCreate) -> JobResponse: + """Submit a new inference job.""" + try: + result = await job_service.submit_job( + dataset_id=job.dataset_id, + algorithm=job.algorithm, + parameters=job.parameters, + name=job.name, + description=job.description, + ) + return result + except Exception as e: + logger.error(f"Failed to submit job: {str(e)}") + raise HTTPException( + status_code=status.HTTP_400_BAD_REQUEST, + detail=f"Failed to submit job: {str(e)}", + ) + + +@router.get("", response_model=JobListResponse) +async def list_jobs( + skip: int = Query(0, ge=0), + limit: int = Query(10, ge=1, le=100), + status_filter: Optional[JobStatusEnum] = Query(None, alias="status"), + dataset_id: Optional[str] = None, + algorithm: Optional[str] = None, +) -> JobListResponse: + """List jobs with optional filters.""" + try: + result = await job_service.list_jobs( + skip=skip, + limit=limit, + status=status_filter, + dataset_id=dataset_id, + algorithm=algorithm, + ) + return JobListResponse(**result) + except Exception as e: + logger.error(f"Failed to list jobs: {str(e)}") + raise HTTPException( + status_code=status.HTTP_400_BAD_REQUEST, + detail="Failed to list jobs", + ) + + +@router.get("/{job_id}", response_model=JobResponse) +async def get_job(job_id: str) -> JobResponse: + """Get job by ID.""" + try: + job = await job_service.get_job(job_id) + if not job: + raise HTTPException( + status_code=status.HTTP_404_NOT_FOUND, + detail=f"Job {job_id} not found", + ) + return job + except HTTPException: + raise + except Exception as e: + logger.error(f"Failed to get job: {str(e)}") + raise HTTPException( + status_code=status.HTTP_400_BAD_REQUEST, + detail="Failed to get job", + ) + + +@router.get("/{job_id}/logs", response_model=JobLogResponse) +async def get_job_logs(job_id: str) -> JobLogResponse: + """Get job execution logs.""" + try: + job = await job_service.get_job(job_id) + if not job: + raise HTTPException( + status_code=status.HTTP_404_NOT_FOUND, + detail=f"Job {job_id} not found", + ) + + logs = await job_service.get_job_logs(job_id) + if logs is None: + logs = "No logs available" + + return JobLogResponse( + job_id=job_id, + logs=logs, + timestamp=job.updated_at or job.started_at, + ) + except HTTPException: + raise + except Exception as e: + logger.error(f"Failed to get job logs: {str(e)}") + raise HTTPException( + status_code=status.HTTP_400_BAD_REQUEST, + detail="Failed to retrieve logs", + ) + + +@router.delete("/{job_id}", response_model=JobCancellationResponse) +async def cancel_job(job_id: str) -> JobCancellationResponse: + """Cancel a job.""" + try: + success = await job_service.cancel_job(job_id) + + if not success: + raise HTTPException( + status_code=status.HTTP_400_BAD_REQUEST, + detail=f"Cannot cancel job {job_id}", + ) + + return JobCancellationResponse( + job_id=job_id, + cancelled=True, + message=f"Job {job_id} cancellation requested", + ) + except HTTPException: + raise + except Exception as e: + logger.error(f"Failed to cancel job: {str(e)}") + raise HTTPException( + status_code=status.HTTP_400_BAD_REQUEST, + detail="Failed to cancel job", + ) diff --git a/app/api/results.py b/app/api/results.py new file mode 100644 index 0000000000000000000000000000000000000000..37ff511fd232340a0a79dd6331a1a30f276a7a3e --- /dev/null +++ b/app/api/results.py @@ -0,0 +1,275 @@ +""" +API endpoints for result management. +""" + +from typing import Optional +from fastapi import APIRouter, Query, HTTPException, status, FileResponse +from fastapi.responses import StreamingResponse +import logging +from pathlib import Path + +from app.models.result import ( + ResultResponse, + ResultListResponse, + NetworkComparison, + ResultSummary, +) +from app.workers.tasks import compute_metrics, compare_networks, export_results + +logger = logging.getLogger(__name__) +router = APIRouter(prefix="/results", tags=["results"]) + + +@router.get("/job/{job_id}", response_model=ResultResponse) +async def get_job_result(job_id: str) -> ResultResponse: + """Get result for a job.""" + try: + from app.core.config import settings + + job_dir = settings.RESULTS_DIR / job_id + if not job_dir.exists(): + raise HTTPException( + status_code=status.HTTP_404_NOT_FOUND, + detail=f"Result for job {job_id} not found", + ) + + # Find network file + network_file = None + for f in job_dir.glob("*_network.*"): + if f.is_file(): + network_file = f + break + + if not network_file: + raise HTTPException( + status_code=status.HTTP_404_NOT_FOUND, + detail="Network file not found", + ) + + result_data = { + "id": job_id, + "job_id": job_id, + "dataset_id": "unknown", + "algorithm": "unknown", + "network_file": str(network_file), + "created_at": datetime.utcnow(), + } + + return ResultResponse(**result_data) + + except HTTPException: + raise + except Exception as e: + logger.error(f"Failed to get result: {str(e)}") + raise HTTPException( + status_code=status.HTTP_400_BAD_REQUEST, + detail="Failed to get result", + ) + + +@router.get("/job/{job_id}/summary", response_model=ResultSummary) +async def get_result_summary(job_id: str) -> ResultSummary: + """Get result summary.""" + try: + from app.core.config import settings + import pandas as pd + + job_dir = settings.RESULTS_DIR / job_id + + # Find network file + network_file = None + for f in job_dir.glob("*_network.*"): + if f.is_file(): + network_file = f + break + + if not network_file: + raise HTTPException( + status_code=status.HTTP_404_NOT_FOUND, + detail="Network file not found", + ) + + # Compute metrics + network = pd.read_csv(network_file, sep="\t", header=None) + num_edges = len(network) + nodes = set(network[0]) | set(network[1]) + num_nodes = len(nodes) + + # Compute density + density = (2 * num_edges) / (num_nodes * (num_nodes - 1)) if num_nodes > 1 else 0 + + # Compute degree statistics + degree_dict = {} + for _, row in network.iterrows(): + degree_dict[row[0]] = degree_dict.get(row[0], 0) + 1 + degree_dict[row[1]] = degree_dict.get(row[1], 0) + 1 + + degrees = list(degree_dict.values()) + avg_degree = sum(degrees) / len(degrees) if degrees else 0 + max_degree = max(degrees) if degrees else 0 + + summary = ResultSummary( + total_edges=num_edges, + num_nodes=num_nodes, + density=float(density), + avg_degree=float(avg_degree), + max_degree=int(max_degree), + ) + + return summary + + except HTTPException: + raise + except Exception as e: + logger.error(f"Failed to compute summary: {str(e)}") + raise HTTPException( + status_code=status.HTTP_400_BAD_REQUEST, + detail="Failed to compute summary", + ) + + +@router.post("/compare", response_model=NetworkComparison) +async def compare_result_networks( + job_id_1: str, + job_id_2: str, +) -> NetworkComparison: + """Compare two result networks.""" + try: + from app.core.config import settings + import pandas as pd + + # Find network files + def get_network_file(job_id: str) -> Path: + job_dir = settings.RESULTS_DIR / job_id + for f in job_dir.glob("*_network.*"): + if f.is_file(): + return f + raise FileNotFoundError(f"Network file for job {job_id}") + + network_file_1 = get_network_file(job_id_1) + network_file_2 = get_network_file(job_id_2) + + # Load networks + net1 = pd.read_csv(network_file_1, sep="\t", header=None) + net2 = pd.read_csv(network_file_2, sep="\t", header=None) + + # Convert to edge sets + edges1 = set(zip(net1[0], net1[1])) + edges2 = set(zip(net2[0], net2[1])) + + # Compute metrics + intersection = edges1 & edges2 + union = edges1 | edges2 + jaccard_index = len(intersection) / len(union) if len(union) > 0 else 0 + + comparison = NetworkComparison( + network1_id=job_id_1, + network2_id=job_id_2, + jaccard_index=float(jaccard_index), + overlap_edges=len(intersection), + edges_only_in_1=len(edges1 - edges2), + edges_only_in_2=len(edges2 - edges1), + ) + + return comparison + + except Exception as e: + logger.error(f"Failed to compare networks: {str(e)}") + raise HTTPException( + status_code=status.HTTP_400_BAD_REQUEST, + detail="Failed to compare networks", + ) + + +@router.get("/job/{job_id}/network/download") +async def download_network(job_id: str, format: str = "tsv"): + """Download network file.""" + try: + from app.core.config import settings + + job_dir = settings.RESULTS_DIR / job_id + + # Find network file + network_file = None + for f in job_dir.glob("*_network.*"): + if f.is_file(): + network_file = f + break + + if not network_file: + raise HTTPException( + status_code=status.HTTP_404_NOT_FOUND, + detail="Network file not found", + ) + + if format.lower() == "json": + import pandas as pd + import json + + network = pd.read_csv(network_file, sep="\t", header=None) + data = { + "edges": [ + { + "source": row[0], + "target": row[1], + "weight": float(row[2]) if len(row) > 2 else 1.0, + } + for _, row in network.iterrows() + ] + } + + from io import BytesIO + + output = BytesIO() + output.write(json.dumps(data).encode()) + output.seek(0) + + return StreamingResponse( + iter([output.getvalue()]), + media_type="application/json", + headers={ + "Content-Disposition": f"attachment; filename=network.json" + }, + ) + else: + return FileResponse( + network_file, + media_type="text/tab-separated-values", + filename=f"network.tsv", + ) + + except HTTPException: + raise + except Exception as e: + logger.error(f"Failed to download network: {str(e)}") + raise HTTPException( + status_code=status.HTTP_400_BAD_REQUEST, + detail="Failed to download network", + ) + + +@router.post("/job/{job_id}/export") +async def export_job_results( + job_id: str, + export_format: str = Query("json", regex="^(json|graphml|csv)$"), +): + """Export job results in specified format.""" + try: + task = export_results.delay(job_id=job_id, export_format=export_format) + + return { + "task_id": task.id, + "job_id": job_id, + "export_format": export_format, + "status": "processing", + } + + except Exception as e: + logger.error(f"Failed to export results: {str(e)}") + raise HTTPException( + status_code=status.HTTP_400_BAD_REQUEST, + detail="Failed to export results", + ) + + +from datetime import datetime diff --git a/app/api/runs.py b/app/api/runs.py new file mode 100644 index 0000000000000000000000000000000000000000..d02fddfad9049ef3411e71649db6f153e6d39181 --- /dev/null +++ b/app/api/runs.py @@ -0,0 +1,149 @@ +from fastapi import APIRouter, BackgroundTasks, HTTPException +from pydantic import BaseModel +from app.services.hf_datasets import prepare_expression_matrix +from app.registry.runs import create_run +from app.services.storage import ( + create_run, + get_run, + get_run_metrics, + update_run +) +from app.services.datasets import stage_dataset +from app.services.beeline_runner import execute_run +from threading import Thread +from app.services.runs import execute_run + +router = APIRouter(prefix="/runs", tags=["Runs"]) + +@router.post("/") +def start_run(payload: dict, background: BackgroundTasks): + dataset_id = payload.get("dataset_id") + algorithms = payload.get("algorithms", []) + + if not dataset_id: + raise HTTPException(status_code=422, detail="dataset_id is required") + return {"error": "No Dataset selected"} + + if not algorithms: + raise HTTPException(status_code=422, detail="algorithms must be a non-empty array") + return {"error": "No Algorithm selected"} + + # algorithm = algorithms[0] + algorithm = algorithms[0].lower() + + params = payload.get("params", {}) + + run_id = create_run(dataset_id, algorithm) + + dataset_path = stage_dataset(dataset_id) + + background.add_task( + execute_run, + run_id, + dataset_path, + algorithm, + params + ) + + return { + "run_id": run_id, + "status": "running" + } + +@router.post("/") +def start_run(payload: dict, background: BackgroundTasks): + dataset_id = payload.get("dataset_id") + algorithms = payload.get("algorithms", []) + params = payload.get("params", {}) + + if not dataset_id: + raise HTTPException(status_code=422, detail="dataset_id is required") + + if not algorithms: + raise HTTPException(status_code=422, detail="algorithms must be non-empty") + + algorithm = algorithms[0].lower() + + run_id = create_run(dataset_id, algorithm) + + dataset_path = stage_dataset(dataset_id) + + background.add_task( + execute_run, + run_id, + dataset_path, + algorithm, + params + ) + + return { + "run_id": run_id, + "status": "running" + } + +@router.post("/") +def start_run(payload: dict): + run_id = payload["run_id"] + + Thread( + target=execute_run, + args=( + run_id, + payload["dataset_path"], + payload["algorithm"], + payload.get("params", {}) + ), + daemon=True + ).start() + + return { + "run_id": run_id, + "status": "queued" + } + + +class RunRequest(BaseModel): + dataset_id: str + algorithm: str + params: dict = {} + + +@router.post("/") +def start_run(payload: RunRequest, background: BackgroundTasks): + run_id = create_run( + dataset=payload.dataset_id, + algorithm=payload.algorithm + ) + + try: + dataset_path = prepare_expression_matrix(payload.dataset_id) + except Exception as e: + raise HTTPException(status_code=400, detail=str(e)) + + background.add_task( + execute_run, + run_id, + dataset_path, + payload.algorithm, + payload.params + ) + + return { + "run_id": run_id, + "status": "running" + } + + +@router.get("/{run_id}") +def run_status(run_id: str): + run = get_run(run_id) + + if not run: + return {"error": "Run not found"} + + return run + + +@router.get("/{run_id}/metrics") +def run_metrics(run_id: str): + return get_run_metrics(run_id) diff --git a/app/config.py b/app/config.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/app/core/__init__.py b/app/core/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ec8b3817ec047d1958a6bc8080e3c4ddb5d98e97 --- /dev/null +++ b/app/core/__init__.py @@ -0,0 +1 @@ +"""App core module init.""" diff --git a/app/core/config.py b/app/core/config.py new file mode 100644 index 0000000000000000000000000000000000000000..c61f9468668367c7edf9d0a8efa76b13fc63d4df --- /dev/null +++ b/app/core/config.py @@ -0,0 +1,110 @@ +""" +Configuration management using Pydantic BaseSettings. +Supports environment variables and .env files. +""" + +from typing import List, Optional +from pydantic import Field +from pydantic_settings import BaseSettings +from pathlib import Path + + +class Settings(BaseSettings): + """Application settings with environment variable support.""" + + # Project Info + PROJECT_NAME: str = "WebGenie - Beeline GRN Inference Backend" + PROJECT_VERSION: str = "1.0.0" + PROJECT_DESCRIPTION: str = "FastAPI backend for Gene Regulatory Network inference" + + # Server Configuration + API_V1_PREFIX: str = "/api/v1" + DEBUG: bool = Field(default=False, env="DEBUG") + LOG_LEVEL: str = Field(default="INFO", env="LOG_LEVEL") + + # CORS Configuration + CORS_ORIGINS: List[str] = Field( + default=[ + "http://localhost", + "http://localhost:3000", + "http://localhost:5173", + "http://127.0.0.1", + "http://127.0.0.1:3000", + "http://127.0.0.1:5173", + ], + env="CORS_ORIGINS", + ) + CORS_CREDENTIALS: bool = True + CORS_METHODS: List[str] = ["*"] + CORS_HEADERS: List[str] = ["*"] + + # Database Configuration + DATABASE_URL: str = Field( + default="sqlite:///./webgenie.db", env="DATABASE_URL" + ) + + # Redis Configuration (for Celery) + REDIS_URL: str = Field( + default="redis://localhost:6379/0", env="REDIS_URL" + ) + + # Celery Configuration + CELERY_BROKER_URL: str = Field( + default="redis://localhost:6379/1", env="CELERY_BROKER_URL" + ) + CELERY_RESULT_BACKEND: str = Field( + default="redis://localhost:6379/2", env="CELERY_RESULT_BACKEND" + ) + + # File Paths + BASE_DIR: Path = Path(__file__).resolve().parent.parent.parent + DATA_DIR: Path = Field(default=Path("/data"), env="DATA_DIR") + RESULTS_DIR: Path = Field(default=Path("/data/results"), env="RESULTS_DIR") + DATASETS_DIR: Path = Field(default=Path("/data/datasets"), env="DATASETS_DIR") + TEMP_DIR: Path = Field(default=Path("/tmp/webgenie"), env="TEMP_DIR") + + # Job Configuration + MAX_CONCURRENT_JOBS: int = Field(default=4, env="MAX_CONCURRENT_JOBS") + JOB_TIMEOUT_SECONDS: int = Field(default=86400, env="JOB_TIMEOUT_SECONDS") # 24 hours + POLL_INTERVAL_SECONDS: int = 5 + + # API Configuration + MAX_UPLOAD_SIZE: int = Field( + default=1024 * 1024 * 500, env="MAX_UPLOAD_SIZE" # 500MB + ) + + # Algorithm Configuration + ALGORITHM_TIMEOUT: int = Field(default=86400, env="ALGORITHM_TIMEOUT") + ALGORITHM_MEMORY_LIMIT: str = Field(default="8g", env="ALGORITHM_MEMORY_LIMIT") + + # HuggingFace Configuration + HF_TOKEN: Optional[str] = Field(default=None, env="HF_TOKEN") + HF_DATASET_ORG: str = "cskokgibbs" + HF_DATASET_PREFIX: str = "datasets" + + # Docker Configuration + DOCKER_REGISTRY: str = Field(default="grnbeeline", env="DOCKER_REGISTRY") + USE_DOCKER: bool = Field(default=True, env="USE_DOCKER") + + # Logging Configuration + LOG_FORMAT: str = "json" # json or text + LOG_FILE: Path = Field(default=Path("/var/log/webgenie/app.log")) + + class Config: + """Pydantic config.""" + + env_file = ".env" + env_file_encoding = "utf-8" + case_sensitive = True + extra = "ignore" + + +# Global settings instance +settings = Settings() + +# Ensure required directories exist +settings.DATA_DIR.mkdir(parents=True, exist_ok=True) +settings.RESULTS_DIR.mkdir(parents=True, exist_ok=True) +settings.DATASETS_DIR.mkdir(parents=True, exist_ok=True) +settings.TEMP_DIR.mkdir(parents=True, exist_ok=True) +settings.LOG_FILE.parent.mkdir(parents=True, exist_ok=True) diff --git a/app/core/logging.py b/app/core/logging.py new file mode 100644 index 0000000000000000000000000000000000000000..a46ebf8bd1c26258dbd331f9659b4b289a171301 --- /dev/null +++ b/app/core/logging.py @@ -0,0 +1,146 @@ +""" +Structured logging configuration with JSON output support. +""" + +import logging +import logging.config +import json +from typing import Any, Dict +from datetime import datetime +from pathlib import Path +from pythonjsonlogger import jsonlogger + +from app.core.config import settings + + +class CustomJsonFormatter(jsonlogger.JsonFormatter): + """Custom JSON formatter with additional context.""" + + def add_fields( + self, + log_record: Dict[str, Any], + record: logging.LogRecord, + message_dict: Dict[str, Any], + ) -> None: + """Add custom fields to log record.""" + super().add_fields(log_record, record, message_dict) + log_record["timestamp"] = datetime.utcnow().isoformat() + log_record["level"] = record.levelname + log_record["logger"] = record.name + log_record["module"] = record.module + log_record["function"] = record.funcName + log_record["line"] = record.lineno + + # Add job_id if available in extra + if hasattr(record, "job_id"): + log_record["job_id"] = record.job_id + if hasattr(record, "dataset_id"): + log_record["dataset_id"] = record.dataset_id + if hasattr(record, "algorithm"): + log_record["algorithm"] = record.algorithm + + +def setup_logging() -> None: + """Configure application logging.""" + + # Ensure log directory exists + log_dir = settings.LOG_FILE.parent + log_dir.mkdir(parents=True, exist_ok=True) + + if settings.LOG_FORMAT == "json": + formatter_class = CustomJsonFormatter + formatter_kwargs = {"format": "%(message)s"} + else: + formatter_class = logging.Formatter + formatter_kwargs = { + "format": "%(asctime)s - %(name)s - %(levelname)s - %(message)s" + } + + config = { + "version": 1, + "disable_existing_loggers": False, + "formatters": { + "default": { + "()": formatter_class, + **formatter_kwargs, + }, + "detailed": { + "format": ( + "%(asctime)s - %(name)s - %(levelname)s - " + "%(funcName)s:%(lineno)d - %(message)s" + ) + }, + }, + "handlers": { + "console": { + "class": "logging.StreamHandler", + "level": settings.LOG_LEVEL, + "formatter": "default", + "stream": "ext://sys.stdout", + }, + "file": { + "class": "logging.handlers.RotatingFileHandler", + "level": settings.LOG_LEVEL, + "formatter": "default", + "filename": str(settings.LOG_FILE), + "maxBytes": 10485760, # 10MB + "backupCount": 10, + }, + }, + "loggers": { + "app": { + "level": settings.LOG_LEVEL, + "handlers": ["console", "file"], + "propagate": False, + }, + "uvicorn": { + "level": settings.LOG_LEVEL, + "handlers": ["console", "file"], + "propagate": False, + }, + "uvicorn.access": { + "level": settings.LOG_LEVEL, + "handlers": ["console", "file"], + "propagate": False, + }, + "celery": { + "level": settings.LOG_LEVEL, + "handlers": ["console", "file"], + "propagate": False, + }, + }, + "root": { + "level": settings.LOG_LEVEL, + "handlers": ["console", "file"], + }, + } + + logging.config.dictConfig(config) + + +def get_logger(name: str) -> logging.Logger: + """Get configured logger instance.""" + return logging.getLogger(name) + + +def log_with_context( + logger: logging.Logger, + level: str, + message: str, + job_id: str = None, + dataset_id: str = None, + algorithm: str = None, + **kwargs, +) -> None: + """Log message with context information.""" + extra = {} + if job_id: + extra["job_id"] = job_id + if dataset_id: + extra["dataset_id"] = dataset_id + if algorithm: + extra["algorithm"] = algorithm + extra.update(kwargs) + + log_func = getattr(logger, level.lower(), logger.info) + log_func(message, extra=extra) diff --git a/app/core/tasks.py b/app/core/tasks.py new file mode 100644 index 0000000000000000000000000000000000000000..b07396f41f3fb49df04533ea466eef21c121d816 --- /dev/null +++ b/app/core/tasks.py @@ -0,0 +1,60 @@ +""" +Celery task configuration for asynchronous job execution. +""" + +from celery import Celery +from celery.utils.log import get_task_logger +from kombu import Exchange, Queue +from datetime import timedelta + +from app.core.config import settings + +# Initialize Celery app +celery_app = Celery( + settings.PROJECT_NAME.lower().replace(" ", "-"), + broker=settings.CELERY_BROKER_URL, + backend=settings.CELERY_RESULT_BACKEND, +) + +# Configure Celery +celery_app.conf.update( + # Task configuration + task_serializer="json", + accept_content=["json"], + result_serializer="json", + timezone="UTC", + enable_utc=True, + # Task execution + task_track_started=True, + task_time_limit=settings.JOB_TIMEOUT_SECONDS, + task_soft_time_limit=settings.JOB_TIMEOUT_SECONDS - 60, + worker_prefetch_multiplier=1, + worker_max_tasks_per_child=1000, + # Result backend + result_expires=86400, # 24 hours + # Queue configuration + task_default_queue="default", + task_queues=( + Queue("default", Exchange("tasks"), routing_key="tasks.#"), + Queue("priority", Exchange("priority"), routing_key="priority.#"), + Queue("inference", Exchange("inference"), routing_key="inference.#"), + ), + task_default_exchange="tasks", + task_default_exchange_type="topic", + # Retry configuration + task_acks_late=True, + task_reject_on_worker_lost=True, + # Rate limiting + task_default_rate_limit="100/m", +) + +# Set up periodic tasks if needed +celery_app.conf.beat_schedule = { + "cleanup-old-results": { + "task": "app.workers.tasks.cleanup_old_results", + "schedule": timedelta(hours=6), # Every 6 hours + "kwargs": {"days": 7}, # Clean results older than 7 days + }, +} + +logger = get_task_logger(__name__) diff --git a/app/main.py b/app/main.py new file mode 100644 index 0000000000000000000000000000000000000000..16419b5af7fcdde267bf2f849380c68dc85e4fea --- /dev/null +++ b/app/main.py @@ -0,0 +1,435 @@ +# from ast import If +from fastapi import FastAPI, Query, HTTPException +from fastapi.middleware.cors import CORSMiddleware +from app.registry.catalog import DATASETS, ALGORITHMS +from app.services.hf_datasets import ( + list_beeline_datasets, + extract_metadata, + get_dataset_metadata +) +from huggingface_hub import HfApi +from datasets import load_dataset +import os +from contextlib import asynccontextmanager +from fastapi.responses import JSONResponse +import logging +from app.core.config import settings +from app.core.logging import setup_logging, get_logger +from app.api import datasets, jobs, compare, explorer, algorithm, runs, results, docs +from typing import List, Dict +from pydantic import BaseModel +import json +import duckdb +from pathlib import Path +from datetime import datetime + +# Creating the App +app = FastAPI( + title="WebGenie BEELINE API", + description="Compute and cache dataset metadata from Hugging Face datasets, run Beeline Algorithms on it and produce runs result as AUROC, AUPRC and F1 Score.", + version="1.0.0", +) +log = logging +beeline_datasets = list_beeline_datasets +beeline_datasets_metadat = extract_metadata + +# Setting up logging +setup_logging() +logger = get_logger(__name__) + +@asynccontextmanager +async def lifespan(app: FastAPI): + """Application lifespan context manager.""" + # Starting uup + logger.info(f"Starting {settings.PROJECT_NAME} v{settings.PROJECT_VERSION}") + logger.info(f"Debug mode: {settings.DEBUG}") + logger.info(f"Log level: {settings.LOG_LEVEL}") + logger.info(f"CORS origins: {settings.CORS_ORIGINS}") + + # Verifying directories + logger.info(f"Data directory: {settings.DATA_DIR}") + logger.info(f"Results directory: {settings.RESULTS_DIR}") + logger.info(f"Datasets directory: {settings.DATASETS_DIR}") + logger.info(f"Temp directory: {settings.TEMP_DIR}") + + yield + + # Shuting ddown + logger.info(f"Shutting down {settings.PROJECT_NAME}") + +# Creating FastAPI app +app = FastAPI( + title=settings.PROJECT_NAME, + description=settings.PROJECT_DESCRIPTION, + version=settings.PROJECT_VERSION, + debug=settings.DEBUG, + lifespan=lifespan, +) + +# Adding CORS middleware now, right after app creation +if not HfApi: + app.add_middleware( + CORSMiddleware, + allow_origins=settings.CORS_ORIGINS, + allow_credentials=settings.CORS_CREDENTIALS, + allow_methods=settings.CORS_METHODS, + allow_headers=settings.CORS_HEADERS, + ) +else: + app.add_middleware( + CORSMiddleware, + allow_origins=["*"], + allow_credentials=True, + allow_methods=["*"], + allow_headers=["*"], +) + +class Edge(BaseModel): + job_id: str + edge_id: str + source: str + target: str + supporting_algorithms: List[str] + scores_by_algorithm: Dict[str, float] + support_count: int + consensus_score: float + +# Custom exception handlers +@app.exception_handler(ValueError) +async def value_error_handler(request, exc): + """Handle ValueError exceptions.""" + logger.error(f"ValueError: {str(exc)}") + return JSONResponse( + status_code=400, + content={"detail": str(exc)}, + ) + +@app.exception_handler(Exception) +async def general_exception_handler(request, exc): + """Handle general exceptions.""" + logger.error(f"Unhandled exception: {str(exc)}", exc_info=True) + return JSONResponse( + status_code=500, + content={"detail": "Internal server error"}, + ) + +class DatasetMetadata(BaseModel): + id: str + name: str + organism: str + type: str + genes: int + cells: int + edges: int | None + source: str + last_updated: datetime + +HF_TOKEN = os.getenv("HF_TOKEN") +if not HF_TOKEN: + raise RuntimeError("HF_TOKEN environment variable not set") + +OWNER = "ukandu" + +api = HfApi(token=HF_TOKEN) +DEFAULT_DATASET_ID = "ukandu/BEELINE-mCAD" + +class DatasetMetadata(BaseModel): + id: str + name: str + organism: str + type: str + genes: int + cells: int + edges: int | None + source: str + last_updated: str + +CACHE_DB = Path("data/hf_datasets.duckdb") +CACHE_DB.parent.mkdir(exist_ok=True) +BASE_DIR = Path(__file__).resolve().parent + +conn = duckdb.connect(CACHE_DB.as_posix()) +def get_conn(): + return duckdb.connect(CACHE_DB.as_posix()) + +# Initializing DB schema at startup +with get_conn() as conn: + conn.execute(""" + CREATE TABLE IF NOT EXISTS datasets ( + id TEXT PRIMARY KEY, + name TEXT, + organism TEXT, + type TEXT, + genes INTEGER, + cells INTEGER, + edges INTEGER, + source TEXT, + last_updated TEXT + ) + """) + conn.close() + +# Including routers +app.include_router( + datasets.router, + prefix=settings.API_V1_PREFIX, +) + +app.include_router( + jobs.router, + prefix=settings.API_V1_PREFIX, +) + +app.include_router( + explorer.router, + prefix=settings.API_V1_PREFIX, +) + +app.include_router( + compare.router, + prefix=settings.API_V1_PREFIX, +) + +app.include_router( + algorithm.router, + prefix=settings.API_V1_PREFIX, +) + +app.include_router( + runs.router, + prefix=settings.API_V1_PREFIX, +) + +app.include_router( + results.router, + prefix=settings.API_V1_PREFIX, +) + +app.include_router( + docs.router, + prefix=settings.API_V1_PREFIX, +) + +# Health check endpoint +@app.get("/health") +async def health_check() -> dict: + """Health check endpoint.""" + # datasets = api.list_datasets(author="ukandu") + + return { + "status": "Ok (App is Healthy)", + "title": "WebGenie BEELINE API", + "description": ( + "Compute and cache dataset metadata from Hugging Face datasets, " + "run Beeline algorithms on it and produce results such as " + "AUROC, AUPRC, and F1 score." + ), + "version": settings.PROJECT_VERSION, + "version": settings.PROJECT_VERSION, + "debug": settings.DEBUG, + "datasets": DATASETS, + "algorithms": ALGORITHMS + } + +# Listing all +@app.get("/all") +def list_beeline_datasets_route(): + datasets = api.list_datasets(author="ukandu") + return [ + d.id for d in datasets + if d.id.startswith("ukandu/BEELINE") + and not d.id.endswith("-cache") + ] + +# Root endpoint +@app.get("/") +async def root() -> dict: + """Root endpoint.""" + return { + "name": settings.PROJECT_NAME, + "version": settings.PROJECT_VERSION, + "api_prefix": settings.API_V1_PREFIX, + "docs": f"{settings.API_V1_PREFIX}/docs", + "health": "/health", + } + +# Single Algorithm +@app.get(f"{settings.API_V1_PREFIX}/algorithms") +async def get_algorithms() -> dict: + """Get list of available algorithms.""" + algorithms = [ + { + "name": "SCODE", + "description": "Single-Cell Optimal Experiment Design", + "docker_image": f"{settings.DOCKER_REGISTRY}/scode", + }, + { + "name": "SCNS", + "description": "Single-Cell Network Synthesis", + "docker_image": f"{settings.DOCKER_REGISTRY}/scns", + }, + { + "name": "SINCERITIES", + "description": "Simultaneous Circuit Inference and Clustering", + "docker_image": f"{settings.DOCKER_REGISTRY}/sincerities", + }, + { + "name": "PIDC", + "description": "Partial Information Decomposition and Context", + "docker_image": f"{settings.DOCKER_REGISTRY}/pidc", + }, + { + "name": "GRNVBEM", + "description": "Gene Regulatory Network Variational Bayes EM", + "docker_image": f"{settings.DOCKER_REGISTRY}/grnvbem", + }, + { + "name": "GENIE3", + "description": "GRN Inference using Ensemble trees", + "docker_image": f"{settings.DOCKER_REGISTRY}/genie3", + }, + { + "name": "GRNBOOST2", + "description": "GRN inference using Gradient Boosting", + "docker_image": f"{settings.DOCKER_REGISTRY}/grnboost2", + }, + { + "name": "LEAP", + "description": "Laplacian Eigenmaps", + "docker_image": f"{settings.DOCKER_REGISTRY}/leap", + }, + { + "name": "JUMP3", + "description": "Jump3: Gene Regulatory Network Inference from Multi-Platform Data", + "docker_image": f"{settings.DOCKER_REGISTRY}/jump3", + }, + { + "name": "PPCOR", + "description": "Partial Pearson Correlation", + "docker_image": f"{settings.DOCKER_REGISTRY}/ppcor", + }, + { + "name": "GRISLI", + "description": "Gene Regulatory Inference from Single-cell Lineages", + "docker_image": f"{settings.DOCKER_REGISTRY}/grisli", + }, + { + "name": "SINGE", + "description": "Single-cell Inference of Networks using Granger Ensembles", + "docker_image": f"{settings.DOCKER_REGISTRY}/singe", + }, + { + "name": "SCRIBE", + "description": "Single-Cell Regulation through Iterative Back-Edges", + "docker_image": f"{settings.DOCKER_REGISTRY}/scribe", + }, + { + "name": "SCSGL", + "description": "Single-Cell Sparse Graphical Lasso", + "docker_image": f"{settings.DOCKER_REGISTRY}/scsgl", + }, + ] + return { + "algorithms": algorithms, + "total": len(algorithms), + } + +# Single Job +@app.get("/grn/{job_id}", response_model=List[Edge]) +async def get_grn(job_id: str): + with CACHE_DB.open() as f: + data = json.load(f) + + # Attaching job_id to each edge + return [ + { + **edge, + "job_id": job_id, + } + for edge in data + ] + +# Single Datset +@app.get("/dataset/{dataset_id}", response_model=DatasetMetadata) +def get_dataset_metadata( + dataset_id: str = Query( + DEFAULT_DATASET_ID, + description=datasets.desc + ) +): + """ + Fetch dataset metadata from cache or compute it from Hugging Face. + """ + + # Checking cache + cached = conn.execute( + "SELECT * FROM datasets WHERE id = ?", + (dataset_id,) + ).fetchone() + + if cached: + return dict(zip( + ["id", "name", "organism", "type", "genes", "cells", "edges", "source", "last_updated"], + cached + )) + + # Loading dataset + try: + ds = load_dataset(dataset_id) + except Exception as e: + raise HTTPException(status_code=404, detail=f"Dataset not found: {e}") + + # Expressing matrix stats + try: + expr = ds["train"] + genes = len(expr.column_names) - 1 # excluding cell_id + cells = expr.num_rows + except Exception: + raise HTTPException(status_code=400, detail="Dataset missing a valid train split") + + # Gold standard edges + edges = None + if "gold_standard" in ds: + edges = ds["gold_standard"].num_rows + + # Including Dataset card metadata + try: + info = api.dataset_info(dataset_id) + card = info.cardData or {} + except Exception: + card = {} + + organism = card.get("organism", "unknown") + dataset_type = card.get("dataset_type", "scRNA-seq") + + record = { + "id": dataset_id, + "name": dataset_id.split("/")[-1], + "organism": organism, + "type": dataset_type, + "genes": genes, + "cells": cells, + "edges": edges, + "source": "huggingface", + "last_updated": info.last_modified if "info" in locals() else None, + } + + # Caching result + conn.execute( + "INSERT INTO datasets VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)", + tuple(record.values()) + ) + + return record + + +if __name__ == "__main__": + import uvicorn + + uvicorn.run( + "app.main:app", + host="0.0.0.0", + port=8000, + reload=settings.DEBUG, + log_level=settings.LOG_LEVEL.lower(), + ) diff --git a/app/models/__init__.py b/app/models/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..20894e1d64938242e3c99811ba86138d9c8e7d4d --- /dev/null +++ b/app/models/__init__.py @@ -0,0 +1 @@ +"""Models module init.""" diff --git a/app/models/compare.py b/app/models/compare.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/app/models/dashboard.py b/app/models/dashboard.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/app/models/dataset.py b/app/models/dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..0bdaab21ebbb9ae742f2b67f497d58927e44f95b --- /dev/null +++ b/app/models/dataset.py @@ -0,0 +1,87 @@ +""" +Pydantic models for Dataset management. +""" + +from typing import Optional, List, Dict, Any +from datetime import datetime +from pydantic import BaseModel, Field + + +class DatasetSource(BaseModel): + """Dataset source information.""" + + source_type: str = Field(..., description="Source type (huggingface, local, etc.)") + url: str = Field(..., description="Dataset URL or path") + metadata: Dict[str, Any] = Field(default_factory=dict, description="Source metadata") + + +class DatasetSchema(BaseModel): + """Dataset schema information.""" + + gene_column: str = Field(..., description="Column name for genes") + cell_column: str = Field(..., description="Column name for cells") + expression_column: str = Field(..., description="Column name for expression values") + metadata_columns: List[str] = Field(default_factory=list, description="Metadata columns") + + +class DatasetBase(BaseModel): + """Base dataset model.""" + + name: str = Field(..., description="Dataset name") + description: Optional[str] = Field(default=None, description="Dataset description") + species: Optional[str] = Field(default=None, description="Species name") + tissue: Optional[str] = Field(default=None, description="Tissue type") + num_genes: Optional[int] = Field(default=None, description="Number of genes") + num_cells: Optional[int] = Field(default=None, description="Number of cells") + + +class DatasetCreate(DatasetBase): + """Model for creating a dataset.""" + + source: DatasetSource = Field(..., description="Dataset source") + schema: DatasetSchema = Field(..., description="Dataset schema") + + +class DatasetUpdate(BaseModel): + """Model for updating a dataset.""" + + description: Optional[str] = None + metadata: Optional[Dict[str, Any]] = None + + +class DatasetResponse(DatasetBase): + """Model for dataset response.""" + + id: str = Field(..., description="Dataset unique identifier") + source: DatasetSource = Field(..., description="Dataset source") + schema: DatasetSchema = Field(..., description="Dataset schema") + file_path: Optional[str] = Field(default=None, description="Path to dataset file") + file_size: Optional[int] = Field(default=None, description="Dataset file size in bytes") + created_at: datetime = Field(..., description="Creation timestamp") + updated_at: datetime = Field(..., description="Last update timestamp") + metadata: Dict[str, Any] = Field(default_factory=dict, description="Additional metadata") + + class Config: + """Model config.""" + + from_attributes = True + + +class DatasetListResponse(BaseModel): + """Model for dataset list response.""" + + total: int = Field(..., description="Total number of datasets") + items: List[DatasetResponse] = Field(..., description="Dataset list") + page: int = Field(..., description="Current page") + per_page: int = Field(..., description="Items per page") + + +class DatasetPreview(BaseModel): + """Model for dataset preview.""" + + id: str = Field(..., description="Dataset ID") + name: str = Field(..., description="Dataset name") + num_rows: int = Field(..., description="Number of rows") + num_columns: int = Field(..., description="Number of columns") + columns: List[str] = Field(..., description="Column names") + sample_data: List[Dict[str, Any]] = Field(..., description="Sample data rows") diff --git a/app/models/datasets.py b/app/models/datasets.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/app/models/explorer.py b/app/models/explorer.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/app/models/job.py b/app/models/job.py new file mode 100644 index 0000000000000000000000000000000000000000..4846f4d2af3f01e8f34bf501474ba0a2d2cc278c --- /dev/null +++ b/app/models/job.py @@ -0,0 +1,88 @@ +""" +Pydantic models for Job management. +""" + +from enum import Enum +from typing import Optional, List, Dict, Any +from datetime import datetime +from pydantic import BaseModel, Field + + +class JobStatusEnum(str, Enum): + """Job status enumeration.""" + + PENDING = "pending" + SUBMITTED = "submitted" + RUNNING = "running" + COMPLETED = "completed" + FAILED = "failed" + CANCELLED = "cancelled" + PAUSED = "paused" + + +class JobBase(BaseModel): + """Base job model.""" + + dataset_id: str = Field(..., description="Dataset identifier") + algorithm: str = Field(..., description="Algorithm name") + parameters: Dict[str, Any] = Field(default_factory=dict, description="Algorithm parameters") + name: Optional[str] = Field(default=None, description="Human-readable job name") + description: Optional[str] = Field(default=None, description="Job description") + + +class JobCreate(JobBase): + """Model for creating a job.""" + + pass + + +class JobUpdate(BaseModel): + """Model for updating a job.""" + + status: Optional[JobStatusEnum] = None + progress: Optional[float] = None + error_message: Optional[str] = None + + +class JobResponse(JobBase): + """Model for job response.""" + + id: str = Field(..., description="Job unique identifier") + status: JobStatusEnum = Field(..., description="Current job status") + progress: float = Field(default=0.0, description="Progress percentage (0-100)") + started_at: Optional[datetime] = Field(default=None, description="Job start timestamp") + ended_at: Optional[datetime] = Field(default=None, description="Job end timestamp") + error_message: Optional[str] = Field(default=None, description="Error message if failed") + celery_task_id: Optional[str] = Field(default=None, description="Celery task ID") + result_path: Optional[str] = Field(default=None, description="Path to result files") + log_file: Optional[str] = Field(default=None, description="Path to log file") + + class Config: + """Model config.""" + + from_attributes = True + + +class JobListResponse(BaseModel): + """Model for job list response.""" + + total: int = Field(..., description="Total number of jobs") + items: List[JobResponse] = Field(..., description="Job list") + page: int = Field(..., description="Current page") + per_page: int = Field(..., description="Items per page") + + +class JobLogResponse(BaseModel): + """Model for job logs response.""" + + job_id: str = Field(..., description="Job ID") + logs: str = Field(..., description="Log content") + timestamp: datetime = Field(..., description="Log timestamp") + + +class JobCancellationResponse(BaseModel): + """Model for job cancellation response.""" + + job_id: str = Field(..., description="Job ID") + cancelled: bool = Field(..., description="Whether cancellation was successful") + message: str = Field(..., description="Cancellation message") diff --git a/app/models/result.py b/app/models/result.py new file mode 100644 index 0000000000000000000000000000000000000000..ea9c15c49c5a7e4f2fbf629ce693a28b279f86a3 --- /dev/null +++ b/app/models/result.py @@ -0,0 +1,82 @@ +""" +Pydantic models for Result management. +""" + +from typing import Optional, List, Dict, Any +from datetime import datetime +from pydantic import BaseModel, Field + + +class ResultMetrics(BaseModel): + """Result metrics.""" + + auc_roc: Optional[float] = Field(default=None, description="AUC-ROC score") + auc_pr: Optional[float] = Field(default=None, description="AUC-PR score") + mcc: Optional[float] = Field(default=None, description="Matthew's correlation coefficient") + precision: Optional[float] = Field(default=None, description="Precision") + recall: Optional[float] = Field(default=None, description="Recall") + f1_score: Optional[float] = Field(default=None, description="F1 score") + execution_time: Optional[float] = Field(default=None, description="Execution time in seconds") + + +class ResultBase(BaseModel): + """Base result model.""" + + job_id: str = Field(..., description="Associated job ID") + dataset_id: str = Field(..., description="Associated dataset ID") + algorithm: str = Field(..., description="Algorithm name") + + +class ResultCreate(ResultBase): + """Model for creating a result.""" + + network_file: str = Field(..., description="Path to network file") + summary: Optional[Dict[str, Any]] = Field(default=None, description="Result summary") + metrics: Optional[ResultMetrics] = Field(default=None, description="Computed metrics") + + +class ResultResponse(ResultBase): + """Model for result response.""" + + id: str = Field(..., description="Result unique identifier") + network_file: str = Field(..., description="Path to network file") + summary: Optional[Dict[str, Any]] = Field(default=None, description="Result summary") + metrics: Optional[ResultMetrics] = Field(default=None, description="Computed metrics") + created_at: datetime = Field(..., description="Creation timestamp") + file_size: Optional[int] = Field(default=None, description="Network file size in bytes") + metadata: Dict[str, Any] = Field(default_factory=dict, description="Additional metadata") + + class Config: + """Model config.""" + + from_attributes = True + + +class ResultListResponse(BaseModel): + """Model for result list response.""" + + total: int = Field(..., description="Total number of results") + items: List[ResultResponse] = Field(..., description="Result list") + page: int = Field(..., description="Current page") + per_page: int = Field(..., description="Items per page") + + +class NetworkComparison(BaseModel): + """Network comparison result.""" + + network1_id: str = Field(..., description="First network result ID") + network2_id: str = Field(..., description="Second network result ID") + jaccard_index: float = Field(..., description="Jaccard similarity index") + overlap_edges: int = Field(..., description="Number of overlapping edges") + edges_only_in_1: int = Field(..., description="Edges only in first network") + edges_only_in_2: int = Field(..., description="Edges only in second network") + + +class ResultSummary(BaseModel): + """Summary of result statistics.""" + + total_edges: int = Field(..., description="Total number of edges") + num_nodes: int = Field(..., description="Number of nodes") + density: float = Field(..., description="Network density") + avg_degree: float = Field(..., description="Average degree") + max_degree: int = Field(..., description="Maximum degree") diff --git a/app/models/run.py b/app/models/run.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/app/registry/__init__.py b/app/registry/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/app/registry/catalog.py b/app/registry/catalog.py new file mode 100644 index 0000000000000000000000000000000000000000..8db8bf6d59830104ef3bd5b11d75c5f03310d2fc --- /dev/null +++ b/app/registry/catalog.py @@ -0,0 +1,29 @@ +from datetime import datetime +from hg_os_cache import dataset, algorithm + +DATASETS = [ + { + "id": dataset.i, + "slug": dataset.l, + "name": dataset.n, + "organism": dataset.o, + "type": dataset.t + "genes": dataset.g, + "cells": dataset.c, + "edges": dataset.e, + "source": dataset.s, + "lastUpdated": dataset.u, + "sparklineData": dataset.d + } +] + +ALGORITHMS = [ + { + "id": algorithm.i, + "name": algorithm.n, + "family": algorithm.f, + "docker_image": algorithm.d, + "supports_weighted": algorithm.w + } +] + diff --git a/app/registry/runs.py b/app/registry/runs.py new file mode 100644 index 0000000000000000000000000000000000000000..a8edeee16e1884027e2675fdb86c088a6f212fea --- /dev/null +++ b/app/registry/runs.py @@ -0,0 +1,106 @@ +import duckdb +from pathlib import Path +from datetime import datetime +import uuid +import json + +DB_PATH = Path("data/runs.duckdb") +DB_PATH.parent.mkdir(exist_ok=True) + +conn = duckdb.connect(DB_PATH.as_posix()) + +conn.execute(""" +CREATE TABLE IF NOT EXISTS runs ( + run_id TEXT PRIMARY KEY, + dataset_id TEXT, + algorithm TEXT, + status TEXT, + progress INTEGER, + metrics JSON, + error TEXT, + created_at TIMESTAMP, + updated_at TIMESTAMP +) +""") + +def create_run(dataset_id: str, algorithm: str) -> str: + run_id = str(uuid.uuid4()) + now = datetime.utcnow() + + conn.execute( + """ + INSERT INTO runs VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) + """, + ( + run_id, + dataset_id, + algorithm, + "queued", + 0, + None, + None, + now, + now + ) + ) + return run_id + + +def update_run( + run_id: str, + status: str = None, + progress: int = None, + metrics: dict = None, + error: str = None +): + now = datetime.utcnow() + + row = conn.execute( + "SELECT * FROM runs WHERE run_id = ?", + (run_id,) + ).fetchone() + + if not row: + return + + conn.execute( + """ + UPDATE runs SET + status = COALESCE(?, status), + progress = COALESCE(?, progress), + metrics = COALESCE(?, metrics), + error = COALESCE(?, error), + updated_at = ? + WHERE run_id = ? + """, + ( + status, + progress, + json.dumps(metrics) if metrics else None, + error, + now, + run_id + ) + ) + + +def get_run(run_id: str) -> dict | None: + row = conn.execute( + "SELECT * FROM runs WHERE run_id = ?", + (run_id,) + ).fetchone() + + if not row: + return None + + keys = [ + "run_id", "dataset_id", "algorithm", "status", + "progress", "metrics", "error", + "created_at", "updated_at" + ] + + record = dict(zip(keys, row)) + if record["metrics"]: + record["metrics"] = json.loads(record["metrics"]) + + return record diff --git a/app/services/__init__.py b/app/services/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..599a97e1ad11b8f629e415179e0fc3fee2f516fd --- /dev/null +++ b/app/services/__init__.py @@ -0,0 +1 @@ +"""Services module init.""" diff --git a/app/services/__pycache__/__init__.cpython-314.pyc b/app/services/__pycache__/__init__.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..05b6a624f96546425049ac3338f0a8fe7c296530 Binary files /dev/null and b/app/services/__pycache__/__init__.cpython-314.pyc differ diff --git a/app/services/__pycache__/beeline_runner.cpython-314.pyc b/app/services/__pycache__/beeline_runner.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3eb38cace654f4112503859ce068721ee440acac Binary files /dev/null and b/app/services/__pycache__/beeline_runner.cpython-314.pyc differ diff --git a/app/services/__pycache__/hf_datasets.cpython-314.pyc b/app/services/__pycache__/hf_datasets.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..eba4dc1aafd42d5c93a063aa7c97634449813967 Binary files /dev/null and b/app/services/__pycache__/hf_datasets.cpython-314.pyc differ diff --git a/app/services/__pycache__/storage.cpython-314.pyc b/app/services/__pycache__/storage.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..427a23ed907e880f426aaf9ec50eefaf47dbb588 Binary files /dev/null and b/app/services/__pycache__/storage.cpython-314.pyc differ diff --git a/app/services/beeline.py b/app/services/beeline.py new file mode 100644 index 0000000000000000000000000000000000000000..5a644111340b66ac7eae2aa9191c6e6431471767 --- /dev/null +++ b/app/services/beeline.py @@ -0,0 +1,141 @@ +import numpy as np +import pandas as pd +from sklearn.metrics import roc_auc_score, average_precision_score +from scipy.stats import pearsonr, spearmanr +from sklearn.ensemble import RandomForestRegressor + + +def run_beeline_algorithm( + algorithm: str, + dataset_path: str, + params: dict +) -> pd.DataFrame: + """ + Returns inferred network as DataFrame: + [regulator, target, weight] + """ + + expr = pd.read_parquet(dataset_path) + + genes = expr.columns.tolist() + X = expr.values + + edges = [] + + if algorithm == "pearson": + for i, g1 in enumerate(genes): + for j, g2 in enumerate(genes): + if i >= j: + continue + w, _ = pearsonr(X[:, i], X[:, j]) + edges.append((g1, g2, abs(w))) + + elif algorithm == "spearman": + for i, g1 in enumerate(genes): + for j, g2 in enumerate(genes): + if i >= j: + continue + w, _ = spearmanr(X[:, i], X[:, j]) + edges.append((g1, g2, abs(w))) + + elif algorithm == "genie3": + n_trees = params.get("n_estimators", 100) + + for target_idx, target in enumerate(genes): + X_other = np.delete(X, target_idx, axis=1) + y = X[:, target_idx] + + model = RandomForestRegressor( + n_estimators=n_trees, + n_jobs=-1 + ) + model.fit(X_other, y) + + importances = model.feature_importances_ + regulators = [g for g in genes if g != target] + + for r, w in zip(regulators, importances): + edges.append((r, target, w)) + + else: + raise ValueError(f"Unsupported algorithm: {algorithm}") + + return pd.DataFrame(edges, columns=["regulator", "target", "weight"]) + + + +def run_beeline_algorithm( + algorithm: str, + dataset_path: str, + params: dict +) -> pd.DataFrame: + """ + Run a BEELINE-style GRN inference algorithm. + + Returns: + DataFrame with columns: + [regulator, target, weight] + """ + + # Expect dataset_path to be a parquet or csv expression matrix + if dataset_path.endswith(".parquet"): + expr = pd.read_parquet(dataset_path) + else: + expr = pd.read_csv(dataset_path) + + genes = expr.columns.tolist() + X = expr.values + + edges = [] + + algorithm = algorithm.lower() + + # ------------------------ + # Pearson Correlation + # ------------------------ + if algorithm == "pearson": + for i, g1 in enumerate(genes): + for j, g2 in enumerate(genes): + if i >= j: + continue + w, _ = pearsonr(X[:, i], X[:, j]) + edges.append((g1, g2, abs(float(w)))) + + # ------------------------ + # Spearman Correlation + # ------------------------ + elif algorithm == "spearman": + for i, g1 in enumerate(genes): + for j, g2 in enumerate(genes): + if i >= j: + continue + w, _ = spearmanr(X[:, i], X[:, j]) + edges.append((g1, g2, abs(float(w)))) + + # ------------------------ + # GENIE3 (Random Forest) + # ------------------------ + elif algorithm == "genie3": + n_estimators = params.get("n_estimators", 100) + + for target_idx, target in enumerate(genes): + X_other = np.delete(X, target_idx, axis=1) + y = X[:, target_idx] + + model = RandomForestRegressor( + n_estimators=n_estimators, + n_jobs=-1, + random_state=0 + ) + model.fit(X_other, y) + + regulators = [g for g in genes if g != target] + importances = model.feature_importances_ + + for r, w in zip(regulators, importances): + edges.append((r, target, float(w))) + + else: + raise ValueError(f"Unsupported BEELINE algorithm: {algorithm}") + + return pd.DataFrame(edges, columns=["regulator", "target", "weight"]) diff --git a/app/services/beeline_runner.py b/app/services/beeline_runner.py new file mode 100644 index 0000000000000000000000000000000000000000..b08054d343d213646159b5e4f3eccb790a0a016f --- /dev/null +++ b/app/services/beeline_runner.py @@ -0,0 +1,38 @@ +import subprocess +from pathlib import Path + +from app.services.results_parser import parse_results +from app.services.storage import save_metrics, update_run + +RUNS_DIR = Path("data/runs") +RUNS_DIR.mkdir(parents=True, exist_ok=True) + +def execute_run(run_id, dataset_path, algorithm, params): + output_dir = RUNS_DIR / run_id + output_dir.mkdir(parents=True, exist_ok=True) + + update_run(run_id, "running", 10) + + cmd = [ + "docker", "run", "--rm", + "-v", f"{dataset_path}:/input", + "-v", f"{output_dir}:/output", + f"grnbeeline/{algorithm}", + "--input", "/input", + "--output", "/output" + ] + + for k, v in params.items(): + cmd.extend([f"--{k}", str(v)]) + + update_run(run_id, "running", 30) + subprocess.run(cmd, check=True) + + update_run(run_id, "running", 70) + + metrics = parse_results( + pred_path=output_dir / "inferred_network.tsv", + gold_path=output_dir / "gold_standard.tsv" + ) + + save_metrics(run_id, metrics) diff --git a/app/services/datasets.py b/app/services/datasets.py new file mode 100644 index 0000000000000000000000000000000000000000..69273227f2330a1c4ae783b2cd72b95b9a61cef1 --- /dev/null +++ b/app/services/datasets.py @@ -0,0 +1,37 @@ +from datasets import load_dataset +from pathlib import Path + +DATASETS_DIR = Path("data/datasets") +DATASETS_DIR.mkdir(parents=True, exist_ok=True) + +HF_REPO = "ukandu" + +def stage_dataset(dataset_id: str) -> Path: + ds = load_dataset(f"{HF_REPO}/{dataset_id}") + + out_dir = DATASETS_DIR / dataset_id + out_dir.mkdir(parents=True, exist_ok=True) + + expr_path = out_dir / "expression.tsv" + gold_path = out_dir / "gold_standard.tsv" + + ds["train"].to_pandas().to_csv(expr_path, sep="\t", index=False) + ds["gold"].to_pandas().to_csv(gold_path, sep="\t", index=False) + + return out_dir + + +def exec_data(dataset_id: str) -> Path: + ds = load_dataset(dataset_id) + + out_dir = DATA_ROOT / dataset_id.replace("/", "__") + out_dir.mkdir(parents=True, exist_ok=True) + + # Save expression matrix + ds["train"].to_csv(out_dir / "expression.csv", index=False) + + # Save gold standard if exists + if "gold_standard" in ds: + ds["gold_standard"].to_csv(out_dir / "gold_standard.csv", index=False) + + return out_dir diff --git a/app/services/datasets_service.py b/app/services/datasets_service.py new file mode 100644 index 0000000000000000000000000000000000000000..1a15fad43458325bfb457ad30c7b9e93db2c9e98 --- /dev/null +++ b/app/services/datasets_service.py @@ -0,0 +1,249 @@ +""" +Dataset management service. +Handles dataset registration, validation, and metadata management. +""" + +import os +import json +import hashlib +from typing import Optional, List, Dict, Any +from datetime import datetime +from pathlib import Path +import pandas as pd +import logging + +from app.core.config import settings +from app.models.dataset import DatasetResponse, DatasetSchema, DatasetSource + +logger = logging.getLogger(__name__) + + +class DatasetService: + """Service for managing datasets.""" + + def __init__(self): + """Initialize dataset service.""" + self.datasets_dir = settings.DATASETS_DIR + self.datasets_dir.mkdir(parents=True, exist_ok=True) + self.metadata_file = self.datasets_dir / "metadata.json" + self._load_metadata() + + def _load_metadata(self) -> None: + """Load datasets metadata from file.""" + if self.metadata_file.exists(): + with open(self.metadata_file, "r") as f: + self.metadata = json.load(f) + else: + self.metadata = {} + + def _save_metadata(self) -> None: + """Save datasets metadata to file.""" + with open(self.metadata_file, "w") as f: + json.dump(self.metadata, f, indent=2, default=str) + + def _generate_dataset_id(self, name: str) -> str: + """Generate unique dataset ID.""" + timestamp = datetime.utcnow().isoformat() + hash_input = f"{name}:{timestamp}" + hash_id = hashlib.md5(hash_input.encode()).hexdigest()[:12] + return f"{name.lower().replace(' ', '-')}-{hash_id}" + + def _compute_file_hash(self, file_path: Path) -> str: + """Compute SHA256 hash of file.""" + sha256_hash = hashlib.sha256() + with open(file_path, "rb") as f: + for byte_block in iter(lambda: f.read(4096), b""): + sha256_hash.update(byte_block) + return sha256_hash.hexdigest() + + async def register_dataset( + self, + name: str, + source: DatasetSource, + schema: DatasetSchema, + description: Optional[str] = None, + species: Optional[str] = None, + tissue: Optional[str] = None, + metadata: Optional[Dict[str, Any]] = None, + ) -> DatasetResponse: + """Register a new dataset.""" + try: + dataset_id = self._generate_dataset_id(name) + + # Create dataset directory + dataset_dir = self.datasets_dir / dataset_id + dataset_dir.mkdir(parents=True, exist_ok=True) + + # Store source information + source_info = { + **source.dict(), + "registered_at": datetime.utcnow().isoformat(), + } + + # Save metadata + dataset_metadata = { + "id": dataset_id, + "name": name, + "description": description, + "species": species, + "tissue": tissue, + "source": source_info, + "schema": schema.dict(), + "created_at": datetime.utcnow().isoformat(), + "updated_at": datetime.utcnow().isoformat(), + "metadata": metadata or {}, + } + + self.metadata[dataset_id] = dataset_metadata + self._save_metadata() + + logger.info( + f"Dataset registered: {dataset_id}", + extra={"dataset_id": dataset_id, "name": name}, + ) + + return DatasetResponse(**dataset_metadata) + + except Exception as e: + logger.error( + f"Failed to register dataset: {str(e)}", + extra={"dataset_id": name}, + ) + raise + + async def get_dataset(self, dataset_id: str) -> Optional[DatasetResponse]: + """Get dataset by ID.""" + if dataset_id not in self.metadata: + logger.warning(f"Dataset not found: {dataset_id}") + return None + + return DatasetResponse(**self.metadata[dataset_id]) + + async def list_datasets( + self, skip: int = 0, limit: int = 10 + ) -> Dict[str, Any]: + """List all registered datasets.""" + all_datasets = list(self.metadata.values()) + total = len(all_datasets) + items = [DatasetResponse(**d) for d in all_datasets[skip : skip + limit]] + + return { + "total": total, + "items": items, + "page": skip // limit + 1, + "per_page": limit, + } + + async def delete_dataset(self, dataset_id: str) -> bool: + """Delete a dataset.""" + try: + if dataset_id not in self.metadata: + logger.warning(f"Dataset not found: {dataset_id}") + return False + + # Remove metadata + del self.metadata[dataset_id] + self._save_metadata() + + # Remove dataset directory + dataset_dir = self.datasets_dir / dataset_id + if dataset_dir.exists(): + import shutil + + shutil.rmtree(dataset_dir) + + logger.info(f"Dataset deleted: {dataset_id}") + return True + + except Exception as e: + logger.error(f"Failed to delete dataset: {str(e)}") + raise + + async def update_dataset_metadata( + self, dataset_id: str, metadata: Dict[str, Any] + ) -> DatasetResponse: + """Update dataset metadata.""" + if dataset_id not in self.metadata: + logger.warning(f"Dataset not found: {dataset_id}") + raise ValueError(f"Dataset {dataset_id} not found") + + dataset = self.metadata[dataset_id] + dataset["metadata"].update(metadata) + dataset["updated_at"] = datetime.utcnow().isoformat() + + self._save_metadata() + logger.info(f"Dataset metadata updated: {dataset_id}") + + return DatasetResponse(**dataset) + + async def get_dataset_preview( + self, dataset_id: str, num_rows: int = 5 + ) -> Optional[Dict[str, Any]]: + """Get preview of dataset.""" + dataset = await self.get_dataset(dataset_id) + if not dataset: + return None + + try: + # Try to load and preview the dataset file + dataset_dir = self.datasets_dir / dataset_id + dataset_file = dataset_dir / "data.csv" + + if not dataset_file.exists(): + logger.warning(f"Dataset file not found: {dataset_file}") + return None + + df = pd.read_csv(dataset_file, nrows=num_rows) + + return { + "id": dataset_id, + "name": dataset.name, + "num_rows": len(df), + "num_columns": len(df.columns), + "columns": df.columns.tolist(), + "sample_data": df.head(num_rows).to_dict("records"), + } + + except Exception as e: + logger.error(f"Failed to preview dataset: {str(e)}") + return None + + async def validate_dataset_schema( + self, dataset_id: str, file_path: Path + ) -> bool: + """Validate dataset schema.""" + try: + dataset = await self.get_dataset(dataset_id) + if not dataset: + return False + + df = pd.read_csv(file_path) + + # Check required columns + required_columns = [ + dataset.schema.gene_column, + dataset.schema.cell_column, + dataset.schema.expression_column, + ] + + for col in required_columns: + if col not in df.columns: + logger.error( + f"Missing required column: {col}", + extra={"dataset_id": dataset_id}, + ) + return False + + logger.info( + f"Dataset schema validation passed", + extra={"dataset_id": dataset_id}, + ) + return True + + except Exception as e: + logger.error(f"Schema validation failed: {str(e)}") + return False + + +# Global service instance +dataset_service = DatasetService() diff --git a/app/services/hf_datasets.py b/app/services/hf_datasets.py new file mode 100644 index 0000000000000000000000000000000000000000..d66b2ec4d4dde409912695d3b2d437ca584de062 --- /dev/null +++ b/app/services/hf_datasets.py @@ -0,0 +1,232 @@ +import os +import pandas as pd +from typing import List, Dict +from huggingface_hub import HfApi +from datasets import load_dataset +import duckdb +from functools import lru_cache +from pathlib import Path + +HF_TOKEN = os.getenv("HF_TOKEN") + +CACHE_DB = Path("data/hf_datasets.duckdb") +CACHE_DB.parent.mkdir(exist_ok=True) +DATA_DIR.mkdir(parents=True, exist_ok=True) + +OWNER = "Ukandu Chimeremeze James" +HF_ORG = "ukandu" + +api = HfApi(token=HF_TOKEN) + +conn = duckdb.connect(CACHE_DB.as_posix()) + +conn.execute(""" +CREATE TABLE IF NOT EXISTS datasets ( + id TEXT PRIMARY KEY, + name TEXT, + organism TEXT, + type TEXT, + genes INTEGER, + cells INTEGER, + edges INTEGER, + source TEXT, + last_updated TEXT +) +""") + + +def stage_dataset(dataset_id: str): + """ + Download dataset contents locally for execution + """ + return load_dataset( + f"{OWNER}/{dataset_id}", + token=HF_TOKEN + ) + + +@lru_cache(maxsize=1) + +def add_dataset(name: str, data: dict): + """ + Placeholder for dataset upload + (requires push_to_hub implementation) + """ + return { + "status": "not_implemented", + "dataset": name + } + +def list_beeline_datasets(): + """ + Discover BEELINE datasets from HF Hub + """ + repos = api.list_datasets(author=HF_ORG) + + return [ + repo.id + for repo in repos + if "BEELINE" in repo.id + ] + +def list_beeline_datasets(): + datasets = api.list_datasets(author="cskokgibbs") + + return [ + d.id + for d in datasets + if d.id.startswith("cskokgibbs/BEELINE") + and not d.id.endswith("-cache") + ] + +def get_all_dataset_metadata(dataset_id: str) -> Dict: + """ + Detailed metadata for a single dataset + """ + info = api.dataset_info(f"{OWNER}/{dataset_id}") + + return { + "id": info.id, + "description": info.description, + "downloads": info.downloads, + "likes": info.likes, + "tags": info.tags, + "configs": info.configs, + "last_modified": info.last_modified + } + +def extract_metadata(dataset_id: str): + """ + Extract metadata from HF Data Studio + files + """ + ds = load_dataset(dataset_id, split="train") + + genes = ds.num_columns + cells = ds.num_rows + + # Heuristics (safe defaults) + organism = "Unknown" + data_type = "scRNA-seq" + + if "mouse" in dataset_id.lower() or "mdc" in dataset_id.lower(): + organism = "Mus musculus" + elif "hep" in dataset_id.lower() or "human" in dataset_id.lower(): + organism = "Homo sapiens" + + return { + "id": dataset_id, + "slug": dataset_id.split("/")[-1], + "name": dataset_id.split("/")[-1].replace("-", " "), + "organism": organism, + "type": data_type, + "genes": genes, + "cells": cells, + "source": "huggingface", + } + +def list_beeline_datasets(): + datasets = api.list_datasets(author="cskokgibbs") + return [ + d.id for d in datasets + if d.id.startswith("cskokgibbs/BEELINE") + ] + +def compute_dataset_stats(dataset_id: str): + ds = load_dataset(dataset_id) + + # Expression matrix + expr = ds["train"] + genes = len(expr.column_names) - 1 # excluding cell_id + cells = expr.num_rows + + # Gold standard edges + try: + gs = ds["gold_standard"] + edges = gs.num_rows + except: + edges = None + + return genes, cells, edges + + +def extract_card_metadata(dataset_id: str): + info = api.dataset_info(dataset_id) + card = info.cardData or {} + + return { + "organism": card.get("organism", "unknown"), + "type": card.get("dataset_type", "scRNA-seq"), + "last_updated": info.last_modified + } + + +def list_available_datasets() -> List[Dict]: + """ + List all dataset repos under cskokgibbs + """ + datasets = api.list_datasets(author=OWNER) + + return [ + { + "id": ds.id, + "private": ds.private, + "downloads": ds.downloads, + "likes": ds.likes, + "last_modified": ds.last_modified + } + for ds in datasets + ] + +def prepare_expression_matrix(dataset_id: str) -> str: + """ + Downloads a BEELINE dataset from HF and returns + a local parquet path usable by algorithms. + """ + + ds = load_dataset(dataset_id) + + if "train" not in ds: + raise ValueError("Dataset has no train split") + + expr = ds["train"].to_pandas() + + path = DATA_DIR / f"{dataset_id.split('/')[-1]}.parquet" + expr.to_parquet(path) + + return path.as_posix() + + +def get_dataset_metadata(dataset_id: str): + cached = conn.execute( + "SELECT * FROM datasets WHERE id = ?", + (dataset_id,) + ).fetchone() + + if cached: + return dict(zip( + ["id","name","organism","type","genes","cells","edges","source","last_updated"], + cached + )) + + genes, cells, edges = compute_dataset_stats(dataset_id) + card = extract_card_metadata(dataset_id) + + record = { + "id": dataset_id, + "name": dataset_id.split("/")[-1], + "organism": card["organism"], + "type": card["type"], + "genes": genes, + "cells": cells, + "edges": edges, + "source": "huggingface", + "last_updated": card["last_updated"] + } + + conn.execute( + "INSERT INTO datasets VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)", + tuple(record.values()) + ) + + return record + diff --git a/app/services/inference_service.py b/app/services/inference_service.py new file mode 100644 index 0000000000000000000000000000000000000000..7d0297d46126cb7d894007438f6bd0166e6af8f5 --- /dev/null +++ b/app/services/inference_service.py @@ -0,0 +1,256 @@ +""" +Inference service for running GRN algorithms. +""" + +import os +import json +import subprocess +import logging +from typing import Dict, Any, Optional +from pathlib import Path +from datetime import datetime + +from app.core.config import settings + +logger = logging.getLogger(__name__) + + +class InferenceService: + """Service for running GRN inference algorithms.""" + + def __init__(self): + """Initialize inference service.""" + self.results_dir = settings.RESULTS_DIR + self.temp_dir = settings.TEMP_DIR + self.docker_registry = settings.DOCKER_REGISTRY + self.use_docker = settings.USE_DOCKER + + def _get_docker_image(self, algorithm: str) -> str: + """Get Docker image name for algorithm.""" + algorithm_lower = algorithm.lower() + return f"{self.docker_registry}/{algorithm_lower}" + + def _create_job_directory(self, job_id: str) -> Path: + """Create job-specific directory.""" + job_dir = self.results_dir / job_id + job_dir.mkdir(parents=True, exist_ok=True) + return job_dir + + async def run_algorithm( + self, + job_id: str, + dataset_id: str, + algorithm: str, + dataset_path: str, + parameters: Dict[str, Any], + ) -> Dict[str, Any]: + """Run a GRN inference algorithm.""" + try: + job_dir = self._create_job_directory(job_id) + log_file = job_dir / "execution.log" + output_file = job_dir / f"{algorithm.lower()}_network.tsv" + + logger.info( + f"Starting inference with {algorithm}", + extra={"job_id": job_id, "algorithm": algorithm, "dataset_id": dataset_id}, + ) + + # Prepare command based on algorithm + cmd = self._prepare_algorithm_command( + algorithm=algorithm, + dataset_path=dataset_path, + output_path=str(output_file), + parameters=parameters, + job_dir=str(job_dir), + ) + + # Run algorithm + with open(log_file, "w") as lf: + process = await self._execute_command(cmd, lf) + + if process.returncode != 0: + error_msg = f"Algorithm execution failed with code {process.returncode}" + logger.error( + error_msg, + extra={"job_id": job_id, "algorithm": algorithm}, + ) + raise RuntimeError(error_msg) + + # Validate output + if not output_file.exists(): + raise RuntimeError(f"Output file not created: {output_file}") + + # Generate result summary + result = { + "job_id": job_id, + "dataset_id": dataset_id, + "algorithm": algorithm, + "status": "completed", + "output_file": str(output_file), + "log_file": str(log_file), + "completed_at": datetime.utcnow().isoformat(), + "metrics": await self._compute_metrics(output_file, dataset_path), + } + + logger.info( + f"Algorithm execution completed", + extra={"job_id": job_id, "algorithm": algorithm}, + ) + + return result + + except Exception as e: + logger.error( + f"Algorithm execution failed: {str(e)}", + extra={"job_id": job_id, "algorithm": algorithm}, + ) + raise + + def _prepare_algorithm_command( + self, + algorithm: str, + dataset_path: str, + output_path: str, + parameters: Dict[str, Any], + job_dir: str, + ) -> list: + """Prepare command for algorithm execution.""" + if self.use_docker: + return self._prepare_docker_command( + algorithm, dataset_path, output_path, parameters, job_dir + ) + else: + return self._prepare_python_command( + algorithm, dataset_path, output_path, parameters, job_dir + ) + + def _prepare_docker_command( + self, + algorithm: str, + dataset_path: str, + output_path: str, + parameters: Dict[str, Any], + job_dir: str, + ) -> list: + """Prepare Docker command for algorithm.""" + docker_image = self._get_docker_image(algorithm) + + # Volume mappings + volumes = [ + f"{dataset_path}:/data/input:ro", + f"{output_path}:/data/output/network.tsv", + f"{job_dir}:/data/logs", + ] + + # Base docker command + cmd = ["docker", "run", "--rm"] + + # Add volume mounts + for volume in volumes: + cmd.extend(["-v", volume]) + + # Add memory limit + cmd.extend(["-m", settings.ALGORITHM_MEMORY_LIMIT]) + + # Add image and default script + cmd.append(docker_image) + + # Algorithm-specific parameters would be added here + # This is a generic template + cmd.extend([ + "bash", "-c", + f"cd /data && python run{algorithm}.py --input /data/input --output /data/output" + ]) + + return cmd + + def _prepare_python_command( + self, + algorithm: str, + dataset_path: str, + output_path: str, + parameters: Dict[str, Any], + job_dir: str, + ) -> list: + """Prepare Python command for algorithm.""" + # This would use the refactored Python runners from BLRun + runner_module = self._get_python_runner(algorithm) + + cmd = [ + "python", + "-m", + runner_module, + "--input", + dataset_path, + "--output", + output_path, + "--log", + str(Path(job_dir) / "execution.log"), + ] + + # Add parameters + for key, value in parameters.items(): + cmd.extend([f"--{key}", str(value)]) + + return cmd + + def _get_python_runner(self, algorithm: str) -> str: + """Get Python runner module for algorithm.""" + runner_map = { + "SCODE": "app.services.runners.scode_runner", + "SCNS": "app.services.runners.scns_runner", + "SINCERITIES": "app.services.runners.sincerities_runner", + "PIDC": "app.services.runners.pidc_runner", + "GRNVBEM": "app.services.runners.grnvbem_runner", + "GENIE3": "app.services.runners.genie3_runner", + "GRNBOOST2": "app.services.runners.grnboost2_runner", + "LEAP": "app.services.runners.leap_runner", + "JUMP3": "app.services.runners.jump3_runner", + "PPCOR": "app.services.runners.ppcor_runner", + "GRISLI": "app.services.runners.grisli_runner", + "SINGE": "app.services.runners.singe_runner", + "SCRIBE": "app.services.runners.scribe_runner", + "SCSGL": "app.services.runners.scsgl_runner", + } + + return runner_map.get(algorithm.upper(), "app.services.runners.generic_runner") + + async def _execute_command(self, cmd: list, log_file) -> subprocess.CompletedProcess: + """Execute command and capture output.""" + try: + process = subprocess.run( + cmd, + stdout=log_file, + stderr=subprocess.STDOUT, + timeout=settings.ALGORITHM_TIMEOUT, + ) + return process + except subprocess.TimeoutExpired: + logger.error("Algorithm execution timeout") + raise RuntimeError("Algorithm execution timed out") + + async def _compute_metrics( + self, + output_file: Path, + dataset_path: str, + ) -> Dict[str, Any]: + """Compute metrics for result.""" + try: + # Parse network file + import pandas as pd + + network_df = pd.read_csv(output_file, sep="\t", header=None) + + metrics = { + "total_edges": len(network_df), + "num_unique_genes": len(set(network_df[0]) | set(network_df[1])), + } + + return metrics + except Exception as e: + logger.warning(f"Failed to compute metrics: {str(e)}") + return {} + + +# Global service instance +inference_service = InferenceService() diff --git a/app/services/jobs_service.py b/app/services/jobs_service.py new file mode 100644 index 0000000000000000000000000000000000000000..f34015bba06ba83f5cf6b320eff83bdef8bacddf --- /dev/null +++ b/app/services/jobs_service.py @@ -0,0 +1,273 @@ +""" +Job management service. +Handles job lifecycle, persistence, and monitoring. +""" + +import os +import json +import uuid +import logging +from typing import Optional, List, Dict, Any +from datetime import datetime +from pathlib import Path + +from app.core.config import settings +from app.models.job import JobStatusEnum, JobResponse +from app.workers.tasks import run_inference_job + +logger = logging.getLogger(__name__) + + +class JobService: + """Service for managing jobs.""" + + def __init__(self): + """Initialize job service.""" + self.jobs_dir = settings.RESULTS_DIR + self.jobs_dir.mkdir(parents=True, exist_ok=True) + self.metadata_file = self.jobs_dir / "jobs_metadata.json" + self._load_jobs_metadata() + + def _load_jobs_metadata(self) -> None: + """Load jobs metadata from file.""" + if self.metadata_file.exists(): + try: + with open(self.metadata_file, "r") as f: + self.jobs = json.load(f) + except Exception as e: + logger.error(f"Failed to load jobs metadata: {str(e)}") + self.jobs = {} + else: + self.jobs = {} + + def _save_jobs_metadata(self) -> None: + """Save jobs metadata to file.""" + try: + with open(self.metadata_file, "w") as f: + json.dump(self.jobs, f, indent=2, default=str) + except Exception as e: + logger.error(f"Failed to save jobs metadata: {str(e)}") + + def _generate_job_id(self) -> str: + """Generate unique job ID.""" + return f"job-{uuid.uuid4().hex[:12]}" + + def _create_job_directory(self, job_id: str) -> Path: + """Create job-specific directory.""" + job_dir = self.jobs_dir / job_id + job_dir.mkdir(parents=True, exist_ok=True) + return job_dir + + async def submit_job( + self, + dataset_id: str, + algorithm: str, + parameters: Dict[str, Any], + name: Optional[str] = None, + description: Optional[str] = None, + ) -> JobResponse: + """Submit a new inference job.""" + try: + job_id = self._generate_job_id() + job_dir = self._create_job_directory(job_id) + + # Create job metadata + job_metadata = { + "id": job_id, + "dataset_id": dataset_id, + "algorithm": algorithm, + "parameters": parameters, + "name": name or f"{algorithm} on {dataset_id}", + "description": description, + "status": JobStatusEnum.SUBMITTED.value, + "progress": 0.0, + "started_at": None, + "ended_at": None, + "error_message": None, + "celery_task_id": None, + "result_path": str(job_dir), + "log_file": str(job_dir / "execution.log"), + "created_at": datetime.utcnow().isoformat(), + "updated_at": datetime.utcnow().isoformat(), + } + + # Store metadata + self.jobs[job_id] = job_metadata + self._save_jobs_metadata() + + # Submit async task + dataset_path = settings.DATASETS_DIR / dataset_id / "data.csv" + + task = run_inference_job.delay( + job_id=job_id, + dataset_id=dataset_id, + algorithm=algorithm, + dataset_path=str(dataset_path), + parameters=parameters, + ) + + # Update with task ID + self.jobs[job_id]["celery_task_id"] = task.id + self.jobs[job_id]["status"] = JobStatusEnum.RUNNING.value + self.jobs[job_id]["started_at"] = datetime.utcnow().isoformat() + self._save_jobs_metadata() + + logger.info( + f"Job submitted", + extra={ + "job_id": job_id, + "algorithm": algorithm, + "dataset_id": dataset_id, + "task_id": task.id, + }, + ) + + return JobResponse(**self.jobs[job_id]) + + except Exception as e: + logger.error(f"Failed to submit job: {str(e)}") + raise + + async def get_job(self, job_id: str) -> Optional[JobResponse]: + """Get job by ID.""" + if job_id not in self.jobs: + logger.warning(f"Job not found: {job_id}") + return None + + job_data = self.jobs[job_id] + + # Check if associated Celery task exists and update status + if job_data.get("celery_task_id"): + task_id = job_data["celery_task_id"] + # Could check Celery task state here to update status + # For now, returning stored metadata + + return JobResponse(**job_data) + + async def list_jobs( + self, + skip: int = 0, + limit: int = 10, + status: Optional[JobStatusEnum] = None, + dataset_id: Optional[str] = None, + algorithm: Optional[str] = None, + ) -> Dict[str, Any]: + """List jobs with optional filters.""" + all_jobs = list(self.jobs.values()) + + # Apply filters + if status: + all_jobs = [j for j in all_jobs if j["status"] == status.value] + if dataset_id: + all_jobs = [j for j in all_jobs if j["dataset_id"] == dataset_id] + if algorithm: + all_jobs = [j for j in all_jobs if j["algorithm"] == algorithm] + + # Sort by creation date (newest first) + all_jobs.sort(key=lambda x: x["created_at"], reverse=True) + + total = len(all_jobs) + items = [JobResponse(**j) for j in all_jobs[skip : skip + limit]] + + return { + "total": total, + "items": items, + "page": skip // limit + 1, + "per_page": limit, + } + + async def cancel_job(self, job_id: str) -> bool: + """Cancel a job.""" + try: + if job_id not in self.jobs: + logger.warning(f"Job not found: {job_id}") + return False + + job_data = self.jobs[job_id] + + # Check if job is still running + if job_data["status"] not in [ + JobStatusEnum.PENDING.value, + JobStatusEnum.SUBMITTED.value, + JobStatusEnum.RUNNING.value, + ]: + logger.warning(f"Cannot cancel job with status: {job_data['status']}") + return False + + # Try to revoke Celery task + if job_data.get("celery_task_id"): + from celery import current_app + + current_app.control.revoke(job_data["celery_task_id"], terminate=True) + + # Update job status + self.jobs[job_id]["status"] = JobStatusEnum.CANCELLED.value + self.jobs[job_id]["ended_at"] = datetime.utcnow().isoformat() + self._save_jobs_metadata() + + logger.info(f"Job cancelled: {job_id}") + return True + + except Exception as e: + logger.error(f"Failed to cancel job: {str(e)}") + raise + + async def get_job_logs(self, job_id: str) -> Optional[str]: + """Get job execution logs.""" + try: + if job_id not in self.jobs: + logger.warning(f"Job not found: {job_id}") + return None + + log_file = Path(self.jobs[job_id]["log_file"]) + + if not log_file.exists(): + logger.warning(f"Log file not found: {log_file}") + return None + + with open(log_file, "r") as f: + return f.read() + + except Exception as e: + logger.error(f"Failed to retrieve logs: {str(e)}") + return None + + async def update_job_status( + self, + job_id: str, + status: JobStatusEnum, + progress: Optional[float] = None, + error_message: Optional[str] = None, + ) -> bool: + """Update job status.""" + try: + if job_id not in self.jobs: + logger.warning(f"Job not found: {job_id}") + return False + + self.jobs[job_id]["status"] = status.value + self.jobs[job_id]["updated_at"] = datetime.utcnow().isoformat() + + if progress is not None: + self.jobs[job_id]["progress"] = max(0, min(100, progress)) + + if error_message: + self.jobs[job_id]["error_message"] = error_message + + if status in [ + JobStatusEnum.COMPLETED, + JobStatusEnum.FAILED, + JobStatusEnum.CANCELLED, + ]: + self.jobs[job_id]["ended_at"] = datetime.utcnow().isoformat() + + self._save_jobs_metadata() + return True + + except Exception as e: + logger.error(f"Failed to update job status: {str(e)}") + raise + + +# Global service instance +job_service = JobService() diff --git a/app/services/metrics.py b/app/services/metrics.py new file mode 100644 index 0000000000000000000000000000000000000000..df25566f053ef03221a19132974c3bf2801299c8 --- /dev/null +++ b/app/services/metrics.py @@ -0,0 +1,47 @@ +import pandas as pd +from sklearn.metrics import roc_auc_score, average_precision_score, f1_score + +def compute_metrics(inferred: pd.DataFrame, gold_path: str) -> dict: + gold = pd.read_parquet(gold_path) + + inferred["edge"] = inferred["regulator"] + "→" + inferred["target"] + gold["edge"] = gold["regulator"] + "→" + gold["target"] + + merged = inferred.merge( + gold[["edge"]], + on="edge", + how="left", + indicator=True + ) + + y_true = (merged["_merge"] == "both").astype(int) + y_score = merged["weight"].values + + return { + "auroc": float(roc_auc_score(y_true, y_score)), + "auprc": float(average_precision_score(y_true, y_score)), + "f1": float(f1_score(y_true, y_score > y_score.mean())) + } + +def expose_metrics(inferred: pd.DataFrame) -> dict: + """ + Exposing placeholder metrics for now. + These will later be replaced by real AUROC/AUPRC/F1 + once gold standards are wired. + + This prevents refactors. + """ + + if inferred.empty: + return { + "edges": 0, + "mean_weight": 0.0, + "max_weight": 0.0 + } + + return { + "edges": int(len(inferred)), + "mean_weight": float(inferred["weight"].mean()), + "max_weight": float(inferred["weight"].max()) + } + diff --git a/app/services/results_parser.py b/app/services/results_parser.py new file mode 100644 index 0000000000000000000000000000000000000000..26dcbdf2389fc248afcbc81e4e871258f5ea9572 --- /dev/null +++ b/app/services/results_parser.py @@ -0,0 +1,39 @@ +import pandas as pd +from sklearn.metrics import ( + roc_auc_score, + average_precision_score, + f1_score, + precision_recall_curve +) + +def parse_results(pred_path, gold_path, threshold=0.5): + pred = pd.read_csv(pred_path, sep="\t") + gold = pd.read_csv(gold_path, sep="\t") + + gold_edges = set( + zip(gold.iloc[:, 0], gold.iloc[:, 1]) + ) + + y_true = [] + y_score = [] + + for _, row in pred.iterrows(): + edge = (row[0], row[1]) + y_true.append(1 if edge in gold_edges else 0) + y_score.append(row[2]) + + auroc = roc_auc_score(y_true, y_score) + auprc = average_precision_score(y_true, y_score) + + y_pred = [1 if s >= threshold else 0 for s in y_score] + f1 = f1_score(y_true, y_pred) + + precision, recall, _ = precision_recall_curve(y_true, y_score) + + return { + "auroc": auroc, + "auprc": auprc, + "f1": f1, + "precision_curve": precision.tolist(), + "recall_curve": recall.tolist() + } diff --git a/app/services/runners/__init__.py b/app/services/runners/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ee862e708142c0691e6a48b7c008be6699b16031 --- /dev/null +++ b/app/services/runners/__init__.py @@ -0,0 +1 @@ +"""Runners module init.""" diff --git a/app/services/runners/generic_runner.py b/app/services/runners/generic_runner.py new file mode 100644 index 0000000000000000000000000000000000000000..b8569dd180afad52e6d50e2d38e194a4d2c3e495 --- /dev/null +++ b/app/services/runners/generic_runner.py @@ -0,0 +1,101 @@ +""" +Generic algorithm runner that can be extended for specific algorithms. +""" + +from typing import Dict, Any, Optional +import pandas as pd +import logging + +from app.services.runners.utils import BaseRunner, load_expression_data, save_network + +logger = logging.getLogger(__name__) + + +class GenericGRNRunner(BaseRunner): + """Generic GRN inference runner.""" + + def __init__(self): + """Initialize generic runner.""" + super().__init__("generic") + + def run( + self, + input_file: str, + output_file: str, + parameters: Dict[str, Any], + **kwargs, + ) -> Dict[str, Any]: + """Run generic GRN inference.""" + try: + # Validate input + if not self.validate_input(input_file): + raise RuntimeError("Input validation failed") + + # Load data + data = load_expression_data(input_file) + if data is None: + raise RuntimeError("Failed to load expression data") + + self.logger.info(f"Loaded data: {data.shape}") + + # Run inference (basic correlation) + network = self._infer_network(data, parameters) + + # Save output + if not save_network(network, output_file): + raise RuntimeError("Failed to save network") + + # Validate output + if not self.validate_output(output_file): + raise RuntimeError("Output validation failed") + + return { + "status": "completed", + "output_file": output_file, + "metrics": { + "num_edges": len(network), + "num_genes": len(set(network[0]) | set(network[1])), + }, + } + + except Exception as e: + self.logger.error(f"Execution failed: {str(e)}") + raise + + def _infer_network( + self, + data: pd.DataFrame, + parameters: Dict[str, Any], + ) -> pd.DataFrame: + """Infer GRN using correlation.""" + from app.services.runners.utils import compute_correlation + + correlation = compute_correlation(data) + + # Get threshold + threshold = parameters.get("correlation_threshold", 0.5) + + # Extract edges + edges = [] + for i in range(len(correlation)): + for j in range(i + 1, len(correlation)): + corr_value = abs(correlation.iloc[i, j]) + if corr_value >= threshold: + edges.append([ + correlation.index[i], + correlation.columns[j], + corr_value, + ]) + + return pd.DataFrame(edges, columns=["TF", "Target", "Score"]) + + +# Convenience function for running +async def run_generic( + input_file: str, + output_file: str, + parameters: Dict[str, Any], +) -> Dict[str, Any]: + """Run generic GRN inference.""" + runner = GenericGRNRunner() + return runner.run(input_file, output_file, parameters) diff --git a/app/services/runners/utils.py b/app/services/runners/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..09f911faa1b5b5c993518778fa5fdefaa6298320 --- /dev/null +++ b/app/services/runners/utils.py @@ -0,0 +1,179 @@ +""" +Generic runner template and utilities for algorithm execution. +""" + +import logging +from typing import Dict, Any, Optional +from pathlib import Path +import pandas as pd + + +logger = logging.getLogger(__name__) + + +class BaseRunner: + """Base class for algorithm runners.""" + + def __init__(self, algorithm_name: str): + """Initialize runner.""" + self.algorithm_name = algorithm_name + self.logger = logging.getLogger(f"runners.{algorithm_name.lower()}") + + def run( + self, + input_file: str, + output_file: str, + parameters: Dict[str, Any], + **kwargs, + ) -> Dict[str, Any]: + """Run algorithm. Must be implemented by subclasses.""" + raise NotImplementedError + + def validate_input(self, input_file: str) -> bool: + """Validate input file.""" + try: + if not Path(input_file).exists(): + self.logger.error(f"Input file not found: {input_file}") + return False + + df = pd.read_csv(input_file) + if df.empty: + self.logger.error("Input file is empty") + return False + + self.logger.info(f"Input validation passed: {input_file}") + return True + + except Exception as e: + self.logger.error(f"Input validation failed: {str(e)}") + return False + + def validate_output(self, output_file: str) -> bool: + """Validate output file.""" + try: + if not Path(output_file).exists(): + self.logger.error(f"Output file not found: {output_file}") + return False + + df = pd.read_csv(output_file, sep="\t", header=None) + if df.empty: + self.logger.error("Output file is empty") + return False + + self.logger.info(f"Output validation passed: {output_file}") + return True + + except Exception as e: + self.logger.error(f"Output validation failed: {str(e)}") + return False + + def parse_parameters(self, parameters: Dict[str, Any]) -> Dict[str, Any]: + """Parse and validate algorithm parameters.""" + return parameters + + def get_default_parameters(self) -> Dict[str, Any]: + """Get default parameters for algorithm.""" + return {} + + +def load_expression_data(file_path: str) -> Optional[pd.DataFrame]: + """Load expression data from file.""" + try: + if file_path.endswith(".csv"): + return pd.read_csv(file_path, index_col=0) + elif file_path.endswith(".tsv"): + return pd.read_csv(file_path, sep="\t", index_col=0) + elif file_path.endswith(".h5ad"): + try: + import anndata + adata = anndata.read_h5ad(file_path) + return pd.DataFrame( + adata.X.T, + index=adata.var_names, + columns=adata.obs_names, + ) + except ImportError: + logger.error("anndata not installed, cannot read h5ad files") + return None + else: + logger.warning(f"Unknown file format: {file_path}") + return None + except Exception as e: + logger.error(f"Failed to load expression data: {str(e)}") + return None + + +def save_network( + network_df: pd.DataFrame, + output_file: str, + format: str = "tsv", +) -> bool: + """Save network to file.""" + try: + output_path = Path(output_file) + output_path.parent.mkdir(parents=True, exist_ok=True) + + if format == "tsv": + network_df.to_csv( + output_file, + sep="\t", + index=False, + header=False, + ) + elif format == "csv": + network_df.to_csv(output_file, index=False) + else: + logger.warning(f"Unknown format: {format}, using TSV") + network_df.to_csv( + output_file, + sep="\t", + index=False, + header=False, + ) + + logger.info(f"Network saved: {output_file}") + return True + + except Exception as e: + logger.error(f"Failed to save network: {str(e)}") + return False + + +def compute_correlation(data: pd.DataFrame) -> pd.DataFrame: + """Compute Pearson correlation matrix.""" + return data.T.corr() + + +def compute_mutual_information(data: pd.DataFrame) -> pd.DataFrame: + """Compute mutual information matrix.""" + from sklearn.preprocessing import scale + from scipy.stats import entropy + import numpy as np + + n_genes = data.shape[0] + mi_matrix = np.zeros((n_genes, n_genes)) + + scaled_data = scale(data.T, axis=0).T + + for i in range(n_genes): + for j in range(i + 1, n_genes): + gene_i = scaled_data[i] + gene_j = scaled_data[j] + + # Digitize to 10 bins + digitized_i = np.digitize(gene_i, np.linspace(-3, 3, 10)) + digitized_j = np.digitize(gene_j, np.linspace(-3, 3, 10)) + + # Compute MI + pxy = np.histogram2d(digitized_i, digitized_j, bins=10)[0] / len(gene_i) + px = np.histogram(digitized_i, bins=10)[0] / len(gene_i) + py = np.histogram(digitized_j, bins=10)[0] / len(gene_j) + + px_py = np.outer(px, py) + nz = pxy > 0 + + mi = np.sum(pxy[nz] * np.log(pxy[nz] / (px_py[nz] + 1e-10))) + mi_matrix[i, j] = mi + mi_matrix[j, i] = mi + + return pd.DataFrame(mi_matrix) diff --git a/app/services/runs.py b/app/services/runs.py new file mode 100644 index 0000000000000000000000000000000000000000..4db0885250b5578320a588ac53b30448b96ef40a --- /dev/null +++ b/app/services/runs.py @@ -0,0 +1,61 @@ +from app.services.beeline import run_beeline_algorithm +from app.services.metrics import compute_metrics +from app.registry.runs import update_run + +def execute_run(run_id, dataset_path, algorithm, params): + try: + update_run(run_id, status="running", progress=10) + + output = run_beeline_algorithm( + algorithm=algorithm, + dataset_path=dataset_path, + params=params + ) + + metrics = compute_metrics(output) + + update_run( + run_id, + status="completed", + progress=100, + metrics=metrics + ) + + except Exception as e: + update_run( + run_id, + status="failed", + error=str(e), + progress=0 + ) + raise + +def execute_runs_params(run_id, dataset_path, gold_path, algorithm, params): + try: + update_run(run_id, status="running", progress=10) + + inferred = run_beeline_algorithm( + algorithm=algorithm, + dataset_path=dataset_path, + params=params + ) + + update_run(run_id, progress=70) + + metrics = compute_metrics(inferred, gold_path) + + update_run( + run_id, + status="completed", + progress=100, + metrics=metrics + ) + + except Exception as e: + update_run( + run_id, + status="failed", + progress=0, + error=str(e) + ) + raise diff --git a/app/services/storage.py b/app/services/storage.py new file mode 100644 index 0000000000000000000000000000000000000000..d2d8ec1fcb3eea275da841810c1b29fc54021876 --- /dev/null +++ b/app/services/storage.py @@ -0,0 +1,101 @@ +import duckdb +import uuid +from pathlib import Path +from datetime import datetime + +DB_PATH = Path("data/beeline.duckdb") +DB_PATH.parent.mkdir(parents=True, exist_ok=True) + +conn = duckdb.connect(DB_PATH.as_posix()) + +conn.execute(""" +CREATE TABLE IF NOT EXISTS runs ( + run_id TEXT PRIMARY KEY, + dataset TEXT, + algorithm TEXT, + status TEXT, + progress INT, + created_at TIMESTAMP +) +""") + +conn.execute(""" +CREATE TABLE IF NOT EXISTS metrics ( + run_id TEXT, + auroc DOUBLE, + auprc DOUBLE, + f1 DOUBLE +) +""") + +def create_run(dataset: str, algorithm: str) -> str: + run_id = str(uuid.uuid4()) + conn.execute( + """ + INSERT INTO runs VALUES (?, ?, ?, ?, ?, ?) + """, + ( + run_id, + dataset, + algorithm, + "running", + 0, + datetime.utcnow() + ) + ) + return run_id + + +def update_run(run_id: str, status: str, progress: int): + conn.execute( + """ + UPDATE runs SET status = ?, progress = ? + WHERE run_id = ? + """, + (status, progress, run_id) + ) + + +def save_metrics(run_id: str, metrics: dict): + conn.execute( + "INSERT INTO metrics VALUES (?, ?, ?, ?)", + ( + run_id, + metrics["auroc"], + metrics["auprc"], + metrics["f1"] + ) + ) + update_run(run_id, "completed", 100) + + +def get_run(run_id: str): + row = conn.execute( + "SELECT run_id, status, progress FROM runs WHERE run_id = ?", + (run_id,) + ).fetchone() + + if not row: + return None + + return { + "run_id": row[0], + "status": row[1], + "progress": row[2] + } + + +def get_run_metrics(run_id: str): + row = conn.execute( + "SELECT auroc, auprc, f1 FROM metrics WHERE run_id = ?", + (run_id,) + ).fetchone() + + if row is None: + return None + + return { + "auroc": row[0], + "auprc": row[1], + "f1": row[2] + } diff --git a/app/workers/__init__.py b/app/workers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..97fb1f4c562333b856850c2a4924f36946498ecd --- /dev/null +++ b/app/workers/__init__.py @@ -0,0 +1 @@ +"""Workers module init.""" diff --git a/app/workers/tasks.py b/app/workers/tasks.py new file mode 100644 index 0000000000000000000000000000000000000000..40cbb1fa1f5503677f1152f3dc73fa295e6f0164 --- /dev/null +++ b/app/workers/tasks.py @@ -0,0 +1,272 @@ +""" +Celery task definitions for asynchronous job execution. +""" + +import os +import json +import logging +from typing import Dict, Any +from datetime import datetime, timedelta +from pathlib import Path + +from app.core.tasks import celery_app +from app.services.inference_service import inference_service + +logger = logging.getLogger(__name__) + + +@celery_app.task(bind=True, name="app.workers.tasks.run_inference_job") +def run_inference_job( + self, + job_id: str, + dataset_id: str, + algorithm: str, + dataset_path: str, + parameters: Dict[str, Any], +) -> Dict[str, Any]: + """Run GRN inference job asynchronously.""" + try: + logger.info( + f"Starting inference task", + extra={"job_id": job_id, "algorithm": algorithm}, + ) + + # Update task state to running + self.update_state( + state="PROGRESS", + meta={"current": 0, "total": 100, "status": "Initializing algorithm"}, + ) + + # Run algorithm + result = inference_service.run_algorithm( + job_id=job_id, + dataset_id=dataset_id, + algorithm=algorithm, + dataset_path=dataset_path, + parameters=parameters, + ) + + logger.info( + f"Inference task completed", + extra={"job_id": job_id, "algorithm": algorithm}, + ) + + return result + + except Exception as e: + logger.error( + f"Inference task failed: {str(e)}", + extra={"job_id": job_id, "algorithm": algorithm}, + ) + self.update_state( + state="FAILURE", + meta={ + "exc_type": type(e).__name__, + "exc_message": str(e), + }, + ) + raise + + +@celery_app.task(bind=True, name="app.workers.tasks.compare_networks") +def compare_networks( + self, + network_file_1: str, + network_file_2: str, +) -> Dict[str, Any]: + """Compare two GRN networks.""" + try: + import pandas as pd + + logger.info("Starting network comparison") + + # Load networks + net1 = pd.read_csv(network_file_1, sep="\t", header=None) + net2 = pd.read_csv(network_file_2, sep="\t", header=None) + + # Convert to edge sets + edges1 = set(zip(net1[0], net1[1])) + edges2 = set(zip(net2[0], net2[1])) + + # Compute metrics + intersection = edges1 & edges2 + union = edges1 | edges2 + jaccard_index = len(intersection) / len(union) if len(union) > 0 else 0 + + result = { + "jaccard_index": float(jaccard_index), + "overlap_edges": len(intersection), + "edges_only_in_1": len(edges1 - edges2), + "edges_only_in_2": len(edges2 - edges1), + "total_edges_1": len(edges1), + "total_edges_2": len(edges2), + } + + logger.info(f"Network comparison completed: {result}") + return result + + except Exception as e: + logger.error(f"Network comparison failed: {str(e)}") + raise + + +@celery_app.task( + name="app.workers.tasks.cleanup_old_results", + expires=3600, +) +def cleanup_old_results(days: int = 7) -> Dict[str, Any]: + """Clean up old result files.""" + try: + from app.core.config import settings + import shutil + + logger.info(f"Starting cleanup of results older than {days} days") + + results_dir = settings.RESULTS_DIR + cutoff_time = datetime.utcnow() - timedelta(days=days) + deleted_count = 0 + deleted_size = 0 + + for job_dir in results_dir.iterdir(): + if not job_dir.is_dir(): + continue + + # Check if directory is older than cutoff + mtime = datetime.fromtimestamp(job_dir.stat().st_mtime) + if mtime < cutoff_time: + try: + size = sum( + f.stat().st_size + for f in job_dir.rglob("*") + if f.is_file() + ) + shutil.rmtree(job_dir) + deleted_count += 1 + deleted_size += size + logger.info(f"Deleted old results: {job_dir.name}") + except Exception as e: + logger.error(f"Failed to delete {job_dir}: {str(e)}") + + logger.info( + f"Cleanup completed: {deleted_count} directories, " + f"{deleted_size / (1024 * 1024):.2f} MB freed" + ) + + return { + "deleted_count": deleted_count, + "freed_mb": deleted_size / (1024 * 1024), + } + + except Exception as e: + logger.error(f"Cleanup task failed: {str(e)}") + raise + + +@celery_app.task(name="app.workers.tasks.compute_metrics") +def compute_metrics(result_file: str) -> Dict[str, Any]: + """Compute metrics for a result network.""" + try: + import pandas as pd + + logger.info(f"Computing metrics for {result_file}") + + network = pd.read_csv(result_file, sep="\t", header=None) + + # Compute basic network metrics + num_edges = len(network) + nodes = set(network[0]) | set(network[1]) + num_nodes = len(nodes) + density = (2 * num_edges) / (num_nodes * (num_nodes - 1)) + + # Degree statistics + degree_dict = {} + for _, row in network.iterrows(): + degree_dict[row[0]] = degree_dict.get(row[0], 0) + 1 + degree_dict[row[1]] = degree_dict.get(row[1], 0) + 1 + + degrees = list(degree_dict.values()) + avg_degree = sum(degrees) / len(degrees) if degrees else 0 + max_degree = max(degrees) if degrees else 0 + + metrics = { + "total_edges": int(num_edges), + "num_nodes": int(num_nodes), + "density": float(density), + "avg_degree": float(avg_degree), + "max_degree": int(max_degree), + } + + logger.info(f"Metrics computed: {metrics}") + return metrics + + except Exception as e: + logger.error(f"Metrics computation failed: {str(e)}") + raise + + +@celery_app.task(name="app.workers.tasks.export_results") +def export_results(job_id: str, export_format: str = "json") -> Dict[str, Any]: + """Export job results in specified format.""" + try: + from app.core.config import settings + + logger.info(f"Exporting results for job {job_id} in {export_format} format") + + job_dir = settings.RESULTS_DIR / job_id + if not job_dir.exists(): + raise FileNotFoundError(f"Job directory not found: {job_dir}") + + export_dir = job_dir / f"export_{export_format}" + export_dir.mkdir(parents=True, exist_ok=True) + + # Copy and convert files based on format + network_file = None + for f in job_dir.glob("*_network.*"): + if f.is_file(): + network_file = f + break + + if network_file is None: + raise FileNotFoundError("No network file found in job directory") + + if export_format == "json": + import pandas as pd + import json + + network = pd.read_csv(network_file, sep="\t", header=None) + export_file = export_dir / "network.json" + + data = { + "edges": [ + {"source": row[0], "target": row[1], "weight": row[2] if len(row) > 2 else 1.0} + for _, row in network.iterrows() + ] + } + + with open(export_file, "w") as f: + json.dump(data, f, indent=2) + + elif export_format == "graphml": + import pandas as pd + import networkx as nx + + network = pd.read_csv(network_file, sep="\t", header=None) + G = nx.DiGraph() + + for _, row in network.iterrows(): + weight = row[2] if len(row) > 2 else 1.0 + G.add_edge(row[0], row[1], weight=weight) + + export_file = export_dir / "network.graphml" + nx.write_graphml(G, str(export_file)) + + logger.info(f"Results exported to {export_file}") + + return { + "export_format": export_format, + "export_file": str(export_file), + } + + except Exception as e: + logger.error(f"Export failed: {str(e)}") + raise