### Project Installation and Setup (Bash) Source: https://github.com/linkml/valuesets/blob/main/README.md This Bash snippet outlines the steps to clone the LinkML Valuesets project repository and install its dependencies using uv. This is the initial setup for development. ```bash git clone https://github.com/linkml/valuesets cd valuesets uv install ``` -------------------------------- ### Modular ValueSet Installation (Bash) Source: https://github.com/linkml/valuesets/blob/main/README.md This Bash snippet illustrates how to install modular components of the valuesets package using pip. It allows users to install only the necessary domain-specific packages, reducing installation size. ```bash # Future: Install only what you need pip install valuesets-core # Core functionality pip install valuesets-bio # Biological domains pip install valuesets-materials # Materials science pip install valuesets-clinical # Clinical/medical ``` -------------------------------- ### Example Protected Slot Configuration (YAML) Source: https://github.com/linkml/valuesets/blob/main/docs/slot-generation.md Demonstrates a LinkML slot configuration that includes manual customizations and comments indicating protection. The smart_slot_syncer will preserve these fields during updates. ```yaml mineralogy_feedstock: description: Types of mineral feedstock sources... range: MineralogyFeedstockClass required: true # Manual customization - preserved comments: - "Required field for mining operation records" - "Manual customization - do not modify" # Protection marker ``` -------------------------------- ### Audit Trail Example (JSON) Source: https://github.com/linkml/valuesets/blob/main/docs/slot-generation.md An example of the changelog generated by smart_slot_syncer.py when the --changelog flag is used. It records timestamped changes like slot additions and updates. ```json [ { "timestamp": "2025-10-02T18:30:22.123456", "change": "ADD: mineralogy_feedstock (range: MineralogyFeedstockClass)" }, { "timestamp": "2025-10-02T18:30:22.124567", "change": "UPDATE: old_slot range: OldEnum → NewEnum" } ] ``` -------------------------------- ### Python Cross-Domain Integration Example Source: https://github.com/linkml/valuesets/blob/main/docs/manuscript/manuscript.md Demonstrates how to combine enumerations from different domains (Biology, Statistics, Chemistry) within a Python class and access their semantic information. This example utilizes the 'valuesets' library to access predefined enumerations and their associated meanings. ```python from valuesets.enums.bio.taxonomy import CommonOrganismTaxaEnum from valuesets.enums.statistics import StatisticalTest from valuesets.enums.chemistry import ChemicalElement # Combine enumerations from different domains class Experiment: organism: CommonOrganismTaxaEnum test_method: StatisticalTest treatment_element: ChemicalElement exp = Experiment( organism=CommonOrganismTaxaEnum.MOUSE, test_method=StatisticalTest.ANOVA, treatment_element=ChemicalElement.ZINC ) # Access semantic information print(exp.organism.get_meaning()) # NCBITaxon:10090 print(exp.test_method.get_meaning()) # STATO:0000159 print(exp.treatment_element.get_meaning()) # CHEBI:27363 ``` -------------------------------- ### Python Enum Usage: Sex and Description Source: https://github.com/linkml/valuesets/blob/main/README.md Demonstrates the basic usage of a Python enum for 'Sex' from the core module, showing how to access its value, meaning (ontology term), and description. This serves as a simple example of how the value sets can be applied. ```python from valuesets.enums.core import SexEnum s = SexEnum.MALE print(s.value) # "MALE" print(s.get_meaning()) # "NCIT:C20197" print(s.get_description())# "Male sex" ``` -------------------------------- ### Example Generated Python Enum with Metadata Class Source: https://github.com/linkml/valuesets/blob/main/templates/README.md An example of Python code generated by the custom Jinja2 template. It includes a standard string-based Enum and a corresponding Meta class to hold and provide access to enum member descriptions at runtime. ```python class DataAbsentEnumMeta: """Metadata holder for DataAbsentEnum enum values""" _descriptions = { "Unknown": "The value is expected to exist but is not known.", # ... more descriptions } @classmethod def description(cls, member: "DataAbsentEnum") -> Optional[str]: """Get description for enum member""" return cls._descriptions.get(member.name, None) class DataAbsentEnum(str, Enum): """Used to specify why content is missing.""" # Enum members Unknown = "unknown" # Metadata access methods def get_description(self) -> Optional[str]: """Get description for this enum value""" return DataAbsentEnumMeta.description(self) ``` -------------------------------- ### LinkML Class Definition with Generated Slots Source: https://github.com/linkml/valuesets/blob/main/docs/slot-generation.md This YAML example shows how to define a LinkML class, `MiningOperation`, and incorporate generated slots derived from enums. It illustrates referencing enum-based slots like `mineralogy_feedstock` and `beneficiation_pathway`, as well as a multivalued slot `extractable_target_element`. ```yaml classes: MiningOperation: description: A mining operation record slots: - mineralogy_feedstock # References MineralogyFeedstockClass enum - beneficiation_pathway # References BeneficiationPathway enum - extractable_target_element # Multivalued, references ExtractableTargetElement enum ``` -------------------------------- ### Using Generated Rich Enums (Python) Source: https://github.com/linkml/valuesets/blob/main/RICH_ENUMS.md Example code demonstrating how to use generated rich enums in Python. It shows standard enum usage, accessing rich metadata like descriptions and meanings, and performing lookups by ontology terms. ```python from valuesets.datamodel.valuesets import AnatomicalSide # Use like a normal enum left = AnatomicalSide.LEFT print(left) # "LEFT" print(left == "LEFT") # True # Access rich metadata print(left.get_description()) # "Left side of a bilaterally symmetric organism" print(left.get_meaning()) # "BSPO:0000000" print(left.get_annotations()) # {...} # Lookup by ontology term anterior = AnatomicalSide.from_meaning("BSPO:0000055") print(anterior) # AnatomicalSide.ANTERIOR # Get all ontology mappings meanings = AnatomicalSide.get_all_meanings() # {"LEFT": "BSPO:0000000", "RIGHT": "BSPO:0000007", ...} ``` -------------------------------- ### Future Python Dynamic Enum Expansion Source: https://github.com/linkml/valuesets/blob/main/README.md Illustrates a future capability for dynamic enums in Python, where enums can be expanded at runtime by querying ontologies. This example shows how `expand_from_ontology()` could be used to populate an enum with all subtypes of a given concept. ```python # Future: Dynamically expand enum with all neuron subtypes cell_types = CellTypeEnum.expand_from_ontology() # Would add: MOTOR_NEURON, SENSORY_NEURON, INTERNEURON, etc. ``` -------------------------------- ### Python Enum Usage: Taxonomy and Cell Biology Source: https://github.com/linkml/valuesets/blob/main/README.md Shows how to use Python enums for biological data, including common organisms with NCBI Taxonomy IDs, cell cycle phases, and cell types with CL and GO mappings. It also includes an example of filtering enums based on taxonomic levels. ```python from valuesets.enums.bio.taxonomy import CommonOrganismTaxaEnum, BiologicalKingdom from valuesets.enums.bio.cell_biology import CellCyclePhase, CellType # Model organisms with NCBI Taxonomy IDs human = CommonOrganismTaxaEnum.HUMAN print(human.get_meaning()) # "NCBITaxon:9606" print(human.get_description()) # "Homo sapiens (human)" # Cell biology with CL and GO mappings phase = CellCyclePhase.S_PHASE print(phase.get_meaning()) # "GO:0000084" neuron = CellType.NEURON print(neuron.get_meaning()) # "CL:0000540" # Get all organisms at a specific taxonomic level mammals = [org for org in CommonOrganismTaxaEnum if 'MAMMALIA' in str(org)] ``` -------------------------------- ### Python Hierarchical Enum Relationships Source: https://github.com/linkml/valuesets/blob/main/README.md Demonstrates the support for hierarchical 'is_a' relationships within Python enums, using `ViralGenomeTypeEnum` as an example to show how specific types inherit from broader categories. ```python # Some enums support hierarchical is_a relationships from valuesets.enums import ViralGenomeTypeEnum # Baltimore classification with hierarchy positive_rna = ViralGenomeTypeEnum.SSRNA_POSITIVE # Group IV # inherits from SSRNA (single-stranded RNA) ``` -------------------------------- ### LinkML Dynamic Enum YAML Configuration Source: https://github.com/linkml/valuesets/blob/main/README.md Provides an example of a LinkML schema definition for a dynamic enum (`CellTypeEnum`) using YAML. This configuration specifies static values with ontology mappings and defines how the enum can be dynamically expanded from an ontology based on specified source nodes and relationship types. ```yaml # Example: A dynamic enum that pulls values from an ontology CellTypeEnum: permissible_values: NEURON: meaning: CL:0000540 ASTROCYTE: meaning: CL:0002585 # Dynamic expansion from Cell Ontology reachable_from: source_ontology: obo:cl source_nodes: - CL:0000540 # neuron include_self: false relationship_types: - rdfs:subClassOf ``` -------------------------------- ### Generate Project Site Source: https://github.com/linkml/valuesets/blob/main/AGENTS.md Generates the project site, likely including documentation or rendered schemas. This command should be run after every edit to check for mistakes. ```shell just site ``` -------------------------------- ### Available Development Commands (Bash) Source: https://github.com/linkml/valuesets/blob/main/README.md This Bash snippet lists the available commands provided by the 'just' task runner for the LinkML Valuesets project. These commands facilitate common development tasks like testing, linting, and building documentation. ```bash just --list # Show all available commands just test # Run tests just doctest # Run doctests just lint # Run linting just site # Build documentation site ``` -------------------------------- ### Run Project Linting Source: https://github.com/linkml/valuesets/blob/main/AGENTS.md Applies linting rules to the project code and schemas. Linting helps maintain code quality, consistency, and adherence to project standards. ```shell just lint ``` -------------------------------- ### Run Project Tests Source: https://github.com/linkml/valuesets/blob/main/AGENTS.md Executes the test suite for the LinkML Value Sets project. Running tests helps ensure the integrity and correctness of the value set definitions and associated code. ```shell just test ``` -------------------------------- ### Command-Line Code Generation for Multiple Languages Source: https://github.com/linkml/valuesets/blob/main/README.md Shows how to use the `linkml-convert` command-line tool to generate schema and type definitions for various programming languages and formats, including JSON Schema, TypeScript, and SQL DDL. ```bash # Generate JSON Schema for web apps linkml-convert schema.yaml -t json-schema # Generate TypeScript definitions linkml-convert schema.yaml -t typescript # Generate SQL DDL linkml-convert schema.yaml -t sql ``` -------------------------------- ### Preview Sync Changes with smart_slot_syncer.py (Bash) Source: https://github.com/linkml/valuesets/blob/main/docs/slot-generation.md Perform a dry run of the smart_slot_syncer.py script to preview proposed slot synchronization changes without applying them to the schema files. Use the verbose flag for detailed output. ```bash uv run python src/valuesets/generators/smart_slot_syncer.py schema.yaml --dry-run -v ``` -------------------------------- ### Configure LinkML Pydantic Generator with Custom Templates Source: https://github.com/linkml/valuesets/blob/main/templates/README.md Command-line instruction to run the LinkML Pydantic generator, specifying a directory for custom Jinja2 templates. This allows for customized output generation, such as enhanced enums. ```bash uv run gen-pydantic --template-dir templates/pydantic schema.yaml ``` -------------------------------- ### Preview Slots with auto_slot_injector.py (Bash) Source: https://github.com/linkml/valuesets/blob/main/docs/slot-generation.md Use the auto_slot_injector.py script in preview mode to see proposed slot definitions for a single schema file without making any changes. ```bash uv run python src/valuesets/generators/auto_slot_injector.py schema.yaml --mode preview ``` -------------------------------- ### Sync All Schemas in Batch with smart_slot_syncer.py (Bash) Source: https://github.com/linkml/valuesets/blob/main/docs/slot-generation.md Process all schema files within a directory using the smart_slot_syncer.py script in batch mode with in-place modifications. This is useful for updating multiple schemas simultaneously. ```bash uv run python src/valuesets/generators/smart_slot_syncer.py src/valuesets/schema --batch --in-place ``` -------------------------------- ### Perform In-Place Slot Sync with smart_slot_syncer.py (Bash) Source: https://github.com/linkml/valuesets/blob/main/docs/slot-generation.md Use the smart_slot_syncer.py script to synchronize slots with a schema file in-place. This utility intelligently adds new slots for enums and preserves existing manual customizations. ```bash uv run python src/valuesets/generators/smart_slot_syncer.py schema.yaml --in-place ``` -------------------------------- ### Makefile Configuration for LinkML Pydantic Generator Arguments Source: https://github.com/linkml/valuesets/blob/main/templates/README.md Makefile snippet showing how to set arguments for the LinkML Pydantic generator, specifically pointing to a directory containing custom templates. This is a common way to manage build configurations. ```makefile LINKML_GENERATORS_PYDANTIC_ARGS=--template-dir templates/pydantic ``` -------------------------------- ### Generate Changelog with smart_slot_syncer.py (Bash) Source: https://github.com/linkml/valuesets/blob/main/docs/slot-generation.md Generate a changelog detailing the synchronization changes made by smart_slot_syncer.py. This helps in tracking modifications to slots and their corresponding enums. ```bash uv run python src/valuesets/generators/smart_slot_syncer.py schema.yaml --in-place --changelog changes.json -v ``` -------------------------------- ### SQL DDL Generation for Database Schemas Source: https://github.com/linkml/valuesets/blob/main/docs/manuscript/manuscript.md Generates SQL Data Definition Language (DDL) CREATE TABLE statements with constraints. This is used for defining database schemas that align with LinkML models. ```sql CREATE TABLE my_enum_table ( id INT PRIMARY KEY AUTO_INCREMENT, enum_value VARCHAR(50) NOT NULL UNIQUE ); -- Consider adding a CHECK constraint for allowed values if your SQL dialect supports it easily -- For example, in PostgreSQL: -- ALTER TABLE my_enum_table ADD CONSTRAINT check_enum_value CHECK (enum_value IN ('value1', 'value2')); ``` -------------------------------- ### Generate Comprehensive Slots with auto_slot_injector.py (Bash) Source: https://github.com/linkml/valuesets/blob/main/docs/slot-generation.md Generate a comprehensive slots file by processing all schemas in a directory using auto_slot_injector.py. This utility creates new slot definitions based on enums found across multiple schema files. ```bash uv run python src/valuesets/generators/auto_slot_injector.py src/valuesets/schema --mode generate --output generated_slots.yaml ``` -------------------------------- ### Python Valueset Enumeration Usage and Metadata Access Source: https://github.com/linkml/valuesets/blob/main/docs/manuscript/manuscript.md Demonstrates common usage patterns for LinkML-generated Python enumerations, including direct access, reverse lookups by meaning, accessing descriptions and annotations, and type-safe validation using Pydantic. ```Python # Pattern 1: Direct enumeration usage from valuesets.enums.bio.cell_cycle import CellCyclePhase phase = CellCyclePhase.G1 assert phase.value == "G1" assert phase.get_meaning() == "GO:0051318" # Pattern 2: Reverse lookup by meaning found = CellCyclePhase.from_meaning("GO:0051318") assert found == CellCyclePhase.G1 # Pattern 3: Metadata access desc = phase.get_description() annotations = phase.get_annotations() # Pattern 4: Validation from valuesets.datamodel import ExperimentMetadata data = ExperimentMetadata(cell_phase=CellCyclePhase.G1) # Type-safe ``` -------------------------------- ### LinkML Schema Definition for Enumerations Source: https://github.com/linkml/valuesets/blob/main/docs/manuscript/manuscript.md Defines the structure for creating enumerations within a specific domain using LinkML syntax in YAML. It includes fields for schema name, ID, prefixes, enumeration name, description, permissible values, and optional meaning/annotations. ```yaml name: schema_name id: https://w3id.org/linkml/valuesets/domain/schema_name prefixes: ontology_prefix: http://purl.obolibrary.org/obo/ONTOLOGY_ enums: EnumerationName: description: Human-readable description permissible_values: VALUE_ONE: description: Value description meaning: ontology_prefix:0000001 annotations: additional_metadata: value ``` -------------------------------- ### Sync LinkML Slots in CI (Dry Run) Source: https://github.com/linkml/valuesets/blob/main/docs/slot-generation.md This command runs the slot syncer script in a CI pipeline to check if slots are in sync with the schema. It performs a dry run, meaning it will report discrepancies without making any changes. This is useful for ensuring consistency before deployment. ```bash uv run python src/valuesets/generators/smart_slot_syncer.py src/valuesets/schema --batch --dry-run ``` -------------------------------- ### Validate LinkML Schema Changes Source: https://github.com/linkml/valuesets/blob/main/AGENTS.md This command validates LinkML schema definitions to ensure they conform to LinkML specifications. It is crucial to run this command after any schema modifications to catch errors early. ```shell just validate ``` -------------------------------- ### OWL Generation for Ontology Integration Source: https://github.com/linkml/valuesets/blob/main/docs/manuscript/manuscript.md Generates OWL2 classes with semantic relationships for ontology integration. This allows LinkML schemas to be integrated with existing semantic web ontologies. ```owl Value 1 Value 2 ``` -------------------------------- ### Inject Slots into Schema with auto_slot_injector.py (Bash) Source: https://github.com/linkml/valuesets/blob/main/docs/slot-generation.md Inject generated slot definitions directly into a specified schema file using auto_slot_injector.py. The output will be saved to a new file, preserving the original schema. ```bash uv run python src/valuesets/generators/auto_slot_injector.py schema.yaml --mode inject --output modified.yaml ``` -------------------------------- ### Python Rich Enum Metadata Retrieval Source: https://github.com/linkml/valuesets/blob/main/README.md Illustrates how to access rich metadata associated with Python enum members, including names, values, descriptions, and custom annotations. It also shows how to retrieve all descriptions for an enum at once. ```python from valuesets.enums.bio.structural_biology import CryoEMGridType grid = CryoEMGridType.QUANTIFOIL metadata = grid.get_metadata() print(metadata) # { # 'name': 'QUANTIFOIL', # 'value': 'QUANTIFOIL', # 'description': 'Quantifoil holey carbon grid', # 'annotations': { # 'hole_sizes': '1.2/1.3, 2/1, 2/2 μm common', # 'manufacturer': 'Quantifoil' # } # } # Get all grid types with their descriptions at once all_grids = CryoEMGridType.get_all_descriptions() # {'C_FLAT': 'C-flat holey carbon grid', 'QUANTIFOIL': ...} ``` -------------------------------- ### Generate Python Models with Rich Enums (Bash) Source: https://github.com/linkml/valuesets/blob/main/RICH_ENUMS.md Command-line instructions to generate Python models using rich enum support, which is the default behavior. These commands leverage the 'just' build tool for project-specific generation tasks. ```bash # Generate Python models with rich enum support (DEFAULT) just gen-python # Generate entire project with rich Python enums (DEFAULT) just gen-project # Run all generation including docs just site # If you need the dataclass version for some reason just gen-python-dataclass ``` -------------------------------- ### Python Utility Functions for Enum Ontology Mappings Source: https://github.com/linkml/valuesets/blob/main/README.md Showcases utility functions for working with enum ontology mappings in Python. `get_all_meanings` retrieves all ontology mappings for an enum, and `list_metadata` provides descriptions for all enum values. `from_meaning` allows finding an enum member by its ontology term. ```python from valuesets.enums.spatial import AnatomicalPlane # Get all ontology mappings for an enum mappings = AnatomicalPlane.get_all_meanings() print(mappings) # {'SAGITTAL': 'BSPO:0000417', 'CORONAL': 'BSPO:0000019', ...} # List all metadata for every value in an enum all_metadata = AnatomicalPlane.list_metadata() for name, meta in all_metadata.items(): print(f"{name}: {meta.get('description', 'No description')}") # Find enum by ontology term (useful for data integration) plane = AnatomicalPlane.from_meaning("BSPO:0000417") # Returns SAGITTAL ``` -------------------------------- ### Python Enum Usage: Structural Biology and Spatial Qualifiers Source: https://github.com/linkml/valuesets/blob/main/README.md Illustrates the use of Python enums for structural biology techniques and spatial qualifiers. It shows how to retrieve enum values, descriptions, ontology mappings (CHMO, BSPO), and annotations. It also demonstrates looking up enums by their semantic meaning. ```python from valuesets.enums.bio.structural_biology import StructuralBiologyTechnique from valuesets.enums.spatial.spatial_qualifiers import AnatomicalSide # Rich enums with metadata and ontology mappings technique = StructuralBiologyTechnique.CRYO_EM print(technique.value) # "CRYO_EM" print(technique.get_description()) # "Cryo-electron microscopy" print(technique.get_meaning()) # "CHMO:0002413" (Chemical Methods Ontology) print(technique.get_annotations()) # {'resolution_range': '2-30 Å typical', ...} # Spatial relationships with BSPO mappings side = AnatomicalSide.LEFT print(side.get_meaning()) # "BSPO:0000000" (Biological Spatial Ontology) # Look up enums by their ontology terms found = AnatomicalSide.from_meaning("BSPO:0000000") # Returns LEFT ``` -------------------------------- ### Major LinkML Schema Refactoring with Refresh Mode Source: https://github.com/linkml/valuesets/blob/main/docs/slot-generation.md This command is used for significant schema reorganizations, such as major enum refactoring. It utilizes the `--mode refresh` option along with `--in-place` to automatically update the schema and then requires manual restoration of any custom modifications. ```bash uv run python src/valuesets/generators/smart_slot_syncer.py schema.yaml --in-place --mode refresh ``` -------------------------------- ### Python Enum Usage: Statistics and Data Science Source: https://github.com/linkml/valuesets/blob/main/README.md Demonstrates the application of Python enums in statistics and data science contexts. It covers standardized statistical tests with STATO mappings, p-value thresholds with annotations, and common data science components like dataset splits and model types. ```python from valuesets.enums.statistics import StatisticalTest, PValueThreshold from valuesets.enums.data_science import DatasetSplitType, ModelType # Standardized statistical tests with STATO ontology mappings test = StatisticalTest.STUDENTS_T_TEST print(test.get_meaning()) # "STATO:0000176" print(test.get_description()) # "Student's t-test for comparing means" # ML pipeline with standard splits split = DatasetSplitType.TRAIN model = ModelType.RANDOM_FOREST # P-value thresholds with clear semantics threshold = PValueThreshold.SIGNIFICANT print(threshold.get_annotations()) # {'value': 0.05, 'symbol': '*'} ``` -------------------------------- ### Python Enums with Ontology Mappings Source: https://github.com/linkml/valuesets/blob/main/README.md Demonstrates how to use Python enums that are enriched with semantic metadata, providing IDE support and type checking. Accessing the 'meaning' attribute retrieves the ontology mapping for an enum value. ```python # Type-safe enums with ontology mappings status = VitalStatusEnum.ALIVE print(status.meaning) # "NCIT:C37987" ``` -------------------------------- ### JSON Schema Generation for Validation Source: https://github.com/linkml/valuesets/blob/main/docs/manuscript/manuscript.md Generates Draft-07 compatible JSON Schemas for data validation. This is primarily used for validating data in REST APIs. ```json { "$schema": "http://json-schema.org/draft-07/schema#", "title": "MyEnumSchema", "description": "Schema for validating MyEnum values", "enum": ["value1", "value2"] } ``` -------------------------------- ### Remove Orphaned Slots with smart_slot_syncer.py (Bash) Source: https://github.com/linkml/valuesets/blob/main/docs/slot-generation.md Use the smart_slot_syncer.py script with the `--remove-orphans` flag to clean up slots that no longer correspond to any defined enums. It will warn if an orphaned slot has manual customizations. ```bash uv run python src/valuesets/generators/smart_slot_syncer.py schema.yaml --in-place --remove-orphans ``` -------------------------------- ### Python Semantic Interoperability with 'Stealth Semantics' Source: https://github.com/linkml/valuesets/blob/main/README.md Illustrates 'stealth semantics' in Python, enabling interoperability between different systems even when they use different naming conventions for the same concepts. It shows how to compare enum meanings using `get_meaning()` or a utility function `same_meaning_as`. ```python # Example: Different systems use different names for the same concept from valuesets.enums.medical import BloodTypeEnum from external_system import PatientBloodType # Third-party enum # Even though the enum values might be named differently: # BloodTypeEnum.A_POSITIVE vs PatientBloodType.A_POS # They map to the same SNOMED code: SNOMED:278149003 if blood_type.get_meaning() == patient_blood.get_meaning(): # Semantic interoperability - works across different naming conventions process_compatible_blood_type() # Or use the utility function if same_meaning_as(blood_type, patient_blood): process_compatible_blood_type() ``` -------------------------------- ### Construct Semantic Query with Python and SPARQL Source: https://github.com/linkml/valuesets/blob/main/docs/manuscript/manuscript.md This Python code demonstrates how to construct a semantic SPARQL query to retrieve gene-function relationships from a knowledge graph. It leverages enumeration meanings from valuesets.enums.bio.go_evidence to filter evidence codes. The query is built dynamically using an f-string and executed via the query_knowledge_graph function. It requires the sparql library and custom enum types. ```python from valuesets.enums.bio.go_evidence import GOEvidenceCode from sparql import query_knowledge_graph # Build semantic query using enumeration meanings evidence_codes = [ GOEvidenceCode.EXPERIMENTAL.get_meaning(), GOEvidenceCode.DIRECT_ASSAY.get_meaning(), GOEvidenceCode.MUTANT_PHENOTYPE.get_meaning() ] sparql_query = f""" SELECT ?gene ?function WHERE {{ ?gene hasFunction ?function . ?function hasEvidence ?evidence . FILTER(?evidence IN ({','.join(evidence_codes)})) """ results = query_knowledge_graph(sparql_query) ``` -------------------------------- ### Python Pydantic Enum Generation with Metadata Source: https://github.com/linkml/valuesets/blob/main/docs/manuscript/manuscript.md Generates Python Enum classes with methods for accessing semantic information like ontology mappings, descriptions, and annotations. This approach preserves rich metadata while maintaining simple usage patterns. It's primarily used for scientific computing and data analysis. ```python from enum import Enum class MyEnum(Enum): VALUE1 = "value1" VALUE2 = "value2" def get_meaning(self) -> str: # Placeholder for ontology mapping retrieval return f"Meaning of {self.value}" def get_description(self) -> str: # Placeholder for description retrieval return f"Description of {self.value}" def get_annotations(self) -> dict: # Placeholder for annotation retrieval return {"key": "value"} # Example Usage: print(MyEnum.VALUE1.get_meaning()) print(MyEnum.VALUE1.get_description()) print(MyEnum.VALUE1.get_annotations()) ``` -------------------------------- ### Validate Dataset Pipeline with Python Source: https://github.com/linkml/valuesets/blob/main/docs/manuscript/manuscript.md This Python function validates a pandas DataFrame based on several data quality indicators such as completeness, consistency, accuracy, and timeliness. It utilizes custom checks (e.g., check_completeness) and returns a dictionary of quality check descriptions and their scores. Dependencies include pandas and custom enum types from valuesets.enums.data_science. ```python from valuesets.enums.data_science import DataQualityIndicator import pandas as pd def validate_dataset(df: pd.DataFrame) -> dict: quality_checks = { DataQualityIndicator.COMPLETENESS: check_completeness(df), DataQualityIndicator.CONSISTENCY: check_consistency(df), DataQualityIndicator.ACCURACY: check_accuracy(df), DataQualityIndicator.TIMELINESS: check_timeliness(df) } return { check.get_description(): score for check, score in quality_checks.items() } ``` -------------------------------- ### Conditional Production Use (Python) Source: https://github.com/linkml/valuesets/blob/main/README.md This Python snippet demonstrates a check for the maturity level of an enumeration definition before it is used in production. It assumes the existence of an `enum_def` object with a `maturity_level` attribute and a `use_in_production` function. ```python if enum_def.maturity_level == MaturityLevel.STABLE: use_in_production() ``` -------------------------------- ### Protect Manual Customizations in LinkML Schema Source: https://github.com/linkml/valuesets/blob/main/docs/slot-generation.md This YAML snippet demonstrates how to mark specific slots in a LinkML schema to prevent them from being auto-updated by the syncer script. By defining a slot with custom properties like description and range, and potentially adding comments, you can indicate that it requires manual intervention. ```yaml my_custom_slot: description: "Manually crafted slot" range: MyEnum required: true comments: - "Custom validation logic - do not modify" ``` -------------------------------- ### Proposed Enhancement to LinkML EnumValue Dataclass Source: https://github.com/linkml/valuesets/blob/main/templates/README.md A Python dataclass definition for `EnumValue` within the LinkML generator, showing proposed additions of `meaning` and `annotations` fields. This change would enable richer metadata to be passed to templates. ```python @dataclass class EnumValue: label: str value: str description: Optional[str] = None meaning: Optional[str] = None # Add this annotations: Optional[Dict[str, Any]] = None # Add this ``` -------------------------------- ### TypeScript Enum Generation with Const Assertions Source: https://github.com/linkml/valuesets/blob/main/docs/manuscript/manuscript.md Generates type-safe TypeScript enums with const assertions. This is suitable for web applications and Node.js services where type safety and immutability are important. ```typescript enum MyEnum { VALUE1 = "value1", VALUE2 = "value2" } // Using const assertions for immutability and type safety const MY_ENUM_VALUE1 = MyEnum.VALUE1 as const; const MY_ENUM_VALUE2 = MyEnum.VALUE2 as const; // Example Usage: console.log(MY_ENUM_VALUE1); console.log(MY_ENUM_VALUE2); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.