Skip to content

~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.

refactor: remove dead benchmark and citation functions (#3187)

LearningCircuitd3570c355a5e
diff --git a/docs/cli-tools.md b/docs/cli-tools.md
index 6797efcc22..43702a04ba 100644
--- a/docs/cli-tools.md
+++ b/docs/cli-tools.md
@@ -17,7 +17,7 @@ Run benchmarks to evaluate search quality and compare configurations.
### Basic Usage
```bash
-python -m local_deep_research.benchmarks.cli <command> [options]
+python -m local_deep_research.benchmarks.cli.benchmark_commands <command> [options]
```
### Commands
@@ -27,7 +27,7 @@ python -m local_deep_research.benchmarks.cli <command> [options]
Tests factual question answering accuracy.
```bash
-python -m local_deep_research.benchmarks.cli simpleqa [options]
+python -m local_deep_research.benchmarks.cli.benchmark_commands simpleqa [options]
```
**Options:**
@@ -52,7 +52,7 @@ python -m local_deep_research.benchmarks.cli simpleqa [options]
```bash
# Run 50 examples with Ollama
-python -m local_deep_research.benchmarks.cli simpleqa \
+python -m local_deep_research.benchmarks.cli.benchmark_commands simpleqa \
--examples 50 \
--search-provider ollama \
--search-model llama3.2
@@ -63,7 +63,7 @@ python -m local_deep_research.benchmarks.cli simpleqa \
Tests complex reasoning and multi-step research.
```bash
-python -m local_deep_research.benchmarks.cli browsecomp [options]
+python -m local_deep_research.benchmarks.cli.benchmark_commands browsecomp [options]
```
Same options as `simpleqa`.
@@ -72,7 +72,7 @@ Same options as `simpleqa`.
```bash
# Run BrowseComp with focused-iteration strategy
-python -m local_deep_research.benchmarks.cli browsecomp \
+python -m local_deep_research.benchmarks.cli.benchmark_commands browsecomp \
--examples 20 \
--search-strategy iterdrag \
--iterations 5
@@ -83,7 +83,7 @@ python -m local_deep_research.benchmarks.cli browsecomp \
Compare multiple search configurations on the same dataset.
```bash
-python -m local_deep_research.benchmarks.cli compare [options]
+python -m local_deep_research.benchmarks.cli.benchmark_commands compare [options]
```
**Options:**
@@ -98,7 +98,7 @@ python -m local_deep_research.benchmarks.cli compare [options]
```bash
# Compare configurations
-python -m local_deep_research.benchmarks.cli compare \
+python -m local_deep_research.benchmarks.cli.benchmark_commands compare \
--dataset simpleqa \
--examples 30
```
@@ -106,7 +106,7 @@ python -m local_deep_research.benchmarks.cli compare \
#### `list` - List Available Benchmarks
```bash
-python -m local_deep_research.benchmarks.cli list
+python -m local_deep_research.benchmarks.cli.benchmark_commands list
```
Shows available benchmark datasets and their descriptions.
diff --git a/src/local_deep_research/benchmarks/cli.py b/src/local_deep_research/benchmarks/cli.py
deleted file mode 100644
index 91d7f3ca71..0000000000
--- a/src/local_deep_research/benchmarks/cli.py
+++ /dev/null
@@ -1,380 +0,0 @@
-"""
-Command-line interface for benchmarking functionality.
-
-This module provides a command-line interface for running parameter
-optimization, comparison, and benchmarking tasks.
-"""
-
-import argparse
-
-# import logging - replaced with loguru
-from loguru import logger
-import os
-from pathlib import Path
-import sys
-from datetime import datetime, UTC
-
-from ..config.paths import get_data_directory
-from .comparison import compare_configurations
-from .efficiency import ResourceMonitor, SpeedProfiler
-from .optimization import optimize_parameters
-
-# Configure logging - using loguru instead
-
-
-def parse_args():
- """Parse command line arguments."""
- parser = argparse.ArgumentParser(
- description="Local Deep Research Benchmarking Tools",
- formatter_class=argparse.RawDescriptionHelpFormatter,
- epilog="""
-Examples:
- # Run parameter optimization
- python -m local_deep_research.benchmarks.cli optimize "What are the latest advancements in quantum computing?"
-
- # Compare different configurations
- python -m local_deep_research.benchmarks.cli compare "What are the effects of climate change?" --configs configs.json
-
- # Run efficiency profiling
- python -m local_deep_research.benchmarks.cli profile "How do neural networks work?"
-""",
- )
-
- subparsers = parser.add_subparsers(dest="command", help="Command to run")
-
- # Optimizer parser
- optimize_parser = subparsers.add_parser(
- "optimize", help="Optimize parameters"
- )
- optimize_parser.add_argument("query", help="Research query to optimize for")
- optimize_parser.add_argument(
- "--output-dir",
- default=str(get_data_directory() / "optimization_results"),
- help="Directory to save results",
- )
- optimize_parser.add_argument("--model", help="Model name for the LLM")
- optimize_parser.add_argument("--provider", help="Provider for the LLM")
- optimize_parser.add_argument("--search-tool", help="Search tool to use")
- optimize_parser.add_argument(
- "--temperature", type=float, default=0.7, help="LLM temperature"
- )
- optimize_parser.add_argument(
- "--n-trials",
- type=int,
- default=30,
- help="Number of parameter combinations to try",
- )
- optimize_parser.add_argument(
- "--timeout", type=int, help="Maximum seconds to run optimization"
- )
- optimize_parser.add_argument(
- "--n-jobs",
- type=int,
- default=1,
- help="Number of parallel jobs for optimization",
- )
- optimize_parser.add_argument(
- "--study-name", help="Name of the Optuna study"
- )
- optimize_parser.add_argument(
- "--speed-focus", action="store_true", help="Focus optimization on speed"
- )
- optimize_parser.add_argument(
- "--quality-focus",
- action="store_true",
- help="Focus optimization on quality",
- )
-
- # Comparison parser
- compare_parser = subparsers.add_parser(
- "compare", help="Compare configurations"
- )
- compare_parser.add_argument("query", help="Research query to compare with")
- compare_parser.add_argument(
- "--configs",
- required=True,
- help="JSON file with configurations to compare",
- )
- compare_parser.add_argument(
- "--output-dir",
- default="data/benchmark_results/comparison",
- help="Directory to save results",
- )
- compare_parser.add_argument("--model", help="Model name for the LLM")
- compare_parser.add_argument("--provider", help="Provider for the LLM")
- compare_parser.add_argument("--search-tool", help="Search tool to use")
- compare_parser.add_argument(
- "--repetitions",
- type=int,
- default=1,
- help="Number of repetitions for each configuration",
- )
-
- # Profiling parser
- profile_parser = subparsers.add_parser(
- "profile", help="Profile resource usage"
- )
- profile_parser.add_argument("query", help="Research query to profile")
- profile_parser.add_argument(
- "--output-dir",
- default="data/benchmark_results/profiling",
- help="Directory to save results",
- )
- profile_parser.add_argument("--model", help="Model name for the LLM")
- profile_parser.add_argument("--provider", help="Provider for the LLM")
- profile_parser.add_argument("--search-tool", help="Search tool to use")
- profile_parser.add_argument(
- "--iterations", type=int, default=2, help="Number of search iterations"
- )
- profile_parser.add_argument(
- "--questions", type=int, default=2, help="Questions per iteration"
- )
- profile_parser.add_argument(
- "--strategy", default="iterdrag", help="Search strategy to use"
- )
-
- return parser.parse_args()
-
-
-def run_optimization(args):
- """Run parameter optimization."""
- logger.info(f"Starting parameter optimization for query: {args.query}")
-
- # Determine metric weights based on focus
- metric_weights = None
- if args.speed_focus:
- metric_weights = {"speed": 0.8, "quality": 0.2}
- elif args.quality_focus:
- metric_weights = {"quality": 0.8, "speed": 0.2}
-
- # Run optimization
- best_params, best_score = optimize_parameters(
- query=args.query,
- output_dir=args.output_dir,
- model_name=args.model,
- provider=args.provider,
- search_tool=args.search_tool,
- temperature=args.temperature,
- n_trials=args.n_trials,
- timeout=args.timeout,
- n_jobs=args.n_jobs,
- study_name=args.study_name,
- metric_weights=metric_weights,
- )
-
- # Print results
- print("\nOptimization Results:")
- print("====================")
- print(f"Best Parameters: {best_params}")
- print(f"Best Score: {best_score:.4f}")
- print(f"Results saved to: {args.output_dir}")
-
- return 0
-
-
-def run_comparison(args):
- """Run configuration comparison."""
- import json
-
- logger.info(f"Comparing configurations for query: {args.query}")
-
- # Load configurations from file
- try:
- with open(args.configs, "r") as f:
- configurations = json.load(f)
-
- if not isinstance(configurations, list):
- logger.error("Configurations file must contain a JSON array")
- return 1
-
- if not configurations:
- logger.error("No configurations found in the file")
- return 1
- except Exception:
- logger.exception("Error loading configurations file")
- return 1
-
- # Run comparison
- results = compare_configurations(
- query=args.query,
- configurations=configurations,
- output_dir=args.output_dir,
- model_name=args.model,
- provider=args.provider,
- search_tool=args.search_tool,
- repetitions=args.repetitions,
- )
-
- # Print summary
- print("\nComparison Results:")
- print("==================")
- print(f"Configurations tested: {results['configurations_tested']}")
- print(f"Successful configurations: {results['successful_configurations']}")
- print(f"Failed configurations: {results['failed_configurations']}")
-
- # Print ranking
- print("\nRanking by Overall Score:")
- for i, result in enumerate(
- [r for r in results["results"] if r.get("success", False)]
- ):
- print(
- f"{i + 1}. {result['name']}: {result.get('overall_score', 0):.4f}"
- )
-
- print(f"\nResults saved to: {results.get('report_path', args.output_dir)}")
-
- return 0
-
-
-def run_profiling(args):
- """Run resource profiling."""
-
- from local_deep_research.config.llm_config import get_llm
- from local_deep_research.config.search_config import get_search
- from local_deep_research.search_system import AdvancedSearchSystem
-
- logger.info(f"Profiling resource usage for query: {args.query}")
-
- # Create output directory
- os.makedirs(args.output_dir, exist_ok=True)
-
- # Initialize profiling tools
- speed_profiler = SpeedProfiler()
- resource_monitor = ResourceMonitor(sampling_interval=0.5)
-
- # Start profiling
- speed_profiler.start()
- resource_monitor.start()
-
- llm = None
- search = None
- system = None
- try:
- # Initialize system
- with speed_profiler.timer("initialization"):
- # Get LLM
- llm = get_llm(model_name=args.model, provider=args.provider)
-
- # Get search engine
- search = None
- if args.search_tool:
- search = get_search(args.search_tool, llm_instance=llm)
-
- # Create search system
- system = AdvancedSearchSystem(llm=llm, search=search)
- system.max_iterations = args.iterations
- system.questions_per_iteration = args.questions
- system.strategy_name = args.strategy
-
- # Run analysis
- with speed_profiler.timer("analysis"):
- results = system.analyze_topic(args.query)
-
- # Stop profiling
- speed_profiler.stop()
- resource_monitor.stop()
-
- # Get profiling results
- timing_results = speed_profiler.get_summary()
- resource_results = resource_monitor.get_combined_stats()
-
- # Print summary
- print("\nProfiling Results:")
- print("=================")
-
- # Timing summary
- print("\nTiming Summary:")
- total_duration = timing_results.get("total_duration", 0)
- print(f"Total execution time: {total_duration:.2f} seconds")
-
- # Component breakdown
- print("\nComponent Breakdown:")
- for name, value in timing_results.items():
- if name != "total_duration" and name.endswith("_duration"):
- component = name.replace("_duration", "")
- duration = value
- percent = (
- (duration / total_duration * 100)
- if total_duration > 0
- else 0
- )
- print(f"- {component}: {duration:.2f}s ({percent:.1f}%)")
-
- # Resource summary
- print("\nResource Usage Summary:")
- print(
- f"Peak memory: {resource_results.get('process_memory_max_mb', 0):.1f} MB"
- )
- print(
- f"Average memory: {resource_results.get('process_memory_avg_mb', 0):.1f} MB"
- )
- print(f"Peak CPU: {resource_results.get('process_cpu_max', 0):.1f}%")
- print(f"Average CPU: {resource_results.get('process_cpu_avg', 0):.1f}%")
-
- # Save results
- from ..security.file_write_verifier import write_json_verified
-
- timestamp = datetime.now(UTC).strftime("%Y%m%d_%H%M%S")
- results_file = str(
- Path(args.output_dir) / f"profiling_results_{timestamp}.json"
- )
-
- results_data = {
- "query": args.query,
- "configuration": {
- "model": args.model,
- "provider": args.provider,
- "search_tool": args.search_tool,
- "iterations": args.iterations,
- "questions_per_iteration": args.questions,
- "strategy": args.strategy,
- },
- "timing_results": timing_results,
- "resource_results": resource_results,
- "findings_count": len(results.get("findings", [])),
- "knowledge_length": len(results.get("current_knowledge", "")),
- "timestamp": timestamp,
- }
-
- write_json_verified(
- results_file,
- results_data,
- "benchmark.allow_file_output",
- context="profiling results",
- )
-
- print(f"\nDetailed results saved to: {results_file}")
-
- return 0
-
- except Exception:
- # Stop profiling on error
- speed_profiler.stop()
- resource_monitor.stop()
-
- logger.exception("Error during profiling")
- return 1
- finally:
- from ..utilities.resource_utils import safe_close
-
- safe_close(system, "benchmark system")
- safe_close(search, "benchmark search engine")
- safe_close(llm, "benchmark LLM")
-
-
-def main():
- """Main entry point for the CLI."""
- args = parse_args()
-
- if args.command == "optimize":
- return run_optimization(args)
- if args.command == "compare":
- return run_comparison(args)
- if args.command == "profile":
- return run_profiling(args)
- print("Please specify a command. Use --help for more information.")
- return 1
-
-
-if __name__ == "__main__":
- sys.exit(main())
diff --git a/src/local_deep_research/benchmarks/efficiency/resource_monitor.py b/src/local_deep_research/benchmarks/efficiency/resource_monitor.py
index 7690593aa9..4c4b032a40 100644
--- a/src/local_deep_research/benchmarks/efficiency/resource_monitor.py
+++ b/src/local_deep_research/benchmarks/efficiency/resource_monitor.py
@@ -371,42 +371,3 @@ class ResourceMonitor:
"process_data": self.process_data,
"system_data": self.system_data,
}
-
-
-def check_system_resources() -> Dict[str, Any]:
- """
- Check current system resources.
-
- Returns:
- Dictionary with current resource usage information
- """
- if not PSUTIL_AVAILABLE:
- return {"error": "psutil not available", "available": False}
-
- try:
- # Get basic system information
- cpu_count = psutil.cpu_count(logical=True)
- cpu_physical = psutil.cpu_count(logical=False)
- cpu_percent = psutil.cpu_percent(interval=0.1)
-
- memory = psutil.virtual_memory()
- disk = psutil.disk_usage("/")
-
- # Format results
- return {
- "available": True,
- "cpu_count": cpu_count,
- "cpu_physical": cpu_physical,
- "cpu_percent": cpu_percent,
- "memory_total_gb": memory.total / (1024**3),
- "memory_available_gb": memory.available / (1024**3),
- "memory_used_gb": memory.used / (1024**3),
- "memory_percent": memory.percent,
- "disk_total_gb": disk.total / (1024**3),
- "disk_free_gb": disk.free / (1024**3),
- "disk_percent": disk.percent,
- }
-
- except Exception as e:
- logger.exception("Error checking system resources")
- return {"error": str(e), "available": False}
diff --git a/src/local_deep_research/benchmarks/metrics/README.md b/src/local_deep_research/benchmarks/metrics/README.md
index 3d19f1f204..e9a56a40ab 100644
--- a/src/local_deep_research/benchmarks/metrics/README.md
+++ b/src/local_deep_research/benchmarks/metrics/README.md
@@ -67,8 +67,6 @@ combined_score = calculate_combined_score(
```python
from local_deep_research.benchmarks.metrics.visualization import (
plot_optimization_history,
- plot_parameter_importance,
- plot_quality_vs_speed
)
# Plot optimization history
diff --git a/src/local_deep_research/benchmarks/metrics/visualization.py b/src/local_deep_research/benchmarks/metrics/visualization.py
index 4a59841d6a..c42c228e8a 100644
--- a/src/local_deep_research/benchmarks/metrics/visualization.py
+++ b/src/local_deep_research/benchmarks/metrics/visualization.py
@@ -6,9 +6,7 @@ of benchmark and optimization results.
"""
from loguru import logger
-from typing import Any, Dict, List, Optional
-
-import numpy as np
+from typing import List, Optional
# Check if matplotlib is available
@@ -67,157 +65,3 @@ def plot_optimization_history(
logger.info(f"Saved optimization history plot to {output_file}")
return fig
-
-
-def plot_parameter_importance(
- parameter_names: List[str],
- importance_values: List[float],
- output_file: Optional[str] = None,
- title: str = "Parameter Importance",
-) -> Optional[Figure]:
- """
- Plot parameter importance.
-
- Args:
- parameter_names: List of parameter names
- importance_values: List of importance values
- output_file: Path to save the plot (if None, returns figure without saving)
- title: Plot title
-
- Returns:
- Matplotlib figure or None if matplotlib is not available
- """
- if not MATPLOTLIB_AVAILABLE:
- logger.warning("Matplotlib not available. Cannot create plot.")
- return None
-
- # Sort by importance
- sorted_indices = np.argsort(importance_values)
- sorted_names = [parameter_names[i] for i in sorted_indices]
- sorted_values = [importance_values[i] for i in sorted_indices]
-
- fig, ax = plt.subplots(figsize=(10, 6))
- y_pos = range(len(sorted_names))
-
- # Create horizontal bar chart
- ax.barh(y_pos, sorted_values, align="center")
- ax.set_yticks(y_pos)
- ax.set_yticklabels(sorted_names)
- ax.invert_yaxis() # Labels read top-to-bottom
-
- # Add labels and title
- ax.set_xlabel("Importance")
- ax.set_title(title)
- ax.grid(True, linestyle="--", alpha=0.3, axis="x")
-
- # Save or return
- if output_file:
- fig.tight_layout()
- fig.savefig(output_file, dpi=300, bbox_inches="tight")
- logger.info(f"Saved parameter importance plot to {output_file}")
-
- return fig
-
-
-def plot_quality_vs_speed(
- quality_scores: List[float],
- speed_scores: List[float],
- _parameter_values: Optional[List[Dict[str, Any]]] = None,
- output_file: Optional[str] = None,
- title: str = "Quality vs. Speed Trade-off",
-) -> Optional[Figure]:
- """
- Plot quality vs. speed trade-off.
-
- Args:
- quality_scores: List of quality scores
- speed_scores: List of speed scores
- parameter_values: Optional list of parameter dictionaries for each point
- output_file: Path to save the plot (if None, returns figure without saving)
- title: Plot title
-
- Returns:
- Matplotlib figure or None if matplotlib is not available
- """
- if not MATPLOTLIB_AVAILABLE:
- logger.warning("Matplotlib not available. Cannot create plot.")
- return None
-
- fig, ax = plt.subplots(figsize=(10, 8))
-
- # Create scatter plot
- scatter = ax.scatter(
- speed_scores,
- quality_scores,
- c=np.arange(len(quality_scores)),
- cmap="viridis",
- alpha=0.7,
- s=100,
- )
-
- # Add colorbar to show trial number
- cbar = plt.colorbar(scatter)
- cbar.set_label("Trial Number")
-
- # Add labels and title
- ax.set_xlabel("Speed Score (higher = faster)")
- ax.set_ylabel("Quality Score (higher = better)")
- ax.set_title(title)
- ax.grid(True, linestyle="--", alpha=0.5)
-
- # Add reference lines
- ax.axhline(
- y=0.7,
- color="r",
- linestyle="--",
- alpha=0.3,
- label="Good Quality Threshold",
- )
- ax.axvline(
- x=0.7,
- color="g",
- linestyle="--",
- alpha=0.3,
- label="Good Speed Threshold",
- )
-
- # Mark Pareto frontier
- if len(quality_scores) > 2:
- try:
- # Identify Pareto frontier points
- pareto_points = []
- for i in range(len(quality_scores)):
- is_pareto = True
- for j in range(len(quality_scores)):
- if i != j:
- if (
- quality_scores[j] >= quality_scores[i]
- and speed_scores[j] >= speed_scores[i]
- ):
- if (
- quality_scores[j] > quality_scores[i]
- or speed_scores[j] > speed_scores[i]
- ):
- is_pareto = False
- break
- if is_pareto:
- pareto_points.append((speed_scores[i], quality_scores[i]))
-
- # Sort pareto points by speed score
- pareto_points.sort()
- if pareto_points:
- pareto_x, pareto_y = zip(*pareto_points, strict=False)
- ax.plot(pareto_x, pareto_y, "k--", label="Pareto Frontier")
- ax.scatter(pareto_x, pareto_y, c="red", s=50, alpha=0.8)
- except Exception:
- logger.warning("Error calculating Pareto frontier")
-
- ax.legend()
-
- # Save or return
- if output_file:
- fig.tight_layout()
- fig.savefig(output_file, dpi=300, bbox_inches="tight")
- logger.info(f"Saved quality vs. speed plot to {output_file}")
-
- return fig
diff --git a/src/local_deep_research/text_optimization/citation_formatter.py b/src/local_deep_research/text_optimization/citation_formatter.py
index d05ed555ac..89ddaa2b18 100644
--- a/src/local_deep_research/text_optimization/citation_formatter.py
+++ b/src/local_deep_research/text_optimization/citation_formatter.py
@@ -385,22 +385,6 @@ class CitationFormatter:
self._create_source_word_replacer(formatter), content
)
- def _to_superscript(self, text: str) -> str:
- """Convert text to Unicode superscript."""
- superscript_map = {
- "0": "⁰",
- "1": "¹",
- "2": "²",
- "3": "³",
- "4": "⁴",
- "5": "⁵",
- "6": "⁶",
- "7": "⁷",
- "8": "⁸",
- "9": "⁹",
- }
- return "".join(superscript_map.get(c, c) for c in text)
-
def _extract_domain(self, url: str) -> str:
"""Extract domain name from URL."""
try:
diff --git a/tests/benchmarks/efficiency/test_resource_monitor_coverage.py b/tests/benchmarks/efficiency/test_resource_monitor_coverage.py
index d0a0480b1a..3784d63a2e 100644
--- a/tests/benchmarks/efficiency/test_resource_monitor_coverage.py
+++ b/tests/benchmarks/efficiency/test_resource_monitor_coverage.py
@@ -6,7 +6,6 @@ Covers paths not exercised by the existing high-value test file:
handles exceptions during collection
- Start/stop cycle: creates thread, joins thread, sets flag, resets data
- Context manager: delegates to start/stop and collects data
-- check_system_resources: exception path returns error dict
- print_summary: output with both sections, system-only section
- get_combined_stats: zero system memory edge case, no system stats present
"""
@@ -15,7 +14,6 @@ from unittest.mock import MagicMock, patch
from local_deep_research.benchmarks.efficiency.resource_monitor import (
ResourceMonitor,
- check_system_resources,
)
@@ -317,29 +315,6 @@ class TestContextManager:
mock_thread.join.assert_called_once()
-# ---------------------------------------------------------------------------
-# check_system_resources
-# ---------------------------------------------------------------------------
-
-
-class TestCheckSystemResourcesException:
- """Tests for check_system_resources exception handling."""
-
- @patch(
- "local_deep_research.benchmarks.efficiency.resource_monitor.PSUTIL_AVAILABLE",
- True,
- )
- @patch("local_deep_research.benchmarks.efficiency.resource_monitor.psutil")
- def test_exception_returns_error_dict(self, mock_psutil):
- """When psutil calls raise, the function returns an error dict."""
- mock_psutil.cpu_count.side_effect = OSError("permission denied")
-
- result = check_system_resources()
-
- assert result["available"] is False
- assert "permission denied" in result["error"]
-
-
# ---------------------------------------------------------------------------
# print_summary
# ---------------------------------------------------------------------------
diff --git a/tests/benchmarks/efficiency/test_resource_monitor_high_value.py b/tests/benchmarks/efficiency/test_resource_monitor_high_value.py
index 79cb2dc5f1..324e326c46 100644
--- a/tests/benchmarks/efficiency/test_resource_monitor_high_value.py
+++ b/tests/benchmarks/efficiency/test_resource_monitor_high_value.py
@@ -1,14 +1,13 @@
"""High-value tests for benchmarks/efficiency/resource_monitor.py.
Covers ResourceMonitor init, start/stop lifecycle, stats computation,
-export_data, context manager, and check_system_resources.
+export_data, and context manager.
"""
-from unittest.mock import MagicMock, patch
+from unittest.mock import patch
from local_deep_research.benchmarks.efficiency.resource_monitor import (
ResourceMonitor,
- check_system_resources,
)
@@ -184,42 +183,3 @@ class TestResourceMonitorLifecycle:
monitor.can_monitor = False
monitor.start()
assert monitor.monitoring is False
-
-
-class TestCheckSystemResources:
- """Test the check_system_resources function."""
-
- @patch(
- "local_deep_research.benchmarks.efficiency.resource_monitor.PSUTIL_AVAILABLE",
- False,
- )
- def test_returns_error_without_psutil(self):
- """Returns error dict when psutil not available."""
- result = check_system_resources()
- assert result["available"] is False
- assert "error" in result
-
- @patch(
- "local_deep_research.benchmarks.efficiency.resource_monitor.PSUTIL_AVAILABLE",
- True,
- )
- @patch("local_deep_research.benchmarks.efficiency.resource_monitor.psutil")
- def test_returns_system_info_with_psutil(self, mock_psutil):
- """Returns system info when psutil is available."""
- mock_psutil.cpu_count.return_value = 8
- mock_psutil.cpu_percent.return_value = 25.0
- mock_psutil.virtual_memory.return_value = MagicMock(
- total=16 * 1024**3,
- available=8 * 1024**3,
- used=8 * 1024**3,
- percent=50.0,
- )
- mock_psutil.disk_usage.return_value = MagicMock(
- total=500 * 1024**3,
- free=250 * 1024**3,
- percent=50.0,
- )
- result = check_system_resources()
- assert result["available"] is True
- assert result["cpu_count"] == 8
- assert result["memory_percent"] == 50.0
diff --git a/tests/benchmarks/test_resource_monitor.py b/tests/benchmarks/test_resource_monitor.py
index 92d78d8661..3d986793cc 100644
--- a/tests/benchmarks/test_resource_monitor.py
+++ b/tests/benchmarks/test_resource_monitor.py
@@ -434,39 +434,6 @@ class TestResourceMonitorDuration:
assert 4.9 < stats["duration"] < 5.1 # Allow for small variance
-class TestCheckSystemResources:
- """Tests for check_system_resources function."""
-
- def test_check_system_resources(self):
- """Test checking system resources."""
- from local_deep_research.benchmarks.efficiency.resource_monitor import (
- check_system_resources,
- )
-
- result = check_system_resources()
-
- # Should return a dict with availability info
- assert isinstance(result, dict)
- assert "available" in result
-
- def test_check_system_resources_returns_valid_data(self):
- """Test that system resources include expected fields when available."""
- from local_deep_research.benchmarks.efficiency.resource_monitor import (
- check_system_resources,
- PSUTIL_AVAILABLE,
- )
-
- result = check_system_resources()
-
- if PSUTIL_AVAILABLE:
- assert result["available"] is True
- assert "cpu_count" in result
- assert "memory_total_gb" in result
- assert "disk_total_gb" in result
- else:
- assert result["available"] is False
-
-
class TestResourceMonitorSamplingInterval:
"""Tests for sampling interval configuration."""
diff --git a/tests/benchmarks/test_visualization_high_value.py b/tests/benchmarks/test_visualization_high_value.py
index 9b429d0529..fd906ed31c 100644
--- a/tests/benchmarks/test_visualization_high_value.py
+++ b/tests/benchmarks/test_visualization_high_value.py
@@ -91,137 +91,3 @@ class TestPlotOptimizationHistory:
import matplotlib.pyplot as plt
plt.close(fig)
-
-
-class TestPlotParameterImportance:
- """Tests for plot_parameter_importance."""
-
- def test_returns_none_when_matplotlib_unavailable(self):
- """Returns None when MATPLOTLIB_AVAILABLE is False."""
- with patch(
- "local_deep_research.benchmarks.metrics.visualization.MATPLOTLIB_AVAILABLE",
- False,
- ):
- from local_deep_research.benchmarks.metrics.visualization import (
- plot_parameter_importance,
- )
-
- result = plot_parameter_importance(["a", "b"], [0.3, 0.7])
- assert result is None
-
- def test_sorts_by_importance(self):
- """Parameters are sorted by importance value."""
- from local_deep_research.benchmarks.metrics.visualization import (
- plot_parameter_importance,
- MATPLOTLIB_AVAILABLE,
- )
-
- if not MATPLOTLIB_AVAILABLE:
- pytest.skip("matplotlib not installed")
-
- fig = plot_parameter_importance(["low", "high", "mid"], [0.1, 0.9, 0.5])
- assert fig is not None
- import matplotlib.pyplot as plt
-
- plt.close(fig)
-
- def test_saves_to_file(self, tmp_path):
- """Saves figure when output_file provided."""
- from local_deep_research.benchmarks.metrics.visualization import (
- plot_parameter_importance,
- MATPLOTLIB_AVAILABLE,
- )
-
- if not MATPLOTLIB_AVAILABLE:
- pytest.skip("matplotlib not installed")
-
- out = str(tmp_path / "importance.png")
- fig = plot_parameter_importance(["a"], [0.5], output_file=out)
- assert (tmp_path / "importance.png").exists()
- import matplotlib.pyplot as plt
-
- plt.close(fig)
-
-
-class TestPlotQualityVsSpeed:
- """Tests for plot_quality_vs_speed."""
-
- def test_returns_none_when_matplotlib_unavailable(self):
- """Returns None when MATPLOTLIB_AVAILABLE is False."""
- with patch(
- "local_deep_research.benchmarks.metrics.visualization.MATPLOTLIB_AVAILABLE",
- False,
- ):
- from local_deep_research.benchmarks.metrics.visualization import (
- plot_quality_vs_speed,
- )
-
- result = plot_quality_vs_speed([0.5], [0.5])
- assert result is None
-
- def test_pareto_frontier_with_three_points(self):
- """Pareto frontier calculation works with 3+ points."""
- from local_deep_research.benchmarks.metrics.visualization import (
- plot_quality_vs_speed,
- MATPLOTLIB_AVAILABLE,
- )
-
- if not MATPLOTLIB_AVAILABLE:
- pytest.skip("matplotlib not installed")
-
- fig = plot_quality_vs_speed([0.5, 0.8, 0.3, 0.9], [0.9, 0.5, 0.3, 0.8])
- assert fig is not None
- import matplotlib.pyplot as plt
-
- plt.close(fig)
-
- def test_two_points_skips_pareto(self):
- """With only 2 points, Pareto frontier is skipped."""
- from local_deep_research.benchmarks.metrics.visualization import (
- plot_quality_vs_speed,
- MATPLOTLIB_AVAILABLE,
- )
-
- if not MATPLOTLIB_AVAILABLE:
- pytest.skip("matplotlib not installed")
-
- fig = plot_quality_vs_speed([0.5, 0.8], [0.5, 0.8])
- assert fig is not None
- import matplotlib.pyplot as plt
-
- plt.close(fig)
-
- def test_saves_to_file(self, tmp_path):
- """Saves figure when output_file provided."""
- from local_deep_research.benchmarks.metrics.visualization import (
- plot_quality_vs_speed,
- MATPLOTLIB_AVAILABLE,
- )
-
- if not MATPLOTLIB_AVAILABLE:
- pytest.skip("matplotlib not installed")
-
- out = str(tmp_path / "qvs.png")
- fig = plot_quality_vs_speed(
- [0.5, 0.8, 0.9], [0.9, 0.5, 0.8], output_file=out
- )
- assert (tmp_path / "qvs.png").exists()
- import matplotlib.pyplot as plt
-
- plt.close(fig)
-
- def test_identical_points(self):
- """Handles identical quality/speed scores gracefully."""
- from local_deep_research.benchmarks.metrics.visualization import (
- plot_quality_vs_speed,
- MATPLOTLIB_AVAILABLE,
- )
-
- if not MATPLOTLIB_AVAILABLE:
- pytest.skip("matplotlib not installed")
-
- fig = plot_quality_vs_speed([0.5, 0.5, 0.5], [0.5, 0.5, 0.5])
- assert fig is not None
- import matplotlib.pyplot as plt
-
- plt.close(fig)
diff --git a/tests/text_optimization/test_citation_formatter_behavior.py b/tests/text_optimization/test_citation_formatter_behavior.py
index 81634c277c..167ff81e53 100644
--- a/tests/text_optimization/test_citation_formatter_behavior.py
+++ b/tests/text_optimization/test_citation_formatter_behavior.py
@@ -551,41 +551,6 @@ class TestCitationFormatterFormatDomainIdAlwaysHyperlinks:
assert "github.com-1" in result
-class TestCitationFormatterToSuperscript:
- """Tests for _to_superscript method."""
-
- def test_converts_single_digit(self):
- """Converts single digit to superscript."""
- from local_deep_research.text_optimization.citation_formatter import (
- CitationFormatter,
- )
-
- formatter = CitationFormatter()
- result = formatter._to_superscript("1")
- assert result == "¹"
-
- def test_converts_all_digits(self):
- """Converts all digits 0-9 to superscript."""
- from local_deep_research.text_optimization.citation_formatter import (
- CitationFormatter,
- )
-
- formatter = CitationFormatter()
- expected = "⁰¹²³⁴⁵⁶⁷⁸⁹"
- result = formatter._to_superscript("0123456789")
- assert result == expected
-
- def test_leaves_non_digits_unchanged(self):
- """Leaves non-digit characters unchanged."""
- from local_deep_research.text_optimization.citation_formatter import (
- CitationFormatter,
- )
-
- formatter = CitationFormatter()
- result = formatter._to_superscript("a1b")
- assert result == "a¹b"
-
-
class TestCitationFormatterUnicodeBrackets:
"""Tests for handling Unicode lenticular brackets."""
diff --git a/tests/text_optimization/test_citation_formatter_high_value.py b/tests/text_optimization/test_citation_formatter_high_value.py
index f8510c068c..35efab733f 100644
--- a/tests/text_optimization/test_citation_formatter_high_value.py
+++ b/tests/text_optimization/test_citation_formatter_high_value.py
@@ -150,36 +150,6 @@ class TestParseSources:
assert result["3"][0] == "Shared Title"
-# ---------------------------------------------------------------------------
-# CitationFormatter._to_superscript
-# ---------------------------------------------------------------------------
-
-
-class TestToSuperscript:
- def setup_method(self):
- self.fmt = CitationFormatter()
-
- def test_single_digit(self):
- assert self.fmt._to_superscript("1") == "\u00b9"
-
- def test_multiple_digits(self):
- assert self.fmt._to_superscript("42") == "\u2074\u00b2"
-
- def test_all_digits(self):
- result = self.fmt._to_superscript("0123456789")
- assert len(result) == 10
- assert (
- result
- == "\u2070\u00b9\u00b2\u00b3\u2074\u2075\u2076\u2077\u2078\u2079"
- )
-
- def test_non_digit_passthrough(self):
- assert self.fmt._to_superscript("a") == "a"
-
- def test_empty_string(self):
- assert self.fmt._to_superscript("") == ""
-
-
# ---------------------------------------------------------------------------
# CitationFormatter._replace_comma_citations
# ---------------------------------------------------------------------------