from typing import Any, Dict, List, Optional import numpy as np from sklearn.metrics.pairwise import cosine_similarity from .prevalence import get_disease_prevalence # Compute the jaccard score between the user's symptom vector and a disease's symptom vector def compute_jaccard(user_vec: np.ndarray, disease_vec: np.ndarray) -> float: # Convert to boolean vectors for set operations u = user_vec.astype(bool) d = disease_vec.astype(bool) # Compute the intersection and union of the symptom sets to calculate the Jaccard similarity intersection = np.logical_and(u, d).sum() union = np.logical_or(u, d).sum() if union == 0: return 0.0 return float(intersection / union) # Compute the coverage score: what percentage of the user's symptoms are covered by the disease's symptoms def compute_coverage(user_vec: np.ndarray, disease_vec: np.ndarray) -> float: # Convert to boolean vectors for set operations u = user_vec.astype(bool) d = disease_vec.astype(bool) # Compute the intersection of the user's symptoms that are present in the disease's symptoms # and divide by the total number of user symptoms to get coverage intersection = np.logical_and(u, d).sum() total_user = u.sum() if total_user == 0: return 0.0 return float(intersection / total_user) # Compute a rarity penalty based on disease prevalence, with a stronger penalty for rarer diseases def compute_rarity_penalty(prevalence: int) -> float: # Keep the penalty btw 0 and 1 so rare diseases are penalized but can still # be considered when symptom evidence is very strong. return float(np.clip(1.0 / np.sqrt(max(prevalence, 1)), 0.0, 1.0)) # Compute a hybrid score (combines jaccard, tfidf cosine similarity, coverage, and rarity penalty with tunable weights) def compute_hybrid_score( jaccard: float, tfidf_cosine: float, coverage: float, rarity_penalty: float, # Set the weights for each part of the hybrid score - the values are chosen based on trial and error w_j: float = 0.25, w_t: float = 0.25, w_c: float = 0.10, w_r: float = 0.40, ) -> float: # The weights can be tuned. The rarity penalty is subtracted to discourage rare diseases unless other scores are very high. base = (w_j * jaccard) + (w_t * tfidf_cosine) + (w_c * coverage) return float(base - (w_r * rarity_penalty)) # Score candidate diseases based on multiple metrics and return a ranked list of candidates with their scores def score_candidates( user_binary_vec: np.ndarray, user_tfidf_vec, faiss_indices: np.ndarray, binary_matrix: np.ndarray, tfidf_matrix, diseases: List[str], disease_counts: Dict[str, int], prevalence_map: Dict[str, int], mapped_user_symptoms: List[str], max_candidates: int = 20, top_n: int = 5, travel_exposure: bool = False, structured_context: Optional[Dict[str, Any]] = None, ) -> List[Dict[str, Any]]: del disease_counts # Compute the user's binary vector and TF-IDF vector for similarity calculations user_bin = user_binary_vec[0] tfidf_cosines = cosine_similarity(user_tfidf_vec, tfidf_matrix)[0] structured_context = structured_context or {} # Define a set of very common symptoms - we can use them to penalize diseases that only match on these common_symptoms = { "fever", "high_fever", "mild_fever", "headache", "runny_nose", "cough", "fatigue", } results = [] # Loop through the candidate diseases returned by the FAISS index and compute various scores for each candidate for rank, idx in enumerate(faiss_indices[0][:max_candidates]): disease = diseases[idx] disease_bin = binary_matrix[idx] prevalence = prevalence_map.get(disease, get_disease_prevalence(disease)) # Calculate Jaccard similarity and coverage jacc = compute_jaccard(user_bin, disease_bin) cov = compute_coverage(user_bin, disease_bin) # Filter out candidates that have very low Jaccard similarity and coverage if jacc < 0.15 and cov < 0.10: continue # Calculate TF-IDF cosine similarity and rarity penalty tfidf_sim = float(tfidf_cosines[idx]) rarity_penalty = compute_rarity_penalty(prevalence) # Penalize rare diseases, but allow them when symptom # coverage is very high or travel/exposure context supports them. if not travel_exposure and prevalence < 100 and cov < 0.60: continue # Penalize if the disease only matches on common symptoms if set(mapped_user_symptoms).issubset(common_symptoms): rarity_penalty *= 2.0 # Compute the hybrid score combining all metrics hybrid = compute_hybrid_score(jacc, tfidf_sim, cov, rarity_penalty) # Adjust the hybrid score if the user indicates symptom progression or a certain duration if structured_context.get("progression") == "worsening": hybrid += 0.03 * cov if structured_context.get("duration"): hybrid += 0.02 * min(cov, 1.0) # Adjust the hybrid score based on travel exposure and specific exposures mentioned (i.e mosquito bites) exposures = structured_context.get("exposures", []) if travel_exposure and exposures: hybrid += 0.02 if any("mosquito" in exposure for exposure in exposures) and prevalence < 100: hybrid += 0.08 if any("travel" in exposure for exposure in exposures) and prevalence < 100: hybrid += 0.05 results.append( { "disease": disease, "index": int(idx), "faiss_rank": int(rank), "jaccard": float(jacc), "coverage": float(cov), "tfidf_cosine": tfidf_sim, "rarity_penalty": float(rarity_penalty), "hybrid_score": float(hybrid), } ) results.sort(key=lambda x: x["hybrid_score"], reverse=True) return results[:top_n]