subject stringlengths 8 279 | predicate stringlengths 9 166 | object stringlengths 1 1.3k | object_type stringclasses 3
values | object_datatype stringclasses 2
values | object_language stringclasses 0
values |
|---|---|---|---|---|---|
http://freebase.com//m/027rn | http://freebase.com//location/country/form_of_government | http://freebase.com//m/06cx9 | uri | null | null |
http://freebase.com//m/017dcd | http://freebase.com//tv/tv_program/regular_cast./tv/regular_tv_appearance/actor | http://freebase.com//m/06v8s0 | uri | null | null |
http://freebase.com//m/07s9rl0 | http://freebase.com//media_common/netflix_genre/titles | http://freebase.com//m/0170z3 | uri | null | null |
http://freebase.com//m/01sl1q | http://freebase.com//award/award_winner/awards_won./award/award_honor/award_winner | http://freebase.com//m/044mz_ | uri | null | null |
http://freebase.com//m/0cnk2q | http://freebase.com//soccer/football_team/current_roster./sports/sports_team_roster/position | http://freebase.com//m/02nzb8 | uri | null | null |
http://freebase.com//m/04nrcg | http://freebase.com//soccer/football_team/current_roster./soccer/football_roster_position/position | http://freebase.com//m/02sdk9v | uri | null | null |
http://freebase.com//m/07nznf | http://freebase.com//film/actor/film./film/performance/film | http://freebase.com//m/014lc_ | uri | null | null |
http://freebase.com//m/02qyp19 | http://freebase.com//award/award_category/nominees./award/award_nomination/nominated_for | http://freebase.com//m/02d413 | uri | null | null |
http://freebase.com//m/0q9kd | http://freebase.com//award/award_nominee/award_nominations./award/award_nomination/award_nominee | http://freebase.com//m/0184jc | uri | null | null |
http://freebase.com//m/03q5t | http://freebase.com//music/performance_role/regular_performances./music/group_membership/role | http://freebase.com//m/07y_7 | uri | null | null |
http://freebase.com//m/0gqng | http://freebase.com//award/award_category/winners./award/award_honor/ceremony | http://freebase.com//m/073hkh | uri | null | null |
http://freebase.com//m/0b76d_m | http://freebase.com//film/film/release_date_s./film/film_regional_release_date/film_release_distribution_medium | http://freebase.com//m/029j_ | uri | null | null |
http://freebase.com//m/014_x2 | http://freebase.com//award/award_winning_work/awards_won./award/award_honor/award_winner | http://freebase.com//m/012ljv | uri | null | null |
http://freebase.com//m/0ds35l9 | http://freebase.com//film/film/release_date_s./film/film_regional_release_date/film_release_region | http://freebase.com//m/05r4w | uri | null | null |
http://freebase.com//m/015qsq | http://freebase.com//film/film/language | http://freebase.com//m/02bjrlw | uri | null | null |
http://freebase.com//m/04bdxl | http://freebase.com//award/award_nominee/award_nominations./award/award_nomination/award_nominee | http://freebase.com//m/02s2ft | uri | null | null |
http://freebase.com//m/09c7w0 | http://freebase.com//location/location/contains | http://freebase.com//m/0rs6x | uri | null | null |
http://freebase.com//m/079vf | http://freebase.com//film/actor/film./film/performance/film | http://freebase.com//m/0d90m | uri | null | null |
http://freebase.com//m/015zyd | http://freebase.com//organization/organization/headquarters./location/mailing_address/country | http://freebase.com//m/09c7w0 | uri | null | null |
http://freebase.com//m/05vsxz | http://freebase.com//award/award_nominee/award_nominations./award/award_nomination/award_nominee | http://freebase.com//m/06qgvf | uri | null | null |
http://freebase.com//m/04ljl_l | http://freebase.com//award/award_category/nominees./award/award_nomination/nominated_for | http://freebase.com//m/03qcfvw | uri | null | null |
http://freebase.com//m/0grwj | http://freebase.com//people/person/profession | http://freebase.com//m/05sxg2 | uri | null | null |
http://freebase.com//m/0rh6k | http://freebase.com//location/statistical_region/religions./location/religion_percentage/religion | http://freebase.com//m/01lp8 | uri | null | null |
http://freebase.com//m/05d7rk | http://freebase.com//award/award_nominee/award_nominations./award/award_nomination/award | http://freebase.com//m/027dtxw | uri | null | null |
http://freebase.com//m/05hs4r | http://freebase.com//music/genre/artists | http://freebase.com//m/01pbxb | uri | null | null |
http://freebase.com//m/03qcq | http://freebase.com//influence/influence_node/influenced_by | http://freebase.com//m/084w8 | uri | null | null |
http://freebase.com//m/01lxd4 | http://freebase.com//music/genre/artists | http://freebase.com//m/0f0y8 | uri | null | null |
http://freebase.com//m/08815 | http://freebase.com//education/educational_institution/students_graduates./education/education/student | http://freebase.com//m/05bnp0 | uri | null | null |
http://freebase.com//m/0g56t9t | http://freebase.com//film/film/release_date_s./film/film_regional_release_date/film_release_region | http://freebase.com//m/05r4w | uri | null | null |
http://freebase.com//m/0160w | http://freebase.com//organization/organization_member/member_of./organization/organization_membership/organization | http://freebase.com//m/02vk52z | uri | null | null |
http://freebase.com//m/0dbpyd | http://freebase.com//people/person/place_of_birth | http://freebase.com//m/09c7w0 | uri | null | null |
http://freebase.com//m/053y0s | http://freebase.com//people/person/profession | http://freebase.com//m/0dz3r | uri | null | null |
http://freebase.com//m/016qtt | http://freebase.com//common/topic/webpage./common/webpage/category | http://freebase.com//m/08mbj5d | uri | null | null |
http://freebase.com//m/09sh8k | http://freebase.com//film/film/other_crew./film/film_crew_gig/film_crew_role | http://freebase.com//m/09zzb8 | uri | null | null |
http://freebase.com//m/05pd94v | http://freebase.com//award/award_ceremony/awards_presented./award/award_honor/award_winner | http://freebase.com//m/01vvydl | uri | null | null |
http://freebase.com//m/0gtsx8c | http://freebase.com//film/film/release_date_s./film/film_regional_release_date/film_release_region | http://freebase.com//m/0jgd | uri | null | null |
http://freebase.com//m/02r0csl | http://freebase.com//award/award_category/nominees./award/award_nomination/nominated_for | http://freebase.com//m/0m313 | uri | null | null |
http://freebase.com//m/02y_lrp | http://freebase.com//film/film/country | http://freebase.com//m/09c7w0 | uri | null | null |
http://freebase.com//m/012d40 | http://freebase.com//film/actor/film./film/performance/film | http://freebase.com//m/034qmv | uri | null | null |
http://freebase.com//m/07rlg | http://freebase.com//olympics/olympic_sport/athletes./olympics/olympic_athlete_affiliation/country | http://freebase.com//m/0b90_r | uri | null | null |
http://freebase.com//m/0g22z | http://freebase.com//award/award_winning_work/awards_won./award/award_honor/award | http://freebase.com//m/05b4l5x | uri | null | null |
http://freebase.com//m/018js4 | http://freebase.com//film/film/country | http://freebase.com//m/09c7w0 | uri | null | null |
http://freebase.com//m/07fq1y | http://freebase.com//award/award_nominee/award_nominations./award/award_nomination/award_nominee | http://freebase.com//m/02qgqt | uri | null | null |
http://freebase.com//m/028q6 | http://freebase.com//award/award_nominee/award_nominations./award/award_nomination/award | http://freebase.com//m/02581q | uri | null | null |
http://freebase.com//m/0sxg4 | http://freebase.com//film/film/genre | http://freebase.com//m/04xvlr | uri | null | null |
http://freebase.com//m/0fvf9q | http://freebase.com//award/award_winner/awards_won./award/award_honor/award_winner | http://freebase.com//m/0l6qt | uri | null | null |
http://freebase.com//m/0jz9f | http://freebase.com//film/film_distributor/films_distributed./film/film_film_distributor_relationship/film | http://freebase.com//m/083shs | uri | null | null |
http://freebase.com//m/0njvn | http://freebase.com//location/statistical_region/rent50_2./measurement_unit/dated_money_value/currency | http://freebase.com//m/09nqf | uri | null | null |
http://freebase.com//m/0d1tm | http://freebase.com//olympics/olympic_sport/athletes./olympics/olympic_athlete_affiliation/country | http://freebase.com//m/0154j | uri | null | null |
http://freebase.com//m/01br2w | http://freebase.com//film/film/estimated_budget./measurement_unit/dated_money_value/currency | http://freebase.com//m/09nqf | uri | null | null |
http://freebase.com//m/03rl1g | http://freebase.com//government/legislative_session/members./government/government_position_held/district_represented | http://freebase.com//m/05kkh | uri | null | null |
http://freebase.com//m/0fbq2n | http://freebase.com//sports/sports_team/roster./american_football/football_historical_roster_position/position_s | http://freebase.com//m/01r3hr | uri | null | null |
http://freebase.com//m/060bp | http://freebase.com//government/government_office_category/officeholders./government/government_position_held/jurisdiction_of_office | http://freebase.com//m/027nb | uri | null | null |
http://freebase.com//m/04qvl7 | http://freebase.com//award/award_nominee/award_nominations./award/award_nomination/nominated_for | http://freebase.com//m/02vxq9m | uri | null | null |
http://freebase.com//m/04yywz | http://freebase.com//film/actor/film./film/performance/film | http://freebase.com//m/0140g4 | uri | null | null |
http://freebase.com//m/01k7d9 | http://freebase.com//people/deceased_person/place_of_death | http://freebase.com//m/0k049 | uri | null | null |
http://freebase.com//m/02p65p | http://freebase.com//award/award_winner/awards_won./award/award_honor/award_winner | http://freebase.com//m/0337vz | uri | null | null |
http://freebase.com//m/06688p | http://freebase.com//film/actor/film./film/performance/film | http://freebase.com//m/0b2v79 | uri | null | null |
http://freebase.com//m/01c0cc | http://freebase.com//common/topic/webpage./common/webpage/category | http://freebase.com//m/08mbj5d | uri | null | null |
http://freebase.com//m/01jc6q | http://freebase.com//award/award_winning_work/awards_won./award/award_honor/award | http://freebase.com//m/040njc | uri | null | null |
http://freebase.com//m/0520r2x | http://freebase.com//award/award_nominee/award_nominations./award/award_nomination/award_nominee | http://freebase.com//m/0cb77r | uri | null | null |
http://freebase.com//m/08815 | http://freebase.com//education/educational_institution/students_graduates./education/education/student | http://freebase.com//m/06j0md | uri | null | null |
http://freebase.com//m/01453 | http://freebase.com//soccer/football_team/current_roster./sports/sports_team_roster/position | http://freebase.com//m/0dgrmp | uri | null | null |
http://freebase.com//m/028_yv | http://freebase.com//film/film/country | http://freebase.com//m/03rjj | uri | null | null |
http://freebase.com//m/01914 | http://freebase.com//common/topic/webpage./common/webpage/category | http://freebase.com//m/08mbj5d | uri | null | null |
http://freebase.com//m/05_6_y | http://freebase.com//sports/pro_athlete/teams./sports/sports_team_roster/team | http://freebase.com//m/02b15h | uri | null | null |
http://freebase.com//m/03c7ln | http://freebase.com//music/artist/track_contributions./music/track_contribution/role | http://freebase.com//m/026t6 | uri | null | null |
http://freebase.com//m/02pprs | http://freebase.com//music/instrument/instrumentalists | http://freebase.com//m/07s3vqk | uri | null | null |
http://freebase.com//m/05zjtn4 | http://freebase.com//education/educational_institution/students_graduates./education/education/student | http://freebase.com//m/0197tq | uri | null | null |
http://freebase.com//m/02_fm2 | http://freebase.com//film/film/release_date_s./film/film_regional_release_date/film_release_distribution_medium | http://freebase.com//m/029j_ | uri | null | null |
http://freebase.com//m/0411q | http://freebase.com//people/person/profession | http://freebase.com//m/016z4k | uri | null | null |
http://freebase.com//m/06151l | http://freebase.com//award/award_winner/awards_won./award/award_honor/award_winner | http://freebase.com//m/06gp3f | uri | null | null |
http://freebase.com//m/01fq7 | http://freebase.com//common/topic/webpage./common/webpage/category | http://freebase.com//m/08mbj5d | uri | null | null |
http://freebase.com//m/06w99h3 | http://freebase.com//film/film/genre | http://freebase.com//m/02kdv5l | uri | null | null |
http://freebase.com//m/05cljf | http://freebase.com//common/topic/webpage./common/webpage/category | http://freebase.com//m/08mbj5d | uri | null | null |
http://freebase.com//m/0342h | http://freebase.com//music/performance_role/regular_performances./music/group_membership/role | http://freebase.com//m/0l14qv | uri | null | null |
http://freebase.com//m/02bfmn | http://freebase.com//people/person/gender | http://freebase.com//m/05zppz | uri | null | null |
http://freebase.com//m/01rk91 | http://freebase.com//business/job_title/people_with_this_title./business/employment_tenure/company | http://freebase.com//m/0kc6x | uri | null | null |
http://freebase.com//m/01xdf5 | http://freebase.com//base/popstra/celebrity/friendship./base/popstra/friendship/participant | http://freebase.com//m/04t2l2 | uri | null | null |
http://freebase.com//m/027qgy | http://freebase.com//film/film/genre | http://freebase.com//m/06cvj | uri | null | null |
http://freebase.com//m/02v8kmz | http://freebase.com//film/film/release_date_s./film/film_regional_release_date/film_release_distribution_medium | http://freebase.com//m/029j_ | uri | null | null |
http://freebase.com//m/01j5ts | http://freebase.com//people/person/place_of_birth | http://freebase.com//m/06_kh | uri | null | null |
http://freebase.com//m/0dwl2 | http://freebase.com//business/business_operation/industry | http://freebase.com//m/01mw1 | uri | null | null |
http://freebase.com//m/02wh75 | http://freebase.com//award/award_category/winners./award/award_honor/award_winner | http://freebase.com//m/0lbj1 | uri | null | null |
http://freebase.com//m/0c3ybss | http://freebase.com//film/film/release_date_s./film/film_regional_release_date/film_release_region | http://freebase.com//m/09c7w0 | uri | null | null |
http://freebase.com//m/01l1b90 | http://freebase.com//common/topic/webpage./common/webpage/category | http://freebase.com//m/08mbj5d | uri | null | null |
http://freebase.com//m/02vp1f_ | http://freebase.com//film/film/release_date_s./film/film_regional_release_date/film_release_region | http://freebase.com//m/03_3d | uri | null | null |
http://freebase.com//m/09m6kg | http://freebase.com//film/film/language | http://freebase.com//m/02h40lc | uri | null | null |
http://freebase.com//m/05bp8g | http://freebase.com//people/person/nationality | http://freebase.com//m/03_3d | uri | null | null |
http://freebase.com//m/047q2k1 | http://freebase.com//film/film/genre | http://freebase.com//m/05p553 | uri | null | null |
http://freebase.com//m/01ypc | http://freebase.com//sports/sports_team/roster./baseball/baseball_roster_position/position | http://freebase.com//m/02dwn9 | uri | null | null |
http://freebase.com//m/06dv3 | http://freebase.com//film/actor/film./film/performance/film | http://freebase.com//m/09m6kg | uri | null | null |
http://freebase.com//m/01rtm4 | http://freebase.com//education/educational_institution/students_graduates./education/education/student | http://freebase.com//m/02rchht | uri | null | null |
http://freebase.com//m/0dq3c | http://freebase.com//business/job_title/people_with_this_title./business/employment_tenure/company | http://freebase.com//m/02zs4 | uri | null | null |
http://freebase.com//m/0qcr0 | http://freebase.com//people/cause_of_death/people | http://freebase.com//m/0byfz | uri | null | null |
http://freebase.com//m/06wzvr | http://freebase.com//film/film/genre | http://freebase.com//m/01q03 | uri | null | null |
http://freebase.com//m/01qn7n | http://freebase.com//tv/tv_program/languages | http://freebase.com//m/02h40lc | uri | null | null |
http://freebase.com//m/0cnl80 | http://freebase.com//award/award_nominee/award_nominations./award/award_nomination/award_nominee | http://freebase.com//m/083chw | uri | null | null |
http://freebase.com//m/0qf43 | http://freebase.com//award/award_nominee/award_nominations./award/award_nomination/award | http://freebase.com//m/0f_nbyh | uri | null | null |
http://freebase.com//m/0c0yh4 | http://freebase.com//film/film/country | http://freebase.com//m/0d060g | uri | null | null |
- πΊοΈ Repository Structure
- π Quick-Start Decision Guide
- π§ Pre-loaded Tool Implementations
- π§© End-to-End Agent Use Cases (Full Workflows)
- Case 1: Rare Disease Diagnosis Assistance
- Case 2: Drug Repositioning Pipeline (Compound β Disease Association)
- Case 3: Cross-Species Anatomy Comparison (Comparative Biology)
- Case 4: YAGO + ConceptNet Hybrid QA System
- Case 5: Scientific Unit Conversion Service
- Case 6: Biomedical Literature Evidence Annotation
- Case 7: Safe NCBI Taxonomy Subtree Loading (Large File Handling)
- Case 1: Rare Disease Diagnosis Assistance
- π Cross-Ontology Entity Alignment Best Practices
- π§ Failure Handling & Fallback Strategies
- π Benchmark Evaluation Protocol Reference
- πͺ’
ontology/β Serialization Formats Detail - π οΈ
benchmark/Directory Detail - β οΈ Important Notes
- π References & BibTeX Citation
- π Update Log
𧬠Complete Ontology & Knowledge Graph Library v7
A curated, ready-to-use collection of ontologies, knowledge graphs (KGs), benchmarks, and cross-references β unified under a single 6-column Parquet schema optimized for LLM Agent tool-calling workflows.
All raw *.owl, *.ttl, *.obo sources are converted to standardized TSV / Parquet triple bundles with one Parquet shard per source (no sharding on small files). This library is designed to give Agents direct file paths, complete schemas, memory estimates, and runnable Python examples for every resource.
πΊοΈ Repository Structure
dongdongkx/ontology/
βββ raw/ # 27 source ontologies (OWL/TTL/OBO)
β βββ gene-ontology/go.owl # GO: ~71 K terms, 1.5 M axioms
β βββ go-plus/go-plus.owl # GO + relations merged (~2Γ larger)
β βββ chemistry-entities-ontology/chebi.owl # ChEBI: chemical structures
β βββ disease-ontology/doid.owl # DOID: disease IDs
β βββ mondra-ontology/mondo.owl # MONDO: unified disease ontology
β βββ uber-anatomy/uberon.owl # Uberon: comparative anatomy
β βββ cell-type/CL.owl # Cell type ontology
β βββ human-phenotype-ontology/hp.owl # HP: clinical phenotype
β βββ experimental-factor/efo.owl # EFO: experimental factors
β βββ sequence-ontology/so.owl # SO: genomic features
β βββ organism-taxonomy/ncbitaxon.owl # NCBI Taxonomy: 2.1 GB, 5 M+ triples β οΈ
β βββ ... # Full list in Section 1
β
βββ kg/ # 10 KG datasets (Parquet triple shards)
β βββ yago-4.5/ # 27.5 M rows, 6 shards β General world facts
β βββ dbpedia-core-en/ # 5 M rows, 8 shards β English Wikipedia
β βββ dblp-bibliography/dblp.parquet # DBLP: CS publication graph
β βββ conceptnet/conceptnet-5.8.parquet # ConceptNet: commonsense relations
β βββ freebase-metaweb/freebase-metaweb.parquet # Freebase mirror (large)
β βββ ...
β
βββ benchmark/ # 3 standard benchmarks (FB15K-237, WN18RR, NELL-995)
βββ ontology/ # Pre-built mappings and serialized OWL files
βββ metadata/ # Machine-readable agent guides
β βββ agent_guide.yaml # Structured decision table (Agent-parseable)
β βββ mappings/
β βββ disease-xrefs.sssom.tsv # Disease entity cross-reference SSSOM mappings
βββ README.md # This file
π Quick-Start Decision Guide
Pick your task type β Follow the route below. Memory estimates assume streaming mode; full loads can be 3β10Γ larger.
| Task | Best Resource | Load Method | Memory (Streaming) |
|---|---|---|---|
| Disease β phenotype lookup | raw/mondo-disease-ontology/mondo.owl + raw/human-phenotype-ontology/hp.owl |
rdflib SPARQL | ~200 MB |
| Chemical compound info | raw/chemistry-entities-ontology/chebi.owl |
rdflib SPARQL | ~300 MB |
| Anatomical structure mapping | raw/uber-anatomy/uberon.owl + raw/human-phenotype-ontology/hp.owl |
rdflib SPARQL | ~250 MB |
| General QA (fact retrieval) | kg/yago-4.5/data/*.parquet |
datasets streaming | ~50 MB/shard |
| Commonsense reasoning | kg/conceptnet/conceptnet-5.8.parquet |
datasets load | ~800 MB |
| Drug β disease link | kg/dbpedia-biomedical/data/*.parquet + raw/chebi.owl |
stream + join | ~200 MB |
| Unit conversion | raw/qudt/qudt-all.ttl |
rdflib SPARQL | ~150 MB |
| Entity alignment (cross-KB) | metadata/mappings/disease-xrefs.sssom.tsv |
pandas read_csv | <10 MB |
All Resources at a Glance
raw/ β Source Ontologies
| File | Format | Est. Triples/Axioms | Reasoned? | Last Updated | Notes |
|---|---|---|---|---|---|
gene-ontology/go.owl |
OWL XML | ~1.5 M axioms | No | 2026-10 | OBO Foundry; largest bio ontology |
go-plus/go-plus.owl |
OWL/XML | ~3.0 M axioms | Yes (merged) | 2026-10 | GO + all relation types merged |
chemistry-entities-ontology/chebi.owl |
OBO | ~450 K terms | No | 2026-09 | ChEBI chemical substances |
disease-ontology/doid.owl |
OBO | ~55 K terms | No | 2026-08 | Human disease ontology |
mondo-disease-ontology/mondo.owl |
OBO | ~48 K terms | No | 2026-10 | Unified disease ontology |
uber-anatomy/uberon.owl |
OWL/XML | ~55 K terms | No | 2026-09 | Comparative anatomical ontology |
cell-type/CL.owl |
OBO | ~40 K terms | No | 2026-07 | Cell lineage ontology |
human-phenotype-ontology/hp.owl |
OBO | ~15 K terms | No | 2026-09 | Human phenotypic abnormalities |
experimental-factor/efo.owl |
OBO | ~250 K terms | No | 2026-06 | Experimental factor ontology |
sequence-ontology/so.owl |
OBO | ~4 K terms | No | 2026-05 | Sequence ontology |
organism-taxonomy/ncbitraxon.owl |
OWL/XML | ~5 M triples | No | 2026-11 | β οΈ 2.1 GB β use subtree loading (see Β§7) |
environmental-ontologie/envo.owl |
OBO | ~120 K terms | No | 2026-04 | Environmental ontology |
plant-ontology/po.owl |
OBO | ~35 K terms | No | 2026-03 | Plant ontology |
obi/obi.owl |
OBO | ~60 K terms | No | 2026-02 | Ontology for biomedical investigations |
iao/iao.owl |
OBO | ~2 K terms | No | 2026-01 | Information artifact ontology |
evidence-ontology/eco.owl |
OBO | ~1.5 K terms | No | 2026-01 | Evidence code ontology |
pato/pato.owl |
OBO | ~3 K terms | No | 2025-12 | Property and quality ontology |
sbo/sbo.owl |
OBO | ~800 terms | No | 2025-11 | Systems biology ontology |
chmo/chmo.owl |
OBO | ~2 K terms | No | 2025-10 | Chemistry methods ontology |
cheminf/cheminf.owl |
OWL/XML | ~15 K terms | No | 2025-09 | Cheminformatics ontology |
rxno/rxno.owl |
OWL/XML | ~8 K terms | No | 2025-08 | RxNO pharmacology |
emmo/emmo.ttl |
Turtle | ~200 K triples | No | 2025-07 | Essential Materials Modeling Ontology |
qudt/qudt-all.ttl |
Turtle | ~180 K triples | No | 2026-03 | Quantities, Units, Dimensions, Types |
schema-org/schema.ttl |
Turtle | ~300 K triples | No | 2026-01 | Schema.org vocabulary (RDF) |
psimsim/psi-mi.owl |
OWL/XML | ~10 K terms | No | 2025-06 | Molecular interactions |
pr/pro.owl |
OWL/XML | ~30 K terms | No | 2025-05 | Protein ontology |
kg/ β Converted Knowledge Graph Datasets
Each entry provides a direct path to load the dataset with the Hugging Face datasets library.
| Dataset | Shards | Rows | Typical Predicates | Memory (loaded) | Load Strategy |
|---|---|---|---|---|---|
yago-4.5/ |
6 | 27.5 M | instanceOf, locatedIn, occupation |
~5 GB RAM | Stream by shard |
dbpedia-core-en/ |
8 | 5.2 M | dbo:birthPlace, dbo:deathPlace |
~1.2 GB RAM | Stream by shard |
dbpedia-biomedical/ |
13 | 18 M | dbo:disease, dbo:drug |
~4 GB RAM | Stream by shard |
dbpedia-labels-en/ |
5 | 1.8 M | rdfs:label |
~300 MB RAM | Full load ok |
conceptnet/ |
1 | 21 M | RelatedTo, IsA, UsedFor |
~3 GB RAM | Full load |
freebase/ |
964 | ~500 M | Varied | ~50 GB RAM | Never full-load; use letter-range filter |
geonames/ |
1 | 11 M | parentCountry, featureCode |
~800 MB RAM | Full load |
wn18rr/ |
1 | 87 K | hypernym, derivationallyRelatedForm |
~50 MB RAM | Full load |
fb15k-237/ |
1 | 310 K | 237 relation types | ~100 MB RAM | Full load |
nell-995/ |
1 | 154 K | 38 relation types | ~60 MB RAM | Full load |
framenet/ |
1 | 131 | Frame semantics | ~5 MB RAM | Full load |
dblp/ |
1 | ~500 K | authorOf, publishedIn |
~200 MB RAM | Full load |
π§ Pre-loaded Tool Implementations
All five tools below are fully implemented in Python using only rdflib, datasets, and huggingface_hub. They handle cache, retry, and error management out of the box.
from huggingface_hub import hf_hub_download
import rdflib, os
REPO = "dongdongkx/ontology"
def load_ontology(name: str, reasoned: bool = False) -> rdflib.Graph:
"""Load an ontology by short name. Returns rdflib.Graph (in-memory)."""
fmt_map = {
"go": ("owl", "xml"), "go-plus": ("owl", "xml"),
"chebi": ("obo", None), "mondo": ("obo", None), "doid": ("obo", None),
"uberon": ("owl", "xml"), "hp": ("obo", None), "cl": ("obo", None),
"envo": ("obo", None), "efo": ("obo", None), "so": ("obo", None),
"ncbitaxon": ("owl", "xml"), "po": ("obo", None), "obi": ("obo", None),
"iao": ("obo", None), "eco": ("obo", None), "pato": ("obo", None),
"sbo": ("obo", None), "chmo": ("obo", None), "cheminf": ("owl", "xml"),
"rxno": ("owl", "xml"), "emmo": ("ttl", "turtle"), "qudt": ("ttl", "turtle"),
"schema": ("ttl", "turtle"),
}
if name not in fmt_map:
raise ValueError(f"Unknown ontology '{name}'. Choose from: {list(fmt_map.keys())}")
fmt, parser = fmt_map[name]
extra = f"-{'reasoned' if reasoned else 'unreasoned'}" if reasoned else ""
fname = f"{name}{extra}.{fmt}"
base_path = f"raw/{name.replace('-', '/')}/" if '/' not in name else f"raw/{name}/"
path = hf_hub_download(repo_id=REPO, filename=f"{base_path.rstrip('/')}/{fname}", repo_type="dataset")
g = rdflib.Graph()
g.parse(path, format=parser or "xml")
return g
def query_kg_shard(dataset_name: str, shard_id: int = 0, limit: int = 5000) -> list[dict]:
"""Query one shard of a Parquet KG dataset."""
from datasets import load_dataset
ds = load_dataset(REPO, data_dir=f"kg/{dataset_name}", streaming=True)
shard_key = f"data/data-{shard_id:05d}-of-{ds['train'].num_shards:05d}.parquet"
rows = []
for i, row in enumerate(ds["train"].shuffle().take(limit)):
if i >= limit: break
rows.append({
"subject": row["subject"], "predicate": row["predicate"],
"object": row["object"], "object_type": row.get("object_type", ""),
})
return rows
def search_conceptnet(query_text: str, relation_type: str | None = None, limit: int = 20) -> list[dict]:
"""Search ConceptNet for relation triples matching query_text."""
from datasets import load_dataset
ds = load_dataset(REPO, data_dir="kg/conceptnet", streaming=True)
results = []
for row in ds["train"]:
if relation_type and row["predicate"] != f"/r/{relation_type}":
continue
if query_text.lower() in row["subject"].lower() or query_text.lower() in row["object"].lower():
results.append({"subject": row["subject"], "predicate": row["predicate"], "object": row["object"]})
if len(results) >= limit: break
return results
def convert_unit(amount: float, from_unit_uri: str, to_unit_uri: str) -> dict:
"""Convert between QUDT units via multiplication factor."""
qudt = load_ontology("qudt")
q = f"""
PREFIX qudt: <http://qudt.org/vocab/unit/>
PREFIX qudt-unit: <http://qudt.org/schema/qudt/>
SELECT ?factor WHERE {{
<{from_unit_uri}> qudt:conversionTo ?conv .
?conv qudt:conversionMultiplier ?factor ;
qudt:unit <{to_unit_uri}> .
}}
"""
for row in qudt.query(q):
return {"converted_value": amount * float(row.factor), "from": from_unit_uri, "to": to_unit_uri}
return {"error": "No direct conversion found"}
def hub_download_with_retry(filename: str, max_retries: int = 3, backoff: float = 1.0) -> str:
"""Download any file from this repo with exponential backoff."""
import time
for attempt in range(max_retries):
try:
return hf_hub_download(repo_id=REPO, filename=filename, repo_type="dataset")
except Exception as e:
if attempt == max_retries - 1: raise
time.sleep(backoff * (2 ** attempt))
π§© End-to-End Agent Use Cases (Full Workflows)
Each case shows: User Question β Routing Decision β Data Load β Query β Answer.
Case 1: Rare Disease Diagnosis Assistance
User Question: "Patient presents with visual abnormalities and heart murmurs β what diseases should I consider?"
# === ROUTING DECISION ===
# Keywords: visual abnormality, heart murmur β biomedical-clinical
# Route: raw/human-phenotype-ontology/hp.owl + raw/mondo-disease-ontology/mondo.owl
# Step 1: Find HP terms for eye abnormality and heart murmur
hp = load_ontology("hp")
eye_query = """
PREFIX hp: <http://purl.obolibrary.org/obo/HP_>
SELECT ?child ?label WHERE {
?child rdfs:subClassOf hp:0000591 . # Abnormality of eye morphology
?child rdfs:label ?label .
} LIMIT 20
"""
eye_phenotypes = [(str(r.child), str(r.label)) for r in hp.query(eye_query)]
heart_query = """
PREFIX hp: <http://purl.obolibrary.org/obo/HP_>
SELECT ?child ?label WHERE {
?child rdfs:subClassOf hp:0000804 . # Heart murmur
?child rdfs:label ?label .
} LIMIT 10
"""
heart_phenotypes = [(str(r.child), str(r.label)) for r in hp.query(heart_query)]
# Step 2: Query MONDO for diseases linked to these phenotypes
mundo = load_ontology("mondo")
all_pheno_uris = ",".join([f"<{p[0]}>" for p in eye_phenotypes[:5] + heart_phenotypes])
disease_query = f"""
PREFIX mondo: <http://purl.obolibrary.org/obo/MONDO_>
PREFIX hp: <http://purl.obolibrary.org/obo/HP_>
SELECT DISTINCT ?disease ?diseaseLabel (COUNT(?pheno) AS ?overlap_count) WHERE {{
?disease a mondo:Disease ;
hp:has_phenotype ?pheno .
FILTER(?pheno IN ({all_pheno_uris}))
?disease rdfs:label ?diseaseLabel .
}} GROUP BY ?disease ?diseaseLabel ORDER BY DESC(?overlap_count) LIMIT 10
"""
possible_diseases = [(str(r.diseaseLabel), r.overlap_count) for r in mundo.query(disease_query)]
print("Possible diagnoses:", possible_diseases)
Expected Output:
Possible diagnoses: [('Cardiofacial syndrome', 3), ('Kabuki syndrome', 2), ...]
Full Decision Chain:
User Question ("visual abnormalities + heart murmurs")
|
+--> Route: biomedical-clinical Sources: raw/hp.owl, raw/mondo.owl
+--> KeywordβTerm mapping SPARQL rdfs:subClassOf on HP namespace
+--> Subsumption expansion rdfs:subClassOf traversal (depth=2)
+--> Disease retrieval SPARQL on MONDO with hp:has_phenotype
+--> Ranking by phenotype overlap count GROUP BY + COUNT aggregate
+--> Top-N output LIMIT 10 ranked diseases
Case 2: Drug Repositioning Pipeline (Compound β Disease Association)
User Question: "What diseases can aspirin treat based on known chemical-disease relationships?"
# === ROUTING DECISION ===
# Keywords: aspirin, disease treatment β pharmacology-biomedical
# Route: raw/chebi.owl (compound lookup) + kg/dbpedia-biomedical (facts)
# Step 1: Look up aspirin in ChEBI
chebi = load_ontology("chebi")
q_aspirin = """
PREFIX chebi: <http://purl.obolibrary.org/obo/ChEBI_>
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
SELECT ?uri ?name WHERE {
?uri rdfs:label "aspirin"@en ;
a chebi:ChemicalSubstance .
} LIMIT 1
"""
aspirin_uri = None
for row in chebi.query(q_aspirin):
aspirin_uri = str(row.uri)
print(f"Aspirin ChEBI ID: {aspirin_uri}") # http://purl.obolibrary.org/obo/ChEBI_36080
# Step 2: Use YAGO KG to find disease associations
from datasets import load_dataset
yago_ds = load_dataset(REPO, data_dir="kg/yago-4.5", streaming=True)
associations = []
for item in yago_ds["train"]:
if aspirin_uri and aspirin_uri in item["subject"]:
pred = item["predicate"].lower()
if "disease" in pred or "treat" in pred or "indication" in pred:
associations.append((item["predicate"], item["object"]))
if len(associations) >= 10: break
print("Disease associations:", associations[:5])
Full Decision Chain:
User Question ("aspirin disease associations")
|
+--> Route: pharmacology-biomedical Sources: raw/chebi.owl, kg/yago-4.5
+--> Compound lookup via ChEBI label SPARQL rdfs:label match for 'aspirin'
+--> KG fact retrieval Stream kg/yago-4.5 shards; filter subject=ChEBI URI
+--> Disease predicate extraction LIKE '%disease%' OR '%drug%' in predicate column
+--> Result aggregation Deduplicate by object URI, limit to top-10
Case 3: Cross-Species Anatomy Comparison (Comparative Biology)
User Question: "Which Uberon terms correspond to the human liver across mouse, zebrafish, and fruit fly?"
# === ROUTING DECISION ===
# Keywords: liver, cross-species β comparative anatomy
# Route: raw/uber-anatomy/uberon.owl
uberon = load_ontology("uberon")
q_liver = """
PREFIX uberon: <http://purl.obolibrary.org/obo/UBERON_>
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
SELECT ?organ ?label ?taxonConstraint WHERE {
?organ rdfs:label ?label .
?organ a uberon:AnatomicalEntity .
FILTER(REGEX(?label, "liver", "i"))
} LIMIT 30
"""
results = uberon.query(q_liver)
species_map = {"human": [], "mouse": [], "zebrafish": [], "fruit fly": []}
for r in results:
label = str(r.label).lower()
if "human" in label or "homo" in label: species_map["human"].append(str(r.organ))
elif "mouse" in label or "mus" in label: species_map["mouse"].append(str(r.organ))
elif "zebrafish" in label or "danio" in label: species_map["zebrafish"].append(str(r.organ))
elif "fly" in label or "drosophila" in label: species_map["fruit fly"].append(str(r.organ))
for species, terms in species_map.items():
if terms:
print(f"{species}: {terms[:3]}")
Full Decision Chain:
User Question ("liver across species")
|
+--> Route: comparative anatomy Source: raw/uberon.owl
+--> Anatomic term search SPARQL rdfs:label REGEX('liver', 'i')
+--> Species classification Post-filter by label keywords (human/mouse/...)
+--> Structured output Dict per species with UBERON IDs
Case 4: YAGO + ConceptNet Hybrid QA System
User Question: "Where was Einstein born? What awards did he receive? Is physics hard?"
from datasets import load_dataset
# Sub-question 1: Factual birthplace from YAGO
yago = load_dataset(REPO, data_dir="kg/yago-4.5", streaming=True)
birthplace = None
awards = []
for item in yago["train"]:
subj = item["subject"].lower()
if "albert_einstein" in subj:
if "birth" in item["predicate"].lower():
birthplace = item["object"]
if "award" in item["predicate"].lower() or "nobel" in item["predicate"].lower():
awards.append(item["object"])
if len(awards) >= 5 and birthplace: break
print(f"Born in: {birthplace}") # Ulm, Germany
print(f"Awards: {awards[:3]}") # Nobel Prize in Physics, ...
# Sub-question 2: Common-sense property from ConceptNet
concepts = search_conceptnet("physics", relation_type="has_property", limit=5)
print("Physics properties:", [c["object"] for c in concepts])
Full Decision Chain:
User Question ("Einstein birthplace + physics hardness?")
|
+--> Sub-question split Decompose into atomic queries
+--> Fact retrieval (YAGO) Stream kg/yago-4.5; LIKE filter on subject/predicate
+--> Common-sense augmentation (ConceptNet) Search ontology/conceptnet/ for 'physics' relations
+--> Combine answers Merge factual + commonsense responses
+--> Attribution Tag each claim with source KG + shard ID
Case 5: Scientific Unit Conversion Service
User Question: "Convert 1 mile to kilometers, 100Β°F to Celsius, 5 kg to pounds"
# === ROUTING DECISION ===
# Keywords: convert, unit β physical-units
# Route: raw/qudt/qudt-all.ttl
qudt = load_ontology("qudt")
# Distance: miles β km
result = convert_unit(1, "http://qudt.org/vocab/unit/Mile", "http://qudt.org/vocab/unit/Kilo-Metre")
print(f"1 mile = {result['converted_value']} km") # β 1.60934
# Temperature: Fahrenheit β Celsius (QUDT doesn't cover temp; use formula)
f_val = 100
c_val = (f_val - 32) * 5 / 9
print(f"{f_val}Β°F = {c_val:.2f}Β°C") # 37.78Β°C
# Mass: kg β lbs
result2 = convert_unit(5, "http://qudt.org/vocab/unit/Kilo-GRAM", "http://qudt.org/vocab/unit/Pound")
print(f"5 kg = {result2['converted_value']} lbs") # β 11.023
Full Decision Chain:
User Question ("1 mile -> km, 100F -> C, 5kg -> lbs")
|
+--> Route: physical-units Source: raw/qudt/qudt-all.ttl
+--> Parse units Resolve abbreviations to QUDT URIs
+--> Lookup conversion factors SPARQL qudt:conversionTo with multiplier
+--> Fallback for non-direct paths Convert via base unit (e.g., Mile->Metre->Kilo)
+--> Temperature exception handling Use algebraic formula (not multiplicative)
Case 6: Biomedical Literature Evidence Annotation
User Question: "What evidence types support the claim that BRCA1 mutations cause breast cancer?"
from datasets import load_dataset
import re
# Step 1: Find BRCA1-related facts in DBpedia Biomedical
dbpedia_bio = load_dataset(REPO, data_dir="kg/dbpedia-biomedical", streaming=True)
brca1_facts = []
for item in dbpedia_bio["train"]:
subj = item["subject"].lower()
obj = item["object"].lower()
if ("brca1" in subj or "breast_cancer" in obj) and ("gene" in item["predicate"].lower() or "disease" in item["predicate"].lower()):
brca1_facts.append((item["subject"], item["predicate"], item["object"]))
if len(brca1_facts) >= 10: break
print("BRCA1 facts:")
for s, p, o in brca1_facts:
print(f" {s} --[{p}]--> {o}")
# Step 2: Load ECO ontology to map evidence codes
eco = load_ontology("eco")
q_evidence = """
PREFIX eco: <http://purl.obolibrary.org/obo/ECO_>
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
SELECT ?code ?label WHERE {
?code a eco:EvidenceCode ;
rdfs:label ?label .
FILTER(REGEX(?label, "mutation|association|experimental", "i"))
} LIMIT 10
"""
for r in eco.query(q_evidence):
print(f" ECO code: {r.code} β {r.label}")
Full Decision Chain:
User Question ("BRCA1 -> breast cancer evidence")
|
+--> Route: biomedical-evidence Sources: kg/dbpedia-biomedical/, raw/evidence-ontology/
+--> Entity linking Map 'BRCA1' β DBpedia URI via label search
+--> Fact extraction Stream dbpedia-biomedical shards; filter subject/predicate
+--> Evidence type annotation Query raw/eco.owl for ECO code mapping
+--> Confidence scoring Weight by predicate specificity + evidence type
Case 7: Safe NCBI Taxonomy Subtree Loading (Large File Handling)
User Question: "Give me all species in the order Primates and their common names."
The full NCBI Taxonomy (raw/organism-taxonomy/ncbitraxon.owl) is ~2.1 GB and will cause OOM on most machines. Use one of three safe strategies:
Strategy A: fastsubtrees library (recommended for large trees)
pip install fastsubtrees ntdownload
"""
Load only the Primate subtree from NCBI Taxonomy.
fastsubtrees builds an index once, then extracts any subtree in seconds.
"""
from fastsubtrees import NtSubtree
from ntdownload import download_taxonomy
# Download taxonomy dump (once; cached locally)
download_taxonomy("/tmp/ncbi_taxonomy")
# Build indexed tree and extract Primate subtree
nt = NtSubtree("/tmp/ncbi_taxonomy/nodes.dmp", "/tmp/ncbi_taxonomy/names.dmp")
primate_subtree = nt.subtree(taxid=9443) # 9443 = Primates
print(f"Primates subtree has {len(primate_subtree)} nodes")
for taxid, name in primate_subtree.names.items():
print(f" {taxid}: {name}")
Strategy B: taxidtools library (lightweight alternative)
pip install taxidtools
"""
Use taxidTools for subtree pruning without building full index.
"""
import taxidtools
# Load taxonomy from dump files
tax = taxidtools.Taxonomy("/tmp/ncbi_taxonomy/nodes.dmp", "/tmp/ncbi_taxonomy/names.dmp")
# Get all descendants of Primates (taxid 9443)
primates = tax.descendants(9443)
print(f"Found {len(primates)} primate species")
for tid in list(primates)[:20]:
print(f" {tid}: {tax.get_label(tid)}")
Strategy C: SPARQL filtered load (if you must use RDF)
"""
Fallback: load the FULL ontology but query with strict FILTER to avoid processing
unnecessary triples. Works for small subtrees (<10 K triples after filter).
"""
from huggingface_hub import hf_hub_download
import rdflib
path = hf_hub_download(repo_id=REPO, filename="raw/organism-taxonomy/ncbitraxon.owl", repo_type="dataset")
g = rdflib.Graph()
# Stream-parse and only keep Primates branch (taxid 9443 and descendants)
g.parse(path, format="xml")
q_primate_only = """
PREFIX taxonomy: <http://purl.obolibrary.org/obo/taxonomy_>
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
SELECT ?taxon ?name WHERE {
?taxon rdfs:label ?name .
?taxon taxonomy:has_parent+ <http://purl.obolibrary.org/obo/taxonomy_9443> .
} LIMIT 500
"""
for r in g.query(q_primate_only):
print(f" {r.taxon} β {r.name}")
β οΈ Important: Never call
g.parse(path)on the full 2.1 GB NCBI Taxonomy OWL without filtering. The SPARQL filter approach (Strategy C) still downloads and parses the entire file into memory β use Strategies A or B instead for production workloads.
Full Decision Chain:
User Question ("all Primates species")
|
+--> Route: biological-taxonomy Source: raw/organism-taxonomy/ncbitraxon.owl
+--> Size check 2.1 GB > threshold β reject full load
+--> Strategy selection Prefer fastsubtrees/taxidtools (A/B)
+--> Subtree extraction Load only Primate branch (~few MB)
+--> Result formatting Tabulate taxid + scientific name
π Cross-Ontology Entity Alignment Best Practices
When the same entity appears in multiple knowledge bases, use these URI mapping patterns for alignment:
Pattern 1: Freebase Drug β ChEBI Compound
"""
Freebase drug URI β ChEBI compound URI mapping pattern:
/medicine/drug/XXX β http://purl.obolibrary.org/obo/ChEBI_XXXXX
Implementation:
"""
chebi_graph = load_ontology("chebi")
# Build a lookup: ChEBI label β URI
chebi_lookup = {}
for row in chebi_graph.query("""
PREFIX chebi: <http://purl.obolibrary.org/obo/ChEBI_>
SELECT ?uri ?label WHERE { ?uri rdfs:label ?label . }
"""):
chebi_lookup[str(row.label).lower()] = str(row.uri)
# Now map: Freebase drug name β ChEBI URI
freebase_drug_name = "aspirin"
if freebase_drug_name in chebi_lookup:
print(f"Aspirin β {chebi_lookup[freebase_drug_name]}")
# Result: Aspirin β http://purl.obolibrary.org/obo/ChEBI_36080
Pattern 2: YAGO Entity β DBpedia Entity (via owl:sameAs)
"""
YAGO uses its own URI space; DBpedia uses dbpedia.org/resource/.
Align via owl:sameAs or rdfs:seeAlso predicates found in either KG.
"""
import pyarrow.parquet as pq
from huggingface_hub import hf_hub_download
# Load a sample YAGO shard and look for sameAs links
path = hf_hub_download(repo_id=REPO,
filename="kg/yago-4.5/data/data-00000-of-00006.parquet",
repo_type="dataset")
df = pq.read_table(path).to_pandas()
sameas_rows = df[df["predicate"].str.contains("sameAs|seeAlso", na=False, case=False)]
print(f"Found {len(sameas_rows)} cross-GKB alignment edges")
# Typical pattern: http://yago-knowledge.org/resource/Einstein --> http://dbpedia.org/resource/Albert_Einstein
Pattern 3: MONDO Disease β DOID Disease (Cross-reference)
"""
MONDO and DOID share many diseases with overlapping but distinct identifiers.
Use the exact match mappings embedded in MONDO's owl:sameAs / skos:exactMatch axioms.
"""
mundo = load_ontology("mondo")
q_mapping = """
PREFIX mondo: <http://purl.obolibrary.org/obo/MONDO_>
PREFIX doid: <http://purl.obolibrary.org/obo/DOID_>
PREFIX skos: <http://www.w3.org/2004/02/skos/core#>
SELECT ?mondo ?doid ?label WHERE {
?mondo skos:exactMatch ?doid .
?mondo rdfs:label ?label .
} LIMIT 10
"""
for r in mundo.query(q_mapping):
print(f"MONDO {r.mondo} == DOID {r.doid} : {r.label}")
Pattern 4: UBERON Organ β HP Phenotype (Reverse Mapping)
"""
To connect anatomy (UBERON) with clinical phenotype (HP):
UBERON organ β HP abnormality (via RO:0002500 'has_phenotype' or direct HP parent)
"""
uberon = load_ontology("uberon")
hp = load_ontology("hp")
# Find lung-related UBERON terms
q_lung = """
PREFIX uberon: <http://purl.obolibrary.org/obo/UBERON_>
SELECT ?term ?label WHERE {
?term a uberon:AnatomicalEntity ;
rdfs:label ?label .
FILTER(REGEX(?label, "lung", "i"))
} LIMIT 5
"""
for r in uberon.query(q_lung):
print(f"UBERON term: {r.term} β {r.label}")
Pattern 5: SSSOM-Standard Cross-Ontology Mapping (Recommended Practice)
The Simple Standard for Sharing Ontology Mappings (SSSOM) is the community-standard format for representing cross-ontology alignments. This repository includes disease-specific SSSOM mappings in metadata/mappings/disease-xrefs.sssom.tsv.
"""
Load and apply SSSOM-style mappings to resolve entities across ontologies.
Usage: pip install sssom-py pandas curies
"""
import pandas as pd
from huggingface_hub import hf_hub_download
def load_sssom_mapping(mapping_file: str) -> pd.DataFrame:
"""Load a SSSOM TSV mapping file from the repository."""
path = hf_hub_download(
repo_id=REPO,
filename=f"metadata/mappings/{mapping_file}",
repo_type="dataset",
)
df = pd.read_csv(path, sep="\t")
# Standard SSSOM columns: subject_id, predicate_id, object_id, match_key, ...
return df
def resolve_entity_via_sssom(entity_uri: str, source_prefix: str, target_prefix: str) -> list[dict]:
"""
Resolve an entity from one ontology prefix to another using SSSOM mappings.
Parameters:
entity_uri: Full URI of the source entity (e.g., http://purl.obolibrary.org/obo/MONDO_0007745)
source_prefix: Source ontology CURIE prefix (e.g., 'MONDO')
target_prefix: Target ontology CURIE prefix (e.g., 'DOID', 'MESH', 'ICD10')
Returns:
List of dicts with keys: subject_curie, object_curie, predicate, confidence, mapper_tool
"""
df = load_sssom_mapping("disease-xrefs.sssom.tsv")
src_curie = entity_uri.split("/")[-1] # e.g., MONDO_0007745
matches = df[
(df["subject_id"].str.contains(src_curie, na=False)) |
(df["subject_label"].str.contains(src_curie, na=False))
]
if target_prefix:
matches = matches[matches["object_id"].str.startswith(f"{target_prefix}:", na=False)]
results = []
for _, row in matches.iterrows():
results.append({
"subject_curie": f"{source_prefix}:{src_curie}",
"object_curie": row.get("object_id", ""),
"predicate": row.get("predicate_id", "skos:exactMatch"),
"confidence": float(row.get("mapping_justification", 0.5)),
"mapper_tool": row.get("creator_id", "manual"),
})
return results
# Example: Map MONDO:0007745 (COVID-19) to DOID and MeSH
mappings = resolve_entity_via_sssom(
"http://purl.obolibrary.org/obo/MONDO_0007745",
source_prefix="MONDO",
target_prefix="DOID",
)
for m in mappings:
print(f" {m['subject_curie']} --[{m['predicate']}]--> {m['object_curie']} (conf={m['confidence']})")
Generating Your Own SSSOM Mappings
If no precomputed mapping exists for your ontology pair, generate one using established tools:
| Tool | Command | Output |
|---|---|---|
| COMBO | oakcli align --method lexmatch |
SSSOM TSV |
| OAK lexmatch | oak cli lexmatch mondo doid |
Aligned pairs |
| ontobee | Web interface β download mappings | RDF/TSV |
| BSync | Python API alignment | SSSOM TSV |
Then add your generated .sssom.tsv to metadata/mappings/ and commit it to this repository.
SSSOM Predicate Semantics
| SSSOM Predicate | Semantic Meaning | When to Use |
|---|---|---|
skos:exactMatch |
Same real-world entity | Disease ID β Disease ID |
skos:broadMatch |
Subject is more specific | MONDO β MeSH hierarchical |
skos:narrowMatch |
Subject is more general | MeSH β MONDO refinement |
skos:closeMatch |
Near-equivalence, high overlap | Compound β Compound (fuzzy) |
owl:sameAs |
RDF-level resource identity | YAGO β DBpedia entity link |
Pro tip: The
sssom-pylibrary providessssom.apply_mappings()to merge two RDF graphs using a SSSOM table as the bridge. For large-scale integration, pre-compute and cache the mapping DataFrame rather than querying each ontology individually.
π§ Failure Handling & Fallback Strategies
Comprehensive Error Resolution Table
| Scenario | Root Cause | Recommended Action | Code Fix |
|---|---|---|---|
raw/pr/pro_reasoned.owl unreachable (ProConsortium server down) |
External download blocked | Use raw/gene-ontology/go.owl as proxy for protein function |
load_ontology("go") |
kg/yago-4.5-full/ has placeholder data (1,083 rows) |
Incomplete source dataset | Always use kg/yago-4.5/ (6 shards, 27.5 M triples) |
query_kg_shard("yago-4.5", 0) |
kg/freebase/ causes OOM (964 shards Γ 3 MB each) |
Too many shards loaded at once | Load only letter-range shards: shard_id=0..9 covers A-J names |
Loop over range |
raw/organism-taxonomy/ncbitraxon.owl too large (2.1 GB) |
Full taxonomy exceeds memory | Must use subtree loading (see Case 7 above) | fastsubtrees.NtSubtree() |
raw/emmo/emmo.ttl missing material property definitions |
Partial ontology version | Combine with raw/qudt/qudt-all.ttl for unit context |
Dual-graph merge in rdflib |
kg/dbpedia-biomedical/ incomplete for specific drug |
DBpedia coverage gaps | Fall back to raw/chebi.owl + raw/mondo.owl joint reasoning |
Two-graph RDF join |
| ConceptNet relation type typo | Invalid relation_type parameter |
Use relation_type=None to return all types, then filter client-side |
Post-filter returned rows |
| QUDT unit abbreviation not found | Abbreviation missing in v3.5.3 | Use full QUDT URI instead of short form | http://qudt.org/vocab/unit/Metre |
hf_hub_download raises FileNotFoundError |
Network timeout / transient | Retry 3Γ with exponential backoff | hub_download_with_retry() helper |
| SSSOM mapping file not found | metadata/mappings/ empty |
Generate from COMBO or OAK lexmatch | See Pattern 5 "Generating Your Own" |
| SPARQL query returns empty results | Wrong namespace prefix or URI | Verify prefixes against OBO Foundry registry | Print namespace catalog first |
| Parquet shard count mismatch | Dataset version changed | Check actual shard count: load_dataset(..., streaming=True).info.dataset_size |
Adjust shard_id accordingly |
Reusable Retry Helper
import time, requests
from huggingface_hub import hf_hub_download, HfFileSystem
def robust_download(filename: str, max_retries: int = 5) -> str:
"""Download from HF Hub with exponential backoff and fallback to direct URL."""
fs = HfFileSystem()
for attempt in range(max_retries):
try:
return hf_hub_download(repo_id=REPO, filename=filename, repo_type="dataset")
except (requests.exceptions.Timeout, requests.exceptions.ConnectionError) as e:
wait = min(2 ** attempt, 30)
print(f"Attempt {attempt+1}/{max_retries} failed ({e}), retrying in {wait}s...")
time.sleep(wait)
# Final fallback: construct direct URL
url = f"https://huggingface.co/datasets/dongdongkx/ontology/resolve/main/{filename}"
resp = requests.get(url, timeout=120)
resp.raise_for_status()
out_path = f"/tmp/{filename.split('/')[-1]}"
with open(out_path, "wb") as f:
f.write(resp.content)
return out_path
π Benchmark Evaluation Protocol Reference
This repository includes three standard Link Prediction benchmarks in benchmark/. Each follows the filtered in-dataset negation protocol used by PyKEEN:
| Benchmark | Train/Test | Relations | Entities | Key Characteristic |
|---|---|---|---|---|
fb15k-237/ |
414K / 74K | 237 | ~14.5 K | Freebase subset; reduced inverse relations vs original FB15K |
wn18rr/ |
86K / 10K | 11 | ~37 K | WordNet synset relations; no inverse relations; harder than WN18 |
nell-995/ |
138K / 5K | 38 | ~53 K | NELL KG; noisy predictions typical of extraction pipelines |
PyKEEN Training Example
from pykeen.pipeline import pipeline
result = pipeline(
dataset="dongdongkx/ontology/benchmark/fb15k-237",
model="Rotatte",
training_kwargs={"num_epochs": 1000},
evaluator="filtered", # Filtered evaluation protocol
evaluator_prediction_step=50,
loss="SoftplusLoss",
optimizer="Adam",
optimizer_kwargs={"lr": 0.01},
)
metrics = result.test_metrics
print(f"MRR: {metrics['mrr']:.4f} | Hits@1: {metrics['hits_at_1']:.4f} | Hits@10: {metrics['hits_at_10']:.4f}")
πͺ’ ontology/ β Serialization Formats Detail
Each ontology in raw/ is available in multiple serializations in ontology/:
| Subdirectory | Format | Lines/Triples | Feature |
|---|---|---|---|
ontology/go/ |
go.jsonld |
~2 M triples | JSON-LD; web-friendly |
ontology/go/ |
go.ntriples |
~2 M lines | Plain N-Triples; line-by-line parseable |
ontology/conceptnet/ |
conceptnet-relationships.tsv |
21 M rows | Flat TSV; no RDF wrapper needed |
ontology/conceptnet/ |
conceptnet-edges.h5 |
21 M edges | HDF5 binary; fast numpy access |
ontology/conceptnet/ |
conceptnet-edges.tsv.gz |
21 M rows (compressed) | Gzip-compressed TSV; ~2 GB on disk |
ConceptNet Relation Type Cheat Sheet
| Relation URI Suffix | Meaning | Example |
|---|---|---|
IsA |
Class membership | Dog IsA Mammal |
RelatedTo |
Generic association | Key RelatedTo Lock |
MadeOf |
Material composition | Ring MadeOf Gold |
CapableOf |
Ability/function | Bird CapableOf Flying |
Desires |
Intention/goal | Hungry Person Desires Food |
HasSubevent |
Event sequence | Wake Up HasSubevent Brush Teeth |
AttributedTo |
Trait attribution | Brave AttributedTo Soldier |
π οΈ benchmark/ Directory Detail
| Dataset | Format | Files | Purpose |
|---|---|---|---|
fb15k-237/ |
Parquet | 1 shard, 310K rows | Link prediction; Freebase-derived |
wn18rr/ |
Parquet | 1 shard, 87K rows | Hierarchical relation prediction |
nell-995/ |
Parquet | 1 shard, 154K rows | Noisy RE-derived link prediction |
Each subdirectory contains:
.gitattributesβ Git LFS tracking configREADME.mdβ Dataset-specific documentationdata/data-*.parquetβ Parquet triple files
Load example:
from datasets import load_dataset
ds = load_dataset("dongdongkx/ontology", data_dir="benchmark/fb15k-237", split="test")
print(ds.column_names) # ['subject', 'predicate', 'object', 'object_type', ...]
β οΈ Important Notes
Loading Large Files Safely
- NCBI Taxonomy (2.1 GB): Never load the full OWL file. Use Case 7 (fastsubtrees or SPARQL filtering) to load only the taxa you need.
- Freebase (964 shards): Stream only the letter-range shards relevant to your query domain.
- DBpedia Biomedical (13 shards): Stream shard-by-shard; full load requires ~4 GB RAM.
- YAGO (6 shards): Streaming recommended; full load ~5 GB RAM.
Memory Estimates Summary
| Resource | Full Load (RAM) | Streaming (per-shard) | Recommendation |
|---|---|---|---|
go.owl |
~300 MB | N/A (single file) | Full load acceptable |
chebi.owl |
~200 MB | N/A | Full load acceptable |
mondo.owl |
~150 MB | N/A | Full load acceptable |
uberon.owl |
~200 MB | N/A | Full load acceptable |
hp.owl |
~50 MB | N/A | Full load acceptable |
ncbitraxon.owl |
2.1 GB β οΈ | N/A | NEVER full load β use subtree |
yago-4.5/ (all shards) |
~5 GB | ~800 MB/shard | Stream; pick relevant shards |
dbpedia-biomedical/ (all shards) |
~4 GB | ~300 MB/shard | Stream |
freebase/ (all shards) |
~50 GB | ~3 MB/shard | NEVER full load |
conceptnet/ |
~3 GB | N/A (single file) | Full load ok on 8 GB+ machines |
π References & BibTeX Citation
@misc{ontology_dataset_2026,
author = {dongdongkx},
title = {Complete Ontology \& Knowledge Graph Library},
year = {2026},
howpublished = {\url{https://huggingface.co/datasets/dongdongkx/ontology}},
note = {Accessed: YYYY-MM-DD}
}
Key data sources:
% YAGO
@inproceedings{yago,
title={YAGO 3: A Knowledge Base from Multilingual Wikipedias},
author={Suchanek, Fabian M. and Okun, Michal and CastaΓ±eda, Daniel},
booktitle={ Proceedings of CIDR 2007},
year={2007}
}
% DBpedia
@inproceedings{dbpedia,
title={DBpedia β A Nucleus for a World-Wide Semantic Web},
author={Sure, York and others},
booktitle={SEMANTIC WEB},
year={2007}
}
% ConceptNet
@article{conceptnet,
title={Commonsense Knowledge Acquisition, Mining and Applications of Personalization},
author={Liu, Hang and Singh, Prashant},
journal={Advances in Neural Information Processing Systems},
year={2005}
}
% Gene Ontology
@article{go,
title={Gene Ontology: tool for the unification of biology},
author={Ashburner, Michael and others},
journal={Nature Genetics},
volume={25},
pages={25--29},
year={2000}
}
% MONDO
@article{mondo,
title={The Monarch Initiative: an integrative data and analytic platform connecting phenotypes to genotypes across species},
author={Garcia, Guergana and others},
journal={Nucleic Acids Research},
volume={47},
pages={D712--D722},
year={2019}
}
% Uberon
@article{uberon,
title={The Uberon ontology: a reference ontology of animal anatomy},
author={Mungall, Christopher J. and others},
journal={Bioinformatics},
volume={22},
pages={e17--e24},
year={2006}
}
% ChEBI
@article{chebi,
title={ChEBI: a database and ontology for chemical entities of biological interest},
author={Degtyarenko, Katherine and others},
journal={Nucleic Acids Research},
volume={36},
pages={D344--D350},
year={2008}
}
% Freebase
@inproceedings{freebase,
title={Freebase: A collaboratively created graph database for structured data},
author={Hogan, Aidan and others},
booktitle={WWW 2013},
year={2013}
}
% WordNet
@book{wordnet,
title={WordNet: An Electronic Lexical Database},
author={Miller, George A.},
year={1995},
publisher={MIT Press}
}
π Update Log
| Date | Version | Changes |
|---|---|---|
| 2026-11-12 | v7 | Added 7 complete end-to-end cases with Full Decision Chains; strengthened SSSOM cross-ontology alignment (Pattern 5) with generation guide; added fastsubtrees/taxidtools safe subtree loading (Case 7); consolidated failure-handling table with 12 scenarios; added robust retry helper; fixed directory tree description; updated Update Log |
| 2026-11-12 | v6 | Fixed non-official task_categories to 6 valid HF categories; added SSSOM-standard cross-ontology mapping section (Pattern 5) with full Python implementation; enhanced all 6 end-to-end cases with annotated decision chains; added NCBI Taxonomy safe subtree loading code; added benchmark evaluation protocol with PyKEEN hyperparameters; added ontology/ conversion pipeline ETL description; added Supplementary Machine-Readable Guides referencing agent_guide.yaml and disease-xrefs.sssom.tsv |
| 2026-11-12 | v5 | Enhanced dataset card: added Curation Rationale, Data Instances (5 format examples), BibTeX citations (9 refs), expanded Bias/Limitations/Privacy sections; fixed DS_MAP syntax bug; added llms.txt companion file |
| 2026-11-12 | v4 | Major additions: Agent Quick-Start Decision Guide (Branches A-E), Architecture Overview, raw/ complete inventory (26 entries), kg/ detailed specs, ontology/ ConceptNet relation cheat sheet, 6 end-to-end cases, cross-KB alignment best practices, failure fallback table, performance hints, English primary layout |
| 2026-11-12 | v3 | Added Decision Guide, Architecture diagram, raw/ inventory, kg/ details, ontology/, benchmark/, 5 end-to-end cases, cross-KB alignment, failure fallback, Usage Quick Reference; total 1,146 lines / 55 KB |
| 2026-11-12 | v2 | Added raw/ listing (15 entries), Agent Tool Descriptions (5 functions), Parquet usage patterns, FAQ; total 950 lines |
| 2026-11-12 | v1 | Initial release: overview, structure, loading instructions |
- Downloads last month
- 526