### Quickstart: Ontology alignment workflow with MistralLLMBERTRetrieverRAG Source: https://ontoaligner.readthedocs.io/gettingstarted/overview.html Complete quickstart example showing the main OntoAligner workflow: load the MaterialInformation MatOnto dataset, encode ontologies, generate predictions with a RAG-based matcher, apply hybrid postprocessing, evaluate, and save matchings as XML. Requires CUDA for the retriever and LLM configurations. ```python from ontoaligner.ontology import MaterialInformationMatOntoOMDataset from ontoaligner.utils import metrics, xmlify from ontoaligner.aligner import MistralLLMBERTRetrieverRAG from ontoaligner.encoder import ConceptParentRAGEncoder from ontoaligner.postprocess import rag_hybrid_postprocessor # Step 1: Initialize the dataset object for MaterialInformation MatOnto dataset task = MaterialInformationMatOntoOMDataset() print("Test Task:", task) # Step 2: Load source and target ontologies along with reference matchings dataset = task.collect( source_ontology_path="assets/MI-MatOnto/mi_ontology.xml", target_ontology_path="assets/MI-MatOnto/matonto_ontology.xml", reference_matching_path="assets/MI-MatOnto/matchings.xml" ) # Step 3: Encode the source and target ontologies encoder_model = ConceptParentRAGEncoder() encoded_ontology = encoder_model(source=dataset['source'], target=dataset['target']) # Step 4: Define configuration for retriever and LLM retriever_config = {"device": 'cuda', "top_k": 5,} llm_config = {"device": "cuda", "max_length": 300, "max_new_tokens": 10, "batch_size": 15} # Step 5: Initialize Generate predictions using RAG-based ontology matcher model = MistralLLMBERTRetrieverRAG(retriever_config=retriever_config, llm_config=llm_config) model.load(llm_path = "mistralai/Mistral-7B-v0.3", ir_path="all-MiniLM-L6-v2") predicts = model.generate(input_data=encoded_ontology) # Step 6: Apply hybrid postprocessing hybrid_matchings, hybrid_configs = rag_hybrid_postprocessor(predicts=predicts, ir_score_threshold=0.1, llm_confidence_th=0.8) evaluation = metrics.evaluation_report(predicts=hybrid_matchings, references=dataset['reference']) print("Hybrid Matching Evaluation Report:", evaluation) # Step 7: Convert matchings to XML format and save the XML representation xml_str = xmlify.xml_alignment_generator(matchings=hybrid_matchings) open("matchings.xml", "w", encoding="utf-8").write(xml_str) ``` -------------------------------- ### Setup and flat prediction grouping helper Source: https://ontoaligner.readthedocs.io/developerguide/reranking.html Setup for reranking examples: imports, dataset loading, reranker initialization, and a helper to convert flat predictions into grouped candidate format. The helper is used when an aligner returns flat source-target-score predictions. ```python # Import required modules import torch from ontoaligner.ontology import MaterialInformationMatOntoOMDataset from ontoaligner.aligner import CrossEncoderReranking from ontoaligner.postprocess import retriever_postprocessor # Load source and target ontologies task = MaterialInformationMatOntoOMDataset() dataset = task.collect( source_ontology_path="assets/MI-MatOnto/mi_ontology.xml", target_ontology_path="assets/MI-MatOnto/matonto_ontology.xml", reference_matching_path="assets/MI-MatOnto/matchings.xml", ) # Select runtime device device = "cuda" if torch.cuda.is_available() else "cpu" # Initialize and load the reranker reranker = CrossEncoderReranking( device=device, top_k=5, normalize_score="sigmoid", ) reranker.load( path="cross-encoder/ms-marco-MiniLM-L6-v2", ) ``` ``` ```python # Convert flat predictions into grouped candidate format def group_predictions_for_reranking(predictions): grouped_predictions = {} for prediction in predictions: source = prediction["source"] target = prediction["target"] score = prediction.get("score", 0.0) if source not in grouped_predictions: grouped_predictions[source] = { "source": source, "target-cands": [], "score-cands": [], } grouped_predictions[source]["target-cands"].append(target) grouped_predictions[source]["score-cands"].append(float(score)) return list(grouped_predictions.values()) ``` ``` -------------------------------- ### Verify OntoAligner installation Source: https://ontoaligner.readthedocs.io/gettingstarted/installation.html After installation, run this Python code to verify that OntoAligner is installed correctly and print its version. ```python import ontoaligner print(ontoaligner.__version__) ``` -------------------------------- ### Install OntoAligner from GitHub Source: https://ontoaligner.readthedocs.io/gettingstarted/installation.html Install the latest version of OntoAligner from the main branch of the GitHub repository using pip. ```bash pip install git+https://github.com/sciknoworg/OntoAligner.git ``` -------------------------------- ### Install OntoAligner from PyPI Source: https://ontoaligner.readthedocs.io/gettingstarted/installation.html Install the latest version of OntoAligner from the Python Package Index using pip. ```bash pip install -U OntoAligner ``` -------------------------------- ### Simple PropMatchAligner setup (recommended) Source: https://ontoaligner.readthedocs.io/aligner/propmatch.html Basic configuration with balanced precision/recall: word2vec format, threshold 0.65, 2 steps, and sim_weight using domain, label, and range. ```python aligner = PropMatchAligner( fmt='word2vec', # Embedding format threshold=0.65, # Minimum similarity for matches steps=2, # Iterative refinement steps sim_weight=[0, 1, 2] # Use domain, label, and range ) ``` -------------------------------- ### Configure AlignerPipeline with Reranking Source: https://ontoaligner.readthedocs.io/developerguide/pipeline.html Example of initializing an AlignerPipeline with a retrieval aligner and a cross-encoder reranker. ```python # Retrieval with reranking AlignerPipeline( encoder=ConceptParentLightweightEncoder(), aligner=SBERTRetrieval( device=device, top_k=10, ), om_dataset=dataset, load_params={ "path": "all-MiniLM-L6-v2", }, reranker=CrossEncoderReranking( device=device, top_k=5, normalize_score="sigmoid", ), reranker_load_params={ "path": "cross-encoder/ms-marco-MiniLM-L6-v2", }, postprocessor=retriever_postprocessor, postprocessor_params={ "threshold": 0.5, }, ) ``` -------------------------------- ### Install OntoAligner in editable mode Source: https://ontoaligner.readthedocs.io/gettingstarted/installation.html Install the package in editable mode, which is ideal for development as changes in the code reflect immediately. ```bash pip install -e . ``` -------------------------------- ### High precision PropMatchAligner setup Source: https://ontoaligner.readthedocs.io/aligner/propmatch.html Configuration for very confident matches: higher threshold (0.85), more steps (3), and optional GPU usage via device='cuda'. ```python aligner = PropMatchAligner( fmt='word2vec', # Embedding format threshold=0.85, # Higher confidence threshold steps=3, # More refinement iterations sim_weight=[0, 1, 2], device='cuda' # Use GPU if available ) ``` -------------------------------- ### Setup: Import OntoAligner and Load Bank-to-FIBO Dataset Source: https://ontoaligner.readthedocs.io/usecases/financial_corporate_actions.html Imports the required OntoAligner components and creates the OLaLaOMDataset task. Collects the source ontology, target ontology, and reference mappings from the specified RDF/XML files. The reference mappings are only used for evaluation, not for generating predictions. Prints the number of source/target concepts and reference matchings, and selects the runtime device (CUDA if available, else CPU). ```python import json import torch from ontoaligner.encoder import OLaLaEncoder from ontoaligner.ontology import OLaLaOMDataset from ontoaligner.utils import metrics, xmlify from ontoaligner.aligner import CrossEncoderReranking from ontoaligner.aligner.olala import OLaLaSBERTRetrieval from ontoaligner.postprocess import retriever_postprocessor task = OLaLaOMDataset() dataset = task.collect( source_ontology_path="../../assets/bank-fibo/source_bank_corporate_actions.rdf", target_ontology_path="../../assets/bank-fibo/target_fibo_corporate_actions.rdf", reference_matching_path="../../assets/bank-fibo/reference_matchings.xml", ) print("Number of Source Concepts:", len(dataset["source"])) print("Number of Target Concepts:", len(dataset["target"])) print("Number of Reference Matchings:", len(dataset["reference"])) device = "cuda" if torch.cuda.is_available() else "cpu" print("Runtime Device:", device) ``` ```text Number of Source Concepts: 32 Number of Target Concepts: 53 Number of Reference Matchings: 31 ``` -------------------------------- ### FLORAAligner complete example (strict and fast modes) Source: https://ontoaligner.readthedocs.io/aligner/flora.html Two configurations: strict supervised mode with conservative scoring and high literal similarity, and fast lightweight mode using string identity and fewer iterations. ```python # Strict, supervised mode aligner = FLORAAligner( alpha=1.0, # Conservative subrelation scoring init_threshold=0.9, # High literal similarity required epsilon=0.001, # Strict convergence training_data="seeds.tsv", # Use known pairs string_identity=False # Still use embeddings for unknown literals ) # Fast, lightweight mode aligner = FLORAAligner( string_identity=True, # No embeddings gramN=50, # Fewer evidence facts max_iterations=20 # Fewer iterations ) ``` -------------------------------- ### KGE Default Mode Example Output Source: https://ontoaligner.readthedocs.io/aligner/kge.html Example output of the KGE default mode, showing a one-to-one alignment with a single target entity and similarity score. ```json { 'source': 'http://mouse.owl#MA_0000143', 'target': 'http://human.owl#HBA_0000214', 'score': 0.87 } ``` -------------------------------- ### KGE Retriever Mode Example Output Source: https://ontoaligner.readthedocs.io/aligner/kge.html Example output of the KGE retriever mode, showing one-to-many alignments with candidate target entities and their similarity scores. ```json [ { "source": "http://mouse.owl#MA_0000143", "target-cands": [ "http://human.owl#HBA_0000214", "http://human.owl#HBA_0000762", "http://human.owl#HBA_0000891" ], "score-cands": [0.87, 0.82, 0.77] }, ... ] ``` -------------------------------- ### Configure Ensemble: Setup device, models, mapper, and aligners Source: https://ontoaligner.readthedocs.io/aligner/ensemble_learning.html Configures runtime settings, model paths, label mapper, RAG/LLM configs, and defines five aligner pipelines (lightweight, sbert, kge, llm, rag) as tuples with weights. Each aligner uses an AlignerPipeline with encoder, aligner, and optional postprocessing. ```python device = "cuda" if torch.cuda.is_available() else "cpu" ir_model_path = "all-MiniLM-L6-v2" llm_model_path = "Qwen/Qwen2.5-1.5B-Instruct" mapper = TFIDFLabelMapper( classifier=LogisticRegression(), ngram_range=(1, 1), label_dict={ "yes": ["yes", "correct", "true", "same", "equivalent", "valid"], "no": ["no", "incorrect", "false", "different", "not same", "invalid"], }, ) retriever_config = { "device": device, "top_k": 5, "threshold": 0.1, } llm_config = { "device": device, "max_length": 300, "max_new_tokens": 10, "batch_size": 1, "answer_set": { "yes": ["yes", "correct", "true", "positive", "valid"], "no": ["no", "incorrect", "false", "negative", "invalid"], }, } aligners = [ ( "lightweight", AlignerPipeline( encoder=ConceptParentLightweightEncoder(), aligner=SimpleFuzzySMLightweight(fuzzy_sm_threshold=0.2), om_dataset=dataset, ), 1.0, ), ( "sbert", AlignerPipeline( encoder=ConceptParentLightweightEncoder(), aligner=SBERTRetrieval(device=device, top_k=5), om_dataset=dataset, load_params={"path": ir_model_path}, ), 1.0, ), ( "kge", AlignerPipeline( encoder=GraphTripleEncoder(), aligner=TransEAligner( model="TransE", device=device, embedding_dim=32, num_epochs=1, train_batch_size=32, eval_batch_size=32, num_negs_per_pos=1, random_seed=42, ), om_dataset=graph_dataset, postprocessor=graph_postprocessor, postprocessor_params={"threshold": 0.0}, ), 1.0, ), ( "llm", AlignerPipeline( encoder=ConceptLLMEncoder(), aligner=AutoModelDecoderLLM( device=device, max_length=300, max_new_tokens=20, batch_size=1, ), om_dataset=dataset, llm_dataset_class=ConceptLLMDataset, load_params={"path": llm_model_path}, postprocessor=llm_postprocessor, postprocessor_params={ "mapper": mapper, "interested_class": "yes", }, ), 1.0, ), ( "rag", AlignerPipeline( encoder=ConceptParentRAGEncoder(), aligner=MistralLLMBERTRetrieverRAG( retriever_config=retriever_config, llm_config=llm_config, ), om_dataset=dataset, load_params={ "llm_path": llm_model_path, "ir_path": ir_model_path, }, postprocessor=rag_heuristic_postprocessor, postprocessor_params={ "topk_confidence_ratio": 3, "topk_confidence_score": 3, }, ), 1.0, ) ] ``` -------------------------------- ### Example output of generate() Source: https://ontoaligner.readthedocs.io/developerguide/pipeline.html Shows the format of the generated matchings: a list of objects with source, target, and score fields. ```json [ {"source": "...", "target": "...", "score": 0.9}, ... ] ``` -------------------------------- ### FLORAAligner usage example Source: https://ontoaligner.readthedocs.io/package_reference/aligners.html Shows how to instantiate FLORAAligner with custom alpha and init_threshold, generate alignments for two knowledge graph files, and print the top three matches with their scores. The output format is 'source -> target: score' with two decimal places. ```python >>> from ontoaligner.aligner.flora import FLORAAligner >>> aligner = FLORAAligner(alpha=3.0, init_threshold=0.7) >>> matchings = aligner.generate(["kg1.ttl", "kg2.ttl"]) >>> for match in matchings[:3]: ... print(f"{match['source']} -> {match['target']}: {match['score']:.2f}") ``` -------------------------------- ### Configure OLaLaAligner with retriever, LLM aligner, and high-precision matcher Source: https://ontoaligner.readthedocs.io/aligner/olala.html Complete configuration example for OLaLaAligner, combining OLaLaSBERTRetrieval, OLaLaLLMAligner, and OLaLaHighPrecisionMatcher. Uses CUDA, greedy decoding (temperature 0.0), and 8-bit loading. ```python retriever = OLaLaSBERTRetrieval( device="cuda", top_k=5, both_directions=True, topk_per_resource=True, ) llm_aligner = OLaLaLLMAligner( device="cuda", max_new_tokens=10, temperature=0.0, truncation=True, max_length=2048, padding=True, system_prompt_template="[INST] {user_prompt} [/INST]", loading_arguments={ "device_map": "auto", "torch_dtype": "torch.float16", "load_in_8bit": True, }, ) hp_aligner = OLaLaHighPrecisionMatcher(confidence=1.0) olala = OLaLaAligner( retriever=retriever, llm_aligner=llm_aligner, hp_aligner=hp_aligner, ) ``` -------------------------------- ### Example usage of evaluation_report, hit_at_k, and mrr Source: https://ontoaligner.readthedocs.io/developerguide/metrics.html Demonstrates importing and using the metrics functions with sample predictions and references. Prints Hit@1, Hit@2, and MRR values. ```python from ontoaligner.utils.metrics import evaluation_report, hit_at_k, mrr predicts = [ {"source": "A", "target": "1", "score": 0.9}, {"source": "A", "target": "2", "score": 0.5}, {"source": "B", "target": "3", "score": 0.8}, ] references = [ {"source": "A", "target": "1"}, {"source": "B", "target": "3"}, ] report = evaluation_report(predicts, references) print(f"Hit@1 : {hit_at_k(predicts, references, k=1):.2f}") print(f"Hit@2 : {hit_at_k(predicts, references, k=2):.2f}") print(f"MRR : {mrr(predicts, references):.2f}") ``` -------------------------------- ### OLaLaLLMDataset.collate_fn Source: https://ontoaligner.readthedocs.io/package_reference/aligners.html Collates OLaLa LLM examples. ```APIDOC ## OLaLaLLMDataset.collate_fn ### Description Collates OLaLa LLM examples. ### Method Function ### Signature `collate_fn(batches)` ### Parameters - **batches** - Required - The batch examples. ### Returns The collated batch. ### Return Type Dict ``` -------------------------------- ### Sample encoded output (Basic Encoder) Source: https://ontoaligner.readthedocs.io/aligner/propmatch.html Example output from the Basic Encoder showing the 'iri' and 'text' fields, where text contains label, domain, and range. ```json { "iri": "http://example.org#hasAuthor", "text": "has author publication person" } ``` -------------------------------- ### Sample encoded output (PropMatch Encoder) Source: https://ontoaligner.readthedocs.io/aligner/propmatch.html Example output from the PropMatch Encoder showing fields for iri, label, domain, range, inverse properties, and combined text. ```python { 'iri': 'http://example.org#hasAuthor', 'label': 'has author', 'domain': ['http://example.org#Publication'], 'domain_text': ['has author', 'publication'], 'range': ['http://example.org#Person'], 'range_text': ['has author', 'person'], 'inverse_of': 'http://example.org#authorOf', 'inverse_label': 'authorOf', 'text': 'has author publication person' } ``` -------------------------------- ### Use TokenSetFuzzySMLightweight aligner Source: https://ontoaligner.readthedocs.io/aligner/lightweight.html Initializes a TokenSetFuzzySMLightweight aligner with a threshold of 0.8 and generates matchings. The example references a model and encoder_output that are not defined in the snippet, so it is illustrative of the API usage pattern. ```python from ontoaligner.aligner import TokenSetFuzzySMLightweight aligner = TokenSetFuzzySMLightweight(threshold=0.8) matchings = model.generate(input_data=encoder_output) ``` -------------------------------- ### Dataset structure example Source: https://ontoaligner.readthedocs.io/aligner/flora.html Shows the structure of each side of the dataset: a single-element list containing entities, predicates, triples, and a Graph object. The graph is passed to the aligner. ```python dataset["source"][0] == { "entities": [{"iri": "http://...", "label": "MyEntity"}, ...], "predicates": {...}, "triples": [("http://subj", "pred", "http://obj"), ...], "graph": # ← passed to the aligner } ``` -------------------------------- ### Initialize PropMatchAligner with Advanced Configuration Source: https://ontoaligner.readthedocs.io/aligner/propmatch.html Provides full control over all parameters including device selection and refinement iterations. ```python aligner = PropMatchAligner( fmt='word2vec', # Embedding format threshold=0.65, # Similarity threshold steps=2, # Refinement iterations sim_weight=[0, 1, 2], # Components to use disable_domain_range=False, device='cuda', # CPU or CUDA lowercase=False ) ``` -------------------------------- ### Initialize FLORAAligner with parameters Source: https://ontoaligner.readthedocs.io/aligner/flora.html Creates a FLORA aligner instance with configuration parameters. The device is set to 'cuda' but auto-detects by default; uncomment to force GPU. The model_id is commented out and only needed if string_identity is False. ```python aligner = FLORAAligner( # Subrelation inference alpha=3.0, # Benefit-of-doubt parameter relinit=0.1, # Initial score for non-identical predicates # Literal bootstrapping init_threshold=0.2, # Min semantic similarity threshold string_identity=True, # Use exact string matching (no embeddings) # Entity matching gramN=100, # Max evidential facts per entity # Convergence epsilon=0.01, # Stop when score change < epsilon max_iterations=100, # Safety cap on iterations # Functionality computation ngrams=[1, 2], # N-gram sizes for predicate functionality # Optional: seed alignments training_data=None, # Tab-separated seed alignments file # Embeddings # model_id='Lihuchen/pearl_small', # Hugging Face model for literal similarity, # set this if `string_identity` is False device='cuda', # Uncomment to force GPU (auto-detects by default) verbose=True, # Enable debug logging to see FLORA progress workers=30, # Number of workers for multiprocessing ) ``` -------------------------------- ### Initialize and execute OntoAlignerPipeline Source: https://ontoaligner.readthedocs.io/gettingstarted/quickstart.html Demonstrates how to instantiate the pipeline with a specific task class and ontology paths, then execute it using the RAG method. ```python import ontoaligner pipeline = ontoaligner.OntoAlignerPipeline( task_class=ontoaligner.ontology.MaterialInformationMatOntoOMDataset, source_ontology_path="source_ontology.xml", target_ontology_path="target_ontology.xml", reference_matching_path="reference.xml" output_dir="results", output_format="xml" ) matchings, evaluation = pipeline(method="rag", llm_path='mistralai/Mistral-7B-v0.3', retriever_path='all-MiniLM-L6-v2', model_class=ontoaligner.aligner.MistralLLMBERTRetrieverRAG, device='cuda', batch_size=15, return_matching=True, evaluate=True, save_matchings=False ) # evaluation output: # {'intersection': 85, # 'precision': 47.22222222222222, # 'recall': 28.14569536423841, # 'f-score': 35.26970954356846, # 'predictions-len': 180, # 'reference-len': 302} ``` -------------------------------- ### Evaluation report example output Source: https://ontoaligner.readthedocs.io/aligner/olala.html Example output of the evaluation report. Shows the metrics: intersection, precision, recall, f-score, and the lengths of predictions and reference. ```python { "intersection": 1317, "precision": 89.4, "recall": 89.1, "f-score": 90.2, "predictions-len": 1478, "reference-len": 1478 } ``` -------------------------------- ### __init__(_prefixes :Dict[str,str]_) Source: https://ontoaligner.readthedocs.io/package_reference/aligners.html Initialize RDF writer with namespace prefixes. ```APIDOC ## __init__(_prefixes :Dict[str,str]_) ### Description Initialize RDF writer with namespace prefixes. ### Method N/A ### Endpoint N/A ### Parameters #### Path Parameters - **prefixes** (Dict[str,str]) - Required - Dictionary mapping prefix names to namespace URIs. Example: {'ex': 'http://example.org/', 'owl': 'http://www.w3.org/2002/07/owl#'} ### Returns None ``` -------------------------------- ### FLORAAligner.get_predicate2super_predicate Source: https://ontoaligner.readthedocs.io/package_reference/aligners.html Gets the computed predicate subsumption scores. ```APIDOC ## FLORAAligner.get_predicate2super_predicate ### Description Gets the computed predicate subsumption scores. ### Method Method ### Signature `get_predicate2super_predicate() -> Dict[Any, Dict[Any, float]]` ### Parameters None ### Returns - **Dict[Any, Dict[Any, float]]** - Predicate subsumption scores. ``` -------------------------------- ### OLaLaLLMDataset.fill_one_sample Source: https://ontoaligner.readthedocs.io/package_reference/aligners.html Builds one OLaLa LLM prompt. ```APIDOC ## OLaLaLLMDataset.fill_one_sample ### Description Builds one OLaLa LLM prompt. ### Method Function ### Signature `fill_one_sample(input_data: Any) -> str` ### Parameters - **input_data** (Any) - Required - One candidate pair. ### Returns The filled prompt. ### Return Type str ``` -------------------------------- ### get_same_as_scores() Source: https://ontoaligner.readthedocs.io/package_reference/aligners.html Get the computed entity alignment scores. ```APIDOC ## get_same_as_scores() ### Description Get the computed entity alignment scores. ### Method N/A ### Endpoint N/A ### Parameters None ### Returns Dictionary mapping source entities to target entities and their scores. ### Response #### Success Response - **returns** (Dict[Any, Dict[Any, float]]) - Dictionary mapping source entities to target entities and their scores. #### Response Example N/A ``` -------------------------------- ### Sample LLM Prediction Output Source: https://ontoaligner.readthedocs.io/aligner/llm.html Example of raw text output generated by the LLM. ```python [' \nNo', ' \nNo', ' \nNo', ' No\n\nConcept 1: Aisi 1', ' \nYes\nThe Reason is'] ``` -------------------------------- ### Create and activate virtual environment Source: https://ontoaligner.readthedocs.io/gettingstarted/installation.html Create a virtual environment and activate it. On Windows, use 'venv\Scripts\activate' instead of 'source venv/bin/activate'. ```bash python -m venv venv source venv/bin/activate # On Windows: venv\Scripts\activate ``` -------------------------------- ### Alignment output format Source: https://ontoaligner.readthedocs.io/aligner/flora.html Example of the alignment output format: a list of dictionaries with source, target, and score. ```python [ { "source": "http://example.org/entity/E1", "target": "http://example.org/entity/E2", "score": 0.91 }, ... ] ``` -------------------------------- ### Encode ontology with ConceptRAGEncoder Source: https://ontoaligner.readthedocs.io/aligner/rag.html Use ConceptRAGEncoder to encode source and target ontologies with reference examples for ICV-RAG alignment. ```python from ontoaligner.encoder import ConceptRAGEncoder encoder_model = ConceptRAGEncoder() encoded_ontology = encoder_model(source=dataset['source'], target=dataset['target'], reference=dataset['reference']) ``` -------------------------------- ### get_core_concept Source: https://ontoaligner.readthedocs.io/package_reference/aligners.html Gets the core concept of an entity. The core concept is the first verb with length > 4 or the first noun with its adjectives. ```APIDOC ## get_core_concept ### Description Gets the core concept of an entity. The core concept is the first verb with length > 4 or the first noun with its adjectives. ### Method get_core_concept ### Endpoint `get_core_concept(entity)` ### Parameters #### Parameters - **entity** (List[str]) - Required - List of words from property label ### Response #### Success Response Returns a list of core concept words. ### Response Example ``` ["concept"] ``` ``` -------------------------------- ### AlignerPipeline.__init__ Source: https://ontoaligner.readthedocs.io/package_reference/pipeline.html Initializes the AlignerPipeline with an encoder, aligner, and optional reranker and postprocessor components. ```APIDOC ## AlignerPipeline.__init__ ### Description Initializes the aligner pipeline with an encoder, aligner, and optional reranker and postprocessor components. ### Method Constructor ### Parameters - **encoder** (BaseEncoder) - Required - Encoder model used to encode the ontology matching dataset. - **aligner** (BaseOMModel) - Required - Ontology matching aligner used to generate predictions. - **om_dataset** (Dict, optional) - Pre-collected ontology matching dataset. Defaults to None. - **load_params** (Dict, optional) - Parameters forwarded to the aligner load method. Defaults to None. - **llm_dataset_class** (Dataset, optional) - Dataset class used to wrap LLM inputs. Defaults to None. - **batch_size** (int, optional) - Batch size used for LLM dataset generation. Defaults to 1. - **shuffle** (bool, optional) - Whether to shuffle LLM dataset batches. Defaults to False. - **reranker** (BaseOMModel, optional) - Optional reranking model used to reorder candidate predictions. Defaults to None. - **reranker_load_params** (Dict, optional) - Parameters forwarded to the reranker load method. Defaults to None. - **reranker_encoder** (BaseEncoder, optional) - Optional encoder used to prepare source and target ontologies text for reranking. Defaults to None. - **reranker_om_dataset** (Dict, optional) - Optional ontology matching dataset used by the reranker encoder. Defaults to None. - **postprocessor** (Any, optional) - Optional postprocessor applied to predictions. Defaults to None. - **postprocessor_params** (Dict, optional) - Optional parameters forwarded to the postprocessor. Defaults to None. - **include_reference** (bool, optional) - Whether to pass reference matchings to the encoder. Defaults to False. - **kwargs** - Additional keyword arguments that may be used for model configuration. ### Returns None ``` -------------------------------- ### graph_postprocessor usage example Source: https://ontoaligner.readthedocs.io/package_reference/postprocess.html Demonstrates how to use graph_postprocessor to filter raw alignment predictions, enforcing one-to-one mappings and applying a similarity threshold. ```python >>> raw_preds = [ ... {"source": "A", "target": "X", "score": 0.9}, ... {"source": "B", "target": "X", "score": 0.8}, ... {"source": "A", "target": "Y", "score": 0.7} ... ] >>> graph_postprocessor(raw_preds, threshold=0.75) ... [{'source': 'A', 'target': 'X', 'score': 0.9}] ``` -------------------------------- ### Create LLM dataset Source: https://ontoaligner.readthedocs.io/aligner/llm.html Prepares the data for the LLM-based matcher by filling in the prompt template using ConceptLLMDataset. ```python llm_dataset = ConceptLLMDataset(source_onto=source_onto, target_onto=target_onto) ``` -------------------------------- ### Output Format: Predicate Subsumption with rdfs:subPropertyOf Source: https://ontoaligner.readthedocs.io/aligner/flora.html Example of a predicate subsumption relationship written using rdfs:subPropertyOf, with a confidence score comment. ```turtle ex:father rdfs:subPropertyOf ex:parent . # 0.92 ``` -------------------------------- ### Use GPTOpenAILLM Source: https://ontoaligner.readthedocs.io/aligner/llm.html Initializes the GPTOpenAILLM model with an OpenAI API key and loads a desired model ID. ```python from ontoaligner.aligner import GPTOpenAILLM model = GPTOpenAILLM(openai_api_key="...") model.load(path='...') # add desired model id ```