feature/Keyword_search_rework #243
@@ -0,0 +1 @@
|
||||
Perhaps not the final version. I did not find the files inside my local git branch. I most likely did not save them, however i made backups sometimes, so i hope these versions are the final ones.
|
||||
@@ -0,0 +1,428 @@
|
||||
#!/usr/bin/env python3
|
||||
import os
|
||||
import sys
|
||||
import json
|
||||
import time
|
||||
import asyncio
|
||||
from pathlib import Path
|
||||
import httpx
|
||||
import numpy as np
|
||||
|
||||
# Load service environment config
|
||||
current_dir = Path(__file__).parent.resolve()
|
||||
project_root = current_dir.parent.parent.resolve()
|
||||
env_path = project_root / "service" / "src" / "main" / "inse" / ".env"
|
||||
|
||||
from dotenv import load_dotenv
|
||||
load_dotenv(dotenv_path=env_path)
|
||||
|
||||
sys.path.append(str(project_root / "service" / "src" / "main"))
|
||||
|
||||
from inse.config import settings
|
||||
from inse.util import get_model
|
||||
|
||||
ELASTIC_URL = settings.elasticsearch_url
|
||||
if ELASTIC_URL and not ELASTIC_URL.endswith("/"):
|
||||
ELASTIC_URL += "/"
|
||||
API_KEY = settings.elasticsearch_api_key
|
||||
|
||||
headers = {
|
||||
"Authorization": f"ApiKey {API_KEY}",
|
||||
"Content-Type": "application/json"
|
||||
}
|
||||
|
||||
FIELDS = [
|
||||
"Social Sciences", "Medicine", "Engineering", "Computer Science",
|
||||
"Arts and Humanities", "Biochemistry, Genetics and Molecular Biology",
|
||||
"Agricultural and Biological Sciences", "Environmental Science",
|
||||
"Business, Management and Accounting", "Psychology", "Materials Science",
|
||||
"Economics, Econometrics and Finance", "Health Professions",
|
||||
"Physics and Astronomy", "Chemistry", "Mathematics", "Neuroscience",
|
||||
"Decision Sciences", "Earth and Planetary Sciences", "Immunology and Microbiology",
|
||||
"Energy", "Pharmacology, Toxicology and Pharmaceutics", "Nursing",
|
||||
"Chemical Engineering", "Dentistry", "Veterinary"
|
||||
]
|
||||
|
||||
QUERIES_FILE = current_dir / "evaluation_queries.json"
|
||||
|
||||
def load_queries():
|
||||
if QUERIES_FILE.exists():
|
||||
print(f"Loading cached queries from {QUERIES_FILE}...")
|
||||
with open(QUERIES_FILE, "r", encoding="utf-8") as f:
|
||||
return json.load(f)
|
||||
else:
|
||||
raise FileNotFoundError(f"Evaluation queries file not found at {QUERIES_FILE}")
|
||||
|
||||
def make_es_payload(query_vector, query_str, config_type, limit=10):
|
||||
if config_type == "display_name":
|
||||
clause = {
|
||||
"knn": {
|
||||
"field": "display_name_vector",
|
||||
"query_vector": query_vector,
|
||||
"k": limit,
|
||||
"num_candidates": 100,
|
||||
"similarity": 0.62
|
||||
}
|
||||
}
|
||||
query_body = {"query": clause}
|
||||
elif config_type == "description":
|
||||
clause = {
|
||||
"knn": {
|
||||
"field": "description_vector",
|
||||
"query_vector": query_vector,
|
||||
"k": limit,
|
||||
"num_candidates": 100,
|
||||
"similarity": 0.62
|
||||
}
|
||||
}
|
||||
query_body = {"query": clause}
|
||||
elif config_type == "keywords":
|
||||
clause = {
|
||||
"nested": {
|
||||
"path": "keyword_vectors",
|
||||
"query": {
|
||||
"knn": {
|
||||
"field": "keyword_vectors.vector",
|
||||
"query_vector": query_vector,
|
||||
"k": limit,
|
||||
"num_candidates": 100,
|
||||
"similarity": 0.62
|
||||
}
|
||||
},
|
||||
"score_mode": "max"
|
||||
}
|
||||
}
|
||||
query_body = {"query": clause}
|
||||
elif config_type == "display_name_and_keywords":
|
||||
query_body = {
|
||||
"query": {
|
||||
"bool": {
|
||||
"should": [
|
||||
{
|
||||
"knn": {
|
||||
"field": "display_name_vector",
|
||||
"query_vector": query_vector,
|
||||
"k": limit,
|
||||
"num_candidates": 100,
|
||||
"similarity": 0.62
|
||||
}
|
||||
},
|
||||
{
|
||||
"nested": {
|
||||
"path": "keyword_vectors",
|
||||
"query": {
|
||||
"knn": {
|
||||
"field": "keyword_vectors.vector",
|
||||
"query_vector": query_vector,
|
||||
"k": limit,
|
||||
"num_candidates": 100,
|
||||
"similarity": 0.62
|
||||
}
|
||||
},
|
||||
"score_mode": "max"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
elif config_type == "display_name_and_description":
|
||||
query_body = {
|
||||
"query": {
|
||||
"bool": {
|
||||
"should": [
|
||||
{
|
||||
"knn": {
|
||||
"field": "display_name_vector",
|
||||
"query_vector": query_vector,
|
||||
"k": limit,
|
||||
"num_candidates": 100,
|
||||
"similarity": 0.62
|
||||
}
|
||||
},
|
||||
{
|
||||
"knn": {
|
||||
"field": "description_vector",
|
||||
"query_vector": query_vector,
|
||||
"k": limit,
|
||||
"num_candidates": 100,
|
||||
"similarity": 0.62
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
elif config_type == "combined":
|
||||
query_body = {
|
||||
"query": {
|
||||
"bool": {
|
||||
"should": [
|
||||
{
|
||||
"knn": {
|
||||
"field": "display_name_vector",
|
||||
"query_vector": query_vector,
|
||||
"k": limit,
|
||||
"num_candidates": 100,
|
||||
"similarity": 0.62
|
||||
}
|
||||
},
|
||||
{
|
||||
"knn": {
|
||||
"field": "description_vector",
|
||||
"query_vector": query_vector,
|
||||
"k": limit,
|
||||
"num_candidates": 100,
|
||||
"similarity": 0.62
|
||||
}
|
||||
},
|
||||
{
|
||||
"nested": {
|
||||
"path": "keyword_vectors",
|
||||
"query": {
|
||||
"knn": {
|
||||
"field": "keyword_vectors.vector",
|
||||
"query_vector": query_vector,
|
||||
"k": limit,
|
||||
"num_candidates": 100,
|
||||
"similarity": 0.62
|
||||
}
|
||||
},
|
||||
"score_mode": "max"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
elif config_type == "lexical_only":
|
||||
query_body = {
|
||||
"query": {
|
||||
"multi_match": {
|
||||
"query": query_str,
|
||||
"fields": ["display_name^3", "keywords^2", "description^1"]
|
||||
}
|
||||
}
|
||||
}
|
||||
elif config_type == "hybrid":
|
||||
query_body = {
|
||||
"query": {
|
||||
"bool": {
|
||||
"should": [
|
||||
{
|
||||
"multi_match": {
|
||||
"query": query_str,
|
||||
"fields": ["display_name^3", "keywords^2", "description^1"]
|
||||
}
|
||||
},
|
||||
{
|
||||
"knn": {
|
||||
"field": "display_name_vector",
|
||||
"query_vector": query_vector,
|
||||
"k": limit,
|
||||
"num_candidates": 100,
|
||||
"similarity": 0.62
|
||||
}
|
||||
},
|
||||
{
|
||||
"knn": {
|
||||
"field": "description_vector",
|
||||
"query_vector": query_vector,
|
||||
"k": limit,
|
||||
"num_candidates": 100,
|
||||
"similarity": 0.62
|
||||
}
|
||||
},
|
||||
{
|
||||
"nested": {
|
||||
"path": "keyword_vectors",
|
||||
"query": {
|
||||
"knn": {
|
||||
"field": "keyword_vectors.vector",
|
||||
"query_vector": query_vector,
|
||||
"k": limit,
|
||||
"num_candidates": 100,
|
||||
"similarity": 0.62
|
||||
}
|
||||
},
|
||||
"score_mode": "max"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
else:
|
||||
raise ValueError(f"Unknown config_type: {config_type}")
|
||||
|
||||
query_body["_source"] = {
|
||||
"excludes": ["display_name_vector", "description_vector", "keyword_vectors", "description"]
|
||||
}
|
||||
query_body["size"] = limit
|
||||
return query_body
|
||||
|
||||
async def evaluate():
|
||||
queries_by_field = load_queries()
|
||||
|
||||
# 1. Warm up model and connection
|
||||
print("\nWarming up model and Elasticsearch connection...")
|
||||
model = get_model()
|
||||
model.encode("warmup search term")
|
||||
|
||||
# Run a dummy check on ES
|
||||
dummy_vector = [0.1] * 768
|
||||
dummy_payload = make_es_payload(dummy_vector, "warmup search term", "display_name")
|
||||
try:
|
||||
with httpx.Client(timeout=10.0) as client:
|
||||
client.post(f"{ELASTIC_URL}topicvectors/_search", json=dummy_payload, headers=headers)
|
||||
print("Warmup complete.")
|
||||
except Exception as exc:
|
||||
print(f"Warmup query failed: {exc}")
|
||||
|
||||
results = []
|
||||
print("\nRunning comprehensive latency evaluation on 520 queries...")
|
||||
query_count = 0
|
||||
|
||||
config_list = [
|
||||
"display_name", "description", "keywords",
|
||||
"display_name_and_keywords", "display_name_and_description",
|
||||
"combined", "lexical_only", "hybrid"
|
||||
]
|
||||
|
||||
with httpx.Client(timeout=30.0) as client:
|
||||
for field, queries in queries_by_field.items():
|
||||
for q in queries:
|
||||
query_count += 1
|
||||
if query_count % 50 == 0:
|
||||
print(f"Processed {query_count} / 520 queries...")
|
||||
|
||||
# Measure encoding latency
|
||||
t0 = time.perf_counter()
|
||||
query_vector = model.encode(q).tolist()
|
||||
t1 = time.perf_counter()
|
||||
encode_time = (t1 - t0) * 1000.0 # ms
|
||||
|
||||
latencies = {}
|
||||
|
||||
# Benchmark each configuration
|
||||
for config in config_list:
|
||||
payload = make_es_payload(query_vector, q, config)
|
||||
t0 = time.perf_counter()
|
||||
try:
|
||||
resp = client.post(f"{ELASTIC_URL}topicvectors/_search", json=payload, headers=headers)
|
||||
resp.raise_for_status()
|
||||
except Exception as exc:
|
||||
# Log error but don't crash
|
||||
pass
|
||||
t1 = time.perf_counter()
|
||||
latencies[config] = (t1 - t0) * 1000.0 # ms
|
||||
|
||||
results.append({
|
||||
"query": q,
|
||||
"field": field,
|
||||
"encode_latency_ms": encode_time,
|
||||
"display_name_latency_ms": latencies.get("display_name", 0.0),
|
||||
"description_latency_ms": latencies.get("description", 0.0),
|
||||
"keywords_latency_ms": latencies.get("keywords", 0.0),
|
||||
"display_name_and_keywords_latency_ms": latencies.get("display_name_and_keywords", 0.0),
|
||||
"display_name_and_description_latency_ms": latencies.get("display_name_and_description", 0.0),
|
||||
"combined_latency_ms": latencies.get("combined", 0.0),
|
||||
"lexical_only_latency_ms": latencies.get("lexical_only", 0.0),
|
||||
"hybrid_latency_ms": latencies.get("hybrid", 0.0)
|
||||
})
|
||||
|
||||
# Calculate global stats
|
||||
encode_l = [r["encode_latency_ms"] for r in results]
|
||||
display_name_l = [r["display_name_latency_ms"] for r in results]
|
||||
description_l = [r["description_latency_ms"] for r in results]
|
||||
keywords_l = [r["keywords_latency_ms"] for r in results]
|
||||
display_name_and_keywords_l = [r["display_name_and_keywords_latency_ms"] for r in results]
|
||||
display_name_and_description_l = [r["display_name_and_description_latency_ms"] for r in results]
|
||||
combined_l = [r["combined_latency_ms"] for r in results]
|
||||
lexical_only_l = [r["lexical_only_latency_ms"] for r in results]
|
||||
hybrid_l = [r["hybrid_latency_ms"] for r in results]
|
||||
|
||||
summary = {
|
||||
"total_queries": len(results),
|
||||
"encode": {
|
||||
"mean": np.mean(encode_l), "median": np.median(encode_l),
|
||||
"p90": np.percentile(encode_l, 90), "p95": np.percentile(encode_l, 95)
|
||||
},
|
||||
"display_name": {
|
||||
"mean": np.mean(display_name_l), "median": np.median(display_name_l),
|
||||
"p90": np.percentile(display_name_l, 90), "p95": np.percentile(display_name_l, 95)
|
||||
},
|
||||
"description": {
|
||||
"mean": np.mean(description_l), "median": np.median(description_l),
|
||||
"p90": np.percentile(description_l, 90), "p95": np.percentile(description_l, 95)
|
||||
},
|
||||
"keywords": {
|
||||
"mean": np.mean(keywords_l), "median": np.median(keywords_l),
|
||||
"p90": np.percentile(keywords_l, 90), "p95": np.percentile(keywords_l, 95)
|
||||
},
|
||||
"display_name_and_keywords": {
|
||||
"mean": np.mean(display_name_and_keywords_l), "median": np.median(display_name_and_keywords_l),
|
||||
"p90": np.percentile(display_name_and_keywords_l, 90), "p95": np.percentile(display_name_and_keywords_l, 95)
|
||||
},
|
||||
"display_name_and_description": {
|
||||
"mean": np.mean(display_name_and_description_l), "median": np.median(display_name_and_description_l),
|
||||
"p90": np.percentile(display_name_and_description_l, 90), "p95": np.percentile(display_name_and_description_l, 95)
|
||||
},
|
||||
"combined": {
|
||||
"mean": np.mean(combined_l), "median": np.median(combined_l),
|
||||
"p90": np.percentile(combined_l, 90), "p95": np.percentile(combined_l, 95)
|
||||
},
|
||||
"lexical_only": {
|
||||
"mean": np.mean(lexical_only_l), "median": np.median(lexical_only_l),
|
||||
"p90": np.percentile(lexical_only_l, 90), "p95": np.percentile(lexical_only_l, 95)
|
||||
},
|
||||
"hybrid": {
|
||||
"mean": np.mean(hybrid_l), "median": np.median(hybrid_l),
|
||||
"p90": np.percentile(hybrid_l, 90), "p95": np.percentile(hybrid_l, 95)
|
||||
}
|
||||
}
|
||||
|
||||
# Save full report to json
|
||||
report_json_path = current_dir / "evaluation_report.json"
|
||||
with open(report_json_path, "w", encoding="utf-8") as f:
|
||||
json.dump({"summary": summary, "results": results}, f, indent=2, ensure_ascii=False)
|
||||
print(f"\nSaved detailed JSON report to {report_json_path}")
|
||||
|
||||
# Generate and save markdown report
|
||||
md_report_path = current_dir / "evaluation_report.md"
|
||||
md_content = f"""# Vector Search Configuration Latency Report
|
||||
Generated on: {time.strftime('%Y-%m-%d %H:%M:%S')}
|
||||
|
||||
This report documents the latency breakdown for different Elasticsearch query configurations across 520 queries, measuring flat vector searches, nested searches, multi-field combinations, pure lexical searches, and full hybrid queries.
|
||||
|
||||
## Latency Summary Table (ms)
|
||||
|
||||
| Query Configuration | Mean | Median | p90 | p95 |
|
||||
| :--- | :---: | :---: | :---: | :---: |
|
||||
| **Embedding Encode** | {summary["encode"]["mean"]:.2f} | {summary["encode"]["median"]:.2f} | {summary["encode"]["p90"]:.2f} | {summary["encode"]["p95"]:.2f} |
|
||||
| **Pure Lexical Search (`multi_match`)** | {summary["lexical_only"]["mean"]:.2f} | {summary["lexical_only"]["median"]:.2f} | {summary["lexical_only"]["p90"]:.2f} | {summary["lexical_only"]["p95"]:.2f} |
|
||||
| **Description Only (`description_vector`)** | {summary["description"]["mean"]:.2f} | {summary["description"]["median"]:.2f} | {summary["description"]["p90"]:.2f} | {summary["description"]["p95"]:.2f} |
|
||||
| **Display Name Only (`display_name_vector`)** | {summary["display_name"]["mean"]:.2f} | {summary["display_name"]["median"]:.2f} | {summary["display_name"]["p90"]:.2f} | {summary["display_name"]["p95"]:.2f} |
|
||||
| **Keywords Only (`keyword_vectors` - Nested)** | {summary["keywords"]["mean"]:.2f} | {summary["keywords"]["median"]:.2f} | {summary["keywords"]["p90"]:.2f} | {summary["keywords"]["p95"]:.2f} |
|
||||
| **Display Name & Description** | {summary["display_name_and_description"]["mean"]:.2f} | {summary["display_name_and_description"]["median"]:.2f} | {summary["display_name_and_description"]["p90"]:.2f} | {summary["display_name_and_description"]["p95"]:.2f} |
|
||||
| **Display Name & Keywords (Nested)** | {summary["display_name_and_keywords"]["mean"]:.2f} | {summary["display_name_and_keywords"]["median"]:.2f} | {summary["display_name_and_keywords"]["p90"]:.2f} | {summary["display_name_and_keywords"]["p95"]:.2f} |
|
||||
| **Combined (All 3 vector fields)** | {summary["combined"]["mean"]:.2f} | {summary["combined"]["median"]:.2f} | {summary["combined"]["p90"]:.2f} | {summary["combined"]["p95"]:.2f} |
|
||||
| **Hybrid Search (Lexical + All 3 vector fields)** | {summary["hybrid"]["mean"]:.2f} | {summary["hybrid"]["median"]:.2f} | {summary["hybrid"]["p90"]:.2f} | {summary["hybrid"]["p95"]:.2f} |
|
||||
|
||||
---
|
||||
|
||||
## 💡 Latency Bottleneck & Configuration Analysis
|
||||
|
||||
1. **Lexical Baseline**: **Pure Lexical Search** has extremely low latency (mean: **{summary["lexical_only"]["mean"]:.2f} ms**), representing standard BM25 keyword matching speed.
|
||||
2. **Impact of Nested Fields**:
|
||||
- Compares **Keywords Only (Nested)** (mean: **{summary["keywords"]["mean"]:.2f} ms**) with **Description Only (Flat)** (mean: **{summary["description"]["mean"]:.2f} ms**).
|
||||
- Combining Display Name with the flat Description (**Display Name & Description**: **{summary["display_name_and_description"]["mean"]:.2f} ms**) is faster than combining Display Name with nested Keywords (**Display Name & Keywords**: **{summary["display_name_and_keywords"]["mean"]:.2f} ms**), demonstrating that nested vector joins add a steady latency premium.
|
||||
3. **Compound Parallel Execution**:
|
||||
- Adding lexical queries to the 3 combined vector queries (**Hybrid Search**: **{summary["hybrid"]["mean"]:.2f} ms**) introduces virtually no latency overhead compared to **Combined** vector-only search (mean: **{summary["combined"]["mean"]:.2f} ms**), proving that standard lexical match is executed concurrently with HNSW vector retrieval.
|
||||
"""
|
||||
with open(md_report_path, "w", encoding="utf-8") as f:
|
||||
f.write(md_content)
|
||||
print(f"Saved Markdown report summary to {md_report_path}")
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(evaluate())
|
||||
@@ -0,0 +1,392 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Professional evaluation pipeline to benchmark different Sentence Transformer models
|
||||
on the OpenAlex topics dataset. Measures Information Retrieval (IR) metrics,
|
||||
Taxonomy Clustering metrics, and operational performance metrics.
|
||||
"""
|
||||
import os
|
||||
import sys
|
||||
import json
|
||||
import time
|
||||
import argparse
|
||||
import random
|
||||
from pathlib import Path
|
||||
import httpx
|
||||
import numpy as np
|
||||
from dotenv import load_dotenv
|
||||
|
||||
# Add service/src/main to python path to load settings
|
||||
current_dir = Path(__file__).parent.resolve()
|
||||
project_root = current_dir.parent.parent.resolve()
|
||||
env_path = project_root / "service" / "src" / "main" / "inse" / ".env"
|
||||
load_dotenv(dotenv_path=env_path)
|
||||
|
||||
sys.path.append(str(project_root / "service" / "src" / "main"))
|
||||
from inse.config import settings
|
||||
|
||||
ELASTIC_URL = settings.elasticsearch_url
|
||||
API_KEY = settings.elasticsearch_api_key
|
||||
|
||||
# Import evaluation libraries
|
||||
from sentence_transformers import SentenceTransformer
|
||||
from sentence_transformers.evaluation import InformationRetrievalEvaluator
|
||||
from sklearn.cluster import KMeans
|
||||
from sklearn import metrics
|
||||
|
||||
DEFAULT_MODELS = [
|
||||
"paraphrase-multilingual-mpnet-base-v2",
|
||||
"BAAI/bge-m3",
|
||||
"google/embeddinggemma-300m",
|
||||
"intfloat/multilingual-e5-small",
|
||||
"intfloat/multilingual-e5-base",
|
||||
"intfloat/multilingual-e5-large",
|
||||
"sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2",
|
||||
#english
|
||||
"sentence-transformers/all-MiniLM-L6-v2",
|
||||
"intfloat/e5-large-v2",
|
||||
"BAAI/bge-large-en-v1.5"
|
||||
]
|
||||
|
||||
def fetch_all_topics():
|
||||
topics = []
|
||||
size = 1000
|
||||
offset = 0
|
||||
headers = {
|
||||
"Authorization": f"ApiKey {API_KEY}",
|
||||
"Content-Type": "application/json"
|
||||
}
|
||||
|
||||
with httpx.Client(timeout=60.0) as client:
|
||||
while True:
|
||||
payload = {
|
||||
"query": {"match_all": {}},
|
||||
"from": offset,
|
||||
"size": size
|
||||
}
|
||||
resp = client.post(
|
||||
f"{ELASTIC_URL.rstrip('/')}/openalex-topics/_search",
|
||||
json=payload,
|
||||
headers=headers
|
||||
)
|
||||
resp.raise_for_status()
|
||||
data = resp.json()
|
||||
hits = data.get("hits", {}).get("hits", [])
|
||||
if not hits:
|
||||
break
|
||||
topics.extend(hits)
|
||||
offset += len(hits)
|
||||
print(f"Fetched {len(topics)} topics...")
|
||||
if len(hits) < size:
|
||||
break
|
||||
|
||||
print(f"Total topics loaded: {len(topics)}")
|
||||
return topics
|
||||
|
||||
def prepare_data(topics, sample_size=None):
|
||||
"""
|
||||
Formulate the IR dataset and clustering taxonomy ground truth labels.
|
||||
"""
|
||||
corpus = {}
|
||||
queries = {}
|
||||
relevant_docs = {}
|
||||
|
||||
# Clustering labels
|
||||
topic_ids = []
|
||||
names_for_clustering = []
|
||||
descriptions_for_clustering = []
|
||||
labels_subfield = []
|
||||
labels_field = []
|
||||
labels_domain = []
|
||||
|
||||
# Build complete corpus dictionary of documents
|
||||
for t in topics:
|
||||
source = t["_source"]
|
||||
doc_id = source["id"]
|
||||
display_name = source.get("display_name") or ""
|
||||
description = source.get("description") or ""
|
||||
doc_text = f"{display_name} {description}".strip()
|
||||
|
||||
corpus[doc_id] = doc_text
|
||||
|
||||
# Taxonomy labels
|
||||
topic_ids.append(doc_id)
|
||||
names_for_clustering.append(display_name.strip())
|
||||
descriptions_for_clustering.append(description.strip())
|
||||
labels_subfield.append(source.get("subfield", {}).get("id") or "unknown_subfield")
|
||||
labels_field.append(source.get("field", {}).get("id") or "unknown_field")
|
||||
labels_domain.append(source.get("domain", {}).get("id") or "unknown_domain")
|
||||
|
||||
sampled_topics = topics
|
||||
if sample_size and sample_size < len(topics):
|
||||
print(f"Sampling {sample_size} topics for query/keyword generation...")
|
||||
sampled_topics = random.sample(topics, sample_size)
|
||||
|
||||
query_count = 0
|
||||
for t in sampled_topics:
|
||||
source = t["_source"]
|
||||
doc_id = source["id"]
|
||||
keywords = source.get("keywords") or []
|
||||
|
||||
for keyword in keywords:
|
||||
if not keyword.strip():
|
||||
continue
|
||||
query_id = f"q_{query_count}"
|
||||
queries[query_id] = keyword
|
||||
|
||||
# Ground truth relevant documents: topic name
|
||||
rel_docs = {doc_id}
|
||||
relevant_docs[query_id] = rel_docs
|
||||
query_count += 1
|
||||
|
||||
print(f"Dataset Formulated: {len(corpus)} corpus documents, {len(queries)} queries.")
|
||||
|
||||
return {
|
||||
"corpus": corpus,
|
||||
"queries": queries,
|
||||
"relevant_docs": relevant_docs,
|
||||
"clustering": {
|
||||
"ids": topic_ids,
|
||||
"names": names_for_clustering,
|
||||
"descriptions": descriptions_for_clustering,
|
||||
"subfield": labels_subfield,
|
||||
"field": labels_field,
|
||||
"domain": labels_domain
|
||||
}
|
||||
}
|
||||
|
||||
def evaluate_model(model_name, data, output_dir):
|
||||
"""
|
||||
Load a model, measure operational speed, and calculate IR + clustering quality.
|
||||
"""
|
||||
model_safe_name = model_name.replace("/", "_").replace("-", "_")
|
||||
report_file = output_dir / f"model_report_{model_safe_name}.json"
|
||||
|
||||
print(f"\n==================================================")
|
||||
print(f"Evaluating Model: '{model_name}'")
|
||||
print(f"==================================================")
|
||||
|
||||
start_load = time.time()
|
||||
try:
|
||||
model = SentenceTransformer(model_name)
|
||||
except Exception as exc:
|
||||
print(f"ERROR: Failed to load model '{model_name}': {exc}")
|
||||
return None
|
||||
|
||||
load_time = time.time() - start_load
|
||||
print(f"Model loaded in {load_time:.2f} seconds.")
|
||||
|
||||
num_params = sum(p.numel() for p in model.parameters())
|
||||
param_count_m = num_params / 1_000_000
|
||||
vector_dim = model.get_sentence_embedding_dimension()
|
||||
print(f"Parameters: {param_count_m:.1f}M, Vector Dimension: {vector_dim}")
|
||||
|
||||
# --- FIXED: Perform a warm-up to initialize computation graphs ---
|
||||
print("Warming up model...")
|
||||
_ = model.encode(["warmup sentence"])
|
||||
|
||||
# 2. Measure Query Latency
|
||||
sample_queries = list(data["queries"].values())[:100]
|
||||
if not sample_queries:
|
||||
sample_queries = ["artificial intelligence", "machine learning"]
|
||||
|
||||
start_lat = time.time()
|
||||
for q in sample_queries:
|
||||
_ = model.encode(q)
|
||||
latency_ms = ((time.time() - start_lat) / len(sample_queries)) * 1000
|
||||
print(f"Average Query Latency: {latency_ms:.2f} ms")
|
||||
|
||||
# 3. Measure Ingestion Throughput
|
||||
sample_docs = list(data["corpus"].values())[:200]
|
||||
start_batch = time.time()
|
||||
_ = model.encode(sample_docs, batch_size=32)
|
||||
batch_time = time.time() - start_batch
|
||||
throughput_docs_sec = len(sample_docs) / batch_time
|
||||
print(f"Ingestion Throughput: {throughput_docs_sec:.2f} docs/sec")
|
||||
|
||||
# 4. Information Retrieval Evaluation
|
||||
print("Running Information Retrieval evaluation (NDCG, MRR, Recall)...")
|
||||
|
||||
# --- FIXED: Use precision_recall_at_k for true recall metrics ---
|
||||
evaluator = InformationRetrievalEvaluator(
|
||||
data["queries"],
|
||||
data["corpus"],
|
||||
data["relevant_docs"], # The evaluator natively accepts sets, no need to cast to lists
|
||||
name=model_safe_name,
|
||||
mrr_at_k=[10],
|
||||
ndcg_at_k=[10],
|
||||
precision_recall_at_k=[10] # This ensures true Recall is calculated across multiple sibling matches
|
||||
)
|
||||
|
||||
ir_results = evaluator(model)
|
||||
|
||||
# Extract keys safely
|
||||
ndcg_key = f"{model_safe_name}_cosine_ndcg@10"
|
||||
mrr_key = f"{model_safe_name}_cosine_mrr@10"
|
||||
recall_key = f"{model_safe_name}_cosine_recall@10" # Changed from accuracy to recall
|
||||
|
||||
ndcg_score = ir_results.get(ndcg_key, 0.0)
|
||||
mrr_score = ir_results.get(mrr_key, 0.0)
|
||||
recall_score = ir_results.get(recall_key, 0.0)
|
||||
|
||||
print(f"NDCG@10: {ndcg_score:.4f}, MRR@10: {mrr_score:.4f}, Recall@10: {recall_score:.4f}")
|
||||
|
||||
# 5. Clustering evaluation against ground-truth taxonomy
|
||||
print("Running Taxonomy Clustering evaluation (NMI)...")
|
||||
|
||||
unique_subfields = list(set(data["clustering"]["subfield"]))
|
||||
n_clusters = len(unique_subfields)
|
||||
|
||||
# Topic Names Clustering
|
||||
print("Clustering Topic Names...")
|
||||
clustering_names = data["clustering"]["names"]
|
||||
name_embeddings = model.encode(clustering_names, show_progress_bar=False, batch_size=64)
|
||||
|
||||
nmi_name = 0.0
|
||||
ari_name = 0.0
|
||||
if n_clusters > 1 and len(name_embeddings) > n_clusters:
|
||||
kmeans_name = KMeans(n_clusters=n_clusters, random_state=42, n_init='auto')
|
||||
assignments_name = kmeans_name.fit_predict(name_embeddings)
|
||||
nmi_name = metrics.normalized_mutual_info_score(data["clustering"]["subfield"], assignments_name)
|
||||
ari_name = metrics.adjusted_rand_score(data["clustering"]["subfield"], assignments_name)
|
||||
print(f"Names - Subfield Clustering NMI: {nmi_name:.4f}, ARI: {ari_name:.4f}")
|
||||
|
||||
# Topic Descriptions Clustering
|
||||
print("Clustering Topic Descriptions...")
|
||||
clustering_descs = data["clustering"]["descriptions"]
|
||||
desc_embeddings = model.encode(clustering_descs, show_progress_bar=False, batch_size=64)
|
||||
|
||||
nmi_desc = 0.0
|
||||
ari_desc = 0.0
|
||||
if n_clusters > 1 and len(desc_embeddings) > n_clusters:
|
||||
kmeans_desc = KMeans(n_clusters=n_clusters, random_state=42, n_init='auto')
|
||||
assignments_desc = kmeans_desc.fit_predict(desc_embeddings)
|
||||
nmi_desc = metrics.normalized_mutual_info_score(data["clustering"]["subfield"], assignments_desc)
|
||||
ari_desc = metrics.adjusted_rand_score(data["clustering"]["subfield"], assignments_desc)
|
||||
print(f"Descriptions - Subfield Clustering NMI: {nmi_desc:.4f}, ARI: {ari_desc:.4f}")
|
||||
|
||||
report = {
|
||||
"model_name": model_name,
|
||||
"parameters_m": param_count_m,
|
||||
"vector_dim": vector_dim,
|
||||
"latency_ms": latency_ms,
|
||||
"throughput_docs_sec": throughput_docs_sec,
|
||||
"ndcg_at_10": ndcg_score,
|
||||
"mrr_at_10": mrr_score,
|
||||
"recall_at_10": recall_score,
|
||||
"name_nmi": nmi_name,
|
||||
"name_ari": ari_name,
|
||||
"desc_nmi": nmi_desc,
|
||||
"desc_ari": ari_desc
|
||||
}
|
||||
|
||||
with open(report_file, "w", encoding="utf-8") as f:
|
||||
json.dump(report, f, indent=2, ensure_ascii=False)
|
||||
print(f"Saved model report to {report_file}")
|
||||
|
||||
return report
|
||||
|
||||
def generate_consolidated_report(output_dir, reports):
|
||||
if not reports:
|
||||
print("No reports to consolidate.")
|
||||
return
|
||||
|
||||
report_file = output_dir / "model_evaluation_report.md"
|
||||
print(f"\nCompiling consolidated report into {report_file}...")
|
||||
|
||||
sorted_reports = sorted(reports, key=lambda x: x["ndcg_at_10"], reverse=True)
|
||||
|
||||
lines = [
|
||||
"# Sentence Transformer Model Evaluation Report",
|
||||
"",
|
||||
"This report aggregates performance metrics and accuracy benchmarks for different Sentence Transformer models evaluated against the OpenAlex topic keywords dataset.",
|
||||
"",
|
||||
"## Overall Leaderboard",
|
||||
"",
|
||||
"| Rank | Model Name | Vector Dim | Params (M) | Query Latency (ms) | Throughput (docs/s) | NDCG@10 | MRR@10 | Recall@10 | Name NMI | Desc NMI |",
|
||||
"| :--- | :--- | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: |"
|
||||
]
|
||||
|
||||
for idx, r in enumerate(sorted_reports):
|
||||
name_nmi = r.get("name_nmi", 0.0)
|
||||
desc_nmi = r.get("desc_nmi", 0.0)
|
||||
lines.append(
|
||||
f"| {idx+1} | `{r['model_name']}` | {r['vector_dim']} | {r['parameters_m']:.1f}M | {r['latency_ms']:.2f}ms | {r['throughput_docs_sec']:.1f} | **{r['ndcg_at_10']:.4f}** | {r['mrr_at_10']:.4f} | {r['recall_at_10']:.4f} | {name_nmi:.4f} | {desc_nmi:.4f} |"
|
||||
)
|
||||
|
||||
lines.extend([
|
||||
"",
|
||||
"### Metric Definitions:",
|
||||
"* **NDCG@10**: Normalized Discounted Cumulative Gain. Measures how well the query maps to the target topic at the top 10 positions.",
|
||||
"* **MRR@10**: Mean Reciprocal Rank. Looks at the average of `1 / rank` for the first correctly matched topic.",
|
||||
"* **Recall@10**: Percentage of times the target document (excluding sibling topics) was successfully retrieved in the top 10.",
|
||||
"* **Name NMI**: Normalized Mutual Information of K-Means clusters of topic display names against ground truth OpenAlex subfields.",
|
||||
"* **Desc NMI**: Normalized Mutual Information of K-Means clusters of topic descriptions against ground truth OpenAlex subfields.",
|
||||
"* **Query Latency**: Time to encode a single search keyword.",
|
||||
"* **Throughput**: Ingestion batch encoding speed."
|
||||
])
|
||||
|
||||
with open(report_file, "w", encoding="utf-8") as f:
|
||||
f.write("\n".join(lines))
|
||||
print(f"Report compiled successfully at {report_file}")
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description="Evaluate Sentence Transformer models on OpenAlex topics.")
|
||||
parser.add_argument("--model", type=str, help="Specific model to evaluate (skips others).")
|
||||
parser.add_argument("--sample-size", type=int, help="Sample size of topics to evaluate keywords for (faster run).")
|
||||
parser.add_argument("--all", action="store_true", help="Evaluate all topics/keywords (default if sample-size omitted).")
|
||||
parser.add_argument("--output-dir", type=str, help="Custom directory to save reports.")
|
||||
parser.add_argument("--force-refresh", action="store_true", help="Force reload topics from Elasticsearch instead of cache.")
|
||||
|
||||
args = parser.parse_args()
|
||||
|
||||
if Path("/data").is_dir():
|
||||
data_dir = Path("/data")
|
||||
else:
|
||||
project_root = Path(__file__).parent.parent.parent.parent.parent.resolve()
|
||||
data_dir = project_root / "service" / "src" / "data"
|
||||
data_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
output_dir = Path(args.output_dir) if args.output_dir else data_dir
|
||||
output_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
cache_file = data_dir / "raw_topics_cache.json"
|
||||
if cache_file.exists() and not args.force_refresh:
|
||||
print(f"Loading topics from local cache: {cache_file}")
|
||||
with open(cache_file, "r", encoding="utf-8") as f:
|
||||
topics = json.load(f)
|
||||
else:
|
||||
topics = fetch_all_topics()
|
||||
with open(cache_file, "w", encoding="utf-8") as f:
|
||||
json.dump(topics, f, indent=2, ensure_ascii=False)
|
||||
print(f"Cached {len(topics)} topics to {cache_file}")
|
||||
|
||||
if not topics:
|
||||
print("Error: No topics dataset available. Make sure Elasticsearch is running or cache exists.")
|
||||
sys.exit(1)
|
||||
|
||||
data = prepare_data(topics, sample_size=args.sample_size)
|
||||
|
||||
models_to_evaluate = DEFAULT_MODELS
|
||||
if args.model:
|
||||
models_to_evaluate = [args.model]
|
||||
|
||||
print(f"Models scheduled for evaluation: {models_to_evaluate}")
|
||||
|
||||
reports = []
|
||||
for m in models_to_evaluate:
|
||||
model_safe_name = m.replace("/", "_").replace("-", "_")
|
||||
report_file = output_dir / f"model_report_{model_safe_name}.json"
|
||||
|
||||
if report_file.exists() and not args.model:
|
||||
print(f"Loading cached evaluation report for '{m}' from {report_file}")
|
||||
with open(report_file, "r", encoding="utf-8") as f:
|
||||
reports.append(json.load(f))
|
||||
else:
|
||||
rep = evaluate_model(m, data, output_dir)
|
||||
if rep:
|
||||
reports.append(rep)
|
||||
|
||||
generate_consolidated_report(output_dir, reports)
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,159 @@
|
||||
# Performance Summary
|
||||
|
||||
520 Keywords as query against hybrid & semantic search
|
||||
|
||||
- Search fields:
|
||||
- display name (Keyword & single vector)
|
||||
- description (Keyword & single vector)
|
||||
- keywords (Keyword & nested vectors)
|
||||
|
||||
- 26 Fields: 20 examples each
|
||||
| # | OpenAlex Field Name | Complete Test Queries |
|
||||
|---|---------------------|-----------------------------------------|
|
||||
| 01 | **Social Sciences** | `sociology, gender inequality in workplace, urbanization trends, political polarization, human rights law, social mobility, qualitative research methods, demographic shifts, cultural anthropology, criminal justice reform, public policy analysis, indigenous languages, voter behavior, globalization effects, community development, media studies, social movements, migration patterns, welfare systems, family dynamics` |
|
||||
| 02 | **Medicine** | `cardiology, diabetes management, oncology treatment options, clinical trials, pediatric care, chronic pain relief, cardiovascular disease prevention, surgical procedures, infectious disease outbreak, medical imaging techniques, hypertension guidelines, patient outcomes, immunotherapy for cancer, epidemiology study, stroke rehabilitation, genetic disorders, telemedicine adoption, internal medicine, diagnostic accuracy, palliative care` |
|
||||
| 03 | **Engineering** | `civil engineering, structural integrity, aerospace propulsion, mechanical design, robotics automation, geotechnical analysis, bridge construction, renewable energy grid, fluid mechanics, electrical circuits, thermodynamics applications, manufacturing optimization, control systems engineering, materials fatigue, hvac design, biomedical devices, transportation infrastructure, signal processing, solid mechanics, industrial engineering` |
|
||||
| 04 | **Computer Science** | `machine learning, natural language processing, cybersecurity protocols, cloud computing architecture, neural networks, database optimization, software engineering practices, computer vision algorithms, blockchain technology, artificial intelligence ethics, human computer interaction, operating systems, distributed ledgers, compiler design, data mining techniques, cryptographic keys, quantum computing algorithms, web development frameworks, reinforcement learning, graph databases` |
|
||||
| 05 | **Arts and Humanities** | `art history, literary criticism, philosophy of mind, renaissance architecture, linguistics morphology, creative writing, musical composition, theater history, postmodern literature, ethics and morality, historical archives, film analysis, religious studies, classical archaeology, metaphysics, cultural heritage preservation, comparative literature, linguistic semantics, medieval art, epistemology` |
|
||||
| 06 | **Biochemistry, Genetics and Molecular Biology** | `dna replication, crispr gene editing, protein folding, rna sequencing, enzyme kinetics, cellular signaling pathways, metabolic pathways, genomic sequencing, molecular cloning, apoptosis mechanism, mitochondrial DNA, epigenetic modifications, proteomics analysis, gene expression regulation, chromatin remodeling, amino acid synthesis, nucleic acids, cellular differentiation, lipid metabolism, transcription factors` |
|
||||
| 07 | **Agricultural and Biological Sciences** | `crop yield optimization, plant physiology, marine biology, soil microbiology, entomology study, botany research, sustainable agriculture, animal behavior, ecology systems, pest management, forestry conservation, photosynthesis mechanism, biodiversity preservation, aquaculture techniques, agronomy practices, seed germination, horticulture science, wildlife ecology, plant pathology, livestock breeding` |
|
||||
| 08 | **Environmental Science** | `climate change mitigation, renewable resource management, air pollution monitoring, microplastics in oceans, deforestation rates, waste management systems, carbon footprint reduction, biodiversity loss, global warming impacts, ecosystem restoration, water quality analysis, urban sustainability, environmental impact assessment, glacier melting, conservation biology, greenhouse gas emissions, soil erosion control, renewable energy transition, climate adaptation strategies, acid rain causes` |
|
||||
| 09 | **Business, Management and Accounting** | `corporate strategy, supply chain logistics, financial auditing, marketing analytics, human resource management, organizational behavior, consumer behavior trends, risk assessment framework, entrepreneurship ecosystems, project management methodologies, accounting principles, brand equity, leadership styles, business ethics, digital transformation strategy, operations management, corporate governance, market segmentation, strategic planning, financial reporting standards` |
|
||||
| 10 | **Psychology** | `cognitive behavioral therapy, developmental psychology, social anxiety disorder, memory retention techniques, neuropsychology assessment, human behavior analysis, mental health counseling, personality traits theory, child development stages, addiction recovery mechanisms, emotional intelligence, perception and sensation, group dynamics psychology, depression treatment outcomes, stress management interventions, motivation theories, cognitive dissonance, behavioral psychology, mindfulness practices, sleep disorders psychology` |
|
||||
| 11 | **Materials Science** | `nanomaterials synthesis, graphene applications, polymers characterization, metallurgy engineering, semiconductor fabrication, composite materials design, biomaterials tissue engineering, thin film deposition, corrosion resistance, superconductors properties, ceramic engineering, alloy development, material degradation, photovoltaic materials, mechanical testing of alloys, smart materials technology, crystal structure analysis, carbon nanotubes research, thermal conductivity materials, magnetic materials applications` |
|
||||
| 12 | **Economics, Econometrics and Finance** | `macroeconomic policy, econometric modeling, financial market analysis, monetary theory, microeconomics principles, game theory applications, inflation rates forecast, labor economics, behavioral finance, portfolio optimization, international trade agreements, fiscal policy impact, time series analysis, asset pricing models, poverty reduction strategies, economic growth models, corporate finance theory, cryptocurrency economics, market equilibrium, public finance management` |
|
||||
| 13 | **Health Professions** | `physical therapy techniques, occupational therapy interventions, speech language pathology, radiologic technology, emergency medical services, healthcare administration, audiology assessments, rehabilitation sciences, clinical nutrition, paramedic protocols, respiratory therapy management, health informatics systems, dietetics practice, patient care quality, medical laboratory technology, orthotics and prosthetics, interprofessional healthcare collaboration, community health education, sports medicine rehabilitation, physician assistant training` |
|
||||
| 14 | **Physics and Astronomy** | `quantum mechanics, astrophysics research, dark matter detection, particle physics collision, general relativity theory, cosmology evolution, exoplanet discovery, nuclear fusion energy, condensed matter physics, string theory concepts, optics and photonics, black hole thermodynamics, gravitational waves detection, statistical mechanics, plasma physics applications, stellar evolution models, high energy physics, quantum entanglement experiments, spectroscopy techniques, thermodynamics principles` |
|
||||
| 15 | **Chemistry** | `organic synthesis, analytical chemistry methods, inorganic compounds coordination, physical chemistry thermodynamics, spectroscopy chemical analysis, catalysis mechanism design, polymer chemistry polymerization, electrochemistry batteries, medicinal chemistry design, chromatography separation techniques, chemical kinetics reactions, mass spectrometry profiling, computational chemistry modeling, environmental chemistry monitoring, photochemistry solar conversion, biophysical chemistry structure, green chemistry principles, molecular orbital theory, supramolecular architecture, crystallography structure determination` |
|
||||
| 16 | **Mathematics** | `linear algebra, differential equations solution, algebraic topology, number theory cryptography, calculus fundamentals, probability and statistics, discrete mathematics structures, numerical analysis algorithms, complex analysis functions, geometry axiom theories, combinatorics counting techniques, mathematical modeling simulation, set theory foundations, graph theory applications, real analysis limits, partial differential equations, abstract algebra groups, optimization theory algorithms, stochastic processes modeling, chaos theory dynamics` |
|
||||
| 17 | **Neuroscience** | `synaptic plasticity, neurodegenerative diseases mechanisms, brain mapping fmri, cognitive neuroscience memory, neurotransmitter receptors pathways, neural network architecture, behavioral neuroscience addiction, neurogenesis adult brain, axon guidance development, spinal cord injury, sensory processing systems, motor control pathways, alzheimer disease pathology, parkinson motor deficits, neuroimmunology inflammation, sleep neural circuits, epilepsy seizure mechanisms, computational neuroscience models, neuropharmacology drugs action, brain computer interface` |
|
||||
| 18 | **Decision Sciences** | `operations research optimization, decision analysis models, multi criteria decision making, game theory strategies, risk analysis management, linear programming applications, forecasting methods business, supply chain optimization, stochastic modeling systems, queuing theory performance, decision tree classification, predictive analytics framework, statistical decision theory, heuristic search optimization, inventory control models, simulation optimization methods, behavioral decision making, utility theory choices, data driven decision support, dynamic programming problems` |
|
||||
| 19 | **Earth and Planetary Sciences** | `plate tectonics geology, seismology earthquake prediction, volcanology eruption monitoring, paleoclimatology proxy data, planetary geology mars, mineralogy crystal structures, sedimentology deposition environments, stratigraphy rock layers, geomorphology landscape evolution, hydrology water cycle, meteorology weather forecasting, oceanography ocean currents, geochemistry isotopic analysis, remote sensing earth, petrology rock formation, impact cratering planetary, paleontology fossil records, glaciology ice sheets, geophysics magnetic fields, environmental geology hazards` |
|
||||
| 20 | **Immunology and Microbiology** | `t cell activation, antibody response mechanics, bacterial resistance antibiotics, viral replication cycle, autoimmune disease pathogenesis, innate immunity defense, vaccine development strategies, microbiome gut health, macrophage polarization function, pathogen virulence factors, cytokine storm response, mycology fungal infections, parasitology host interaction, adaptive immune system, antigen presentation pathway, bacteriophage therapy applications, immunotherapy cancer treatment, microbial biofilms formation, virology host defense, inflammation signaling pathways` |
|
||||
| 21 | **Energy** | `solar cell efficiency, wind turbine aerodynamics, battery energy storage, hydrogen fuel cells, nuclear power generation, biofuel production technologies, geothermal energy extraction, energy grid optimization, fossil fuel alternative, hydroelectric power systems, energy efficiency buildings, carbon capture storage, renewable energy policy, smart grid infrastructure, tidal energy conversion, thermal energy storage, power electronics converters, microgrid energy systems, biomass combustion processes, energy consumption forecasting` |
|
||||
| 22 | **Pharmacology, Toxicology and Pharmaceutics** | `drug delivery systems, pharmacokinetics modeling analysis, pharmacodynamics receptor binding, toxicology safety assessment, pharmaceutical formulation design, bioavailability drug absorption, cytotoxicity assays testing, clinical pharmacology trials, neuropharmacology drug effects, cardiotoxicity drug evaluation, nanoparticle drug carriers, pharmacogenomics personalized medicine, drug metabolism enzymes, adverse drug reactions, controlled release tablets, heavy metal toxicology, target identification drug, natural product pharmacology, dosage form optimization, endocrine disruptors toxicology` |
|
||||
| 23 | **Nursing** | `patient care management, nursing education curriculum, clinical nursing practice, geriatric nursing care, pediatric nursing interventions, critical care nursing, palliative nursing care, nursing leadership styles, community health nursing, evidence based nursing, mental health nursing, maternal newborn nursing, wound care management, nurse practitioner roles, patient safety protocols, nursing burnout prevention, oncology nursing practices, chronic disease management, telehealth nursing care, infection control nursing` |
|
||||
| 24 | **Chemical Engineering** | `process systems engineering, chemical reactor design, transport phenomena fluid, separation processes distillation, catalytic reaction engineering, bioprocess engineering fermentation, thermodynamics chemical mixtures, heat exchanger network, polymer processing extrusion, mass transfer operations, process safety management, fluidized bed reactor, chemical plant optimization, multi phase flow, computational fluid dynamics, industrial scale synthesis, green chemical engineering, adsorption separation kinetics, process control loops, materials processing chemical` |
|
||||
| 25 | **Dentistry** | `endodontic treatment procedures, periodontal disease therapy, orthodontic alignment techniques, dental implant surgery, prosthodontics crown design, pediatric dentistry prevention, oral maxillofacial surgery, dental caries prevention, restorative dentistry materials, oral pathology diagnosis, laser dentistry applications, dental biomaterials wear, cone beam ct, salivary diagnostics biomarkers, aesthetic dentistry veneers, root canal morphology, gingival recession treatment, fluoride treatment efficacy, dental pulp stem cells, temporomandibular joint disorders` |
|
||||
| 26 | **Veterinary** | `veterinary medicine diagnosis, canine parvovirus treatment, feline leukemia virus, equine sports medicine, bovine mastitis control, veterinary surgery techniques, animal nutrition guidelines, zoonotic disease transmission, veterinary oncology treatment, avian medicine care, small animal internal, livestock herd health, veterinary pharmacology drugs, animal welfare assessment, veterinary radiology imaging, feline behavior issues, canine hip dysplasia, veterinary epidemiology outbreaks, companion animal care, exotic pet medicine` |
|
||||
|
||||
## Latency results
|
||||
|
||||
| Query Configuration | Mean | Median | p95 |
|
||||
| :-------------------------------------- | :---: | :----: | :---: |
|
||||
| **Embedding Encode** | 35.81 | 35.11 | 42.98 |
|
||||
| **Pure Lexical Search (`multi_match`)** | 44.03 | 43.21 | 52.12 |
|
||||
|
||||
|
|
||||
| **Description Only (`description_vector`)** | 27.11 | 24.83 | 40.23 |
|
||||
| **Display Name Only (`display_name_vector`)** | 42.71 | 45.33 | 55.51 |
|
||||
| **Keywords Only (`keyword_vectors` - Nested)** | 47.65 | 47.06 | 56.88 |
|
||||
| **Display Name & Description** | 46.62 | 49.22 | 59.43 |
|
||||
| **Display Name & Keywords (Nested)** | 52.11 | 51.36 | 61.22 |
|
||||
| **Combined (All 3 vector fields)** | 57.06 | 55.65 | 67.32 |
|
||||
|
|
||||
| **Hybrid Search (Lexical + All 3 vector fields)** | 58.65 | 57.09 | 69.10 |
|
||||
|
||||
- should query runs hybrid and semantic concurrently => nested Keyword vector search bottleneck
|
||||
- Hybrid returns more results overall due to partailly matching words in display name & Keywords
|
||||
- Query: "Cell Adhesion Molecules Research"
|
||||
- Low rank return: "Q Methodology Applications"
|
||||
- because: ["**Research** Methods", "Qualitative **Research**"] Keywords
|
||||
|
||||
- Changed k & num_candidates to 500 (fixed bug, where not all keywords were considered):
|
||||
| Query Configuration | Mean | Median | p95 |
|
||||
| :--- | :---: | :---: | :---: |
|
||||
| **Embedding Encode** | 38.25 | 37.41 | 45.48 |
|
||||
| **Pure Lexical Search (`multi_match`)** | 44.98 | 43.69 | 55.21 |
|
||||
| **Description Only (`description_vector`)** | 29.69 | 27.76 | 45.46 |
|
||||
| **Display Name Only (`display_name_vector`)** | 45.20 | 46.68 | 59.47 |
|
||||
| **Keywords Only (`keyword_vectors` - Nested)** | 50.00 | 48.89 | 60.61 |
|
||||
| **Display Name & Description** | 49.84 | 51.16 | 66.37 |
|
||||
| **Display Name & Keywords (Nested)** | 55.50 | 54.16 | 66.12 |
|
||||
| **Combined (All 3 vector fields)** | 61.81 | 59.74 | 75.30 |
|
||||
| **Hybrid Search (Lexical + All 3 vector fields)** | 63.25 | 61.05 | 76.39 |
|
||||
|
||||
# Search Score Breakdown & Weight Analysis Report
|
||||
|
||||
---
|
||||
|
||||
## Global Score Contribution
|
||||
|
||||
| Weight Component | Boost | Avg. Score Contribution | Percentage of Total Score |
|
||||
| :-------------------------------------------- | :---: | :---------------------: | :-----------------------: |
|
||||
| **Lexical Match (`multi_match`)** | 1.0 | 36.2275 | 54.31% |
|
||||
| **Title Vector (`display_name_vector`)** | 30.0 | 17.9748 | 26.95% |
|
||||
| **Description Vector (`description_vector`)** | 15.0 | 2.5502 | 3.82% |
|
||||
| **Nested Keywords (`keyword_vectors`)** | 25.0 | 9.9531 | 14.92% |
|
||||
|
||||
| After fix:
|
||||
| **Lexical Match (`multi_match`)** | 1.0 | 38.2910 | 44.79% |
|
||||
| **Title Vector (`display_name_vector`)** | 30.0 | 22.5727 | 26.40% |
|
||||
| **Description Vector (`description_vector`)** | 15.0 | 3.3518 | 3.92% |
|
||||
| **Nested Keywords (`keyword_vectors`)** | 25.0 | 21.2808 | 24.89% |
|
||||
|
||||
---
|
||||
|
||||
## Contribution Breakdown by Field
|
||||
|
||||
| Field | Avg. Score | Lexical % | Title Vector % | Description Vector % | Keywords Vector % |
|
||||
| :------------------------------------------- | :--------: | :-------: | :------------: | :------------------: | :---------------: |
|
||||
| Social Sciences | 76.10 | 42.6% | 27.0% | 6.2% | 24.2% |
|
||||
| Medicine | 71.58 | 43.9% | 26.5% | 4.1% | 25.5% |
|
||||
| Engineering | 67.73 | 43.8% | 27.6% | 3.5% | 25.2% |
|
||||
| Computer Science | 69.63 | 47.3% | 23.4% | 4.0% | 25.3% |
|
||||
| Arts and Humanities | 75.38 | 40.2% | 28.7% | 5.9% | 25.1% |
|
||||
| Biochemistry, Genetics and Molecular Biology | 64.32 | 43.5% | 26.7% | 1.6% | 28.1% |
|
||||
| Agricultural and Biological Sciences | 70.48 | 38.0% | 30.7% | 4.2% | 27.1% |
|
||||
| Environmental Science | 72.92 | 44.3% | 26.3% | 5.0% | 24.3% |
|
||||
| Business, Management and Accounting | 75.14 | 47.1% | 25.8% | 2.7% | 24.5% |
|
||||
| Psychology | 67.50 | 40.8% | 28.5% | 4.9% | 25.8% |
|
||||
| Materials Science | 75.99 | 40.4% | 28.5% | 6.4% | 24.7% |
|
||||
| Economics, Econometrics and Finance | 67.58 | 43.0% | 25.3% | 5.7% | 25.9% |
|
||||
| Health Professions | 62.96 | 41.9% | 28.4% | 3.2% | 26.5% |
|
||||
| Physics and Astronomy | 70.10 | 47.5% | 24.4% | 3.6% | 24.5% |
|
||||
| Chemistry | 73.17 | 44.6% | 26.8% | 4.2% | 24.4% |
|
||||
| Mathematics | 74.83 | 48.1% | 24.7% | 4.4% | 22.9% |
|
||||
| Neuroscience | 68.20 | 45.2% | 24.6% | 5.2% | 25.0% |
|
||||
| Decision Sciences | 67.13 | 49.5% | 23.3% | 2.4% | 24.8% |
|
||||
| Earth and Planetary Sciences | 64.59 | 41.3% | 28.9% | 2.4% | 27.3% |
|
||||
| Immunology and Microbiology | 68.62 | 44.9% | 25.7% | 3.6% | 25.9% |
|
||||
| Energy | 80.04 | 50.3% | 22.8% | 5.4% | 21.6% |
|
||||
| Pharmacology, Toxicology and Pharmaceutics | 64.61 | 45.2% | 26.1% | 2.4% | 26.2% |
|
||||
| Nursing | 75.86 | 47.8% | 26.5% | 2.8% | 22.8% |
|
||||
| Chemical Engineering | 59.12 | 48.5% | 26.0% | 1.1% | 24.4% |
|
||||
| Dentistry | 62.51 | 44.1% | 28.1% | 3.1% | 24.7% |
|
||||
| Veterinary | 53.56 | 49.2% | 26.9% | 1.9% | 22.0% |
|
||||
|
||||
---
|
||||
|
||||
## Score Breakdown Examples (Top Match per Field Sample)
|
||||
|
||||
| Field & Query | Fixed Variant Performance | Bug Variant Performance |
|
||||
| :------------------------------------------------------------ | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|
||||
| **Social Sciences**<br>`"sociology"` | **Topic**: Emile Durkheim and Sociology<br>**Total Score**: 80.7964<br><br>• Lexical: 33.6289<br>• Title KNN: 25.3876<br>• Desc KNN: 12.1561<br>• Key KNN: 24.9897<br><br>**Keywords**:<br>• 'sociology' (0.9996)<br>• 'social conditions' (0.8254) | **Topic**: Emile Durkheim and Sociology<br>**Total Score**: 55.4088<br><br>• Lexical: 33.6289<br>• Title KNN: 0.0000<br>• Desc KNN: 12.1561<br>• Key KNN: 24.9897<br><br>**Keywords**:<br>• 'sociology' (0.9996)<br>• 'social conditions' (0.8254) |
|
||||
| **Medicine**<br>`"cardiology"` | **Topic**: Cardiomyopathy and Myosin Studies<br>**Total Score**: 62.3436<br><br>• Lexical: 0.0000<br>• Title KNN: 26.0134<br>• Desc KNN: 12.4090<br>• Key KNN: 23.9212<br><br>**Keywords**:<br>• 'Cardiomyopathies' (0.9568)<br>• 'Cardiac Imaging' (0.9192) | **Topic**: Cardiac Imaging and Diagnostics<br>**Total Score**: 27.6677<br><br>• Lexical: 0.0000<br>• Title KNN: 27.6677<br>• Desc KNN: 0.0000<br>• Key KNN: 0.0000<br><br>**Keywords**:<br>• 'Cardiac Imaging' (0.9192)<br>• 'Myocardial Infarction' (0.8564) |
|
||||
| **Engineering**<br>`"civil engineering"` | **Topic**: Civil and Structural Engineering Research<br>**Total Score**: 97.2652<br><br>• Lexical: 60.8415<br>• Title KNN: 28.1018<br>• Desc KNN: 12.3099<br>• Key KNN: 24.8941<br><br>**Keywords**:<br>• 'Civil Engineering' (0.9958)<br>• 'Construction' (0.8388) | **Topic**: Civil and Structural Engineering Research<br>**Total Score**: 97.2652<br><br>• Lexical: 60.8415<br>• Title KNN: 28.1018<br>• Desc KNN: 12.3099<br>• Key KNN: 24.8941<br><br>**Keywords**:<br>• 'Civil Engineering' (0.9958)<br>• 'Construction' (0.8388) |
|
||||
| **Computer Science**<br>`"machine learning"` | **Topic**: Machine Learning and Algorithms<br>**Total Score**: 99.2549<br><br>• Lexical: 55.5562<br>• Title KNN: 29.2590<br>• Desc KNN: 12.5187<br>• Key KNN: 24.9693<br><br>**Keywords**:<br>• 'Machine Learning' (0.9988)<br>• 'Deep Learning' (0.9119) | **Topic**: Machine Learning and Algorithms<br>**Total Score**: 74.2856<br><br>• Lexical: 55.5562<br>• Title KNN: 29.2590<br>• Desc KNN: 12.5187<br>• Key KNN: 0.0000<br><br>**Keywords**:<br>• 'Machine Learning' (0.9988)<br>• 'Deep Learning' (0.9119) |
|
||||
| **Arts and Humanities**<br>`"art history"` | **Topic**: Art, Politics, and Modernism<br>**Total Score**: 79.6751<br><br>• Lexical: 41.4462<br>• Title KNN: 26.8390<br>• Desc KNN: 12.2412<br>• Key KNN: 23.1472<br><br>**Keywords**:<br>• 'Contemporary Art' (0.9259)<br>• 'Art Theory' (0.8902) | **Topic**: Art History and Market Analysis<br>**Total Score**: 54.6477<br><br>• Lexical: 44.3255<br>• Title KNN: 27.6256<br>• Desc KNN: 0.0000<br>• Key KNN: 0.0000<br><br>**Keywords**:<br>• 'Art Market' (0.8499) |
|
||||
| **Biochemistry, Genetics...**<br>`"dna replication"` | **Topic**: DNA Repair Mechanisms<br>**Total Score**: 69.5873<br><br>• Lexical: 37.9645<br>• Title KNN: 25.5676<br>• Desc KNN: 0.0000<br>• Key KNN: 21.2950<br><br>**Keywords**:<br>• 'Homologous Recombination' (0.8518) | **Topic**: DNA Repair Mechanisms<br>**Total Score**: 48.2923<br><br>• Lexical: 37.9645<br>• Title KNN: 25.5676<br>• Desc KNN: 0.0000<br>• Key KNN: 0.0000<br><br>**Keywords**:<br>• 'Homologous Recombination' (0.8518) |
|
||||
| **Agricultural Sciences**<br>`"crop yield optimization"` | **Topic**: Crop Yield and Soil Fertility<br>**Total Score**: 86.9026<br><br>• Lexical: 72.9192<br>• Title KNN: 25.6184<br>• Desc KNN: 0.0000<br>• Key KNN: 21.9673<br><br>**Keywords**:<br>• 'Crop Management' (0.8787)<br>• 'Maize Yield' (0.8515) | **Topic**: Soil Management and Crop Yield<br>**Total Score**: 65.6488<br><br>• Lexical: 58.5754<br>• Title KNN: 26.3319<br>• Desc KNN: 0.0000<br>• Key KNN: 0.0000<br><br>**Keywords**:<br>• 'No-till Crop Production' (0.8136) |
|
||||
| **Environmental Science**<br>`"climate change mitigation"` | **Topic**: Climate Change, Adaptation, Migration<br>**Total Score**: 95.6090<br><br>• Lexical: 55.1717<br>• Title KNN: 24.9003<br>• Desc KNN: 12.3419<br>• Key KNN: 23.2867<br><br>**Keywords**:<br>• 'Climate Change' (0.9315) | **Topic**: Climate Change and Sustainable Development<br>**Total Score**: 72.0562<br><br>• Lexical: 52.0331<br>• Title KNN: 27.6359<br>• Desc KNN: 12.3920<br>• Key KNN: 0.0000<br><br>**Keywords**:<br>• 'Climate Change' (0.9314)<br>• 'Environmental Policy' (0.8447) |
|
||||
| **Business & Accounting**<br>`"corporate strategy"` | **Topic**: Political Influence and Corporate Strategies<br>**Total Score**: 70.1485<br><br>• Lexical: 43.3796<br>• Title KNN: 25.4050<br>• Desc KNN: 0.0000<br>• Key KNN: 23.5512<br><br>**Keywords**:<br>• 'Business Strategy' (0.9420)<br>• 'Corporate Governance' (0.8537) | **Topic**: Corporate Management and Leadership<br>**Total Score**: 44.0634<br><br>• Lexical: 18.0385<br>• Title KNN: 26.0249<br>• Desc KNN: 0.0000<br>• Key KNN: 0.0000<br><br>**Keywords**:<br>• _None matched_ |
|
||||
| **Psychology**<br>`"cognitive behavioral therapy"` | **Topic**: Psychological Treatments and Assessments<br>**Total Score**: 74.0625<br><br>• Lexical: 33.9552<br>• Title KNN: 26.3648<br>• Desc KNN: 0.0000<br>• Key KNN: 24.8575<br><br>**Keywords**:<br>• 'Cognitive Behavioral Therapy' (0.9943)<br>• 'Rational Emotive Behavior Therapy' (0.8906) | **Topic**: Psychological Treatments and Assessments<br>**Total Score**: 74.0625<br><br>• Lexical: 33.9552<br>• Title KNN: 26.3648<br>• Desc KNN: 0.0000<br>• Key KNN: 24.8575<br><br>**Keywords**:<br>• 'Cognitive Behavioral Therapy' (0.9943)<br>• 'Rational Emotive Behavior Therapy' (0.8906) |
|
||||
| **Materials Science**<br>`"nanomaterials synthesis"` | **Topic**: Copper-based nanomaterials and applications<br>**Total Score**: 79.3170<br><br>• Lexical: 31.3198<br>• Title KNN: 25.5626<br>• Desc KNN: 12.8334<br>• Key KNN: 23.2389<br><br>**Keywords**:<br>• 'Nanostructures' (0.9296)<br>• 'Nanocrystals' (0.8989) | **Topic**: Nanoparticles: synthesis and applications<br>**Total Score**: 51.4193<br><br>• Lexical: 41.6580<br>• Title KNN: 28.1196<br>• Desc KNN: 0.0000<br>• Key KNN: 0.0000<br><br>**Keywords**:<br>• 'Nanomaterials' (0.9593)<br>• 'Nanoparticles' (0.9017) |
|
||||
| **Economics & Finance**<br>`"macroeconomic policy"` | **Topic**: Monetary Policy and Economic Impact<br>**Total Score**: 77.2466<br><br>• Lexical: 33.6052<br>• Title KNN: 27.9601<br>• Desc KNN: 12.7554<br>• Key KNN: 23.1466<br><br>**Keywords**:<br>• 'Monetary Policy' (0.9259)<br>• 'Fiscal Policy' (0.8719) | **Topic**: Monetary Policy and Economic Impact<br>**Total Score**: 54.1000<br><br>• Lexical: 33.6052<br>• Title KNN: 27.9601<br>• Desc KNN: 12.7554<br>• Key KNN: 0.0000<br><br>**Keywords**:<br>• 'Monetary Policy' (0.9259)<br>• 'Fiscal Policy' (0.8719) |
|
||||
| **Health Professions**<br>`"physical therapy techniques"` | **Topic**: Physical Activity and Health<br>**Total Score**: 63.6719<br><br>• Lexical: 35.4732<br>• Title KNN: 24.8417<br>• Desc KNN: 0.0000<br>• Key KNN: 21.5571<br><br>**Keywords**:<br>• 'Physical Fitness' (0.8623)<br>• 'Exercise' (0.8567) | **Topic**: Physical Education and Training Studies<br>**Total Score**: 41.6865<br><br>• Lexical: 34.0993<br>• Title KNN: 25.9162<br>• Desc KNN: 0.0000<br>• Key KNN: 0.0000<br><br>**Keywords**:<br>• 'Physical Education' (0.8518)<br>• 'Athletic Training' (0.8386) |
|
||||
| **Physics and Astronomy**<br>`"quantum mechanics"` | **Topic**: Quantum Mechanics and Applications<br>**Total Score**: 100.0179<br><br>• Lexical: 62.6773<br>• Title KNN: 29.4806<br>• Desc KNN: 12.8902<br>• Key KNN: 23.1009<br><br>**Keywords**:<br>• 'Quantum Interpretations' (0.9240)<br>• 'Quantum Measurement' (0.9195) | **Topic**: Quantum Mechanics and Non-Hermitian Physics<br>**Total Score**: 82.1469<br><br>• Lexical: 59.7515<br>• Title KNN: 28.2917<br>• Desc KNN: 0.0000<br>• Key KNN: 24.8390<br><br>**Keywords**:<br>• 'Quantum Mechanics' (0.9936)<br>• 'Non-Hermitian Physics' (0.8265) |
|
||||
| **Chemistry**<br>`"organic synthesis"` | **Topic**: Organic Chemistry Synthesis Methods<br>**Total Score**: 93.3478<br><br>• Lexical: 51.1392<br>• Title KNN: 28.8346<br>• Desc KNN: 12.8016<br>• Key KNN: 21.2545<br><br>**Keywords**:<br>• 'Total Synthesis' (0.8502) | **Topic**: Organic Chemistry Synthesis Methods<br>**Total Score**: 72.0932<br><br>• Lexical: 51.1392<br>• Title KNN: 28.8346<br>• Desc KNN: 12.8016<br>• Key KNN: 0.0000<br><br>**Keywords**:<br>• 'Total Synthesis' (0.8502) |
|
||||
| **Mathematics**<br>`"linear algebra"` | **Topic**: Advanced Algebra and Logic<br>**Total Score**: 69.1804<br><br>• Lexical: 21.0841<br>• Title KNN: 26.3365<br>• Desc KNN: 0.0000<br>• Key KNN: 21.7598<br><br>**Keywords**:<br>• 'MV-algebras' (0.8704)<br>• 'Algebraic Semantics' (0.8542) | **Topic**: Matrix Theory and Algorithms<br>**Total Score**: 51.1267<br><br>• Lexical: 42.7259<br>• Title KNN: 0.0000<br>• Desc KNN: 0.0000<br>• Key KNN: 24.3482<br><br>**Keywords**:<br>• 'Numerical Linear Algebra' (0.9739) |
|
||||
| **Neuroscience**<br>`"synaptic plasticity"` | **Topic**: Neuroscience and Neuropharmacology Research<br>**Total Score**: 59.8949<br><br>• Lexical: 34.7332<br>• Title KNN: 0.0000<br>• Desc KNN: 13.1294<br>• Key KNN: 24.0698<br><br>**Keywords**:<br>• 'Synaptic Plasticity' (0.9628)<br>• 'Neuronal Circuits' (0.8298) | **Topic**: Neuroscience and Neuropharmacology Research<br>**Total Score**: 59.8949<br><br>• Lexical: 34.7332<br>• Title KNN: 0.0000<br>• Desc KNN: 13.1294<br>• Key KNN: 24.0698<br><br>**Keywords**:<br>• 'Synaptic Plasticity' (0.9628)<br>• 'Neuronal Circuits' (0.8298) |
|
||||
| **Decision Sciences**<br>`"operations research optimization"` | **Topic**: Operations Management Techniques<br>**Total Score**: 72.2617<br><br>• Lexical: 45.7187<br>• Title KNN: 25.8359<br>• Desc KNN: 0.0000<br>• Key KNN: 20.3829<br><br>**Keywords**:<br>• 'Operations Management' (0.8153) | **Topic**: Management and Optimization Techniques<br>**Total Score**: 67.5272<br><br>• Lexical: 38.2684<br>• Title KNN: 27.0016<br>• Desc KNN: 0.0000<br>• Key KNN: 22.7133<br><br>**Keywords**:<br>• 'Operations Research' (0.9085) |
|
||||
| **Earth Sciences**<br>`"plate tectonics geology"` | **Topic**: Geological and Geochemical Analysis<br>**Total Score**: 81.4082<br><br>• Lexical: 47.1954<br>• Title KNN: 24.9384<br>• Desc KNN: 0.0000<br>• Key KNN: 24.0854<br><br>**Keywords**:<br>• 'Plate Tectonics' (0.9634)<br>• 'Tectonics' (0.9412) | **Topic**: Geological and Geophysical Studies<br>**Total Score**: 76.8806<br><br>• Lexical: 33.5170<br>• Title KNN: 25.9864<br>• Desc KNN: 0.0000<br>• Key KNN: 24.0846<br><br>**Keywords**:<br>• 'Plate Tectonics' (0.9634)<br>• 'Tectonic Model' (0.8970) |
|
||||
| **Immunology & Micro.**<br>`"t cell activation"` | **Topic**: T-cell and B-cell Immunology<br>**Total Score**: 101.7294<br><br>• Lexical: 58.5911<br>• Title KNN: 26.2074<br>• Desc KNN: 12.7561<br>• Key KNN: 22.2172<br><br>**Keywords**:<br>• 'Memory T Cells' (0.8887)<br>• 'TGF-ß' (0.8379) | **Topic**: T-cell and B-cell Immunology<br>**Total Score**: 79.5122<br><br>• Lexical: 58.5911<br>• Title KNN: 26.2074<br>• Desc KNN: 12.7561<br>• Key KNN: 0.0000<br><br>**Keywords**:<br>• 'Memory T Cells' (0.8887)<br>• 'TGF-ß' (0.8379) |
|
||||
| **Energy**<br>`"solar cell efficiency"` | **Topic**: solar cell performance optimization<br>**Total Score**: 100.7331<br><br>• Lexical: 69.7479<br>• Title KNN: 28.9188<br>• Desc KNN: 12.4518<br>• Key KNN: 21.6075<br><br>**Keywords**:<br>• 'Energy Conversion Efficiency' (0.8643)<br>• 'Multijunction Solar Cells' (0.8636) | **Topic**: solar cell performance optimization<br>**Total Score**: 79.1256<br><br>• Lexical: 69.7479<br>• Title KNN: 28.9188<br>• Desc KNN: 12.4518<br>• Key KNN: 0.0000<br><br>**Keywords**:<br>• 'Energy Conversion Efficiency' (0.8643)<br>• 'Multijunction Solar Cells' (0.8636) |
|
||||
| **Pharmacology & Tox.**<br>`"drug delivery systems"` | **Topic**: Advanced Drug Delivery Systems<br>**Total Score**: 101.0864<br><br>• Lexical: 82.7073<br>• Title KNN: 29.0884<br>• Desc KNN: 0.0000<br>• Key KNN: 23.9235<br><br>**Keywords**:<br>• 'Drug Delivery' (0.9569) | **Topic**: Advanced Drug Delivery Systems<br>**Total Score**: 77.1629<br><br>• Lexical: 82.7073<br>• Title KNN: 29.0884<br>• Desc KNN: 0.0000<br>• Key KNN: 0.0000<br><br>**Keywords**:<br>• 'Drug Delivery' (0.9569) |
|
||||
| **Nursing**<br>`"patient care management"` | **Topic**: Family and Patient Care in ICU<br>**Total Score**: 81.2835<br><br>• Lexical: 62.5713<br>• Title KNN: 25.2221<br>• Desc KNN: 0.0000<br>• Key KNN: 23.3629<br><br>**Keywords**:<br>• 'Patient-Centered Care' (0.9345)<br>• 'Critical Care' (0.8654) | **Topic**: Health Services Management and Policy<br>**Total Score**: 49.0703<br><br>• Lexical: 44.9180<br>• Title KNN: 0.0000<br>• Desc KNN: 0.0000<br>• Key KNN: 24.1204<br><br>**Keywords**:<br>• 'patient care' (0.9648)<br>• 'hospital management' (0.9044) |
|
||||
| **Chemical Engineering**<br>`"process systems engineering"` | **Topic**: Systems Engineering Methodologies<br>**Total Score**: 69.4196<br><br>• Lexical: 46.7857<br>• Title KNN: 27.1586<br>• Desc KNN: 0.0000<br>• Key KNN: 21.4144<br><br>**Keywords**:<br>• 'Interdisciplinary System Eng.' (0.8566)<br>• 'Model-Based Systems Eng.' (0.8462) | **Topic**: Control Systems in Engineering<br>**Total Score**: 48.0307<br><br>• Lexical: 30.2824<br>• Title KNN: 25.1976<br>• Desc KNN: 0.0000<br>• Key KNN: 0.0000<br><br>**Keywords**:<br>• _None matched_ |
|
||||
| **Dentistry**<br>`"endodontic treatment procedures"` | **Topic**: Endodontics and Root Canal Treatments<br>**Total Score**: 85.0595<br><br>• Lexical: 33.2248<br>• Title KNN: 27.3373<br>• Desc KNN: 12.9073<br>• Key KNN: 24.7433<br><br>**Keywords**:<br>• 'Endodontic Treatment' (0.9897)<br>• 'Regenerative Endodontics' (0.9185) | **Topic**: Endodontics and Root Canal Treatments<br>**Total Score**: 85.0595<br><br>• Lexical: 33.2248<br>• Title KNN: 27.3373<br>• Desc KNN: 12.9073<br>• Key KNN: 24.7433<br><br>**Keywords**:<br>• 'Endodontic Treatment' (0.9897)<br>• 'Regenerative Endodontics' (0.9185) |
|
||||
| **Veterinary**<br>`"veterinary medicine diagnosis"` | **Topic**: Animal health and immunology<br>**Total Score**: 70.5398<br><br>• Lexical: 36.6445<br>• Title KNN: 24.4738<br>• Desc KNN: 0.0000<br>• Key KNN: 24.6649<br><br>**Keywords**:<br>• 'Veterinary Diagnosis' (0.9866) | **Topic**: Veterinary Medicine and Surgery<br>**Total Score**: 63.5579<br><br>• Lexical: 36.3745<br>• Title KNN: 27.1833<br>• Desc KNN: 0.0000<br>• Key KNN: 0.0000<br><br>**Keywords**:<br>• _None matched_ |
|
||||
+31375
File diff suppressed because it is too large
Load Diff
+28540
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,64 @@
|
||||
# Approach
|
||||
|
||||
**NDCG@10**, **MRR@10**, **Recall@10** :
|
||||
|
||||
- Topic: Document
|
||||
- OpenAlex: "display_name": "Impact of Light on Environment and Health",
|
||||
- Keyword: Query
|
||||
- OpenAlex: "keywords": [
|
||||
"Nighttime Light Data",
|
||||
"Economic Growth",
|
||||
"Light Pollution",
|
||||
"Remote Sensing",
|
||||
"Population Mapping",
|
||||
"Urbanization Dynamics",
|
||||
"Artificial Light",
|
||||
"Satellite Imagery",
|
||||
"Poverty Prediction",
|
||||
"Ecological Impacts" ]
|
||||
|
||||
Each Keyword is searched in the Topic display name Vector space
|
||||
|
||||
# Overall Leaderboard
|
||||
|
||||
> **Note** First round is invalid
|
||||
|
||||
First round (all topics, but included sibling topics messed up metrics)
|
||||
| Rank | Model Name | Vector Dim | Params (M) | Query Latency (ms) | Throughput (docs/s) | NDCG@10 | MRR@10 | Recall@10 | Subfield NMI |
|
||||
| :--- | :--- | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: |
|
||||
| 1 | `intfloat/e5-large-v2` | 1024 | 335.1M | 96.63ms | 5.7 | **0.2304** | 0.5054 | 0.0691 | 0.5917 |
|
||||
| 2 | `BAAI/bge-large-en-v1.5` | 1024 | 335.1M | 96.24ms | 5.8 | **0.2292** | 0.4944 | 0.0691 | 0.5921 |
|
||||
| 3 | `intfloat/multilingual-e5-large` | 1024 | 559.9M | 104.13ms | 4.8 | **0.2131** | 0.4789 | 0.0636 | 0.5900 |
|
||||
| 4 | `google/embeddinggemma-300m` | 768 | 307.6M | 47.11ms | 14.0 | **0.2121** | 0.4479 | 0.0637 | 0.6054 |
|
||||
| 5 | `intfloat/multilingual-e5-base` | 768 | 278.0M | 29.11ms | 16.3 | **0.2100** | 0.4641 | 0.0620 | 0.5919 |
|
||||
| 6 | `intfloat/multilingual-e5-small` | 384 | 117.7M | 12.15ms | 55.3 | **0.2021** | 0.4446 | 0.0594 | 0.5880 |
|
||||
| 7 | `BAAI/bge-m3` | 1024 | 567.8M | 96.92ms | 4.8 | **0.1879** | 0.4219 | 0.0544 | 0.5929 |
|
||||
| 8 | `paraphrase-multilingual-mpnet-base-v2` | 768 | 278.0M | 29.65ms | 17.0 | **0.1792** | 0.3565 | 0.0520 | 0.6010 |
|
||||
| 9 | `sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2` | 384 | 117.7M | 12.12ms | 58.1 | **0.1748** | 0.3494 | 0.0514 | 0.5940 |
|
||||
|
||||
Second adjusted round (500 topics sample size)(seperated clustering into name and description fields)
|
||||
| Rank | Model Name | Vector Dim | Params (M) | Query Latency (ms) | Throughput (docs/s) | NDCG@10 | MRR@10 | Recall@10 | Name NMI | Desc NMI |
|
||||
| :--- | :--- | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: |
|
||||
| 1 | `intfloat/e5-large-v2` | 1024 | 335.1M | 101.71ms | 5.6 | **0.4261** | 0.3797 | 0.5758 | 0.5254 | 0.5947 |
|
||||
| 2 | `BAAI/bge-large-en-v1.5` | 1024 | 335.1M | 98.38ms | 5.6 | **0.4084** | 0.3628 | 0.5546 | 0.5591 | 0.5961 |
|
||||
| 3 | `intfloat/multilingual-e5-large` | 1024 | 559.9M | 111.27ms | 4.8 | **0.3956** | 0.3501 | 0.5424 | 0.5171 | 0.5845 |
|
||||
| 4 | `intfloat/multilingual-e5-base` | 768 | 278.0M | 28.86ms | 17.9 | **0.3807** | 0.3357 | 0.5256 | 0.5374 | 0.5851 |
|
||||
| 5 | `google/embeddinggemma-300m` | 768 | 307.6M | 45.55ms | 15.7 | **0.3558** | 0.3121 | 0.4976 | 0.5485 | 0.6148 |
|
||||
| 6 | `intfloat/multilingual-e5-small` | 384 | 117.7M | 11.74ms | 57.6 | **0.3531** | 0.3050 | 0.5078 | 0.5450 | 0.5914 |
|
||||
| 7 | `sentence-transformers/all-MiniLM-L6-v2` | 384 | 22.7M | 7.07ms | 117.0 | **0.3471** | 0.3034 | 0.4882 | 0.5636 | 0.5936 |
|
||||
| 8 | `BAAI/bge-m3` | 1024 | 567.8M | 96.19ms | 4.9 | **0.3221** | 0.2829 | 0.4484 | 0.5246 | 0.5885 |
|
||||
| 9 | `sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2` | 384 | 117.7M | 12.63ms | 58.0 | **0.2350** | 0.2005 | 0.3468 | 0.5544 | 0.5984 |
|
||||
| 10 | `paraphrase-multilingual-mpnet-base-v2` | 768 | 278.0M | 24.67ms | 22.2 | **0.2347** | 0.1999 | 0.3480 | 0.5638 | 0.6043 |
|
||||
Baseline with all topics for second round:
|
||||
| Rank | Model Name | Vector Dim | Params (M) | Query Latency (ms) | Throughput (docs/s) | NDCG@10 | MRR@10 | Recall@10 | Name NMI | Desc NMI |
|
||||
| 1 | `intfloat/multilingual-e5-base` | 768 | 278.0M | 32.83ms | 16.5 | **0.3751** | 0.3290 | 0.5234 | 0.5374 | 0.5851 |
|
||||
|
||||
## Metric Definitions:
|
||||
|
||||
- **NDCG@10**: Normalized Discounted Cumulative Gain. Measures how well the query maps to the target topic at the top 10 positions.
|
||||
- **MRR@10**: Mean Reciprocal Rank. Looks at the average of `1 / rank` for the first correctly matched topic.
|
||||
- **Recall@10**: Percentage of times the target document (excluding sibling topics) was successfully retrieved in the top 10.
|
||||
- **Name NMI**: Normalized Mutual Information of K-Means clusters of topic display names against ground truth OpenAlex subfields.
|
||||
- **Desc NMI**: Normalized Mutual Information of K-Means clusters of topic descriptions against ground truth OpenAlex subfields.
|
||||
- **Query Latency**: Time to encode a single search keyword.
|
||||
- **Throughput**: Ingestion batch encoding speed.
|
||||
@@ -66,6 +66,10 @@ class ESIndex(StrEnum):
|
||||
DFG_INSTITUTES_V2 = "dfg_institutes_2.0"
|
||||
PROJECTS_DFG_OPENALEX_TOPICS = "projects_dfg_openalex_topics"
|
||||
|
||||
AKTUELLES = "aktuell"
|
||||
AKTUELLES_POSTPROC = "aktuell_postproc"
|
||||
|
||||
|
||||
CORDIS_EU_ORGANIZATIONS_WILDCARD = "cordis_eu_*_organizations"
|
||||
CORDIS_EU_PROJECTS_WILDCARD = "cordis_eu_*_projects"
|
||||
CORDIS_EU_PUBLICATIONS_WILDCARD = "cordis_eu_*_publications"
|
||||
|
||||
@@ -157,6 +157,19 @@ async def test_get_top_topics_for_entity():
|
||||
assert "items" in res
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_get_top_topics_for_entity_projects():
|
||||
res = await get_top_topics_for_entity(
|
||||
entity_id="https://openalex.org/I62318514",
|
||||
entity_type="institution",
|
||||
start_year=2018,
|
||||
end_year=2022,
|
||||
search_type="projects",
|
||||
)
|
||||
assert isinstance(res, dict)
|
||||
assert "items" in res
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_get_trend_data_delegation():
|
||||
res = await get_trend_data(
|
||||
@@ -165,3 +178,4 @@ async def test_get_trend_data_delegation():
|
||||
)
|
||||
assert res is not None
|
||||
assert len(res.series) > 0
|
||||
|
||||
|
||||
@@ -256,9 +256,6 @@ async def get_top_topics_for_entity(
|
||||
|
||||
if search_type == "projects":
|
||||
try:
|
||||
from inse.patents.search_client import PatentSearchClient
|
||||
patent_client = PatentSearchClient()
|
||||
|
||||
short_id = clean_inst_id(entity_id)
|
||||
full_id = to_full_inst_url(entity_id)
|
||||
|
||||
@@ -296,16 +293,11 @@ async def get_top_topics_for_entity(
|
||||
|
||||
project_ids_by_index: Dict[str, List[str]] = {}
|
||||
|
||||
# 1. BUND - use scan to retrieve all project IDs without 10k limits
|
||||
# 1. BUND - filter by institution/country and date range
|
||||
if include_german:
|
||||
bund_filters = []
|
||||
bund_filters = [TrendQueryBuilder.build_date_range_filter("funding_start", start_year, end_year)]
|
||||
if entity_type == "institution":
|
||||
bund_filters.append({
|
||||
"bool": {
|
||||
"should": [{"match": {"Zuwendungsempfänger": {"query": alias, "operator": "and"}}} for alias in aliases],
|
||||
"minimum_should_match": 1,
|
||||
}
|
||||
})
|
||||
bund_filters.append(TrendQueryBuilder.build_bund_receiver_clause(aliases))
|
||||
try:
|
||||
p_ids = []
|
||||
async for hit in elasticsearch.scan(
|
||||
@@ -321,7 +313,7 @@ async def get_top_topics_for_entity(
|
||||
except Exception as e:
|
||||
logger.warning("Failed to fetch BUND project IDs in get_top_topics_for_entity: %s", e)
|
||||
|
||||
# 2. DFG - scan institutes & projects
|
||||
# 2. DFG - filter by institute projects and date range
|
||||
if include_german:
|
||||
try:
|
||||
dfg_pids = []
|
||||
@@ -338,7 +330,7 @@ async def get_top_topics_for_entity(
|
||||
dfg_pids.append(str(p["project_id"]))
|
||||
|
||||
if dfg_pids or entity_type != "institution":
|
||||
dfg_filters = []
|
||||
dfg_filters = [TrendQueryBuilder.build_date_range_filter("funding_start", start_year, end_year)]
|
||||
if dfg_pids:
|
||||
dfg_filters.append({"ids": {"values": dfg_pids}})
|
||||
|
||||
@@ -357,7 +349,7 @@ async def get_top_topics_for_entity(
|
||||
except Exception as e:
|
||||
logger.warning("Failed to fetch DFG project IDs in get_top_topics_for_entity: %s", e)
|
||||
|
||||
# 3. EU CORDIS
|
||||
# 3. EU CORDIS - filter orgs and verify project start dates
|
||||
eu_indices = [
|
||||
(ESIndex.CORDIS_EU_HORIZON_EUROPE_ORGANIZATIONS, ESIndex.CORDIS_EU_HORIZON_EUROPE_PROJECTS, ESIndex.PROJECTS_CORDIS_EU_HEUROPE_TOPICS.value),
|
||||
(ESIndex.CORDIS_EU_HORIZON_2020_ORGANIZATIONS, ESIndex.CORDIS_EU_HORIZON_2020_PROJECTS, ESIndex.PROJECTS_CORDIS_EU_H2020_TOPICS.value),
|
||||
@@ -371,18 +363,35 @@ async def get_top_topics_for_entity(
|
||||
elif entity_type == "country":
|
||||
filter_clauses.append({"term": {"country": entity_id.strip().upper()}})
|
||||
|
||||
eu_org_res = await patent_client._search(
|
||||
eu_org_res = await elasticsearch.search(
|
||||
index=org_idx.value,
|
||||
payload={
|
||||
body={
|
||||
"query": {"bool": {"filter": filter_clauses}},
|
||||
"size": 0,
|
||||
"_source": False,
|
||||
"aggs": {"project_ids": {"terms": {"field": "projectID", "size": 65536}}},
|
||||
},
|
||||
cluster=ESCluster.INSE,
|
||||
)
|
||||
eu_pids = [b["key"] for b in eu_org_res.get("aggregations", {}).get("project_ids", {}).get("buckets", [])]
|
||||
if eu_pids:
|
||||
project_ids_by_index[topic_idx] = eu_pids
|
||||
raw_eu_pids = [b["key"] for b in eu_org_res.get("aggregations", {}).get("project_ids", {}).get("buckets", [])]
|
||||
if raw_eu_pids:
|
||||
# Filter project IDs by start date range
|
||||
dated_eu_pids = []
|
||||
proj_date_filter = [
|
||||
{"terms": {"id": raw_eu_pids}},
|
||||
TrendQueryBuilder.build_date_range_filter("startDate", start_year, end_year),
|
||||
]
|
||||
async for hit in elasticsearch.scan(
|
||||
index=proj_idx.value,
|
||||
query={"bool": {"filter": proj_date_filter}},
|
||||
source=["id"],
|
||||
cluster=ESCluster.INSE,
|
||||
):
|
||||
pid = hit.get("_source", {}).get("id") or hit.get("_id")
|
||||
if pid:
|
||||
dated_eu_pids.append(str(pid))
|
||||
if dated_eu_pids:
|
||||
project_ids_by_index[topic_idx] = dated_eu_pids
|
||||
except Exception as e:
|
||||
logger.warning("Failed to fetch EU project IDs for %s: %s", org_idx.value, e)
|
||||
|
||||
@@ -448,7 +457,7 @@ async def get_top_topics_for_entity(
|
||||
if search_type == "news":
|
||||
try:
|
||||
res = await elasticsearch.search(
|
||||
index="aktuell_postproc",
|
||||
index=ESIndex.AKTUELLES_POSTPROC.value,
|
||||
body={
|
||||
"query": {"match_all": {}},
|
||||
"size": 0,
|
||||
|
||||
@@ -146,7 +146,7 @@ class TrendMetadataResolver:
|
||||
return topic_ids
|
||||
try:
|
||||
res = await elasticsearch.search(
|
||||
index="openalex-topics",
|
||||
index=ESIndex.OPENALEX_TOPICS.value,
|
||||
query={"bool": {"should": [{"match_phrase": {"display_name": t}} for t in topic_names]}},
|
||||
size=len(topic_names) * 2,
|
||||
source=["id", "display_name"],
|
||||
@@ -305,3 +305,90 @@ class TrendQueryBuilder:
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
def build_bund_keyword_query(keyword: str) -> Dict[str, Any]:
|
||||
"""Builds keyword filter clause for BUND projects."""
|
||||
return {
|
||||
"bool": {
|
||||
"should": [{"match": {field: keyword}} for field in BUND_PROJECT_TEXT_FIELDS],
|
||||
"minimum_should_match": 1,
|
||||
}
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
def build_dfg_keyword_query(keyword: str) -> Dict[str, Any]:
|
||||
"""Builds keyword filter clause for DFG projects."""
|
||||
return {
|
||||
"bool": {
|
||||
"should": [
|
||||
{"match": {field: keyword}} for field in DFG_PROJECT_TEXT_FIELDS
|
||||
] + [
|
||||
{"nested": {"path": "publications", "query": {"match": {"publications.title": keyword}}}},
|
||||
{
|
||||
"nested": {
|
||||
"path": "subject_classification",
|
||||
"query": {
|
||||
"bool": {
|
||||
"should": [
|
||||
{"match": {"subject_classification.fach": keyword}},
|
||||
{"match": {"subject_classification.fachkollegium": keyword}},
|
||||
{"match": {"subject_classification.wissenschaftsbereich": keyword}},
|
||||
],
|
||||
"minimum_should_match": 1,
|
||||
}
|
||||
},
|
||||
}
|
||||
},
|
||||
],
|
||||
"minimum_should_match": 1,
|
||||
}
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
def build_cordis_keyword_query(keyword: str) -> Dict[str, Any]:
|
||||
"""Builds keyword filter clause for EU CORDIS projects."""
|
||||
return {
|
||||
"bool": {
|
||||
"should": [{"match": {field: keyword}} for field in CORDIS_PROJECT_TEXT_FIELDS],
|
||||
"minimum_should_match": 1,
|
||||
}
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
def build_bund_receiver_clause(aliases: List[str]) -> Dict[str, Any]:
|
||||
"""Builds Zuwendungsempfänger matching clause for BUND projects."""
|
||||
return {
|
||||
"bool": {
|
||||
"should": [
|
||||
{"match": {BUND_RECEIVER_FIELD: {"query": alias, "operator": "and"}}}
|
||||
for alias in aliases
|
||||
],
|
||||
"minimum_should_match": 1,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
BUND_RECEIVER_FIELD = "Zuwendungsempfänger"
|
||||
BUND_PROJECT_TEXT_FIELDS = [
|
||||
"Thema",
|
||||
"Klartext Leistungsplansystematik",
|
||||
"Förderprofil",
|
||||
"Leistungsplansystematik_fullname",
|
||||
]
|
||||
|
||||
DFG_PROJECT_TEXT_FIELDS = [
|
||||
"title_de",
|
||||
"title_en",
|
||||
"description",
|
||||
"subject_area_de",
|
||||
"subject_area_en",
|
||||
"abstract_de",
|
||||
"abstract_en",
|
||||
"final_report_abstract_de",
|
||||
"final_report_abstract_en",
|
||||
]
|
||||
|
||||
CORDIS_PROJECT_TEXT_FIELDS = ["title", "objective"]
|
||||
AKTUELLES_SEARCH_FIELDS = ["main_content", "full_content", "maintitle", "subtitle", "intro_content"]
|
||||
|
||||
|
||||
@@ -16,6 +16,7 @@ from .model import (
|
||||
from .trend_query_builder import (
|
||||
DEFAULT_INSTITUTION_ID,
|
||||
DEFAULT_INSTITUTION_NAME,
|
||||
AKTUELLES_SEARCH_FIELDS,
|
||||
TrendMetadataResolver,
|
||||
TrendQueryBuilder,
|
||||
clean_inst_id,
|
||||
@@ -573,8 +574,8 @@ class PatentsTrendStrategy(TrendStrategy):
|
||||
"aggs": {"by_year": {"terms": {"field": "date_publication_year", "size": 100}}},
|
||||
}
|
||||
|
||||
msearch_queries.append(("uspto_patents_3.0", uspto_query))
|
||||
msearch_queries.append(("epo_index_1.0", epo_query))
|
||||
msearch_queries.append((ESIndex.USPTO_INDEX.value, uspto_query))
|
||||
msearch_queries.append((ESIndex.EPO_INDEX.value, epo_query))
|
||||
topic_search_indices.append(t)
|
||||
|
||||
if msearch_queries:
|
||||
@@ -693,9 +694,6 @@ class ProjectsTrendStrategy(TrendStrategy):
|
||||
if not filters_map:
|
||||
return TrendResponse(series=[], years=years_range, location_mappings=location_mappings)
|
||||
|
||||
from inse.patents.search_client import PatentSearchClient
|
||||
patent_client = PatentSearchClient()
|
||||
|
||||
# Resolve DFG project IDs for institutions via scan/search without size limit cutoffs
|
||||
dfg_institution_projects: Dict[str, List[str]] = {}
|
||||
|
||||
@@ -775,7 +773,29 @@ class ProjectsTrendStrategy(TrendStrategy):
|
||||
for key in filters_map
|
||||
}
|
||||
|
||||
async def query_project_trends(entity_key: str, entity_type: str, entity_val: Any, topic: str, keyword: str):
|
||||
# Batch all project queries into single msearch request
|
||||
msearch_queries = []
|
||||
meta_indices: List[Tuple[str, str, str]] = [] # (entity_key, topic, agg_type)
|
||||
|
||||
async def prepare_project_trend_queries(entity_key: str, entity_type: str, entity_val: Any, topic: str, keyword: str):
|
||||
eu_indices = [
|
||||
(
|
||||
ESIndex.CORDIS_EU_HORIZON_EUROPE_ORGANIZATIONS,
|
||||
ESIndex.CORDIS_EU_HORIZON_EUROPE_PROJECTS,
|
||||
ESIndex.PROJECTS_CORDIS_EU_HEUROPE_TOPICS.value,
|
||||
),
|
||||
(
|
||||
ESIndex.CORDIS_EU_HORIZON_2020_ORGANIZATIONS,
|
||||
ESIndex.CORDIS_EU_HORIZON_2020_PROJECTS,
|
||||
ESIndex.PROJECTS_CORDIS_EU_H2020_TOPICS.value,
|
||||
),
|
||||
(
|
||||
ESIndex.CORDIS_EU_FP7_ORGANIZATIONS,
|
||||
ESIndex.CORDIS_EU_FP7_PROJECTS,
|
||||
ESIndex.PROJECTS_CORDIS_EU_FP7_TOPICS_MAPPING.value,
|
||||
),
|
||||
]
|
||||
|
||||
async def get_eu_entity_project_ids(org_index: ESIndex) -> List[str]:
|
||||
filter_clauses = []
|
||||
if entity_type == "institution":
|
||||
@@ -787,14 +807,15 @@ class ProjectsTrendStrategy(TrendStrategy):
|
||||
filter_clauses.append({"terms": {"country": entity_val}})
|
||||
|
||||
try:
|
||||
res = await patent_client._search(
|
||||
res = await elasticsearch.search(
|
||||
index=org_index.value,
|
||||
payload={
|
||||
body={
|
||||
"query": {"bool": {"filter": filter_clauses}},
|
||||
"size": 0,
|
||||
"_source": False,
|
||||
"aggs": {"project_ids": {"terms": {"field": "projectID", "size": 65536}}},
|
||||
},
|
||||
cluster=ESCluster.INSE,
|
||||
)
|
||||
buckets = res.get("aggregations", {}).get("project_ids", {}).get("buckets", [])
|
||||
return [b["key"] for b in buckets]
|
||||
@@ -802,26 +823,7 @@ class ProjectsTrendStrategy(TrendStrategy):
|
||||
logger.warning("Failed to query CORDIS orgs index %s: %s", org_index.value, e)
|
||||
return []
|
||||
|
||||
eu_indices = [
|
||||
(
|
||||
ESIndex.CORDIS_EU_HORIZON_EUROPE_ORGANIZATIONS,
|
||||
ESIndex.CORDIS_EU_HORIZON_EUROPE_PROJECTS,
|
||||
"projects_cordiseu_heurope_openalex_topics",
|
||||
),
|
||||
(
|
||||
ESIndex.CORDIS_EU_HORIZON_2020_ORGANIZATIONS,
|
||||
ESIndex.CORDIS_EU_HORIZON_2020_PROJECTS,
|
||||
"projects_cordiseu_h2020_openalex_topics",
|
||||
),
|
||||
(
|
||||
ESIndex.CORDIS_EU_FP7_ORGANIZATIONS,
|
||||
ESIndex.CORDIS_EU_FP7_PROJECTS,
|
||||
"projects_cordiseu_fp7_openalex_topics",
|
||||
),
|
||||
]
|
||||
|
||||
eu_org_ids_list = await asyncio.gather(*(get_eu_entity_project_ids(org_idx) for org_idx, _, _ in eu_indices))
|
||||
actual_tasks = []
|
||||
|
||||
# BUND
|
||||
include_bund = True
|
||||
@@ -834,15 +836,10 @@ class ProjectsTrendStrategy(TrendStrategy):
|
||||
bund_filters = []
|
||||
if entity_type == "institution":
|
||||
aliases = resolved_aliases.get(entity_val, [])
|
||||
bund_filters.append({
|
||||
"bool": {
|
||||
"should": [{"match": {"Zuwendungsempfänger": {"query": alias, "operator": "and"}}} for alias in aliases],
|
||||
"minimum_should_match": 1,
|
||||
}
|
||||
})
|
||||
bund_filters.append(TrendQueryBuilder.build_bund_receiver_clause(aliases))
|
||||
|
||||
if fuzzy:
|
||||
p_ids = topic_project_ids[topic].get("projects_bund_openalex_topics", [])
|
||||
p_ids = topic_project_ids[topic].get(ESIndex.PROJECTS_BUND_TOPICS.value, [])
|
||||
if p_ids:
|
||||
bund_filters.append({"ids": {"values": p_ids}})
|
||||
bund_query = {"query": {"bool": {"filter": bund_filters}}}
|
||||
@@ -852,19 +849,7 @@ class ProjectsTrendStrategy(TrendStrategy):
|
||||
bund_query = {
|
||||
"query": {
|
||||
"bool": {
|
||||
"filter": [
|
||||
{
|
||||
"bool": {
|
||||
"should": [
|
||||
{"match": {"Thema": keyword}},
|
||||
{"match": {"Klartext Leistungsplansystematik": keyword}},
|
||||
{"match": {"Förderprofil": keyword}},
|
||||
{"match": {"Leistungsplansystematik_fullname": keyword}},
|
||||
],
|
||||
"minimum_should_match": 1,
|
||||
}
|
||||
}
|
||||
] + bund_filters
|
||||
"filter": [TrendQueryBuilder.build_bund_keyword_query(keyword)] + bund_filters
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -884,16 +869,8 @@ class ProjectsTrendStrategy(TrendStrategy):
|
||||
}
|
||||
},
|
||||
}
|
||||
|
||||
async def process_bund():
|
||||
try:
|
||||
res = await patent_client._search(index=ESIndex.PROJECTS_BUND_V1.value, payload=bund_payload)
|
||||
return "date", res.get("aggregations", {}).get("projects_by_year", {}).get("buckets", [])
|
||||
except Exception as e:
|
||||
logger.warning("Failed to query BUND projects: %s", e)
|
||||
return "date", []
|
||||
|
||||
actual_tasks.append(process_bund())
|
||||
msearch_queries.append((ESIndex.PROJECTS_BUND_V1.value, bund_payload))
|
||||
meta_indices.append((entity_key, topic, "date"))
|
||||
|
||||
# DFG
|
||||
include_dfg = True
|
||||
@@ -927,39 +904,7 @@ class ProjectsTrendStrategy(TrendStrategy):
|
||||
else:
|
||||
if dfg_inst_pids is not None:
|
||||
dfg_filters.append({"ids": {"values": dfg_inst_pids}})
|
||||
|
||||
dfg_filters.append({
|
||||
"bool": {
|
||||
"should": [
|
||||
{"match": {"title_de": keyword}},
|
||||
{"match": {"title_en": keyword}},
|
||||
{"match": {"description": keyword}},
|
||||
{"match": {"subject_area_de": keyword}},
|
||||
{"match": {"subject_area_en": keyword}},
|
||||
{"match": {"abstract_de": keyword}},
|
||||
{"match": {"abstract_en": keyword}},
|
||||
{"match": {"final_report_abstract_de": keyword}},
|
||||
{"match": {"final_report_abstract_en": keyword}},
|
||||
{"nested": {"path": "publications", "query": {"match": {"publications.title": keyword}}}},
|
||||
{
|
||||
"nested": {
|
||||
"path": "subject_classification",
|
||||
"query": {
|
||||
"bool": {
|
||||
"should": [
|
||||
{"match": {"subject_classification.fach": keyword}},
|
||||
{"match": {"subject_classification.fachkollegium": keyword}},
|
||||
{"match": {"subject_classification.wissenschaftsbereich": keyword}},
|
||||
],
|
||||
"minimum_should_match": 1,
|
||||
}
|
||||
},
|
||||
}
|
||||
},
|
||||
],
|
||||
"minimum_should_match": 1,
|
||||
}
|
||||
})
|
||||
dfg_filters.append(TrendQueryBuilder.build_dfg_keyword_query(keyword))
|
||||
|
||||
if include_dfg:
|
||||
dfg_payload = {
|
||||
@@ -968,18 +913,10 @@ class ProjectsTrendStrategy(TrendStrategy):
|
||||
"_source": False,
|
||||
"aggs": {"projects_by_year": {"terms": {"field": "funding_start", "size": 100}}},
|
||||
}
|
||||
msearch_queries.append((ESIndex.DFG_PROJECTS.value, dfg_payload))
|
||||
meta_indices.append((entity_key, topic, "terms"))
|
||||
|
||||
async def process_dfg():
|
||||
try:
|
||||
res = await patent_client._search(index=ESIndex.DFG_PROJECTS.value, payload=dfg_payload)
|
||||
return "terms", res.get("aggregations", {}).get("projects_by_year", {}).get("buckets", [])
|
||||
except Exception as e:
|
||||
logger.warning("Failed to query DFG projects: %s", e)
|
||||
return "terms", []
|
||||
|
||||
actual_tasks.append(process_dfg())
|
||||
|
||||
# EU Cordis
|
||||
# EU CORDIS
|
||||
for eu_idx, (org_index, proj_index, mapping_key) in enumerate(eu_indices):
|
||||
entity_project_ids = eu_org_ids_list[eu_idx]
|
||||
if not entity_project_ids:
|
||||
@@ -998,12 +935,7 @@ class ProjectsTrendStrategy(TrendStrategy):
|
||||
"bool": {
|
||||
"filter": [
|
||||
{"terms": {"id": entity_project_ids}},
|
||||
{
|
||||
"bool": {
|
||||
"should": [{"match": {"title": keyword}}, {"match": {"objective": keyword}}],
|
||||
"minimum_should_match": 1,
|
||||
}
|
||||
},
|
||||
TrendQueryBuilder.build_cordis_keyword_query(keyword),
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -1024,53 +956,46 @@ class ProjectsTrendStrategy(TrendStrategy):
|
||||
}
|
||||
},
|
||||
}
|
||||
msearch_queries.append((proj_index.value, proj_payload))
|
||||
meta_indices.append((entity_key, topic, "date"))
|
||||
|
||||
async def process_cordis(p_idx=proj_index, payload=proj_payload):
|
||||
try:
|
||||
res = await patent_client._search(index=p_idx.value, payload=payload)
|
||||
return "date", res.get("aggregations", {}).get("projects_by_year", {}).get("buckets", [])
|
||||
except Exception as e:
|
||||
logger.warning("Failed to query CORDIS projects index %s: %s", p_idx.value, e)
|
||||
return "date", []
|
||||
|
||||
actual_tasks.append(process_cordis())
|
||||
|
||||
if not actual_tasks:
|
||||
return
|
||||
|
||||
results = await asyncio.gather(*actual_tasks)
|
||||
year_counts: Dict[int, int] = {}
|
||||
for agg_type, buckets in results:
|
||||
for b in buckets:
|
||||
if agg_type == "date":
|
||||
yr_str = b.get("key_as_string") or str(b.get("key", ""))
|
||||
if yr_str:
|
||||
try:
|
||||
yr = int(yr_str[:4])
|
||||
if start_year <= yr <= end_year:
|
||||
year_counts[yr] = year_counts.get(yr, 0) + b.get("doc_count", 0)
|
||||
except ValueError:
|
||||
pass
|
||||
else:
|
||||
yr_val = b.get("key")
|
||||
if yr_val is not None:
|
||||
try:
|
||||
yr = int(str(yr_val)[:4])
|
||||
if start_year <= yr <= end_year:
|
||||
year_counts[yr] = year_counts.get(yr, 0) + b.get("doc_count", 0)
|
||||
except ValueError:
|
||||
pass
|
||||
|
||||
for yr, count in year_counts.items():
|
||||
accumulated_data[entity_key][topic][yr] = (count, 1)
|
||||
|
||||
tasks = []
|
||||
prep_tasks = []
|
||||
for entity_key, (entity_type, entity_val) in filters_map.items():
|
||||
for idx, topic in enumerate(topics):
|
||||
keyword = keywords[idx] if (keywords and idx < len(keywords)) else topic
|
||||
tasks.append(query_project_trends(entity_key, entity_type, entity_val, topic, keyword))
|
||||
prep_tasks.append(prepare_project_trend_queries(entity_key, entity_type, entity_val, topic, keyword))
|
||||
|
||||
await asyncio.gather(*tasks)
|
||||
await asyncio.gather(*prep_tasks)
|
||||
|
||||
if msearch_queries:
|
||||
try:
|
||||
responses = await elasticsearch.msearch(msearch_queries, cluster=ESCluster.INSE)
|
||||
for idx, res in enumerate(responses):
|
||||
entity_key, topic, agg_type = meta_indices[idx]
|
||||
buckets = res.get("aggregations", {}).get("projects_by_year", {}).get("buckets", [])
|
||||
for b in buckets:
|
||||
if agg_type == "date":
|
||||
yr_str = b.get("key_as_string") or str(b.get("key", ""))
|
||||
if yr_str:
|
||||
try:
|
||||
yr = int(yr_str[:4])
|
||||
if start_year <= yr <= end_year:
|
||||
c_cnt, _ = accumulated_data[entity_key][topic][yr]
|
||||
accumulated_data[entity_key][topic][yr] = (c_cnt + b.get("doc_count", 0), 1)
|
||||
except ValueError:
|
||||
pass
|
||||
else:
|
||||
yr_val = b.get("key")
|
||||
if yr_val is not None:
|
||||
try:
|
||||
yr = int(str(yr_val)[:4])
|
||||
if start_year <= yr <= end_year:
|
||||
c_cnt, _ = accumulated_data[entity_key][topic][yr]
|
||||
accumulated_data[entity_key][topic][yr] = (c_cnt + b.get("doc_count", 0), 1)
|
||||
except ValueError:
|
||||
pass
|
||||
except Exception as e:
|
||||
logger.error("Failed to execute msearch for project trends: %s", e)
|
||||
|
||||
normalized_lookup = self._normalize_series(years_range, accumulated_data, topics)
|
||||
|
||||
@@ -1139,7 +1064,6 @@ class NewsTrendStrategy(TrendStrategy):
|
||||
for t in topics
|
||||
}
|
||||
|
||||
AKTUELLES_SEARCH_FIELDS = ["main_content", "full_content", "maintitle", "subtitle", "intro_content"]
|
||||
STOP_WORDS = {"in", "and", "or", "und", "oder", "der", "die", "das", "von", "mit", "zu", "at", "by", "on", "for", "to", "a", "an", "the"}
|
||||
|
||||
# Scan UDE news postprocessed index to get matching news IDs without size limit cutoffs
|
||||
@@ -1160,7 +1084,7 @@ class NewsTrendStrategy(TrendStrategy):
|
||||
news_ids: Set[str] = set()
|
||||
try:
|
||||
async for hit in elasticsearch.scan(
|
||||
index="aktuell_postproc",
|
||||
index=ESIndex.AKTUELLES_POSTPROC.value,
|
||||
query=es_query,
|
||||
source=["news_id"],
|
||||
cluster=ESCluster.INSE,
|
||||
@@ -1182,7 +1106,7 @@ class NewsTrendStrategy(TrendStrategy):
|
||||
}
|
||||
}
|
||||
async for hit in elasticsearch.scan(
|
||||
index="aktuell",
|
||||
index=ESIndex.AKTUELLES.value,
|
||||
query=content_query,
|
||||
source=["news_id"],
|
||||
cluster=ESCluster.INSE,
|
||||
@@ -1219,7 +1143,7 @@ class NewsTrendStrategy(TrendStrategy):
|
||||
"size": 0,
|
||||
"_source": False,
|
||||
}
|
||||
chunk_queries.append(("aktuell", q_body))
|
||||
chunk_queries.append((ESIndex.AKTUELLES.value, q_body))
|
||||
|
||||
if chunk_queries:
|
||||
try:
|
||||
|
||||
@@ -24,7 +24,12 @@ export type ParamLocation = 'query' | 'header' | 'path' | 'cookie';
|
||||
* Standard types as defined in <a href="https://swagger.io/specification/#data-types">OpenAPI Specification: Data Types</a>
|
||||
*/
|
||||
export type StandardDataType =
|
||||
'integer' | 'number' | 'boolean' | 'string' | 'object' | 'array';
|
||||
| 'integer'
|
||||
| 'number'
|
||||
| 'boolean'
|
||||
| 'string'
|
||||
| 'object'
|
||||
| 'array';
|
||||
|
||||
/**
|
||||
* Standard {@link DataType}s plus your own types/classes.
|
||||
|
||||
@@ -424,16 +424,6 @@
|
||||
<mat-icon>search</mat-icon>
|
||||
Suchen
|
||||
</button>
|
||||
|
||||
<button
|
||||
mat-flat-button
|
||||
color="accent"
|
||||
class="visualize-btn"
|
||||
[disabled]="isSearchDisabled()"
|
||||
(click)="visualize()">
|
||||
<mat-icon>show_chart</mat-icon>
|
||||
Visualisierung
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
|
||||
+2
-1
@@ -122,7 +122,8 @@ export class PersonCompanyConnectionsComponent implements OnInit {
|
||||
const parentRoute = this.route.parent;
|
||||
const authorId = parentRoute?.snapshot.paramMap.get('id');
|
||||
const resolved = parentRoute?.snapshot.data['personData'] as
|
||||
PersonDataResolved | undefined;
|
||||
| PersonDataResolved
|
||||
| undefined;
|
||||
|
||||
if (!authorId || !resolved) {
|
||||
this.loading = false;
|
||||
|
||||
@@ -63,7 +63,8 @@ export class PersonPatentsComponent {
|
||||
.pipe(
|
||||
switchMap((data) => {
|
||||
const resolved = data['personPatents'] as
|
||||
PersonPatentsResolved | undefined;
|
||||
| PersonPatentsResolved
|
||||
| undefined;
|
||||
if (!resolved?.patents$) {
|
||||
return of(null);
|
||||
}
|
||||
|
||||
@@ -17,7 +17,11 @@ import { PatentsCardsComponent } from './patents-cards/patents-cards.component';
|
||||
import { DeliverablesCardsComponent } from './deliverables-cards/deliverables-cards.component';
|
||||
|
||||
export type TabType =
|
||||
'overview' | 'organizations' | 'publications' | 'iprs' | 'deliverables';
|
||||
| 'overview'
|
||||
| 'organizations'
|
||||
| 'publications'
|
||||
| 'iprs'
|
||||
| 'deliverables';
|
||||
|
||||
@Component({
|
||||
selector: 'app-eu-details',
|
||||
|
||||
+4
-1
@@ -25,7 +25,10 @@ import {
|
||||
} from '../../../shared/ui/topic-chip/topic-chip.component';
|
||||
|
||||
type PasteurQuadrant =
|
||||
'pure_basic' | 'use_inspired_basic' | 'pure_applied' | 'not_applicable';
|
||||
| 'pure_basic'
|
||||
| 'use_inspired_basic'
|
||||
| 'pure_applied'
|
||||
| 'not_applicable';
|
||||
|
||||
interface QuadrantDefinition {
|
||||
key: PasteurQuadrant;
|
||||
|
||||
+120
-82
@@ -92,6 +92,87 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Combined Child Component Selectors Row (all filter logic at top before diagrams) -->
|
||||
<div class="comparison-selectors-row">
|
||||
<!-- Countries / Regions Selector -->
|
||||
@if (activeConfig().showLocationSelector) {
|
||||
<app-location-selector
|
||||
class="selector-item"
|
||||
[comparisonCountries]="comparisonCountries()"
|
||||
[comparisonRegions]="comparisonRegions()"
|
||||
[locationQuery]="locationQuery()"
|
||||
[locationSearchResults]="locationSearchResults()"
|
||||
[getEntityColor]="boundGetEntityColor"
|
||||
[isVisible]="boundIsVisible"
|
||||
[selectedPieEntityId]="selectedPieEntity()?.id ?? null"
|
||||
(addLocation)="addLocation($event)"
|
||||
(removeLocation)="removeLocation($event.id, $event.type)"
|
||||
(searchChange)="onLocationSearchChange($event)"
|
||||
(toggleVisibility)="toggleVisibility($event)"
|
||||
(selectPie)="onSelectPieEntity($event)">
|
||||
</app-location-selector>
|
||||
}
|
||||
|
||||
<!-- Top-Autoren einer Einrichtung hinzufügen -->
|
||||
@if (activeConfig().showAuthorSelector) {
|
||||
<app-author-institution-selector
|
||||
class="selector-item"
|
||||
[searchQuery]="authorInstSearchQuery()"
|
||||
[searchResults]="authorInstSearchResults()"
|
||||
(addInstitutionAuthors)="
|
||||
addInstitutionAuthors($event.id, $event.name)
|
||||
"
|
||||
(searchChange)="onAuthorInstSearchChange($event)">
|
||||
</app-author-institution-selector>
|
||||
}
|
||||
|
||||
<!-- Unified Institution Search, Compare, & Recommendations -->
|
||||
@if (activeConfig().showInstitutionSelector) {
|
||||
<app-institution-selector
|
||||
class="selector-item selector-item--main"
|
||||
[activeTab]="selectedSearchType()"
|
||||
[comparisonInstitutions]="comparisonInstitutions()"
|
||||
[primaryInstitution]="primaryInstitution()"
|
||||
[primaryInstitutionName]="primaryInstitutionName()"
|
||||
[topSuggestions]="topSuggestions()"
|
||||
[isSuggestionsLoading]="isSuggestionsLoading()"
|
||||
[activeChartTopic]="activeChartTopic()"
|
||||
[searchQuery]="searchQuery()"
|
||||
[searchResults]="searchResults()"
|
||||
[getEntityColor]="boundGetEntityColor"
|
||||
[isVisible]="boundIsVisible"
|
||||
[selectedPieEntityId]="selectedPieEntity()?.id ?? null"
|
||||
(addInstitution)="addInstitution($event.id, $event.name)"
|
||||
(removeInstitution)="removeInstitution($event)"
|
||||
(searchChange)="onSearchChange($event)"
|
||||
(toggleVisibility)="toggleVisibility($event)"
|
||||
(selectPie)="onSelectPieEntity($event)">
|
||||
</app-institution-selector>
|
||||
}
|
||||
|
||||
<!-- Reusable Author Selection UI -->
|
||||
@if (activeConfig().showAuthorSelector) {
|
||||
<app-author-selector
|
||||
class="selector-item selector-item--main"
|
||||
[activeTab]="selectedSearchType()"
|
||||
[comparisonAuthors]="comparisonAuthors()"
|
||||
[topSuggestions]="recommendedAuthors()"
|
||||
[isSuggestionsLoading]="isSuggestionsLoading()"
|
||||
[activeChartTopic]="activeChartTopic()"
|
||||
[searchQuery]="authorSearchQuery()"
|
||||
[searchResults]="authorSearchResults()"
|
||||
[getEntityColor]="boundGetEntityColor"
|
||||
[isVisible]="boundIsVisible"
|
||||
[selectedPieEntityId]="selectedPieEntity()?.id ?? null"
|
||||
(addAuthor)="addAuthor($event.id, $event.name)"
|
||||
(removeAuthor)="removeAuthor($event)"
|
||||
(searchChange)="onAuthorSearchChange($event)"
|
||||
(toggleVisibility)="toggleVisibility($event)"
|
||||
(selectPie)="onSelectPieEntity($event)">
|
||||
</app-author-selector>
|
||||
}
|
||||
</div>
|
||||
|
||||
<!-- Main Full-Width Content Area -->
|
||||
<main class="trend-main-fullwidth">
|
||||
@if (isPageResolving() || (isTrendLoading() && !rawTrendResponse())) {
|
||||
@@ -109,11 +190,11 @@
|
||||
@if (selectedSearchType() === 'news') {
|
||||
<app-topic-chip
|
||||
[label]="topic"
|
||||
[active]="true"
|
||||
[active]="isVisible('news_topic_' + topic)"
|
||||
[color]="getTopicColor(topic)"
|
||||
[disabled]="false"
|
||||
[matTooltip]="topic"
|
||||
style="pointer-events: none; cursor: default">
|
||||
(chipClick)="toggleVisibility('news_topic_' + topic)">
|
||||
</app-topic-chip>
|
||||
} @else if (selectedTrendTopics().length > 1) {
|
||||
<app-topic-chip
|
||||
@@ -183,86 +264,43 @@
|
||||
</div>
|
||||
}
|
||||
|
||||
<!-- Combined Child Component Selectors Row (fits into a single line on desktop) -->
|
||||
<div class="comparison-selectors-row">
|
||||
<!-- Countries / Regions Selector -->
|
||||
@if (activeConfig().showLocationSelector) {
|
||||
<app-location-selector
|
||||
class="selector-item"
|
||||
[comparisonCountries]="comparisonCountries()"
|
||||
[comparisonRegions]="comparisonRegions()"
|
||||
[locationQuery]="locationQuery()"
|
||||
[locationSearchResults]="locationSearchResults()"
|
||||
[getEntityColor]="boundGetEntityColor"
|
||||
[isVisible]="boundIsVisible"
|
||||
[selectedPieEntityId]="selectedPieEntity()?.id ?? null"
|
||||
(addLocation)="addLocation($event)"
|
||||
(removeLocation)="removeLocation($event.id, $event.type)"
|
||||
(searchChange)="onLocationSearchChange($event)"
|
||||
(toggleVisibility)="toggleVisibility($event)"
|
||||
(selectPie)="onSelectPieEntity($event)">
|
||||
</app-location-selector>
|
||||
}
|
||||
|
||||
<!-- Top-Autoren einer Einrichtung hinzufügen -->
|
||||
@if (activeConfig().showAuthorSelector) {
|
||||
<app-author-institution-selector
|
||||
class="selector-item"
|
||||
[searchQuery]="authorInstSearchQuery()"
|
||||
[searchResults]="authorInstSearchResults()"
|
||||
(addInstitutionAuthors)="
|
||||
addInstitutionAuthors($event.id, $event.name)
|
||||
"
|
||||
(searchChange)="onAuthorInstSearchChange($event)">
|
||||
</app-author-institution-selector>
|
||||
}
|
||||
|
||||
<!-- Unified Institution Search, Compare, & Recommendations -->
|
||||
@if (activeConfig().showInstitutionSelector) {
|
||||
<app-institution-selector
|
||||
class="selector-item selector-item--main"
|
||||
[activeTab]="selectedSearchType()"
|
||||
[comparisonInstitutions]="comparisonInstitutions()"
|
||||
[primaryInstitution]="primaryInstitution()"
|
||||
[primaryInstitutionName]="primaryInstitutionName()"
|
||||
[topSuggestions]="topSuggestions()"
|
||||
[isSuggestionsLoading]="isSuggestionsLoading()"
|
||||
[activeChartTopic]="activeChartTopic()"
|
||||
[searchQuery]="searchQuery()"
|
||||
[searchResults]="searchResults()"
|
||||
[getEntityColor]="boundGetEntityColor"
|
||||
[isVisible]="boundIsVisible"
|
||||
[selectedPieEntityId]="selectedPieEntity()?.id ?? null"
|
||||
(addInstitution)="addInstitution($event.id, $event.name)"
|
||||
(removeInstitution)="removeInstitution($event)"
|
||||
(searchChange)="onSearchChange($event)"
|
||||
(toggleVisibility)="toggleVisibility($event)"
|
||||
(selectPie)="onSelectPieEntity($event)">
|
||||
</app-institution-selector>
|
||||
}
|
||||
|
||||
<!-- Reusable Author Selection UI -->
|
||||
@if (activeConfig().showAuthorSelector) {
|
||||
<app-author-selector
|
||||
class="selector-item selector-item--main"
|
||||
[activeTab]="selectedSearchType()"
|
||||
[comparisonAuthors]="comparisonAuthors()"
|
||||
[topSuggestions]="recommendedAuthors()"
|
||||
[isSuggestionsLoading]="isSuggestionsLoading()"
|
||||
[activeChartTopic]="activeChartTopic()"
|
||||
[searchQuery]="authorSearchQuery()"
|
||||
[searchResults]="authorSearchResults()"
|
||||
[getEntityColor]="boundGetEntityColor"
|
||||
[isVisible]="boundIsVisible"
|
||||
[selectedPieEntityId]="selectedPieEntity()?.id ?? null"
|
||||
(addAuthor)="addAuthor($event.id, $event.name)"
|
||||
(removeAuthor)="removeAuthor($event)"
|
||||
(searchChange)="onAuthorSearchChange($event)"
|
||||
(toggleVisibility)="toggleVisibility($event)"
|
||||
(selectPie)="onSelectPieEntity($event)">
|
||||
</app-author-selector>
|
||||
}
|
||||
</div>
|
||||
<!-- Topic Treemap (Hierarchie-Tree) for Fuzzy Search -->
|
||||
@if (isFuzzy() && activeTreemapData()) {
|
||||
<section class="treemap-section">
|
||||
<div class="chart-holder-card">
|
||||
<h3
|
||||
style="
|
||||
margin-bottom: 16px;
|
||||
font-weight: 700;
|
||||
font-size: 1.1rem;
|
||||
color: #101a3d;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
">
|
||||
<mat-icon style="color: #6366f1">account_tree</mat-icon>
|
||||
Themen-Hierarchie & Verteilung (Treemap)
|
||||
@if (selectedPieEntity()?.name || primaryInstitutionName()) {
|
||||
<span
|
||||
style="
|
||||
font-weight: 500;
|
||||
font-size: 0.95rem;
|
||||
color: #64708f;
|
||||
">
|
||||
·
|
||||
{{ selectedPieEntity()?.name || primaryInstitutionName() }}
|
||||
</span>
|
||||
}
|
||||
</h3>
|
||||
<app-topic-treemap
|
||||
[data]="activeTreemapData()!"
|
||||
[selectedNodeId]="selectedTopicTreemapNode()"
|
||||
(selectedNodeIdChange)="onTopicTreemapNodeChange($event)"
|
||||
(topicSelect)="onTopicTreemapTopicSelect($event)">
|
||||
</app-topic-treemap>
|
||||
</div>
|
||||
</section>
|
||||
}
|
||||
} @else {
|
||||
<div class="no-data-fallback">
|
||||
<mat-icon>trending_up</mat-icon>
|
||||
|
||||
+11
-11
@@ -202,22 +202,22 @@
|
||||
}
|
||||
|
||||
.comparison-selectors-row {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: stretch;
|
||||
display: grid;
|
||||
grid-template-columns: 3fr 7fr;
|
||||
gap: 1.25rem;
|
||||
align-items: stretch;
|
||||
width: 100%;
|
||||
box-sizing: border-box;
|
||||
|
||||
.selector-item {
|
||||
flex: 1 1 300px;
|
||||
min-width: 0;
|
||||
max-width: 100%;
|
||||
box-sizing: border-box;
|
||||
@media (max-width: 900px) {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
|
||||
&.selector-item--main {
|
||||
flex: 2 1 450px;
|
||||
}
|
||||
.selector-item {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
min-width: 0;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+321
-36
@@ -56,6 +56,16 @@ import { AuthorSelectorComponent } from '../../../shared/ui/author-selector/auth
|
||||
import { AuthorInstitutionSelectorComponent } from '../../../shared/ui/author-institution-selector/author-institution-selector.component';
|
||||
import { SearchResultsStateService } from '../../keywords-search/search-results/search-results-state.service';
|
||||
import { LoadingComponent } from '../../../shared/ui/loading/loading.component';
|
||||
import { TopicTreemapComponent } from '../../../shared/ui/topic-treemap/topic-treemap.component';
|
||||
import {
|
||||
TopicTreemapData,
|
||||
TopicTreemapField,
|
||||
TopicTreemapSubfield,
|
||||
TopicTreemapTopic,
|
||||
TopicTreemapValue,
|
||||
TopicTreemapTopicSelect,
|
||||
} from '../../../shared/ui/topic-treemap/topic-treemap.models';
|
||||
import { TopicsService } from '../../../api/api/topics.service';
|
||||
|
||||
export interface CompareItem {
|
||||
id: string;
|
||||
@@ -136,6 +146,7 @@ export const TREND_CONFIGS: Record<string, TrendStrategyConfig> = {
|
||||
AuthorSelectorComponent,
|
||||
AuthorInstitutionSelectorComponent,
|
||||
LoadingComponent,
|
||||
TopicTreemapComponent,
|
||||
],
|
||||
templateUrl: './uni-trend-parent.component.html',
|
||||
styleUrl: './uni-trend-parent.component.scss',
|
||||
@@ -143,6 +154,7 @@ export const TREND_CONFIGS: Record<string, TrendStrategyConfig> = {
|
||||
})
|
||||
export class UniTrendParentComponent implements OnInit {
|
||||
private readonly apiService = inject(UniversityRankingsService);
|
||||
private readonly topicsService = inject(TopicsService);
|
||||
private readonly institutionsApiService = inject(InstitutionsService);
|
||||
private readonly personsApiService = inject(PersonsService);
|
||||
private readonly organizationService = inject(OrganizationService, {
|
||||
@@ -230,6 +242,12 @@ export class UniTrendParentComponent implements OnInit {
|
||||
readonly isTopTopicsLoading = signal<boolean>(false);
|
||||
readonly topTopicsError = signal<boolean>(false);
|
||||
|
||||
// Topic Treemap signals
|
||||
readonly isFuzzy = computed(() => this.state?.fuzzySearch() ?? true);
|
||||
readonly topicTreemap = signal<TopicTreemapData | null>(null);
|
||||
readonly isTreemapLoading = signal<boolean>(false);
|
||||
readonly selectedTopicTreemapNode = signal<string | undefined>(undefined);
|
||||
|
||||
getMappedTopic(topicOrKeyword: string): string {
|
||||
const kws = this.keywords();
|
||||
const topics = this.state?.topicsList() ?? kws;
|
||||
@@ -299,6 +317,197 @@ export class UniTrendParentComponent implements OnInit {
|
||||
});
|
||||
});
|
||||
|
||||
cleanEntityId(id: string | null | undefined): string {
|
||||
if (!id) return '';
|
||||
const lower = id.toLowerCase().trim();
|
||||
return lower.includes('/') ? lower.split('/').pop()! : lower;
|
||||
}
|
||||
|
||||
// Dynamic Treemap Data for Selected Entity (Institution or Author or Region/Country)
|
||||
readonly activeTreemapData = computed<TopicTreemapData | null>(() => {
|
||||
const data = this.trendResponse();
|
||||
const searchType = this.selectedSearchType();
|
||||
const isFuzzy = this.isFuzzy();
|
||||
if (!data || !data.series || !isFuzzy) return null;
|
||||
|
||||
const startYr = this.startYear();
|
||||
const endYr = this.endYear();
|
||||
|
||||
const activePie = this.selectedPieEntity();
|
||||
let targetEntityId: string | undefined = activePie?.id || undefined;
|
||||
let targetEntityName = activePie?.name || 'Ausgewählte Entität';
|
||||
|
||||
if (!targetEntityId) {
|
||||
if (searchType === 'authors') {
|
||||
const firstAuthor = this.comparisonAuthors()[0];
|
||||
targetEntityId = firstAuthor?.id || undefined;
|
||||
targetEntityName = firstAuthor?.name || 'Autor';
|
||||
} else {
|
||||
targetEntityId = this.primaryInstitution() || undefined;
|
||||
targetEntityName = this.primaryInstitutionName();
|
||||
}
|
||||
}
|
||||
|
||||
const cleanTargetId = targetEntityId
|
||||
? this.cleanEntityId(targetEntityId)
|
||||
: '';
|
||||
|
||||
let matchingSeries: TrendSeries[] = [];
|
||||
if (searchType === 'news') {
|
||||
matchingSeries = data.series;
|
||||
} else {
|
||||
matchingSeries = data.series.filter(
|
||||
(s) => this.cleanEntityId(s.entity_id) === cleanTargetId,
|
||||
);
|
||||
if (matchingSeries.length === 0 && data.series.length > 0) {
|
||||
matchingSeries = data.series;
|
||||
}
|
||||
}
|
||||
|
||||
if (matchingSeries.length === 0) return null;
|
||||
|
||||
const keywordEntries = this.state?.selectedKeywordEntries() ?? [];
|
||||
const fieldsMap = new Map<
|
||||
string,
|
||||
{
|
||||
id: string;
|
||||
name: string;
|
||||
subfieldsMap: Map<
|
||||
string,
|
||||
{
|
||||
id: string;
|
||||
name: string;
|
||||
topicsMap: Map<
|
||||
string,
|
||||
{
|
||||
id: string;
|
||||
name: string;
|
||||
total: number;
|
||||
values: TopicTreemapValue[];
|
||||
}
|
||||
>;
|
||||
}
|
||||
>;
|
||||
}
|
||||
>();
|
||||
|
||||
matchingSeries.forEach((s) => {
|
||||
Object.entries(s.topic_data || {}).forEach(
|
||||
([topicName, yearlyDataList]) => {
|
||||
const totalCount = yearlyDataList
|
||||
.filter((y) => y.year >= startYr && y.year <= endYr)
|
||||
.reduce((sum, item) => sum + (item.raw || 0), 0);
|
||||
|
||||
if (totalCount <= 0) return;
|
||||
|
||||
const mappedName = this.getMappedTopic(topicName);
|
||||
const targetLower = topicName.toLowerCase().trim();
|
||||
const mappedLower = mappedName.toLowerCase().trim();
|
||||
|
||||
const match = keywordEntries.find(
|
||||
(e) =>
|
||||
e.topic_mapping?.topic?.display_name?.toLowerCase().trim() ===
|
||||
mappedLower ||
|
||||
e.topic_mapping?.topic?.display_name?.toLowerCase().trim() ===
|
||||
targetLower ||
|
||||
e.llm_keyword?.keyword?.toLowerCase().trim() === targetLower,
|
||||
);
|
||||
|
||||
const fieldName =
|
||||
match?.topic_mapping?.topic?.field?.display_name ||
|
||||
'Information & Communication Technology';
|
||||
const fieldId = match?.topic_mapping?.topic?.field?.id
|
||||
? String(match.topic_mapping.topic.field.id)
|
||||
: 'field_ict';
|
||||
|
||||
const subfieldName =
|
||||
match?.topic_mapping?.topic?.subfield?.display_name || fieldName;
|
||||
const subfieldId = match?.topic_mapping?.topic?.subfield?.id
|
||||
? String(match.topic_mapping.topic.subfield.id)
|
||||
: `subfield_${fieldId}`;
|
||||
|
||||
const topicId = match?.topic_mapping?.topic?.id
|
||||
? String(match.topic_mapping.topic.id)
|
||||
: topicName;
|
||||
|
||||
if (!fieldsMap.has(fieldId)) {
|
||||
fieldsMap.set(fieldId, {
|
||||
id: fieldId,
|
||||
name: fieldName,
|
||||
subfieldsMap: new Map(),
|
||||
});
|
||||
}
|
||||
const fieldEntry = fieldsMap.get(fieldId)!;
|
||||
|
||||
if (!fieldEntry.subfieldsMap.has(subfieldId)) {
|
||||
fieldEntry.subfieldsMap.set(subfieldId, {
|
||||
id: subfieldId,
|
||||
name: subfieldName,
|
||||
topicsMap: new Map(),
|
||||
});
|
||||
}
|
||||
const subfieldEntry = fieldEntry.subfieldsMap.get(subfieldId)!;
|
||||
|
||||
if (!subfieldEntry.topicsMap.has(topicId)) {
|
||||
const yearlyValues: TopicTreemapValue[] = yearlyDataList
|
||||
.filter((y) => y.year >= startYr && y.year <= endYr)
|
||||
.map((y) => ({
|
||||
year: y.year,
|
||||
count: y.raw || 0,
|
||||
share: y.normalized || 0,
|
||||
}));
|
||||
|
||||
subfieldEntry.topicsMap.set(topicId, {
|
||||
id: topicId,
|
||||
name: topicName,
|
||||
total: totalCount,
|
||||
values: yearlyValues,
|
||||
});
|
||||
}
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
const years = Array.from(
|
||||
{ length: endYr - startYr + 1 },
|
||||
(_, i) => startYr + i,
|
||||
);
|
||||
const fields: TopicTreemapField[] = Array.from(fieldsMap.values()).map(
|
||||
(f) => {
|
||||
const subfields: TopicTreemapSubfield[] = Array.from(
|
||||
f.subfieldsMap.values(),
|
||||
).map((sf) => {
|
||||
const topics: TopicTreemapTopic[] = Array.from(sf.topicsMap.values());
|
||||
const sfTotal = topics.reduce((sum, t) => sum + t.total, 0);
|
||||
return {
|
||||
id: sf.id,
|
||||
name: sf.name,
|
||||
total: sfTotal,
|
||||
values: [],
|
||||
topics,
|
||||
};
|
||||
});
|
||||
const fTotal = subfields.reduce((sum, sf) => sum + sf.total, 0);
|
||||
return {
|
||||
id: f.id,
|
||||
name: f.name,
|
||||
total: fTotal,
|
||||
values: [],
|
||||
subfields,
|
||||
};
|
||||
},
|
||||
);
|
||||
|
||||
if (fields.length === 0) return null;
|
||||
|
||||
return {
|
||||
institution_id: cleanTargetId,
|
||||
organization_name: targetEntityName,
|
||||
years,
|
||||
fields,
|
||||
};
|
||||
});
|
||||
|
||||
// Autocomplete UI state
|
||||
readonly searchQuery = signal<string>('');
|
||||
readonly searchResults = signal<AutocompleteResponseResultsInner[]>([]);
|
||||
@@ -316,6 +525,26 @@ export class UniTrendParentComponent implements OnInit {
|
||||
|
||||
readonly entityVisibilityMap = signal<Map<string, boolean>>(new Map());
|
||||
|
||||
isTopicEmpty(topic: string): boolean {
|
||||
const res = this.rawTrendResponse();
|
||||
if (!res || !res.series || res.series.length === 0) return false;
|
||||
const startYr = this.startYear();
|
||||
const endYr = this.endYear();
|
||||
const mapped = this.getMappedTopic(topic).toLowerCase().trim();
|
||||
|
||||
return !res.series.some((s) => {
|
||||
const yearlyList =
|
||||
s.topic_data?.[topic] ||
|
||||
s.topic_data?.[mapped] ||
|
||||
Object.values(s.topic_data || {})[0];
|
||||
if (!yearlyList) return false;
|
||||
const total = yearlyList
|
||||
.filter((y) => y.year >= startYr && y.year <= endYr)
|
||||
.reduce((sum, item) => sum + (item.raw || 0), 0);
|
||||
return total > 0;
|
||||
});
|
||||
}
|
||||
|
||||
isVisible(id: string): boolean {
|
||||
return this.entityVisibilityMap().get(id) !== false;
|
||||
}
|
||||
@@ -337,6 +566,29 @@ export class UniTrendParentComponent implements OnInit {
|
||||
return this.getTopicColor(topicName);
|
||||
}
|
||||
|
||||
if (this.selectedSearchType() === 'all') {
|
||||
const cleanTarget = this.cleanEntityId(entityId).toLowerCase();
|
||||
const allColors: Record<string, string> = {
|
||||
publications: '#3b82f6',
|
||||
works: '#3b82f6',
|
||||
patents: '#10b981',
|
||||
projects: '#f59e0b',
|
||||
news: '#ec4899',
|
||||
};
|
||||
if (allColors[cleanTarget]) {
|
||||
return allColors[cleanTarget];
|
||||
}
|
||||
const seriesList = this.rawTrendResponse()?.series || [];
|
||||
const seriesIdx = seriesList.findIndex(
|
||||
(s) => this.cleanEntityId(s.entity_id).toLowerCase() === cleanTarget,
|
||||
);
|
||||
const fixedColors = ['#3b82f6', '#10b981', '#f59e0b', '#ec4899'];
|
||||
if (seriesIdx !== -1) {
|
||||
return fixedColors[seriesIdx % fixedColors.length];
|
||||
}
|
||||
return '#3b82f6';
|
||||
}
|
||||
|
||||
const cleanId = (id: string | null | undefined): string => {
|
||||
if (!id) return '';
|
||||
const lower = id.toLowerCase().trim();
|
||||
@@ -621,20 +873,50 @@ export class UniTrendParentComponent implements OnInit {
|
||||
if (resolved.topics && resolved.topics.length > 0) {
|
||||
this.selectedTrendTopics.set(resolved.topics);
|
||||
this.fetchedTopics.set([...resolved.topics]);
|
||||
if (
|
||||
!this.activeChartTopic() ||
|
||||
!resolved.topics.includes(this.activeChartTopic())
|
||||
) {
|
||||
this.activeChartTopic.set(resolved.topics[0]);
|
||||
}
|
||||
const firstNonEmpty = resolved.topics.find(
|
||||
(t: string) => !this.isTopicEmpty(t),
|
||||
);
|
||||
const targetTopic = firstNonEmpty || resolved.topics[0];
|
||||
this.activeChartTopic.set(targetTopic);
|
||||
} else {
|
||||
this.fetchedTopics.set([...this.selectedTrendTopics()]);
|
||||
}
|
||||
|
||||
this.fetchedInstitutions.set([...this.comparisonInstitutions()]);
|
||||
this.fetchedCountries.set([...this.comparisonCountries()]);
|
||||
this.fetchedRegions.set([...this.comparisonRegions()]);
|
||||
this.fetchedAuthors.set([...this.comparisonAuthors()]);
|
||||
if (resolved.institutions && resolved.institutions.length > 0) {
|
||||
this.comparisonInstitutions.set(resolved.institutions);
|
||||
this.fetchedInstitutions.set([...resolved.institutions]);
|
||||
} else {
|
||||
this.fetchedInstitutions.set([...this.comparisonInstitutions()]);
|
||||
}
|
||||
|
||||
if (resolved.countries && resolved.countries.length > 0) {
|
||||
this.comparisonCountries.set(resolved.countries);
|
||||
this.fetchedCountries.set([...resolved.countries]);
|
||||
} else {
|
||||
this.fetchedCountries.set([...this.comparisonCountries()]);
|
||||
}
|
||||
|
||||
if (resolved.regions && resolved.regions.length > 0) {
|
||||
this.comparisonRegions.set(resolved.regions);
|
||||
this.fetchedRegions.set([...resolved.regions]);
|
||||
} else {
|
||||
this.fetchedRegions.set([...this.comparisonRegions()]);
|
||||
}
|
||||
|
||||
if (resolved.authors && resolved.authors.length > 0) {
|
||||
this.comparisonAuthors.set(resolved.authors);
|
||||
this.fetchedAuthors.set([...resolved.authors]);
|
||||
} else {
|
||||
this.fetchedAuthors.set([...this.comparisonAuthors()]);
|
||||
}
|
||||
|
||||
if (resolved.treemapData) {
|
||||
this.topicTreemap.set(resolved.treemapData);
|
||||
}
|
||||
|
||||
if (resolved.treemapNode !== undefined) {
|
||||
this.selectedTopicTreemapNode.set(resolved.treemapNode || undefined);
|
||||
}
|
||||
|
||||
this.isTrendLoading.set(false);
|
||||
}
|
||||
@@ -1335,6 +1617,7 @@ export class UniTrendParentComponent implements OnInit {
|
||||
end_year: this.endYear(),
|
||||
chart_mode: this.chartMode(),
|
||||
active_chart_topic: this.activeChartTopic(),
|
||||
treemapNode: this.selectedTopicTreemapNode() ?? null,
|
||||
};
|
||||
|
||||
this.router.navigate([], {
|
||||
@@ -1344,6 +1627,34 @@ export class UniTrendParentComponent implements OnInit {
|
||||
});
|
||||
}
|
||||
|
||||
fetchTreemapData() {
|
||||
const fuzzy = this.state?.fuzzySearch() ?? true;
|
||||
const topics = this.selectedTrendTopics();
|
||||
if (!fuzzy || topics.length === 0) {
|
||||
this.topicTreemap.set(null);
|
||||
return;
|
||||
}
|
||||
this.isTreemapLoading.set(true);
|
||||
this.topicsService.countTopicHierarchy(topics).subscribe({
|
||||
next: (res: any) => {
|
||||
this.topicTreemap.set(res);
|
||||
this.isTreemapLoading.set(false);
|
||||
},
|
||||
error: () => {
|
||||
this.isTreemapLoading.set(false);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
onTopicTreemapNodeChange(nodeId: string | undefined): void {
|
||||
this.selectedTopicTreemapNode.set(nodeId);
|
||||
this.updateUrlParams();
|
||||
}
|
||||
|
||||
onTopicTreemapTopicSelect(topic: TopicTreemapTopicSelect): void {
|
||||
// Topic selected inside treemap component
|
||||
}
|
||||
|
||||
// Checkbox topic toggling
|
||||
onTrendTopicToggle(topic: string, event: Event) {
|
||||
const isChecked = (event.target as HTMLInputElement).checked;
|
||||
@@ -1541,32 +1852,6 @@ export class UniTrendParentComponent implements OnInit {
|
||||
}
|
||||
}
|
||||
|
||||
isTopicEmpty(topic: string): boolean {
|
||||
const data = this.trendResponse();
|
||||
if (!data || !data.series || data.series.length === 0) {
|
||||
return false;
|
||||
}
|
||||
const mapped = this.getMappedTopic(topic);
|
||||
const startYr = this.startYear();
|
||||
const endYr = this.endYear();
|
||||
|
||||
let totalRaw = 0;
|
||||
data.series.forEach((s) => {
|
||||
if (s.visible !== false && s.topic_data) {
|
||||
const items = s.topic_data[topic] || s.topic_data[mapped];
|
||||
if (items) {
|
||||
items.forEach((y) => {
|
||||
if (y.year >= startYr && y.year <= endYr) {
|
||||
totalRaw += y.raw || 0;
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
return totalRaw === 0;
|
||||
}
|
||||
|
||||
// Topic tab toggle (data reuses instantly)
|
||||
updateActiveChartTopic(topic: string) {
|
||||
if (this.isTopicEmpty(topic)) {
|
||||
|
||||
@@ -4,12 +4,22 @@ import { catchError, of, Observable, map } from 'rxjs';
|
||||
import { TrendResponse, UniversityRankingsService } from '../api';
|
||||
import { SearchResultsStateService } from '../modules/keywords-search/search-results/search-results-state.service';
|
||||
|
||||
export interface CompareItem {
|
||||
id: string;
|
||||
name: string;
|
||||
}
|
||||
|
||||
export interface UniTrendResolvedData {
|
||||
trendResponse: TrendResponse | null;
|
||||
searchType: string;
|
||||
topics: string[];
|
||||
keywords: string[];
|
||||
fuzzy: boolean;
|
||||
institutions: CompareItem[];
|
||||
countries: CompareItem[];
|
||||
regions: CompareItem[];
|
||||
authors: CompareItem[];
|
||||
treemapNode?: string | null;
|
||||
}
|
||||
|
||||
export const uniTrendResolver: ResolveFn<UniTrendResolvedData> = (
|
||||
@@ -21,6 +31,7 @@ export const uniTrendResolver: ResolveFn<UniTrendResolvedData> = (
|
||||
|
||||
const searchType = params.get('search_type') || 'publications';
|
||||
const fuzzy = params.get('fuzzy') !== 'false';
|
||||
const treemapNode = params.get('treemapNode');
|
||||
|
||||
// Extract keywords & topics
|
||||
let keywords = params.getAll('keyword');
|
||||
@@ -61,32 +72,42 @@ export const uniTrendResolver: ResolveFn<UniTrendResolvedData> = (
|
||||
keywords = topics;
|
||||
}
|
||||
|
||||
// Parse institutions
|
||||
// Parse comparison items
|
||||
const instParams = params.getAll('institutions');
|
||||
let institutions = instParams.map((i) => {
|
||||
const parsedInstitutions: CompareItem[] = instParams.map((i) => {
|
||||
const parts = i.split('|');
|
||||
const cleanId = parts[0].includes('/')
|
||||
? parts[0].split('/').pop() || parts[0]
|
||||
: parts[0];
|
||||
return cleanId;
|
||||
return { id: cleanId, name: parts[1] || cleanId };
|
||||
});
|
||||
if (institutions.length === 0) {
|
||||
institutions = ['I62318514'];
|
||||
}
|
||||
|
||||
// Parse countries
|
||||
const countryParams = params.getAll('countries');
|
||||
let countries = countryParams.map((c) => c.split('|')[0]);
|
||||
if (countries.length === 0) {
|
||||
countries = ['DE'];
|
||||
}
|
||||
const parsedCountries: CompareItem[] = countryParams.map((c) => {
|
||||
const parts = c.split('|');
|
||||
return { id: parts[0], name: parts[1] || parts[0] };
|
||||
});
|
||||
|
||||
// Parse regions & authors
|
||||
const regionParams = params.getAll('regions');
|
||||
const regions = regionParams.map((r) => r.split('|')[0]);
|
||||
const parsedRegions: CompareItem[] = regionParams.map((r) => {
|
||||
const parts = r.split('|');
|
||||
return { id: parts[0], name: parts[1] || parts[0] };
|
||||
});
|
||||
|
||||
const authorParams = params.getAll('authors');
|
||||
const authors = authorParams.map((a) => a.split('|')[0]);
|
||||
const parsedAuthors: CompareItem[] = authorParams.map((a) => {
|
||||
const parts = a.split('|');
|
||||
return { id: parts[0], name: parts[1] || parts[0] };
|
||||
});
|
||||
|
||||
const instIds =
|
||||
parsedInstitutions.length > 0
|
||||
? parsedInstitutions.map((i) => i.id)
|
||||
: ['I62318514'];
|
||||
const countryIds =
|
||||
parsedCountries.length > 0 ? parsedCountries.map((c) => c.id) : ['DE'];
|
||||
const regionIds = parsedRegions.map((r) => r.id);
|
||||
const authorIds = parsedAuthors.map((a) => a.id);
|
||||
|
||||
const apiService = inject(UniversityRankingsService);
|
||||
|
||||
@@ -95,29 +116,25 @@ export const uniTrendResolver: ResolveFn<UniTrendResolvedData> = (
|
||||
topics,
|
||||
keywords,
|
||||
fuzzy,
|
||||
institutions,
|
||||
countries,
|
||||
regions,
|
||||
authors,
|
||||
instIds,
|
||||
countryIds,
|
||||
regionIds,
|
||||
authorIds,
|
||||
searchType as any,
|
||||
)
|
||||
.pipe(
|
||||
catchError(() => of(null)),
|
||||
map((trendResponse) => ({
|
||||
trendResponse,
|
||||
searchType,
|
||||
topics,
|
||||
keywords,
|
||||
fuzzy,
|
||||
institutions: parsedInstitutions,
|
||||
countries: parsedCountries,
|
||||
regions: parsedRegions,
|
||||
authors: parsedAuthors,
|
||||
treemapNode,
|
||||
})),
|
||||
catchError((err) => {
|
||||
console.error('uniTrendResolver failed to load trend data:', err);
|
||||
return of({
|
||||
trendResponse: null,
|
||||
searchType,
|
||||
topics,
|
||||
keywords,
|
||||
fuzzy,
|
||||
});
|
||||
}),
|
||||
);
|
||||
};
|
||||
|
||||
+6
-3
@@ -6,15 +6,18 @@
|
||||
|
||||
<!-- Autocomplete Search Input for Institutions -->
|
||||
<div class="autocomplete-search">
|
||||
<mat-form-field appearance="outline" class="search-form-field">
|
||||
<mat-icon matPrefix>search</mat-icon>
|
||||
<mat-form-field
|
||||
appearance="outline"
|
||||
class="search-form-field"
|
||||
subscriptSizing="dynamic"
|
||||
style="width: 100%">
|
||||
<mat-label>Einrichtung suchen</mat-label>
|
||||
<input
|
||||
matInput
|
||||
type="text"
|
||||
placeholder="Einrichtung suchen, um deren Top-3 Autoren hinzuzufügen..."
|
||||
[value]="searchQuery()"
|
||||
(input)="onSearchInput($event)" />
|
||||
<mat-icon matPrefix>search</mat-icon>
|
||||
@if (searchQuery()) {
|
||||
<button
|
||||
mat-icon-button
|
||||
|
||||
+8
-30
@@ -1,6 +1,7 @@
|
||||
:host {
|
||||
display: block;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
min-width: 0;
|
||||
max-width: 100%;
|
||||
}
|
||||
@@ -8,11 +9,12 @@
|
||||
.author-institution-selector-container {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
height: 100%;
|
||||
background: white;
|
||||
border: 1px solid #d7e4ff;
|
||||
border-radius: 16px;
|
||||
padding: 24px;
|
||||
box-shadow: 0 8px 24px rgba(15, 23, 42, 0.04);
|
||||
border: 1px solid #e2e8f0;
|
||||
border-radius: 12px;
|
||||
padding: 1.25rem;
|
||||
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.04);
|
||||
box-sizing: border-box;
|
||||
margin-top: 0;
|
||||
width: 100%;
|
||||
@@ -45,37 +47,13 @@
|
||||
}
|
||||
}
|
||||
|
||||
/* Autocomplete Search input */
|
||||
.autocomplete-search {
|
||||
position: relative;
|
||||
width: 100%;
|
||||
|
||||
.search-icon {
|
||||
position: absolute;
|
||||
left: 10px;
|
||||
top: 50%;
|
||||
transform: translateY(-50%);
|
||||
font-size: 18px;
|
||||
width: 18px;
|
||||
height: 18px;
|
||||
color: #9ca3af;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
input {
|
||||
.search-form-field {
|
||||
width: 100%;
|
||||
padding: 0.6rem 0.6rem 0.6rem 2.2rem;
|
||||
border-radius: 8px;
|
||||
border: 1px solid #d1d5db;
|
||||
font-size: 0.8125rem;
|
||||
outline: none;
|
||||
box-sizing: border-box;
|
||||
transition: all 0.2s ease;
|
||||
|
||||
&:focus {
|
||||
border-color: #3b82f6;
|
||||
box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
|
||||
}
|
||||
display: block;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -7,15 +7,18 @@
|
||||
|
||||
<!-- Autocomplete Search Input for Authors -->
|
||||
<div class="autocomplete-search">
|
||||
<mat-form-field appearance="outline" class="search-form-field">
|
||||
<mat-icon matPrefix>search</mat-icon>
|
||||
<mat-form-field
|
||||
appearance="outline"
|
||||
class="search-form-field"
|
||||
subscriptSizing="dynamic"
|
||||
style="width: 100%">
|
||||
<mat-label>Autor vergleichen</mat-label>
|
||||
<input
|
||||
matInput
|
||||
type="text"
|
||||
placeholder="Autor suchen und hinzufügen..."
|
||||
[value]="searchQuery()"
|
||||
(input)="onSearchInput($event)" />
|
||||
<mat-icon matPrefix>search</mat-icon>
|
||||
@if (searchQuery()) {
|
||||
<button
|
||||
mat-icon-button
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
:host {
|
||||
display: block;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
min-width: 0;
|
||||
max-width: 100%;
|
||||
}
|
||||
@@ -8,19 +9,20 @@
|
||||
.author-selector-container {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1.5fr;
|
||||
gap: 24px;
|
||||
gap: 20px;
|
||||
background: white;
|
||||
border: 1px solid #d7e4ff;
|
||||
border-radius: 16px;
|
||||
padding: 24px;
|
||||
box-shadow: 0 8px 24px rgba(15, 23, 42, 0.04);
|
||||
border: 1px solid #e2e8f0;
|
||||
border-radius: 12px;
|
||||
padding: 1.25rem;
|
||||
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.04);
|
||||
box-sizing: border-box;
|
||||
height: 100%;
|
||||
margin-top: 0;
|
||||
|
||||
@media (max-width: 1024px) {
|
||||
grid-template-columns: 1fr;
|
||||
gap: 20px;
|
||||
padding: 16px;
|
||||
gap: 16px;
|
||||
padding: 1rem;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -52,38 +54,14 @@
|
||||
}
|
||||
}
|
||||
|
||||
/* Autocomplete Search input */
|
||||
.autocomplete-search {
|
||||
position: relative;
|
||||
width: 100%;
|
||||
margin-bottom: 1rem;
|
||||
|
||||
.search-icon {
|
||||
position: absolute;
|
||||
left: 10px;
|
||||
top: 50%;
|
||||
transform: translateY(-50%);
|
||||
font-size: 18px;
|
||||
width: 18px;
|
||||
height: 18px;
|
||||
color: #9ca3af;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
input {
|
||||
.search-form-field {
|
||||
width: 100%;
|
||||
padding: 0.6rem 0.6rem 0.6rem 2.2rem;
|
||||
border-radius: 8px;
|
||||
border: 1px solid #d1d5db;
|
||||
font-size: 0.8125rem;
|
||||
outline: none;
|
||||
box-sizing: border-box;
|
||||
transition: all 0.2s ease;
|
||||
|
||||
&:focus {
|
||||
border-color: #3b82f6;
|
||||
box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
|
||||
}
|
||||
display: block;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -148,9 +126,9 @@
|
||||
|
||||
.chips-flex {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
flex-direction: column;
|
||||
gap: 0.5rem;
|
||||
max-height: 180px;
|
||||
max-height: 140px;
|
||||
overflow-y: auto;
|
||||
padding-right: 4px;
|
||||
width: 100%;
|
||||
@@ -158,12 +136,12 @@
|
||||
}
|
||||
|
||||
.comparison-item {
|
||||
display: inline-flex;
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
border: 1px solid #e5e7eb;
|
||||
border-radius: 6px;
|
||||
padding: 0.35rem 0.6rem;
|
||||
padding: 0.4rem 0.65rem;
|
||||
gap: 8px;
|
||||
transition: all 0.2s ease;
|
||||
max-width: 100%;
|
||||
|
||||
@@ -24,15 +24,18 @@
|
||||
|
||||
<!-- Autocomplete Search Input -->
|
||||
<div class="autocomplete-search">
|
||||
<mat-form-field appearance="outline" class="search-form-field">
|
||||
<mat-icon matPrefix>search</mat-icon>
|
||||
<mat-form-field
|
||||
appearance="outline"
|
||||
class="search-form-field"
|
||||
subscriptSizing="dynamic"
|
||||
style="width: 100%">
|
||||
<mat-label>Einrichtung vergleichen</mat-label>
|
||||
<input
|
||||
matInput
|
||||
type="text"
|
||||
placeholder="Einrichtung suchen und hinzufügen..."
|
||||
[value]="searchQuery()"
|
||||
(input)="onSearchInput($event)" />
|
||||
<mat-icon matPrefix>search</mat-icon>
|
||||
@if (searchQuery()) {
|
||||
<button
|
||||
mat-icon-button
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
:host {
|
||||
display: block;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
min-width: 0;
|
||||
max-width: 100%;
|
||||
}
|
||||
@@ -8,19 +9,20 @@
|
||||
.institution-selector-container {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1.5fr;
|
||||
gap: 24px;
|
||||
gap: 20px;
|
||||
background: white;
|
||||
border: 1px solid #d7e4ff;
|
||||
border-radius: 16px;
|
||||
padding: 24px;
|
||||
box-shadow: 0 8px 24px rgba(15, 23, 42, 0.04);
|
||||
border: 1px solid #e2e8f0;
|
||||
border-radius: 12px;
|
||||
padding: 1.25rem;
|
||||
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.04);
|
||||
box-sizing: border-box;
|
||||
height: 100%;
|
||||
margin-top: 0;
|
||||
|
||||
@media (max-width: 1024px) {
|
||||
grid-template-columns: 1fr;
|
||||
gap: 20px;
|
||||
padding: 16px;
|
||||
gap: 16px;
|
||||
padding: 1rem;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -81,38 +83,14 @@
|
||||
}
|
||||
}
|
||||
|
||||
/* Autocomplete Search input */
|
||||
.autocomplete-search {
|
||||
position: relative;
|
||||
width: 100%;
|
||||
margin-bottom: 1rem;
|
||||
|
||||
.search-icon {
|
||||
position: absolute;
|
||||
left: 10px;
|
||||
top: 50%;
|
||||
transform: translateY(-50%);
|
||||
font-size: 18px;
|
||||
width: 18px;
|
||||
height: 18px;
|
||||
color: #9ca3af;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
input {
|
||||
.search-form-field {
|
||||
width: 100%;
|
||||
padding: 0.6rem 0.6rem 0.6rem 2.2rem;
|
||||
border-radius: 8px;
|
||||
border: 1px solid #d1d5db;
|
||||
font-size: 0.8125rem;
|
||||
outline: none;
|
||||
box-sizing: border-box;
|
||||
transition: all 0.2s ease;
|
||||
|
||||
&:focus {
|
||||
border-color: #3b82f6;
|
||||
box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
|
||||
}
|
||||
display: block;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -177,9 +155,9 @@
|
||||
|
||||
.chips-flex {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
flex-direction: column;
|
||||
gap: 0.5rem;
|
||||
max-height: 180px;
|
||||
max-height: 140px;
|
||||
overflow-y: auto;
|
||||
padding-right: 4px;
|
||||
width: 100%;
|
||||
@@ -187,12 +165,12 @@
|
||||
}
|
||||
|
||||
.comparison-item {
|
||||
display: inline-flex;
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
border: 1px solid #e5e7eb;
|
||||
border-radius: 6px;
|
||||
padding: 0.35rem 0.6rem;
|
||||
padding: 0.4rem 0.65rem;
|
||||
gap: 8px;
|
||||
transition: all 0.2s ease;
|
||||
max-width: 100%;
|
||||
|
||||
@@ -1,6 +1,47 @@
|
||||
<div class="control-card">
|
||||
<h3>Länder/Kontinente vergleichen</h3>
|
||||
|
||||
<!-- Autocomplete-Suche für Länder/Kontinente -->
|
||||
<div class="autocomplete-search">
|
||||
<mat-form-field
|
||||
appearance="outline"
|
||||
class="search-form-field"
|
||||
subscriptSizing="dynamic"
|
||||
style="width: 100%">
|
||||
<mat-label>Land oder Kontinent suchen</mat-label>
|
||||
<input
|
||||
matInput
|
||||
type="text"
|
||||
[value]="locationQuery()"
|
||||
(input)="onSearchInput($event)" />
|
||||
<mat-icon matPrefix>search</mat-icon>
|
||||
@if (locationQuery()) {
|
||||
<button
|
||||
mat-icon-button
|
||||
matSuffix
|
||||
(click)="searchChange.emit('')"
|
||||
aria-label="Löschen"
|
||||
type="button">
|
||||
<mat-icon>clear</mat-icon>
|
||||
</button>
|
||||
}
|
||||
</mat-form-field>
|
||||
@if (locationSearchResults().length > 0) {
|
||||
<ul class="autocomplete-results">
|
||||
@for (loc of locationSearchResults(); track loc.id) {
|
||||
<li>
|
||||
<button type="button" (click)="onSelectResult(loc)">
|
||||
<span class="name">{{ loc.display_name }}</span>
|
||||
<span class="hint">{{
|
||||
loc.type === 'country' ? 'Land' : 'Kontinent'
|
||||
}}</span>
|
||||
</button>
|
||||
</li>
|
||||
}
|
||||
</ul>
|
||||
}
|
||||
</div>
|
||||
|
||||
<div class="comparison-list">
|
||||
@if (comparisonCountries().length > 0 || comparisonRegions().length > 0) {
|
||||
<!-- Countries -->
|
||||
@@ -100,42 +141,4 @@
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
|
||||
<!-- Autocomplete-Suche für Länder/Kontinente -->
|
||||
<div class="autocomplete-search">
|
||||
<mat-form-field appearance="outline" class="search-form-field">
|
||||
<mat-icon matPrefix>search</mat-icon>
|
||||
<mat-label>Land oder Kontinent suchen</mat-label>
|
||||
<input
|
||||
matInput
|
||||
type="text"
|
||||
placeholder="Land oder Kontinent suchen..."
|
||||
[value]="locationQuery()"
|
||||
(input)="onSearchInput($event)" />
|
||||
@if (locationQuery()) {
|
||||
<button
|
||||
mat-icon-button
|
||||
matSuffix
|
||||
(click)="searchChange.emit('')"
|
||||
aria-label="Löschen"
|
||||
type="button">
|
||||
<mat-icon>clear</mat-icon>
|
||||
</button>
|
||||
}
|
||||
</mat-form-field>
|
||||
@if (locationSearchResults().length > 0) {
|
||||
<ul class="autocomplete-results">
|
||||
@for (loc of locationSearchResults(); track loc.id) {
|
||||
<li>
|
||||
<button type="button" (click)="onSelectResult(loc)">
|
||||
<span class="name">{{ loc.display_name }}</span>
|
||||
<span class="hint">{{
|
||||
loc.type === 'country' ? 'Land' : 'Kontinent'
|
||||
}}</span>
|
||||
</button>
|
||||
</li>
|
||||
}
|
||||
</ul>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -1,21 +1,25 @@
|
||||
:host {
|
||||
display: block;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
min-width: 0;
|
||||
max-width: 100%;
|
||||
}
|
||||
|
||||
.control-card {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
height: 100%;
|
||||
background: white;
|
||||
border-radius: 10px;
|
||||
border-radius: 12px;
|
||||
padding: 1.25rem;
|
||||
border: 1px solid #e5e7eb;
|
||||
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
|
||||
border: 1px solid #e2e8f0;
|
||||
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.04);
|
||||
box-sizing: border-box;
|
||||
|
||||
h3 {
|
||||
font-size: 0.8rem;
|
||||
font-weight: 600;
|
||||
font-weight: 700;
|
||||
text-transform: uppercase;
|
||||
color: #6b7280;
|
||||
margin: 0 0 0.75rem 0;
|
||||
@@ -23,21 +27,34 @@
|
||||
}
|
||||
}
|
||||
|
||||
.autocomplete-search {
|
||||
position: relative;
|
||||
width: 100%;
|
||||
margin-bottom: 0.75rem;
|
||||
|
||||
.search-form-field {
|
||||
width: 100%;
|
||||
display: block;
|
||||
}
|
||||
}
|
||||
|
||||
.comparison-list {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.4rem;
|
||||
max-height: 200px;
|
||||
gap: 0.5rem;
|
||||
max-height: 140px;
|
||||
overflow-y: auto;
|
||||
margin-bottom: 0.75rem;
|
||||
padding-right: 4px;
|
||||
flex: 1;
|
||||
box-sizing: border-box;
|
||||
|
||||
.empty-list-info {
|
||||
font-size: 0.75rem;
|
||||
color: #9ca3af;
|
||||
text-align: center;
|
||||
padding: 8px 0;
|
||||
padding: 12px 8px;
|
||||
border: 1px dashed #e5e7eb;
|
||||
border-radius: 5px;
|
||||
border-radius: 6px;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -46,8 +63,8 @@
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
border: 1px solid #e5e7eb;
|
||||
border-radius: 5px;
|
||||
padding: 0.3rem 0.5rem;
|
||||
border-radius: 6px;
|
||||
padding: 0.4rem 0.65rem;
|
||||
transition: all 0.2s ease;
|
||||
|
||||
.item-name {
|
||||
@@ -59,7 +76,7 @@
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
max-width: 170px;
|
||||
max-width: 180px;
|
||||
|
||||
mat-icon {
|
||||
font-size: 14px;
|
||||
@@ -102,29 +119,6 @@
|
||||
}
|
||||
}
|
||||
|
||||
.autocomplete-search {
|
||||
position: relative;
|
||||
width: 100%;
|
||||
|
||||
.search-form-field {
|
||||
width: 100%;
|
||||
display: block;
|
||||
}
|
||||
|
||||
input {
|
||||
width: 100%;
|
||||
padding: 0.5rem;
|
||||
border-radius: 5px;
|
||||
border: 1px solid #d1d5db;
|
||||
font-size: 0.8125rem;
|
||||
outline: none;
|
||||
box-sizing: border-box;
|
||||
&:focus {
|
||||
border-color: #3b82f6;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.autocomplete-results {
|
||||
position: absolute;
|
||||
top: 100%;
|
||||
|
||||
Reference in New Issue
Block a user