researchbee / researchbee_journals.py
nikeshn's picture
Upload 47 files
1916d8e verified
Raw History Blame Contribute Delete
39.1 kB
"""
ResearchBee journal index + recommender.
from researchbee_journals import JournalIndex
idx = JournalIndex("journals.db")
idx.lookup(issn="0737-8831") # -> JournalRecord (Library Hi Tech)
idx.recommend(title=..., abstract=...) # -> [Recommendation, ...]
Architecture
------------
Three stages, deliberately separated so the expensive one stays optional:
1. CANDIDATE GENERATION β€” hard ASJC filter (when subject codes are known) plus
FTS5/BM25 over title + publisher + subject names. Pure SQLite, no model,
sub-10ms, returns a few hundred candidates.
2. SEMANTIC RERANK β€” optional. Cosine similarity between the manuscript
embedding and a per-journal centroid. See the honest caveat below.
3. FIT SCORING β€” quartile, indexation state, OA status, coverage
recency, language, publisher agreement coverage. Deterministic, explainable,
and the part that should drive the text ResearchBee shows the researcher.
The caveat on stage 2
---------------------
The Scopus Source List carries no aims-and-scope text. Embedding a journal
*title* against a manuscript *abstract* is a weak signal β€” it recovers obvious
lexical matches ("Journal of Hydrology" for a hydrology paper) and little else.
Real matchers (Jane, Elsevier Journal Finder, WoS Match Manuscript) compare the
manuscript against *articles the journal has published*. To reach that quality
you need article-level text, which means building journal centroids from OpenAlex
works β€” `build_centroids.py` does this. Until centroids exist, `recommend()`
runs stages 1 and 3 only and says so in `Recommendation.method`, rather than
quietly returning title-similarity noise dressed up as semantic matching.
"""
from __future__ import annotations
import re
import html
import sqlite3
import threading
import unicodedata
from dataclasses import dataclass, field, asdict
from pathlib import Path
from typing import Iterable, Sequence
__all__ = ["JournalIndex", "JournalRecord", "Recommendation", "IndexationState"]
# ---------------------------------------------------------------------------
# Indexation state β€” the distinction the old lookup collapsed
# ---------------------------------------------------------------------------
class IndexationState:
"""
Why this exists: 'no quartile' is three materially different answers to a
researcher deciding where to submit.
INDEXED_RANKED in Scopus, has a current SJR and quartile. (30,405)
INDEXED_NEW in Scopus, coverage began 2024+, SJR not yet computed.
SJR needs a ~3-year citation window, so the absence is a
timing artefact, not a quality signal. Safe to submit to.
(326)
INDEXED_UNRANKED SCImago has a record but computes no SJR β€” typically below
its citable-document threshold. Thin but real. (279)
INDEXED_NO_SJR in Scopus, absent from SCImago entirely. Overwhelmingly
book series (1,052), which SJR does not rank at all. Only
~70 are long-running journals, mostly regional titles.
(1,366)
NOT_INDEXED no Scopus source record at all, active or inactive.
And three states for titles Scopus no longer indexes. Keeping them apart is
the whole point: of 16,838 inactive titles only 967 were removed for cause.
Telling a researcher that a journal which merely changed its name is a
quality risk is worse than saying nothing.
DISCONTINUED removed by Scopus for cause. The real red flag. (967)
RENAMED ceased under this title but the work continues elsewhere;
`successor_title` names where. Benign β€” redirect, don't
warn. (~7,000 with a resolvable successor)
CEASED stopped being indexed, no successor recorded and no
discontinuation flag. Usually a journal that folded.
"""
INDEXED_RANKED = "indexed_ranked"
INDEXED_NEW = "indexed_new"
INDEXED_UNRANKED = "indexed_unranked"
INDEXED_NO_SJR = "indexed_no_sjr"
NOT_INDEXED = "not_indexed"
DISCONTINUED = "discontinued"
RENAMED = "renamed"
CEASED = "ceased"
#: States a prospective author should be actively warned about.
WARN = frozenset({DISCONTINUED})
#: States meaning "Scopus does not index new articles here".
NOT_CURRENTLY_INDEXED = frozenset({DISCONTINUED, RENAMED, CEASED, NOT_INDEXED})
MESSAGES = {
INDEXED_RANKED: "Indexed in Scopus with a current SJR quartile.",
INDEXED_NEW: (
"Indexed in Scopus, but coverage is too recent for an SJR quartile. "
"SJR requires roughly three years of citation data; expect a first "
"quartile assignment once that window closes. The missing quartile "
"is not a quality signal."
),
INDEXED_UNRANKED: (
"Indexed in Scopus and listed by SCImago, but no SJR is computed β€” "
"usually because the title publishes too few citable documents to "
"meet SCImago's threshold."
),
INDEXED_NO_SJR: (
"Indexed in Scopus but absent from SCImago. Normal for book series "
"and trade journals, which SJR does not rank. Check the source type "
"before treating this as a concern."
),
NOT_INDEXED: (
"No Scopus source record found β€” this title is not indexed in "
"Scopus, and has no record of having been."
),
DISCONTINUED: (
"Scopus has discontinued this title β€” it was removed from the index "
"rather than ceasing publication. Articles published here will not "
"be indexed in Scopus. Scopus does not publish the reason for an "
"individual discontinuation; grounds range from publication-ethics "
"concerns to metrics such as self-citation, and discontinued titles "
"include some from major publishers. Verify independently before "
"submitting, and do not assume the journal is predatory."
),
RENAMED: (
"This title is no longer indexed under this name, but the journal "
"continues. This is a rename or merger, not a quality concern."
),
CEASED: (
"Scopus no longer indexes this title and no successor is recorded β€” "
"the journal appears to have ceased publication. Not flagged as a "
"discontinuation for cause."
),
}
_ISSN_RE = re.compile(r"[^0-9X]")
def norm_issn(v: str | None) -> str | None:
if not v:
return None
s = _ISSN_RE.sub("", str(v).strip().upper())
if len(s) < 8:
s = s.zfill(8)
return s if len(s) == 8 else None
# ---------------------------------------------------------------------------
# Records
# ---------------------------------------------------------------------------
@dataclass
class JournalRecord:
scopus_id: str
title: str
issn_print: str | None
issn_e: str | None
source_type: str | None
publisher: str | None
publisher_group: str | None
coverage_start: int | None
coverage_end: int | None
coverage_has_gap: bool
oa_unpaywall: bool
medline: bool
has_english: bool
languages: str | None
sjr: float | None
sjr_rank: int | None
sjr_best_quartile: str | None
h_index: int | None
cites_per_doc_2y: float | None
total_docs_year: int | None
oa_diamond: bool
scimago_oa: bool
overton: int | None
country: str | None
scimago_id: str | None = None
lifecycle: str = "active"
successor_title: str | None = None
successor_scopus_id: str | None = None
successor_is_active: bool = False
subjects: list[dict] = field(default_factory=list)
state: str = IndexationState.NOT_INDEXED
state_message: str = ""
@property
def warn(self) -> bool:
"""True when a prospective author should be actively cautioned."""
return self.state in IndexationState.WARN
@property
def currently_indexed(self) -> bool:
return self.state not in IndexationState.NOT_CURRENTLY_INDEXED
def quartile_for(self, asjc: str) -> str | None:
"""Quartile in one specific subject area, not the journal's best."""
for s in self.subjects:
if s["asjc"] == asjc:
return s.get("quartile")
return None
def to_dict(self) -> dict:
return asdict(self)
@dataclass
class Recommendation:
journal: JournalRecord
score: float
reasons: list[str]
method: str
components: dict[str, float] = field(default_factory=dict)
# ---------------------------------------------------------------------------
# Index
# ---------------------------------------------------------------------------
_STOP = set("""
a an the and or but if of in on at to for with by from as is are was were be been
being this that these those it its we our they their he she his her you your not
no can may might will would should could have has had do does did than then so
such other others new novel study studies paper article research results method
methods approach based using used use show shows shown propose proposed present
presented provide provides between among during through both each more most many
much also however therefore thus while when where which who whom what how why
""".split())
class JournalIndex:
"""Thread-safe read-only wrapper over journals.db."""
def __init__(self, db_path: str | Path):
self.db_path = str(db_path)
if not Path(self.db_path).exists():
raise FileNotFoundError(self.db_path)
self._local = threading.local()
self._exact_title_ids: dict[str, list[str]] | None = None
@property
def con(self) -> sqlite3.Connection:
con = getattr(self._local, "con", None)
if con is None:
con = sqlite3.connect(f"file:{self.db_path}?mode=ro", uri=True,
check_same_thread=False)
con.row_factory = sqlite3.Row
con.execute("PRAGMA mmap_size = 268435456")
self._local.con = con
return con
# -- meta ---------------------------------------------------------------
def meta(self) -> dict[str, str]:
return {r["key"]: r["value"] for r in self.con.execute("SELECT * FROM meta")}
# -- lookup -------------------------------------------------------------
@staticmethod
def normalise_identity_title(title: str) -> str:
"""Normalise typography without turning a partial title into an identity."""
value = unicodedata.normalize("NFKC", html.unescape(str(title or ""))).casefold()
value = value.replace("&", " and ")
return " ".join(re.sub(r"[^\w]+", " ", value).split())
def lookup_exact(self, issn: str | None = None, title: str | None = None,
scopus_id: str | None = None) -> JournalRecord | None:
"""Resolve a canonical identity, never the first approximate FTS hit.
IDs and ISSNs take precedence. A title must have a unique complete
normalised match; ambiguous titles remain unresolved so a caller can
request an ISSN. ``lookup`` keeps its discovery-oriented fuzzy behavior.
"""
if scopus_id:
row = self.con.execute(
"SELECT * FROM journals WHERE scopus_id = ?", (str(scopus_id),)
).fetchone()
if row is not None:
return self._to_record(row)
if issn:
key = norm_issn(issn)
if key:
rows = self.con.execute(
"SELECT * FROM journals WHERE issn_e = ? OR issn_print = ? LIMIT 2",
(key, key),
).fetchall()
if len(rows) == 1:
return self._to_record(rows[0])
if len(rows) > 1:
return None
if title:
key = self.normalise_identity_title(title)
if not key:
return None
if self._exact_title_ids is None:
by_title: dict[str, list[str]] = {}
for row in self.con.execute("SELECT scopus_id, title FROM journals"):
normalised = self.normalise_identity_title(row["title"])
by_title.setdefault(normalised, []).append(row["scopus_id"])
self._exact_title_ids = by_title
matches = self._exact_title_ids.get(key, [])
if len(matches) == 1:
return self.lookup(scopus_id=matches[0])
return None
def lookup(self, issn: str | None = None, title: str | None = None,
scopus_id: str | None = None) -> JournalRecord | None:
row = None
if scopus_id:
row = self.con.execute(
"SELECT * FROM journals WHERE scopus_id = ?", (scopus_id,)
).fetchone()
if row is None and issn:
key = norm_issn(issn)
if key:
row = self.con.execute(
"SELECT * FROM journals WHERE issn_e = ? OR issn_print = ? LIMIT 1",
(key, key),
).fetchone()
if row is None and title:
row = self.con.execute(
"SELECT * FROM journals WHERE lower(title) = lower(?) LIMIT 1",
(title.strip(),),
).fetchone()
if row is None:
hits = self._fts(title, limit=1, weights=self._W_LOOKUP)
if hits:
row = self.con.execute(
"SELECT * FROM journals WHERE scopus_id = ?", (hits[0][0],)
).fetchone()
return self._to_record(row) if row else None
def _to_record(self, row: sqlite3.Row) -> JournalRecord:
subs = [
{"asjc": r["asjc"], "name": r["name"], "parent": r["parent_name"],
"quartile": r["quartile"], "is_primary": bool(r["is_primary"])}
for r in self.con.execute(
"""SELECT ja.asjc, ja.is_primary, ja.quartile, a.name, a.parent_name
FROM journal_asjc ja JOIN asjc a ON a.code = ja.asjc
WHERE ja.scopus_id = ? ORDER BY ja.is_primary DESC, ja.asjc""",
(row["scopus_id"],),
)
]
rec = JournalRecord(
scopus_id=row["scopus_id"], title=row["title"],
issn_print=self._fmt(row["issn_print"]), issn_e=self._fmt(row["issn_e"]),
source_type=row["source_type"], publisher=row["publisher"],
publisher_group=row["publisher_group"],
coverage_start=row["coverage_start"], coverage_end=row["coverage_end"],
coverage_has_gap=bool(row["coverage_has_gap"]),
oa_unpaywall=bool(row["oa_unpaywall"]), medline=bool(row["medline"]),
has_english=bool(row["has_english"]), languages=row["languages"],
sjr=row["sjr"], sjr_rank=row["sjr_rank"],
sjr_best_quartile=row["sjr_best_quartile"], h_index=row["h_index"],
cites_per_doc_2y=row["cites_per_doc_2y"],
total_docs_year=row["total_docs_year"],
oa_diamond=bool(row["oa_diamond"]),
scimago_oa=bool(row["scimago_oa"]), overton=row["overton"],
country=row["country"], scimago_id=row["scimago_id"],
lifecycle=row["lifecycle"],
successor_title=row["successor_title"],
successor_scopus_id=row["successor_scopus_id"],
successor_is_active=bool(row["successor_is_active"]),
subjects=subs,
)
rec.state = self._state(row)
rec.state_message = self._message(rec)
return rec
@staticmethod
def _message(rec: "JournalRecord") -> str:
"""Base message, extended with the successor when we resolved one."""
msg = IndexationState.MESSAGES[rec.state]
if rec.successor_title:
where = (
"which is actively indexed"
if rec.successor_is_active
else "which is itself no longer indexed"
)
if rec.state == IndexationState.RENAMED:
msg += f" It continues as {rec.successor_title!r}, {where}."
elif rec.state in (IndexationState.DISCONTINUED, IndexationState.CEASED):
# A successor on a discontinued title does not soften the
# warning β€” it just tells the researcher where to look next.
msg += f" Scopus records a successor title, {rec.successor_title!r}, {where}."
return msg
@staticmethod
def _fmt(s: str | None) -> str | None:
return f"{s[:4]}-{s[4:]}" if s and len(s) == 8 else None
_STATE_BY_STATUS = {
"matched": IndexationState.INDEXED_RANKED,
"no_sjr_new_title": IndexationState.INDEXED_NEW,
"no_sjr_listed_unranked": IndexationState.INDEXED_UNRANKED,
"no_sjr_unmatched": IndexationState.INDEXED_NO_SJR,
}
_STATE_BY_LIFECYCLE = {
"discontinued": IndexationState.DISCONTINUED,
"renamed": IndexationState.RENAMED,
"ceased": IndexationState.CEASED,
}
@classmethod
def _state(cls, row: sqlite3.Row) -> str:
# Lifecycle wins over SJR status. A discontinued title may still carry a
# quartile from when it was indexed, and reporting that quartile as the
# headline would bury the thing the researcher actually needs to know.
lc = cls._STATE_BY_LIFECYCLE.get(row["lifecycle"])
if lc:
return lc
return cls._STATE_BY_STATUS.get(
row["sjr_status"], IndexationState.INDEXED_NO_SJR
)
# -- candidate generation ----------------------------------------------
# bm25 column weights: (scopus_id, title, publisher_group, subjects).
# Publisher is weighted to zero for topical work β€” "University Library
# System" is not evidence that a cinema journal wants your library paper,
# and leaving it at 1.0 lets one publisher flood the candidate pool. It
# stays queryable for name lookups via _W_LOOKUP.
_W_TOPIC = (0.0, 4.0, 0.0, 3.0)
_W_LOOKUP = (0.0, 8.0, 1.0, 0.5)
def _fts(self, text: str, limit: int = 400,
asjc: Sequence[str] | None = None,
weights: tuple[float, ...] | None = None,
active_only: bool = False) -> list[tuple[str, float]]:
terms = self._terms(text)
if not terms:
return []
w = weights or self._W_TOPIC
query = " OR ".join(f'"{t}"' for t in terms)
sql = f"""
SELECT f.scopus_id AS sid,
bm25(journals_fts, {w[0]}, {w[1]}, {w[2]}, {w[3]}) AS rank
FROM journals_fts f WHERE journals_fts MATCH ?
"""
params: list = [query]
if active_only:
# Applied inside candidate generation, not after: the index holds
# 16,838 inactive titles, and letting them consume the candidate
# pool would silently shrink the number of real options considered.
sql += " AND f.scopus_id IN (SELECT scopus_id FROM journals WHERE active = 1)"
if asjc:
marks = ",".join("?" * len(asjc))
sql += f""" AND f.scopus_id IN (
SELECT scopus_id FROM journal_asjc WHERE asjc IN ({marks}))"""
params += list(asjc)
sql += " ORDER BY rank LIMIT ?"
params.append(limit)
return [(r["sid"], r["rank"]) for r in self.con.execute(sql, params)]
@staticmethod
def _terms(text: str, max_terms: int = 24) -> list[str]:
"""
FTS5 treats bare punctuation as syntax, so terms are stripped to word
characters and quoted. Frequency-ordered, stopword-filtered.
"""
from collections import Counter
words = re.findall(r"[A-Za-z][A-Za-z\-]{2,}", (text or "").lower())
words = [w.strip("-") for w in words if w not in _STOP and len(w) > 3]
return [w for w, _ in Counter(words).most_common(max_terms)]
# -- recommend ----------------------------------------------------------
def recommend(
self,
title: str = "",
abstract: str = "",
asjc: Sequence[str] | None = None,
*,
limit: int = 20,
candidate_pool: int = 400,
require_english: bool = True,
require_oa: bool = False,
oa_mode: str = "any",
exclude_book_series: bool = True,
min_quartile: str | None = None,
allowed_quartiles: Sequence[str] | None = None,
publisher_agreements: Iterable[str] = (),
exclude_titles: Iterable[str] = (),
preferred_titles: Iterable[str] = (),
embedder=None,
centroids=None,
asjc_classifier=None,
) -> list[Recommendation]:
"""
`asjc` β€” subject codes to hard-filter on. Supply these when you know the
manuscript's field; recall from free text alone is mediocre.
`min_quartile` β€” 'Q1' or 'Q2'. Applied against the quartile in the
filtered subject area when `asjc` is given, otherwise against
the journal's best quartile.
`publisher_agreements` β€” publisher_group names the institution holds a
read-and-publish deal with; matches get a scoring bonus and an
explicit reason string.
`oa_mode` β€” "any", "open" or "diamond". The source index has a
journal-level OA flag and a separate Diamond flag; it does not
claim that a non-OA title is definitely hybrid.
`allowed_quartiles` β€” exact allowed quartiles (for example Q1/Q2).
`exclude_titles` / `preferred_titles` β€” normalised title controls applied
in code. Preferred titles receive a small bonus but are never
forced above stronger subject matches.
`embedder`/`centroids` β€” optional stage 2. See module docstring.
`asjc_classifier` β€” an AsjcClassifier. When `asjc` is not supplied, the
subject codes are inferred from the manuscript rather than
left empty. This matters more than any other option here: the
subject filter is what makes the results usable, and an
unfiltered free-text search returns unrelated journals.
"""
inferred = None
if not asjc and asjc_classifier is not None:
inferred = asjc_classifier.classify(title=title, abstract=abstract)
asjc = inferred.codes or None
def _norm_title(value: str) -> str:
return re.sub(r"[^a-z0-9]+", " ", (value or "").lower()).strip()
preferred = {_norm_title(t) for t in preferred_titles if _norm_title(str(t))}
excluded = {_norm_title(t) for t in exclude_titles if _norm_title(str(t))}
text = f"{title} {title} {abstract}".strip()
cands = self._fts(text, limit=candidate_pool, asjc=asjc, active_only=True)
# FTS is a precision-first stage. When it returns fewer than the pool
# size, top active journals from the verified subject set are appended
# so a narrow vocabulary match cannot silently hide viable candidates.
if asjc and len(cands) < candidate_pool:
marks = ",".join("?" * len(asjc))
seen_ids = {sid for sid, _ in cands}
extras = self.con.execute(
f"""SELECT DISTINCT j.scopus_id FROM journals j
JOIN journal_asjc ja ON ja.scopus_id = j.scopus_id
WHERE ja.asjc IN ({marks}) AND j.active = 1
ORDER BY coalesce(j.sjr, -1) DESC,
coalesce(j.h_index, -1) DESC, j.title
LIMIT ?""",
(*asjc, candidate_pool),
).fetchall()
# Keep appended ranks just worse than the lexical tail. This
# preserves lexical ordering while allowing deterministic metadata
# scoring to surface a strong journal that used different wording.
tail = max((rank for _, rank in cands), default=0.0)
for offset, row in enumerate(extras, start=1):
sid = row["scopus_id"]
if sid not in seen_ids:
cands.append((sid, tail + offset))
seen_ids.add(sid)
if len(cands) >= candidate_pool:
break
# Resolve author-specified preferred titles to canonical active journal
# records and inject them into the candidate set. They are still subject
# to every hard subject/ranking/access filter below and receive only a
# modest preference bonus; this guarantees eligible preferred titles are
# available for comparison without allowing them to bypass verification.
if preferred:
seen_ids = {sid for sid, _ in cands}
tail = max((rank for _, rank in cands), default=0.0)
injected = 0
for requested in preferred_titles:
requested_key = _norm_title(str(requested))
if not requested_key:
continue
row = self.con.execute(
"""SELECT scopus_id, title FROM journals
WHERE active = 1 AND source_type = 'Journal'
AND lower(title) = lower(?) LIMIT 1""",
(str(requested).strip(),),
).fetchone()
if row is None:
# Punctuation and subtitle variants can defeat the exact SQL
# comparison. Use lookup-weighted FTS only to find a record
# whose normalised canonical title is still an exact match.
for sid, _rank in self._fts(
str(requested), limit=10, weights=self._W_LOOKUP,
active_only=True,
):
candidate = self.con.execute(
"SELECT scopus_id, title, source_type FROM journals WHERE scopus_id = ?",
(sid,),
).fetchone()
if (
candidate is not None
and candidate["source_type"] == "Journal"
and _norm_title(candidate["title"]) == requested_key
):
row = candidate
break
if row is not None and row["scopus_id"] not in seen_ids:
injected += 1
cands.append((row["scopus_id"], tail + injected))
seen_ids.add(row["scopus_id"])
if not cands:
return []
ranks = [r for _, r in cands]
lo, hi = min(ranks), max(ranks)
span = (hi - lo) or 1.0
method = "lexical+fit"
sem: dict[str, float] = {}
if embedder is not None and centroids is not None:
sem = self._semantic(text, [c for c, _ in cands], embedder, centroids)
if sem:
method = "lexical+semantic+fit"
out: list[Recommendation] = []
agreements = {p.lower() for p in publisher_agreements}
allowed_q = {str(q).upper() for q in (allowed_quartiles or []) if str(q).strip()}
mode = str(oa_mode or "any").strip().lower()
if require_oa and mode == "any":
mode = "open"
for sid, rank in cands:
row = self.con.execute(
"SELECT * FROM journals WHERE scopus_id = ?", (sid,)
).fetchone()
if row is None:
continue
if exclude_book_series and row["source_type"] != "Journal":
continue
if require_english and not row["has_english"]:
continue
if require_oa and not row["oa_unpaywall"]:
continue
# Never recommend somewhere Scopus no longer indexes β€” discontinued,
# renamed or ceased. Lookup still returns these (a researcher asking
# about a specific title needs the answer); recommendation must not.
if not row["active"]:
continue
rec = self._to_record(row)
title_key = _norm_title(rec.title)
if title_key in excluded:
continue
# Prefer the best quartile among the manuscript/subject codes, not
# merely the first code returned by a classifier. An explicitly
# preferred title injected above must still belong to the selected
# subject set; otherwise it cannot enter the recommendations.
# Membership is independent of whether SCImago has assigned a
# quartile. Newly indexed journals remain eligible with No filter.
subject_codes = {s["asjc"] for s in rec.subjects}
if asjc and not subject_codes.intersection(asjc):
continue
matched_pairs = [
(code, rec.quartile_for(code)) for code in (asjc or [])
if rec.quartile_for(code)
]
matched_code = None
if matched_pairs:
matched_code, q = min(
matched_pairs,
key=lambda pair: {"Q1": 1, "Q2": 2, "Q3": 3, "Q4": 4}.get(pair[1] or "", 99),
)
else:
q = None if asjc else rec.sjr_best_quartile
if min_quartile and (q is None or q > min_quartile):
continue
if allowed_q and q not in allowed_q:
continue
if mode == "diamond" and not rec.oa_diamond:
continue
if mode in {"open", "fully open", "fully_oa"} and not (
rec.oa_unpaywall or rec.scimago_oa or rec.oa_diamond
):
continue
# bm25 returns lower-is-better; invert to 0..1
lex = max(0.0, min(1.0, 1.0 - ((rank - lo) / span)))
lexical_component = 0.45 * lex
semantic_component = 0.0
score = lexical_component
reasons: list[str] = []
if sem:
semantic_component = 0.30 * sem.get(sid, 0.0)
lexical_component = 0.30 * lex
score = lexical_component + semantic_component
qbonus = {"Q1": 0.25, "Q2": 0.18, "Q3": 0.10, "Q4": 0.04}.get(q or "", 0.0)
score += qbonus
if q:
label = (
f"{q} in {self._asjc_name(matched_code)}"
if matched_code else f"{q} (best quartile)"
)
reasons.append(label)
elif rec.state == IndexationState.INDEXED_NEW:
score += 0.06
reasons.append("Newly indexed β€” no quartile yet, not a quality signal")
if rec.coverage_end and rec.coverage_end >= 2026:
score += 0.05
else:
reasons.append(f"Coverage appears to end {rec.coverage_end} β€” verify status")
if rec.oa_diamond:
# Diamond = no APC and no subscription. For an author without
# grant funding this outranks quartile as a practical criterion,
# so it is weighted above the generic OA flag.
score += 0.10
reasons.append("Diamond open access β€” no APC")
elif rec.oa_unpaywall:
score += 0.06
reasons.append("Open access")
agreement_bonus = 0.0
if rec.publisher_group and rec.publisher_group.lower() in agreements:
agreement_bonus = 0.12
score += agreement_bonus
reasons.append(
f"Publisher appears in your {rec.publisher_group} agreement list β€” title-level eligibility still requires verification"
)
preferred_bonus = 0.0
if title_key in preferred:
preferred_bonus = 0.08
score += preferred_bonus
reasons.append("Author-specified preferred journal; retained for comparison, not automatically promoted")
if rec.coverage_has_gap:
score -= 0.04
reasons.append("Discontinuous Scopus coverage")
if rec.medline:
reasons.append("Medline-sourced")
out.append(Recommendation(
rec, round(score, 4), reasons, method,
components={
"lexical": round(lexical_component, 4),
"semantic": round(semantic_component, 4),
"quartile": round(qbonus, 4),
"agreement": round(agreement_bonus, 4),
"preferred": round(preferred_bonus, 4),
},
))
out.sort(key=lambda r: r.score, reverse=True)
selected = out[:limit]
if preferred and limit > 0:
# Preserve every eligible preferred title inside the bounded result
# set. Replace the lowest-scoring non-preferred item rather than
# inflating the preferred title's score or moving it to the top.
selected_ids = {r.journal.scopus_id for r in selected}
for pref_rec in (r for r in out if _norm_title(r.journal.title) in preferred):
if pref_rec.journal.scopus_id in selected_ids:
continue
replace_at = next(
(
i for i in range(len(selected) - 1, -1, -1)
if _norm_title(selected[i].journal.title) not in preferred
),
None,
)
if replace_at is None:
break
selected_ids.discard(selected[replace_at].journal.scopus_id)
selected[replace_at] = pref_rec
selected_ids.add(pref_rec.journal.scopus_id)
selected.sort(key=lambda r: r.score, reverse=True)
out = selected
# An inferred subject filter silently determines the entire result set,
# so it is never left implicit: every result says which subject was
# inferred and how, giving the user something concrete to correct when
# the classifier picked the wrong field.
if inferred is not None:
note = f"Subject inferred as {', '.join(inferred.names)} ({inferred.method})"
for r in out:
r.reasons.append(note)
r.method = f"{r.method}+asjc:{inferred.method}"
return out
def _asjc_name(self, code: str) -> str:
r = self.con.execute("SELECT name, parent_name FROM asjc WHERE code = ?",
(code,)).fetchone()
return (r["name"] or r["parent_name"]) if r else code
@staticmethod
def _semantic(text, sids, embedder, centroids) -> dict[str, float]:
import numpy as np
v = np.asarray(embedder(text), dtype="float32").ravel()
v /= (np.linalg.norm(v) or 1.0)
got = {s: centroids[s] for s in sids if s in centroids}
if not got:
return {}
keys = list(got)
M = np.vstack([got[k] for k in keys]).astype("float32")
M /= (np.linalg.norm(M, axis=1, keepdims=True) + 1e-9)
sims = M @ v
lo, hi = float(sims.min()), float(sims.max())
span = (hi - lo) or 1.0
return {k: float((s - lo) / span) for k, s in zip(keys, sims)}
# -- subject helpers ----------------------------------------------------
def find_asjc(self, query: str, limit: int = 10) -> list[dict]:
"""Resolve a free-text subject to ASJC codes, for populating the filter."""
like = f"%{query.strip().lower()}%"
return [
dict(r) for r in self.con.execute(
"""SELECT code, name, parent_code, parent_name, n_journals FROM asjc
WHERE lower(name) LIKE ? OR lower(parent_name) LIKE ?
ORDER BY n_journals DESC LIMIT ?""",
(like, like, limit),
)
]
def resolve_asjc(
self,
*,
category: str = "",
area: str = "",
names: Sequence[str] | None = None,
) -> list[dict]:
"""Resolve verified category/area names to ASJC rows.
Exact names are used deliberately. The caller is expected to normalise
free text against the closed vocabulary before reaching this method.
Duplicate category labels in the source list are retained because some
broad miscellaneous categories have both a parent and child code.
"""
wanted = [str(n).strip() for n in (names or []) if str(n).strip()]
if category and category.strip():
wanted.insert(0, category.strip())
out: list[dict] = []
seen: set[str] = set()
for name in wanted:
rows = self.con.execute(
"""SELECT code, name, parent_code, parent_name, n_journals
FROM asjc WHERE lower(name) = lower(?)
ORDER BY n_journals DESC, code""",
(name,),
).fetchall()
for row in rows:
if row["code"] not in seen:
seen.add(row["code"]); out.append(dict(row))
if area and area.strip():
rows = self.con.execute(
"""SELECT code, name, parent_code, parent_name, n_journals
FROM asjc WHERE lower(parent_name) = lower(?)
ORDER BY n_journals DESC, code""",
(area.strip(),),
).fetchall()
for row in rows:
if row["code"] not in seen:
seen.add(row["code"]); out.append(dict(row))
return out
def publisher_titles(self, publisher_group: str) -> int:
return self.con.execute(
"SELECT count(*) FROM journals WHERE publisher_group = ?",
(publisher_group,),
).fetchone()[0]