linkml.generators package#

Submodules#

linkml.generators.csvgen module#

Generate CSVs

class linkml.generators.csvgen.CsvGenerator(schema: ~typing.Union[str, ~typing.TextIO, ~linkml_runtime.linkml_model.meta.SchemaDefinition, ~linkml.utils.generator.Generator], schemaview: ~typing.Optional[~linkml_runtime.utils.schemaview.SchemaView] = None, format: ~typing.Optional[str] = None, metadata: bool = <factory>, useuris: ~typing.Optional[bool] = None, log_level: int = 30, mergeimports: ~typing.Optional[bool] = <factory>, source_file_date: ~typing.Optional[str] = None, source_file_size: ~typing.Optional[int] = None, logger: ~typing.Optional[~logging.Logger] = None, verbose: ~typing.Optional[bool] = None, output: ~typing.Optional[str] = None, namespaces: ~typing.Optional[~linkml_runtime.utils.namespaces.Namespaces] = None, directory_output: bool = False, base_dir: ~typing.Optional[str] = None, metamodel_name_map: ~typing.Optional[~typing.Dict[str, str]] = None, importmap: ~typing.Optional[~typing.Union[str, ~typing.Mapping[str, str]]] = None, emit_prefixes: ~typing.Set[str] = <factory>, metamodel: ~typing.Optional[~linkml.utils.schemaloader.SchemaLoader] = None, stacktrace: bool = False, sep: ~typing.Optional[str] = None, closure: ~typing.Optional[~typing.Set[~linkml_runtime.linkml_model.meta.ClassDefinitionName]] = None, writer: ~typing.Optional[~csv.DictWriter] = None, **_kwargs)[source]#

Bases: Generator

Generates CSV summaries

Note: this generator is not widely used, and has largely been supplanted by schemasheets

closure: Optional[Set[ClassDefinitionName]] = None#

List of classes to include in output

generate_header()[source]#
generatorname: ClassVar[str] = 'csvgen.py'#

Name of the generator. Override with os.path.basename(__file__)

generatorversion: ClassVar[str] = '0.1.1'#

Version of the generator. Consider deprecating and instead use overall linkml version

requires_metamodel: ClassVar[bool] = False#

Generator queries an instance of the metamodel

sep: Optional[str] = None#

Separator for columns

uses_schemaloader: ClassVar[bool] = True#

Old-style generator that uses the SchemaLoader and visitor pattern

valid_formats: ClassVar[List[str]] = ['csv', 'tsv']#

Allowed formats - first format is default

visit_class(cls: ClassDefinition) bool[source]#

Visited once per schema class

@param cls: class being visited @return: Visit slots and end class. False means skip and go on

visit_schema(classes: Optional[List[ClassDefinitionName]] = None, **_) None[source]#

Visited once at the beginning of generation

@param kwargs: Arguments passed through from CLI – implementation dependent

writer: Optional[DictWriter] = None#

Python dictwriter

linkml.generators.dotgen module#

Generate dotfiles

class linkml.generators.dotgen.DotGenerator(*args, **kwargs)[source]#

Bases: Generator

Generates dotfiles

No longer in use: use mermaid generator instead

classdot: Optional[Digraph] = None#
classname: Optional[List[str]] = None#
classnames: Optional[List[str]] = None#
cls_obj: Optional[SlotDefinition] = None#
cls_subj: Optional[SlotDefinition] = None#
directory: Optional[str] = None#
directory_output: bool = True#

True means output is to a directory, False is to stdout

dirname: Optional[str] = None#
edge(*args, **kwargs) None[source]#
end_class(cls: ClassDefinition) None[source]#

Visited after visit_class_slots (if visit_class returned true)

@param cls: class being visited

end_schema(**_) None[source]#

Visited once at the end of generation

@param kwargs: Arguments passed through from CLI – implementation dependent

filedot: Optional[Digraph] = None#
filename: Optional[str] = None#
generatorname: ClassVar[str] = 'dotgen.py'#

Name of the generator. Override with os.path.basename(__file__)

generatorversion: ClassVar[str] = '0.1.1'#

Version of the generator. Consider deprecating and instead use overall linkml version

node(*args, **kwargs) None[source]#
uses_schemaloader: ClassVar[bool] = True#

Old-style generator that uses the SchemaLoader and visitor pattern

valid_formats: ClassVar[List[str]] = ['png', 'bmp', 'canon', 'cgimage', 'cmap', 'cmapx', 'cmapx_np', 'dot', 'dot_json', 'eps', 'exr', 'fig', 'gd', 'gd2', 'gif', 'gtk', 'gv', 'ico', 'imap', 'imap_np', 'ismap', 'jp2', 'jpe', 'jpeg', 'jpg', 'json', 'json0', 'pct', 'pdf', 'pic', 'pict', 'plain', 'plain-ext', 'png', 'pov', 'ps', 'ps2', 'psd', 'sgi', 'svg', 'svgz', 'tga', 'tif', 'tiff', 'tk', 'vml', 'vmlz', 'vrml', 'wbmp', 'webp', 'x11', 'xdot', 'xdot1.2', 'xdot1.4', 'xdot_json', 'xlib']#

Allowed formats - first format is default

visit_all_class_slots: ClassVar[bool] = True#

Visitor ClassVar: False means only visit own slots, True means visit all slots

visit_class(cls: ClassDefinition) bool[source]#

Visited once per schema class

@param cls: class being visited @return: Visit slots and end class. False means skip and go on

visit_class_slot(cls: ClassDefinition, aliased_slot_name: str, slot: SlotDefinition)[source]#

Visited for each slot in a class. If class level visit_all_slots is true, this is visited once for any class that is inherited (class itself, is_a, mixin, apply_to). Otherwise just the own slots.

@param cls: containing class @param aliased_slot_name: Aliased slot name. May not be unique across all class slots @param slot: slot being visited

visit_schema(classname: Optional[List[str]] = None, directory: Optional[str] = None, filename: Optional[str] = None, **_) None[source]#

Visited once at the beginning of generation

@param kwargs: Arguments passed through from CLI – implementation dependent

linkml.generators.excelgen module#

class linkml.generators.excelgen.ExcelGenerator(schema: Union[str, TextIO, linkml_runtime.linkml_model.meta.SchemaDefinition, ForwardRef('Generator')], schemaview: Optional[linkml_runtime.utils.schemaview.SchemaView] = None, format: Optional[str] = None, metadata: bool = <factory>, useuris: Optional[bool] = None, log_level: int = 30, mergeimports: Optional[bool] = <factory>, source_file_date: Optional[str] = None, source_file_size: Optional[int] = None, logger: Optional[logging.Logger] = None, verbose: Optional[bool] = None, output: Optional[str] = None, namespaces: Optional[linkml_runtime.utils.namespaces.Namespaces] = None, directory_output: bool = False, base_dir: str = None, metamodel_name_map: Dict[str, str] = None, importmap: Union[str, Mapping[str, str], NoneType] = None, emit_prefixes: Set[str] = <factory>, metamodel: linkml.utils.schemaloader.SchemaLoader = None, stacktrace: bool = False, **_kwargs)[source]#

Bases: Generator

add_columns_to_worksheet(workbook: Workbook, worksheet_name: str, sheet_headings: List[str]) None[source]#

Get a worksheet by name and add a column to it in an existing workbook.

Parameters:
  • workbook – The workbook to which the worksheet should be added.

  • worksheet_name – Name of the worksheet to add the column to.

  • column_data – List of data to populate the column with.

column_enum_validation(workbook: Workbook, worksheet_name: str, column_name: str, dropdown_values: List[str]) None[source]#

Get worksheet by name and add a dropdown to a specific column in it based on a list of values.

Parameters:
  • workbook – The workbook to which the worksheet should be added.

  • worksheet_name – Name of the worksheet to add the column dropdown to.

  • column_name – Name of the worksheet column to add the dropdown to.

  • dropdown_values – List of dropdown values to add to a column in a worksheet.

create_schema_worksheets(workbook: str) None[source]#

Creates worksheets in a given Excel workbook based on the classes in the schema.

Parameters:

workbook – The workbook to which the worksheet should be added.

create_workbook(workbook_name: str) Workbook[source]#

Creates an Excel workbook using the openpyxl library and returns it.

Parameters:

workbook_name – Name of the workbook to be created.

Returns:

An openpyxl Workbook object representing the newly created workbook.

create_worksheet(workbook: Workbook, worksheet_name: str) Worksheet[source]#

Creates an Excel worksheet with the given name in the given workbook.

Parameters:
  • workbook – The workbook to which the worksheet should be added.

  • worksheet_name – Name of the worksheet to be created.

emit_prefixes: Set[str]#

Prefixes to emit, for RDF-based generators

generatorname: ClassVar[str] = 'excelgen.py'#

Name of the generator. Override with os.path.basename(__file__)

generatorversion: ClassVar[str] = '0.1.1'#

Version of the generator. Consider deprecating and instead use overall linkml version

get_workbook_name(workbook: Workbook) str[source]#

Returns the name of the given workbook.

Parameters:

workbook – The workbook whose name should be returned.

Returns:

Name of the workbook.

mergeimports: Optional[bool]#

True means merge non-linkml sources into importing package. False means separate packages

metadata: bool#

True means include date, generator, etc. information in source header if appropriate

remove_worksheet_by_name(workbook: Workbook, worksheet_name: str) None[source]#

Remove worksheet from workbook by name.

requires_metamodel: ClassVar[bool] = False#

Generator queries an instance of the metamodel

schema: Union[str, TextIO, SchemaDefinition, Generator]#

metamodel compliant schema. Can be URI, file name, actual schema, another generator, an open file or a pre-parsed schema

serialize(**kwargs) str[source]#

Generate output in the required format

Parameters:

kwargs – Generator specific parameters

Returns:

Generated output

uses_schemaloader: ClassVar[bool] = False#

Old-style generator that uses the SchemaLoader and visitor pattern

valid_formats: ClassVar[List[str]] = ['xlsx']#

Allowed formats - first format is default

linkml.generators.flattener module#

linkml.generators.golrgen module#

Generate GOlr YAML schema definitions.

These can be converted to solr schema-xml, and used in amigo-bbop tools

See the golr-views directory in this repo for examples

class linkml.generators.golrgen.GOLRClass(id: str, schema_generating: bool, description: str, display_name: str, document_category: str, weight: int, fields: List[linkml.generators.golrgen.GOLRField] = <factory>, **_kwargs)[source]#

Bases: YAMLRoot

description: str#
display_name: str#
document_category: str#
fields: List[GOLRField]#
id: str#
schema_generating: bool#
weight: int#
class linkml.generators.golrgen.GOLRField(id: str, description: str, display_name: str, property: List = <factory>, cardinality: Optional[str] = None, **_kwargs)[source]#

Bases: YAMLRoot

cardinality: Optional[str] = None#
description: str#
display_name: str#
id: str#
property: List#
class linkml.generators.golrgen.GolrSchemaGenerator(schema: Union[str, TextIO, linkml_runtime.linkml_model.meta.SchemaDefinition, ForwardRef('Generator')], schemaview: Optional[linkml_runtime.utils.schemaview.SchemaView] = None, format: Optional[str] = None, metadata: bool = <factory>, useuris: Optional[bool] = None, log_level: int = 30, mergeimports: Optional[bool] = <factory>, source_file_date: Optional[str] = None, source_file_size: Optional[int] = None, logger: Optional[logging.Logger] = None, verbose: Optional[bool] = None, output: Optional[str] = None, namespaces: Optional[linkml_runtime.utils.namespaces.Namespaces] = None, directory_output: bool = False, base_dir: str = None, metamodel_name_map: Dict[str, str] = None, importmap: Union[str, Mapping[str, str], NoneType] = None, emit_prefixes: Set[str] = <factory>, metamodel: linkml.utils.schemaloader.SchemaLoader = None, stacktrace: bool = False, directory: str = None, class_obj: Optional[linkml.generators.golrgen.GOLRClass] = None, **_kwargs)[source]#

Bases: Generator

class_obj: Optional[GOLRClass] = None#
directory: str = None#
directory_output: bool = True#

True means output is to a directory, False is to stdout

end_class(cls: ClassDefinition) None[source]#

Visited after visit_class_slots (if visit_class returned true)

@param cls: class being visited

generate_header()[source]#
generatorname: ClassVar[str] = 'golrgen.py'#

Name of the generator. Override with os.path.basename(__file__)

generatorversion: ClassVar[str] = '0.1.1'#

Version of the generator. Consider deprecating and instead use overall linkml version

requires_metamodel: ClassVar[bool] = False#

Generator queries an instance of the metamodel

uses_schemaloader: ClassVar[bool] = True#

Old-style generator that uses the SchemaLoader and visitor pattern

valid_formats: ClassVar[List[str]] = ['golr']#

Allowed formats - first format is default

visit_all_class_slots: ClassVar[bool] = True#

Visitor ClassVar: False means only visit own slots, True means visit all slots

visit_class(cls: ClassDefinition) bool[source]#

Visited once per schema class

@param cls: class being visited @return: Visit slots and end class. False means skip and go on

visit_class_slot(cls: ClassDefinition, aliased_slot_name: str, slot: SlotDefinition) None[source]#

Visited for each slot in a class. If class level visit_all_slots is true, this is visited once for any class that is inherited (class itself, is_a, mixin, apply_to). Otherwise just the own slots.

@param cls: containing class @param aliased_slot_name: Aliased slot name. May not be unique across all class slots @param slot: slot being visited

visit_schema(directory: str, **_) None[source]#

Visited once at the beginning of generation

@param kwargs: Arguments passed through from CLI – implementation dependent

linkml.generators.graphqlgen module#

class linkml.generators.graphqlgen.GraphqlGenerator(schema: Union[str, TextIO, linkml_runtime.linkml_model.meta.SchemaDefinition, ForwardRef('Generator')], schemaview: Optional[linkml_runtime.utils.schemaview.SchemaView] = None, format: Optional[str] = None, metadata: bool = <factory>, useuris: Optional[bool] = None, log_level: int = 30, mergeimports: Optional[bool] = <factory>, source_file_date: Optional[str] = None, source_file_size: Optional[int] = None, logger: Optional[logging.Logger] = None, verbose: Optional[bool] = None, output: Optional[str] = None, namespaces: Optional[linkml_runtime.utils.namespaces.Namespaces] = None, directory_output: bool = False, base_dir: str = None, metamodel_name_map: Dict[str, str] = None, importmap: Union[str, Mapping[str, str], NoneType] = None, emit_prefixes: Set[str] = <factory>, metamodel: linkml.utils.schemaloader.SchemaLoader = None, stacktrace: bool = False, **_kwargs)[source]#

Bases: Generator

emit_prefixes: Set[str]#

Prefixes to emit, for RDF-based generators

end_class(cls: ClassDefinition) None[source]#

Visited after visit_class_slots (if visit_class returned true)

@param cls: class being visited

generate_header()[source]#
generatorname: ClassVar[str] = 'graphqlgen.py'#

Name of the generator. Override with os.path.basename(__file__)

generatorversion: ClassVar[str] = '0.1.1'#

Version of the generator. Consider deprecating and instead use overall linkml version

mergeimports: Optional[bool]#

True means merge non-linkml sources into importing package. False means separate packages

metadata: bool#

True means include date, generator, etc. information in source header if appropriate

requires_metamodel: ClassVar[bool] = False#

Generator queries an instance of the metamodel

schema: Union[str, TextIO, SchemaDefinition, Generator]#

metamodel compliant schema. Can be URI, file name, actual schema, another generator, an open file or a pre-parsed schema

uses_schemaloader: ClassVar[bool] = True#

Old-style generator that uses the SchemaLoader and visitor pattern

valid_formats: ClassVar[List[str]] = ['graphql']#

Allowed formats - first format is default

visit_all_class_slots: ClassVar[bool] = True#

Visitor ClassVar: False means only visit own slots, True means visit all slots

visit_class(cls: ClassDefinition) bool[source]#

Visited once per schema class

@param cls: class being visited @return: Visit slots and end class. False means skip and go on

visit_class_slot(cls: ClassDefinition, aliased_slot_name: str, slot: SlotDefinition) None[source]#

Visited for each slot in a class. If class level visit_all_slots is true, this is visited once for any class that is inherited (class itself, is_a, mixin, apply_to). Otherwise just the own slots.

@param cls: containing class @param aliased_slot_name: Aliased slot name. May not be unique across all class slots @param slot: slot being visited

linkml.generators.infer_model module#

linkml.generators.javagen module#

class linkml.generators.javagen.JavaGenerator(schema: ~typing.Union[str, ~typing.TextIO, ~linkml_runtime.linkml_model.meta.SchemaDefinition, Generator], schemaview: ~typing.Optional[~linkml_runtime.utils.schemaview.SchemaView] = None, format: ~typing.Optional[str] = None, metadata: bool = <factory>, useuris: ~typing.Optional[bool] = None, log_level: int = 30, mergeimports: ~typing.Optional[bool] = <factory>, source_file_date: ~typing.Optional[str] = None, source_file_size: ~typing.Optional[int] = None, logger: ~typing.Optional[~logging.Logger] = None, verbose: ~typing.Optional[bool] = None, output: ~typing.Optional[str] = None, namespaces: ~typing.Optional[~linkml_runtime.utils.namespaces.Namespaces] = None, directory_output: bool = False, base_dir: str = None, metamodel_name_map: ~typing.Dict[str, str] = None, importmap: ~typing.Optional[~typing.Union[str, ~typing.Mapping[str, str]]] = None, emit_prefixes: ~typing.Set[str] = <factory>, metamodel: ~linkml.utils.schemaloader.SchemaLoader = None, stacktrace: bool = False, template_file: ~typing.Optional[str] = None, package: str = 'example', generate_records: bool = False, gen_classvars: bool = <factory>, gen_slots: bool = <factory>, genmeta: bool = <factory>, emit_metadata: bool = <factory>, **_kwargs)[source]#

Bases: OOCodeGenerator

Generates java code from a LinkML schema.

Two styles are supported:

  • java classes, using lombok annotations

  • java records

default_value_for_type(typ: str) str[source]#
emit_metadata: bool#
gen_classvars: bool#
gen_slots: bool#
generate_records: bool = False#

If True then use java records (introduced in java 14) rather than classes

generatorname: ClassVar[str] = 'javagen.py'#

Name of the generator. Override with os.path.basename(__file__)

generatorversion: ClassVar[str] = '0.0.1'#

Version of the generator. Consider deprecating and instead use overall linkml version

genmeta: bool#
map_type(t: TypeDefinition, required: bool = False) str[source]#
serialize(directory: str, **kwargs) None[source]#

Generate output in the required format

Parameters:

kwargs – Generator specific parameters

Returns:

Generated output

template_file: Optional[str] = None#

Path to template

valid_formats: ClassVar[List[str]] = ['java']#

Allowed formats - first format is default

linkml.generators.jsonldcontextgen module#

Generate JSON-LD contexts

class linkml.generators.jsonldcontextgen.ContextGenerator(schema: Union[str, TextIO, linkml_runtime.linkml_model.meta.SchemaDefinition, ForwardRef('Generator')], schemaview: Optional[linkml_runtime.utils.schemaview.SchemaView] = None, format: Optional[str] = None, metadata: bool = <factory>, useuris: Optional[bool] = None, log_level: int = 30, mergeimports: Optional[bool] = <factory>, source_file_date: Optional[str] = None, source_file_size: Optional[int] = None, logger: Optional[logging.Logger] = None, verbose: Optional[bool] = None, output: Optional[str] = None, namespaces: Optional[linkml_runtime.utils.namespaces.Namespaces] = None, directory_output: bool = False, base_dir: str = None, metamodel_name_map: Dict[str, str] = None, importmap: Union[str, Mapping[str, str], NoneType] = None, emit_prefixes: Set[str] = <factory>, metamodel: linkml.utils.schemaloader.SchemaLoader = None, stacktrace: bool = False, default_ns: str = None, context_body: Dict = <factory>, slot_class_maps: Dict = <factory>, emit_metadata: bool = <factory>, model: Optional[bool] = <factory>, base: Optional[str] = None, prefixes: Optional[bool] = <factory>, flatprefixes: Optional[bool] = <factory>, **_kwargs)[source]#

Bases: Generator

base: Optional[str] = None#
context_body: Dict#
default_ns: str = None#
emit_metadata: bool#
emit_prefixes: Set[str]#

Prefixes to emit, for RDF-based generators

end_schema(base: Optional[str] = None, output: Optional[str] = None, prefixes: Optional[bool] = True, flatprefixes: Optional[bool] = False, model: Optional[bool] = True, **_) None[source]#

Visited once at the end of generation

@param kwargs: Arguments passed through from CLI – implementation dependent

flatprefixes: Optional[bool]#
generatorname: ClassVar[str] = 'jsonldcontextgen.py'#

Name of the generator. Override with os.path.basename(__file__)

generatorversion: ClassVar[str] = '0.1.1'#

Version of the generator. Consider deprecating and instead use overall linkml version

model: Optional[bool]#
output: Optional[str] = None#

Path to output file. Note all generators may not implement this uniformly, see https://github.com/linkml/linkml/issues/923

prefixes: Optional[bool]#
requires_metamodel: ClassVar[bool] = True#

Generator queries an instance of the metamodel

slot_class_maps: Dict#
uses_schemaloader: ClassVar[bool] = True#

Old-style generator that uses the SchemaLoader and visitor pattern

valid_formats: ClassVar[List[str]] = ['context', 'json']#

Allowed formats - first format is default

visit_all_class_slots: ClassVar[bool] = False#

Visitor ClassVar: False means only visit own slots, True means visit all slots

visit_class(cls: ClassDefinition) bool[source]#

Visited once per schema class

@param cls: class being visited @return: Visit slots and end class. False means skip and go on

visit_schema(base: Optional[str] = None, output: Optional[str] = None, **_)[source]#

Visited once at the beginning of generation

@param kwargs: Arguments passed through from CLI – implementation dependent

visit_slot(aliased_slot_name: str, slot: SlotDefinition) None[source]#

Visited once for every slot definition in the schema.

@param aliased_slot_name: Aliased name of the slot. May not be unique @param slot: visited slot

linkml.generators.jsonldgen module#

Generate JSONld

class linkml.generators.jsonldgen.JSONLDGenerator(schema: ~typing.Union[str, ~typing.TextIO, ~linkml_runtime.linkml_model.meta.SchemaDefinition, ~linkml.utils.generator.Generator], schemaview: ~typing.Optional[~linkml_runtime.utils.schemaview.SchemaView] = None, format: ~typing.Optional[str] = None, metadata: bool = <factory>, useuris: ~typing.Optional[bool] = None, log_level: int = 30, mergeimports: ~typing.Optional[bool] = <factory>, source_file_date: ~typing.Optional[str] = None, source_file_size: ~typing.Optional[int] = None, logger: ~typing.Optional[~logging.Logger] = None, verbose: ~typing.Optional[bool] = None, output: ~typing.Optional[str] = None, namespaces: ~typing.Optional[~linkml_runtime.utils.namespaces.Namespaces] = None, directory_output: bool = False, base_dir: ~typing.Optional[str] = None, metamodel_name_map: ~typing.Optional[~typing.Dict[str, str]] = None, importmap: ~typing.Optional[~typing.Union[str, ~typing.Mapping[str, str]]] = None, emit_prefixes: ~typing.Set[str] = <factory>, metamodel: ~typing.Optional[~linkml.utils.schemaloader.SchemaLoader] = None, stacktrace: bool = False, original_schema: ~typing.Optional[~linkml_runtime.linkml_model.meta.SchemaDefinition] = None, context: ~typing.Optional[str] = None, **_kwargs)[source]#

Bases: Generator

Generates JSON-LD from a Schema

Status: incompletely implemented

Note: this is distinct from ContextGenerator, which generates a JSON-LD context

adjust_slot(slot: SlotDefinition) None[source]#
context: str = None#

Path to a JSONLD context file

end_schema(context: Optional[str] = None, **_) None[source]#

Visited once at the end of generation

@param kwargs: Arguments passed through from CLI – implementation dependent

generatorname: ClassVar[str] = 'jsonldgen.py'#

Name of the generator. Override with os.path.basename(__file__)

generatorversion: ClassVar[str] = '0.0.2'#

Version of the generator. Consider deprecating and instead use overall linkml version

original_schema: SchemaDefinition = None#

See https://github.com/linkml/linkml/issues/871

requires_metamodel: ClassVar[bool] = True#

Generator queries an instance of the metamodel

uses_schemaloader: ClassVar[bool] = True#

Old-style generator that uses the SchemaLoader and visitor pattern

valid_formats: ClassVar[List[str]] = ['jsonld', 'json']#

Allowed formats - first format is default

visit_class(cls: ClassDefinition) bool[source]#

Visited once per schema class

@param cls: class being visited @return: Visit slots and end class. False means skip and go on

visit_slot(aliased_slot_name: str, slot: SlotDefinition) None[source]#

Visited once for every slot definition in the schema.

@param aliased_slot_name: Aliased name of the slot. May not be unique @param slot: visited slot

visit_subset(ss: SubsetDefinition) None[source]#

Visited once for every subset definition in the schema

#param subset: Subset definition

visit_type(typ: TypeDefinition) None[source]#

Visited once for every type definition in the schema

@param typ: Type definition

linkml.generators.jsonschemagen module#

class linkml.generators.jsonschemagen.JsonSchema(*args, **kwargs)[source]#

Bases: UserDict

OPTIONAL_IDENTIFIER_SUFFIX = '__identifier_optional'#
add_def(name: str, subschema: JsonSchema) None[source]#
add_keyword(keyword: str, value: Any)[source]#
add_lax_def(names: Union[str, List[str]], identifier_name: str) None[source]#
add_property(name: str, subschema: JsonSchema, required: bool = False) None[source]#
classmethod array_of(subschema: JsonSchema) JsonSchema[source]#
property is_array#
property is_object#
classmethod ref_for(class_name: Union[str, List[str]], identifier_optional: bool = False)[source]#
to_json(**kwargs) str[source]#
class linkml.generators.jsonschemagen.JsonSchemaGenerator(schema: ~typing.Union[str, ~typing.TextIO, ~linkml_runtime.linkml_model.meta.SchemaDefinition, ~linkml.utils.generator.Generator], schemaview: ~typing.Optional[~linkml_runtime.utils.schemaview.SchemaView] = None, format: ~typing.Optional[str] = None, metadata: bool = <factory>, useuris: ~typing.Optional[bool] = None, log_level: int = 30, mergeimports: ~typing.Optional[bool] = <factory>, source_file_date: ~typing.Optional[str] = None, source_file_size: ~typing.Optional[int] = None, logger: ~typing.Optional[~logging.Logger] = None, verbose: ~typing.Optional[bool] = None, output: ~typing.Optional[str] = None, namespaces: ~typing.Optional[~linkml_runtime.utils.namespaces.Namespaces] = None, directory_output: bool = False, base_dir: ~typing.Optional[str] = None, metamodel_name_map: ~typing.Optional[~typing.Dict[str, str]] = None, importmap: ~typing.Optional[~typing.Union[str, ~typing.Mapping[str, str]]] = None, emit_prefixes: ~typing.Set[str] = <factory>, metamodel: ~typing.Optional[~linkml.utils.schemaloader.SchemaLoader] = None, stacktrace: bool = False, topClass: ~typing.Optional[str] = None, not_closed: ~typing.Optional[bool] = <factory>, indent: int = 4, inline: bool = False, top_class: ~typing.Optional[~typing.Union[~linkml_runtime.linkml_model.meta.ClassDefinitionName, str]] = None, include_range_class_descendants: bool = <factory>, top_level_schema: ~typing.Optional[~linkml.generators.jsonschemagen.JsonSchema] = None, **_kwargs)[source]#

Bases: Generator

Generates JSONSchema documents from a LinkML SchemaDefinition

  • Each linkml class generates a schema

  • inheritance hierarchies are rolled-down from ancestors

  • Composition not yet implemented

  • Enumerations treated as strings

  • Foreign key references are treated as semantics-free strings

file_extension: ClassVar[str] = 'schema.json'#
generate() dict[source]#
generatorname: ClassVar[str] = 'jsonschemagen.py'#

Name of the generator. Override with os.path.basename(__file__)

generatorversion: ClassVar[str] = '0.0.3'#

Version of the generator. Consider deprecating and instead use overall linkml version

get_subschema_for_anonymous_class(cls: AnonymousClassExpression, properties_required: bool = False) Union[None, JsonSchema][source]#
get_subschema_for_slot(slot: SlotDefinition, omit_type: bool = False) JsonSchema[source]#
get_type_info_for_slot_subschema(slot: AnonymousSlotExpression) Tuple[str, str, Union[str, List[str]]][source]#
get_value_constraints_for_slot(slot: Optional[AnonymousSlotExpression]) JsonSchema[source]#
handle_class(cls: ClassDefinition) None[source]#
handle_class_slot(subschema: JsonSchema, cls: ClassDefinition, slot: SlotDefinition) None[source]#
handle_enum(enum: EnumDefinition) None[source]#
include_range_class_descendants: bool#

If set, use an open world assumption and allow the range of a slot to be any descendant of the declared range. Note that if the range of a slot has a type designator, descendants will always be included.

indent: int = 4#
inline: bool = False#
not_closed: Optional[bool]#

If not closed, then an open-ended set of attributes can be instantiated for any object

serialize(**kwargs) str[source]#

Generate output in the required format

Parameters:

kwargs – Generator specific parameters

Returns:

Generated output

start_schema(inline: bool = False) JsonSchema[source]#
topClass: Optional[str] = None#
top_class: Optional[Union[ClassDefinitionName, str]] = None#

Class instantiated by the root node of the document tree

top_level_schema: JsonSchema = None#
uses_schemaloader: ClassVar[bool] = False#

Old-style generator that uses the SchemaLoader and visitor pattern

valid_formats: ClassVar[List[str]] = ['json']#

Allowed formats - first format is default

linkml.generators.lpgen module#

linkml.generators.markdowngen module#

class linkml.generators.markdowngen.MarkdownGenerator(schema: ~typing.Union[str, ~typing.TextIO, ~linkml_runtime.linkml_model.meta.SchemaDefinition, ~linkml.utils.generator.Generator], schemaview: ~typing.Optional[~linkml_runtime.utils.schemaview.SchemaView] = None, format: ~typing.Optional[str] = None, metadata: bool = <factory>, useuris: ~typing.Optional[bool] = None, log_level: int = 30, mergeimports: ~typing.Optional[bool] = <factory>, source_file_date: ~typing.Optional[str] = None, source_file_size: ~typing.Optional[int] = None, logger: ~typing.Optional[~logging.Logger] = None, verbose: ~typing.Optional[bool] = None, output: ~typing.Optional[str] = None, namespaces: ~typing.Optional[~linkml_runtime.utils.namespaces.Namespaces] = None, directory_output: bool = False, base_dir: ~typing.Optional[str] = None, metamodel_name_map: ~typing.Optional[~typing.Dict[str, str]] = None, importmap: ~typing.Optional[~typing.Union[str, ~typing.Mapping[str, str]]] = None, emit_prefixes: ~typing.Set[str] = <factory>, metamodel: ~typing.Optional[~linkml.utils.schemaloader.SchemaLoader] = None, stacktrace: bool = False, directory: ~typing.Optional[str] = None, image_directory: ~typing.Optional[str] = None, classes: ~typing.Optional[~typing.Set[~linkml_runtime.linkml_model.meta.ClassDefinitionName]] = None, image_dir: bool = False, index_file: str = <factory>, noimages: bool = False, noyuml: bool = False, no_types_dir: bool = False, warn_on_exist: bool = False, gen_classes: ~typing.Optional[~typing.Set[~linkml_runtime.linkml_model.meta.ClassDefinitionName]] = None, gen_classes_neighborhood: ~typing.Optional[~linkml.utils.typereferences.References] = None, **_kwargs)[source]#

Bases: Generator

Generates markdown documentation for a LinkML schema

Each schema element (class, slot, type, enum) is translated into its own markdown file; additionally, an index.md is generated that links everything together.

The markdown is suitable for deployment as a MkDocs or Sphinx site

static anchor(id_: str) None[source]#
static anchorend() None[source]#
bbin(obj: Element) str[source]#

Boldify built in types

@param obj: object name or id @return:

static bullet(txt: str, level=0) None[source]#
class_hier(cls: ClassDefinition, level=0) None[source]#
classes: Set[ClassDefinitionName] = None#
desc_for(obj: Element, doing_descs: bool) str[source]#

Return a description for object if it is unique (different than its parent)

@param obj: object to be described @param doing_descs: If false, always return an empty string @return: text or empty string

dir_path(obj: Union[ClassDefinition, SlotDefinition, TypeDefinition, EnumDefinition]) str[source]#
directory: Optional[str] = None#
directory_output: bool = True#

True means output is to a directory, False is to stdout

element_header(obj: Element, name: str, curie: str, uri: str) None[source]#
element_properties(obj: Element) None[source]#
enum_hier(enum: EnumDefinition, level=0) None[source]#
exist_warning(*fpath: str) str[source]#

Create a file name out of fpath and check whether it already exists

frontmatter(thingtype: str, layout='default') None[source]#
gen_classes: Optional[Set[ClassDefinitionName]] = None#
gen_classes_neighborhood: Optional[References] = None#
generatorname: ClassVar[str] = 'markdowngen.py'#

Name of the generator. Override with os.path.basename(__file__)

generatorversion: ClassVar[str] = '0.2.1'#

Version of the generator. Consider deprecating and instead use overall linkml version

header(level: int, txt: str) None[source]#
static id_to_url(id_: str) str[source]#
image_dir: bool = False#
image_directory: Optional[str] = None#
index_file: str#
is_secondary_ref(en: str) bool[source]#

Determine whether ‘en’ is the name of something in the neighborhood of the requested classes

@param en: element name @return: True if ‘en’ is the name of a slot, class or type in the immediate neighborhood of of what we are building

mappings(obj: Union[SlotDefinition, ClassDefinition]) None[source]#
no_types_dir: bool = False#
noimages: bool = False#
noyuml: bool = False#
static para(txt: str) None[source]#
pred_hier(slot: SlotDefinition, level=0) None[source]#
static predicate_cardinality(slot: SlotDefinition) str[source]#

Emit cardinality for a suffix on a predicate

static range_cardinality(slot: SlotDefinition) str[source]#

Emits cardinality decorator at end of type

slot_field(cls: ClassDefinition, slot: SlotDefinition) None[source]#
to_uri(uri_or_curie: str) str[source]#

Return the URI for the slot if known

uses_schemaloader: ClassVar[bool] = True#

Old-style generator that uses the SchemaLoader and visitor pattern

valid_formats: ClassVar[List[str]] = ['md']#

Allowed formats - first format is default

visit_all_class_slots: ClassVar[bool] = False#

Visitor ClassVar: False means only visit own slots, True means visit all slots

visit_class(cls: ClassDefinition) bool[source]#

Visited once per schema class

@param cls: class being visited @return: Visit slots and end class. False means skip and go on

visit_enum(enum: EnumDefinition) None[source]#

Visited once for every enum definition in the schema

@param enum: Enum definition

visit_schema(directory: Optional[str] = None, classes: Optional[Set[ClassDefinitionName]] = None, image_dir: bool = False, index_file: str = 'index.md', noimages: bool = False, **_) None[source]#

Visited once at the beginning of generation

@param kwargs: Arguments passed through from CLI – implementation dependent

visit_slot(aliased_slot_name: str, slot: SlotDefinition) None[source]#

Visited once for every slot definition in the schema.

@param aliased_slot_name: Aliased name of the slot. May not be unique @param slot: visited slot

visit_subset(subset: SubsetDefinition) None[source]#

Visited once for every subset definition in the schema

#param subset: Subset definition

visit_type(typ: TypeDefinition) None[source]#

Visited once for every type definition in the schema

@param typ: Type definition

warn_on_exist: bool = False#

linkml.generators.namespacegen module#

class linkml.generators.namespacegen.NamespaceGenerator(schema: Union[str, TextIO, linkml_runtime.linkml_model.meta.SchemaDefinition, ForwardRef('Generator')], schemaview: Optional[linkml_runtime.utils.schemaview.SchemaView] = None, format: Optional[str] = None, metadata: bool = <factory>, useuris: Optional[bool] = None, log_level: int = 30, mergeimports: Optional[bool] = <factory>, source_file_date: Optional[str] = None, source_file_size: Optional[int] = None, logger: Optional[logging.Logger] = None, verbose: Optional[bool] = None, output: Optional[str] = None, namespaces: Optional[linkml_runtime.utils.namespaces.Namespaces] = None, directory_output: bool = False, base_dir: str = None, metamodel_name_map: Dict[str, str] = None, importmap: Union[str, Mapping[str, str], NoneType] = None, emit_prefixes: Set[str] = <factory>, metamodel: linkml.utils.schemaloader.SchemaLoader = None, stacktrace: bool = False, gen_classvars: bool = <factory>, gen_slots: bool = <factory>, genmeta: bool = <factory>, emit_metadata: bool = <factory>, **_kwargs)[source]#

Bases: PythonGenerator

emit_metadata: bool#
gen_classvars: bool#
gen_namespaces() str[source]#
gen_schema() str[source]#
gen_slots: bool#
generatorname: ClassVar[str] = 'namespacegen.py'#

Name of the generator. Override with os.path.basename(__file__)

generatorversion: ClassVar[str] = '0.0.1'#

Version of the generator. Consider deprecating and instead use overall linkml version

genmeta: bool#
valid_formats: ClassVar[List[str]] = ['py']#

Allowed formats - first format is default

visit_all_class_slots: ClassVar[bool] = False#

Visitor ClassVar: False means only visit own slots, True means visit all slots

linkml.generators.oocodegen module#

class linkml.generators.oocodegen.OOClass(name: str, description: ~typing.Optional[str] = None, is_a: ~typing.Optional[str] = None, mixin: ~typing.Optional[bool] = None, abstract: ~typing.Optional[bool] = None, mixins: ~typing.List[str] = <factory>, fields: ~typing.List[~linkml.generators.oocodegen.OOField] = <factory>, all_fields: ~typing.List[~linkml.generators.oocodegen.OOField] = <factory>, annotations: ~typing.List[str] = <factory>, package: ~typing.Optional[str] = None, source_class: ~typing.Optional[~linkml_runtime.linkml_model.meta.ClassDefinition] = None)[source]#

Bases: object

An object-oriented class

abstract: Optional[bool] = None#
all_fields: List[OOField]#
annotations: List[str]#
description: Optional[str] = None#
fields: List[OOField]#
is_a: Optional[str] = None#
mixin: Optional[bool] = None#
mixins: List[str]#
name: str#
package: str = None#
source_class: ClassDefinition = None#
class linkml.generators.oocodegen.OOCodeGenerator(schema: Union[str, TextIO, linkml_runtime.linkml_model.meta.SchemaDefinition, ForwardRef('Generator')], schemaview: Optional[linkml_runtime.utils.schemaview.SchemaView] = None, format: Optional[str] = None, metadata: bool = <factory>, useuris: Optional[bool] = None, log_level: int = 30, mergeimports: Optional[bool] = <factory>, source_file_date: Optional[str] = None, source_file_size: Optional[int] = None, logger: Optional[logging.Logger] = None, verbose: Optional[bool] = None, output: Optional[str] = None, namespaces: Optional[linkml_runtime.utils.namespaces.Namespaces] = None, directory_output: bool = False, base_dir: str = None, metamodel_name_map: Dict[str, str] = None, importmap: Union[str, Mapping[str, str], NoneType] = None, emit_prefixes: Set[str] = <factory>, metamodel: linkml.utils.schemaloader.SchemaLoader = None, stacktrace: bool = False, template_file: str = None, package: str = 'example', **_kwargs)[source]#

Bases: Generator

create_documents() List[OODocument][source]#

Currently hardcoded for java-style :return:

abstract default_value_for_type(typ: str) str[source]#
generate_enum_label(value: str) str[source]#
generate_enums(all_enums: Dict[EnumDefinitionName, EnumDefinition]) Dict[source]#
get_class_name(cn)[source]#
get_slot_name(sn)[source]#
java_style = True#
make_multivalued(range: str) str[source]#
map_type(t: TypeDefinition, required: bool = False) str[source]#
package: str = 'example'#
replace_invalid_identifier_character(char: str) str[source]#
requires_metamodel: ClassVar[bool] = False#

Generator queries an instance of the metamodel

abstract serialize(directory: str) None[source]#

Generate output in the required format

Parameters:

kwargs – Generator specific parameters

Returns:

Generated output

template_file: str = None#

Path to template

uses_schemaloader: ClassVar[bool] = False#

Old-style generator that uses the SchemaLoader and visitor pattern

visit_all_class_slots: ClassVar[bool] = False#

Visitor ClassVar: False means only visit own slots, True means visit all slots

class linkml.generators.oocodegen.OODocument(name: str, package: ~typing.Optional[str] = None, source_schema: ~typing.Optional[~linkml_runtime.linkml_model.meta.SchemaDefinition] = None, classes: ~typing.List[~linkml.generators.oocodegen.OOClass] = <factory>, imports: ~typing.List[str] = <factory>)[source]#

Bases: object

A collection of one or more OO classes

classes: List[OOClass]#
imports: List[str]#
name: str#
package: str = None#
source_schema: SchemaDefinition = None#
class linkml.generators.oocodegen.OOField(name: str, range: ~typing.Optional[str] = None, default_value: ~typing.Optional[str] = None, annotations: ~typing.List[str] = <factory>, source_slot: ~linkml_runtime.linkml_model.meta.SlotDefinition = <factory>)[source]#

Bases: object

A field belonging to an OO class that corresponds to a LinkML class slot

annotations: List[str]#
default_value: str = None#
name: str#
range: str = None#
source_slot: SlotDefinition#

linkml.generators.owlgen module#

Generate OWL ontology representation of a LinkML schema.

class linkml.generators.owlgen.MetadataProfile(value)[source]#

Bases: Enum

An enumeration of the different kinds of profiles used for metadata of generated OWL elements

linkml = 'linkml'#

Default, uses the slot URIs from the LinkML metamodel

static list()[source]#
ols = 'ols'#
rdfs = 'rdfs'#

RDFS conventions, using core RDFS properties preferentially

class linkml.generators.owlgen.OWLProfile(value)[source]#

Bases: Enum

An enumeration of OWL Profiles.

dl = 'dl'#

Here this means strict OWL DL, with no punning.

full = 'full'#

May include punning (metaclasses).

static list()[source]#
class linkml.generators.owlgen.OwlSchemaGenerator(schema: ~typing.Union[str, ~typing.TextIO, ~linkml_runtime.linkml_model.meta.SchemaDefinition, ~linkml.utils.generator.Generator], schemaview: ~typing.Optional[~linkml_runtime.utils.schemaview.SchemaView] = None, format: ~typing.Optional[str] = None, metadata: bool = <factory>, useuris: ~typing.Optional[bool] = None, log_level: int = 30, mergeimports: ~typing.Optional[bool] = <factory>, source_file_date: ~typing.Optional[str] = None, source_file_size: ~typing.Optional[int] = None, logger: ~typing.Optional[~logging.Logger] = None, verbose: ~typing.Optional[bool] = None, output: ~typing.Optional[str] = None, namespaces: ~typing.Optional[~linkml_runtime.utils.namespaces.Namespaces] = None, directory_output: bool = False, base_dir: ~typing.Optional[str] = None, metamodel_name_map: ~typing.Optional[~typing.Dict[str, str]] = None, importmap: ~typing.Optional[~typing.Union[str, ~typing.Mapping[str, str]]] = None, emit_prefixes: ~typing.Set[str] = <factory>, metamodel: ~typing.Optional[~linkml.utils.schemaloader.SchemaLoader] = None, stacktrace: bool = False, ontology_uri_suffix: ~typing.Optional[str] = None, metadata_profile: ~typing.Optional[~linkml.generators.owlgen.MetadataProfile] = None, metadata_profiles: ~typing.List[~linkml.generators.owlgen.MetadataProfile] = <factory>, metaclasses: bool = <factory>, add_root_classes: bool = <factory>, add_ols_annotations: bool = <factory>, graph: ~typing.Optional[~rdflib.graph.Graph] = None, top_value_uri: ~typing.Optional[~rdflib.term.URIRef] = None, type_objects: bool = <factory>, assert_equivalent_classes: bool = <factory>, use_native_uris: bool = <factory>, mixins_as_expressions: ~typing.Optional[bool] = None, slot_is_literal_map: ~typing.Mapping[str, ~typing.Set[bool]] = <factory>, node_owltypes: ~typing.Mapping[~typing.Union[~rdflib.term.BNode, ~rdflib.term.URIRef], ~typing.Set[~rdflib.term.URIRef]] = <factory>, simplify: bool = <factory>, use_swrl: bool = <factory>, target_profile: ~linkml.generators.owlgen.OWLProfile = <factory>, metamodel_schemaview: ~linkml_runtime.utils.schemaview.SchemaView = <factory>, **_kwargs)[source]#

Bases: Generator

Generates a schema-oriented OWL representation of a LinkML model

OWL Generator Docs

.

  • LinkML ClassDefinitions are translated to OWL Classes

  • LinkML SlotDefinitions are translated to OWL Properties

  • LinkML Enumerations are translated to OWL Classes

  • LinkML TypeDefinitions are translated to OWL Datatypes

The translation aims to be as faithful as possible. But note that OWL is open-world, whereas LinkML is closed-world

add_class(cls: ClassDefinition) None[source]#

Each ClassDefinition is represented as an OWL class.

  • the OWL Class will instantiate ClassDefinition, if schema.metaclasses is true

  • the OWL Class will be annotated using the same properties as the source ClassDefinition

  • induced slots and their ranges added as OWL restrictions; note this will be under the Open World Assumption

This method works by generating an OWL ontology via populating triples in a graph. To understand how the RDF-level operations here related to the OWL representation, consult https://www.w3.org/TR/owl2-mapping-to-rdf/

Parameters:

cls

Returns:

add_constraints(element: Union[SlotDefinition, AnonymousSlotExpression, TypeDefinition, AnonymousTypeExpression], is_literal: Optional[bool] = None) Tuple[List[BNode], Set[URIRef]][source]#
add_enum(e: EnumDefinition) None[source]#
add_metadata(e: Definition, uri: URIRef) None[source]#

Add annotation properties.

Set the profile attribute to the appropriate OWL profile.

Parameters:
  • e – schema element

  • uri – URI representation of schema element

Returns:

add_ols_annotations: bool#
add_root_classes: bool#
add_slot(slot: SlotDefinition, attribute=False) None[source]#
add_type(typ: TypeDefinition) None[source]#
as_graph() Graph[source]#

Generate an rdflib Graph from the LinkML schema.

Returns:

assert_equivalent_classes: bool#

If True, assert equivalence between definition_uris and class_uris

file_extension: ClassVar[str] = 'owl'#
generatorname: ClassVar[str] = 'owlgen.py'#

Name of the generator. Override with os.path.basename(__file__)

generatorversion: ClassVar[str] = '0.1.1'#

Version of the generator. Consider deprecating and instead use overall linkml version

graph: Optional[Graph] = None#

Mutable graph that is being built up during OWL generation.

has_profile(profile: MetadataProfile, default=False) bool[source]#

Determine if a metadata profile is active.

Parameters:
  • profile – profile to check

  • default – True if the configured profiles include the specified profile

Returns:

metaclasses: bool#

if True, include OWL representations of ClassDefinition, SlotDefinition, etc. Introduces punning

metadata_profile: MetadataProfile = None#

Deprecated - use metadata_profiles.

metadata_profiles: List[MetadataProfile]#

By default, use the linkml metadata profile, this allows for overrides.

metamodel_schemaview: SchemaView#
mixins_as_expressions: bool = None#

EXPERIMENTAL: If True, use OWL existential restrictions to represent mixins

node_owltypes: Mapping[Union[BNode, URIRef], Set[URIRef]]#

rdfs:Datatype, owl:Thing

ontology_uri_suffix: str = None#

Suffix to add to the schema name to create the ontology URI, e.g. .owl.ttl

serialize(**kwargs) str[source]#

Serialize the OWL triple graph to a standard RDF serialization format.

Parameters:

kwargs

Returns:

simplify: bool#

Reduce complex expressions to simpler forms

slot_is_literal_map: Mapping[str, Set[bool]]#

DEPRECATED: use node_owltypes

slot_node_owltypes(slot: Union[SlotDefinition, AnonymousSlotExpression]) Set[URIRef][source]#
slot_owl_type(slot: SlotDefinition) URIRef[source]#
target_profile: OWLProfile#

Target OWL profile. Currently the only distinction is between DL and Full

top_value_uri: Optional[URIRef] = None#

If metaclasses=True, then this property is used to connect object shadows to literals

transform_class_expression(cls: Union[ClassDefinition, AnonymousClassExpression], quantifier_predicate: URIRef = rdflib.term.URIRef('http://www.w3.org/2002/07/owl#allValuesFrom')) BNode[source]#

Transform a LinkML class expression into an OWL expression.

If the class includes boolean expressions, then these are recursively transformed (each such inner expression is an anonymous expression)

Parameters:

cls – LinkML class expression (anonymous if called recursively)

Returns:

blank node representing the OWL expression

transform_class_slot_expression(cls: Optional[Union[ClassDefinition, AnonymousClassExpression]], slot: Union[SlotDefinition, AnonymousSlotExpression], main_slot: Optional[SlotDefinition] = None, owl_types: Optional[Set[URIRef]] = None) Union[BNode, URIRef][source]#

Take a ClassExpression and SlotExpression combination and transform to a node.

Parameters:
  • cls

  • slot

  • main_slot

Returns:

type_objects: bool#

if True, represents types as classes (and thus all slots are object properties); typed object classes effectively shadow the main xsd literal types. The purpose of this is to allow a uniform ObjectProperty representation for all slots, without having to commit to being either Data or Object property (OWL-DL does not allow a property to be both.

use_native_uris: bool#

If True, use the definition_uris, otherwise use class_uris.

use_swrl: bool#

Use of SWRL is experimental

uses_schemaloader: ClassVar[bool] = False#

Old-style generator that uses the SchemaLoader and visitor pattern

valid_formats: ClassVar[List[str]] = ['owl', 'ttl', 'json-ld', 'xml', 'n3', 'turtle', 'ttl', 'ntriples', 'nt', 'nt11', 'nquads', 'trix', 'trig', 'hext']#

Allowed formats - first format is default

linkml.generators.prefixmapgen module#

Generate JSON-LD contexts

class linkml.generators.prefixmapgen.PrefixGenerator(schema: Union[str, TextIO, linkml_runtime.linkml_model.meta.SchemaDefinition, ForwardRef('Generator')], schemaview: Optional[linkml_runtime.utils.schemaview.SchemaView] = None, format: Optional[str] = None, metadata: bool = <factory>, useuris: Optional[bool] = None, log_level: int = 30, mergeimports: Optional[bool] = <factory>, source_file_date: Optional[str] = None, source_file_size: Optional[int] = None, logger: Optional[logging.Logger] = None, verbose: Optional[bool] = None, output: Optional[str] = None, namespaces: Optional[linkml_runtime.utils.namespaces.Namespaces] = None, directory_output: bool = False, base_dir: str = None, metamodel_name_map: Dict[str, str] = None, importmap: Union[str, Mapping[str, str], NoneType] = None, emit_prefixes: Set[str] = <factory>, metamodel: linkml.utils.schemaloader.SchemaLoader = None, stacktrace: bool = False, default_ns: str = None, context_body: Dict = <factory>, slot_class_maps: Dict = <factory>, base: str = None, **_kwargs)[source]#

Bases: Generator

base: str = None#
context_body: Dict#
default_ns: str = None#
emit_prefixes: Set[str]#

Prefixes to emit, for RDF-based generators

end_schema(base: Optional[str] = None, output: Optional[str] = None, **_) None[source]#

Visited once at the end of generation

@param kwargs: Arguments passed through from CLI – implementation dependent

generatorname: ClassVar[str] = 'prefixmapgen.py'#

Name of the generator. Override with os.path.basename(__file__)

generatorversion: ClassVar[str] = '0.1.1'#

Version of the generator. Consider deprecating and instead use overall linkml version

slot_class_maps: Dict#
uses_schemaloader: ClassVar[bool] = True#

Old-style generator that uses the SchemaLoader and visitor pattern

valid_formats: ClassVar[List[str]] = ['json', 'tsv']#

Allowed formats - first format is default

visit_all_class_slots: ClassVar[bool] = False#

Visitor ClassVar: False means only visit own slots, True means visit all slots

visit_class(cls: ClassDefinition) bool[source]#

Visited once per schema class

@param cls: class being visited @return: Visit slots and end class. False means skip and go on

visit_schema(base: Optional[str] = None, output: Optional[str] = None, **_)[source]#

Visited once at the beginning of generation

@param kwargs: Arguments passed through from CLI – implementation dependent

visit_slot(aliased_slot_name: str, slot: SlotDefinition) None[source]#

Visited once for every slot definition in the schema.

@param aliased_slot_name: Aliased name of the slot. May not be unique @param slot: visited slot

linkml.generators.projectgen module#

class linkml.generators.projectgen.ProjectConfiguration(directory: str = 'tmp', generator_args: ~typing.Dict[str, ~typing.Dict[str, ~typing.Any]] = <factory>, includes: ~typing.Optional[~typing.List[str]] = None, excludes: ~typing.Optional[~typing.List[str]] = None, mergeimports: ~typing.Optional[bool] = None)[source]#

Bases: object

Global project configuration, and per-generator configurations

directory: str = 'tmp'#
excludes: List[str] = None#
generator_args: Dict[str, Dict[str, Any]]#
includes: List[str] = None#
mergeimports: bool = None#
class linkml.generators.projectgen.ProjectGenerator[source]#

Bases: object

Generates complete project folders

Note this doesn’t conform to overall generator framework, as it is a meta-generator

generate(schema_path: str, config: ~linkml.generators.projectgen.ProjectConfiguration = ProjectConfiguration(directory='tmp', generator_args=defaultdict(<class 'dict'>, {}), includes=None, excludes=None, mergeimports=None))[source]#
linkml.generators.projectgen.get_local_imports(schema_path: str, dir: str)[source]#

linkml.generators.protogen module#

class linkml.generators.protogen.ProtoGenerator(schema: ~typing.Union[str, ~typing.TextIO, ~linkml_runtime.linkml_model.meta.SchemaDefinition, ~linkml.utils.generator.Generator], schemaview: ~typing.Optional[~linkml_runtime.utils.schemaview.SchemaView] = None, format: ~typing.Optional[str] = None, metadata: bool = <factory>, useuris: ~typing.Optional[bool] = None, log_level: int = 30, mergeimports: ~typing.Optional[bool] = <factory>, source_file_date: ~typing.Optional[str] = None, source_file_size: ~typing.Optional[int] = None, logger: ~typing.Optional[~logging.Logger] = None, verbose: ~typing.Optional[bool] = None, output: ~typing.Optional[str] = None, namespaces: ~typing.Optional[~linkml_runtime.utils.namespaces.Namespaces] = None, directory_output: bool = False, base_dir: ~typing.Optional[str] = None, metamodel_name_map: ~typing.Optional[~typing.Dict[str, str]] = None, importmap: ~typing.Optional[~typing.Union[str, ~typing.Mapping[str, str]]] = None, emit_prefixes: ~typing.Set[str] = <factory>, metamodel: ~typing.Optional[~linkml.utils.schemaloader.SchemaLoader] = None, stacktrace: bool = False, relative_slot_num: int = <factory>, **_kwargs)[source]#

Bases: Generator

A Generator for creating Protobuf schemas from a linkml schema.

end_class(cls: ClassDefinition) None[source]#

Visited after visit_class_slots (if visit_class returned true)

@param cls: class being visited

generate_header()[source]#
generatorname: ClassVar[str] = 'protogen.py'#

Name of the generator. Override with os.path.basename(__file__)

generatorversion: ClassVar[str] = '0.1.1'#

Version of the generator. Consider deprecating and instead use overall linkml version

relative_slot_num: int#
uses_schemaloader: ClassVar[bool] = True#

Old-style generator that uses the SchemaLoader and visitor pattern

valid_formats: ClassVar[List[str]] = ['proto']#

Allowed formats - first format is default

visit_all_class_slots: ClassVar[bool] = True#

Visitor ClassVar: False means only visit own slots, True means visit all slots

visit_class(cls: ClassDefinition) bool[source]#

Visited once per schema class

@param cls: class being visited @return: Visit slots and end class. False means skip and go on

visit_class_slot(cls: ClassDefinition, aliased_slot_name: str, slot: SlotDefinition) None[source]#

Visited for each slot in a class. If class level visit_all_slots is true, this is visited once for any class that is inherited (class itself, is_a, mixin, apply_to). Otherwise just the own slots.

@param cls: containing class @param aliased_slot_name: Aliased slot name. May not be unique across all class slots @param slot: slot being visited

linkml.generators.pydanticgen module#

class linkml.generators.pydanticgen.PydanticGenerator(schema: ~typing.Union[str, ~typing.TextIO, ~linkml_runtime.linkml_model.meta.SchemaDefinition, Generator], schemaview: ~typing.Optional[~linkml_runtime.utils.schemaview.SchemaView] = None, format: ~typing.Optional[str] = None, metadata: bool = <factory>, useuris: ~typing.Optional[bool] = None, log_level: int = 30, mergeimports: ~typing.Optional[bool] = <factory>, source_file_date: ~typing.Optional[str] = None, source_file_size: ~typing.Optional[int] = None, logger: ~typing.Optional[~logging.Logger] = None, verbose: ~typing.Optional[bool] = None, output: ~typing.Optional[str] = None, namespaces: ~typing.Optional[~linkml_runtime.utils.namespaces.Namespaces] = None, directory_output: bool = False, base_dir: str = None, metamodel_name_map: ~typing.Dict[str, str] = None, importmap: ~typing.Optional[~typing.Union[str, ~typing.Mapping[str, str]]] = None, emit_prefixes: ~typing.Set[str] = <factory>, metamodel: ~linkml.utils.schemaloader.SchemaLoader = None, stacktrace: bool = False, template_file: str = None, package: str = 'example', pydantic_version: str = <factory>, extra_fields: str = <factory>, gen_mixin_inheritance: bool = <factory>, gen_classvars: bool = <factory>, gen_slots: bool = <factory>, genmeta: bool = <factory>, emit_metadata: bool = <factory>, **_kwargs)[source]#

Bases: OOCodeGenerator

Generates Pydantic-compliant classes from a schema

This is an alternative to the dataclasses-based Pythongen

compile_module(**kwargs) module[source]#

Compiles generated python code to a module :return:

default_value_for_type(typ: str) str[source]#
emit_metadata: bool#
extra_fields: str#
file_extension: ClassVar[str] = 'py'#
gen_classvars: bool#
gen_mixin_inheritance: bool#
gen_slots: bool#
generate_collection_key(slot_ranges: List[str], slot_def: SlotDefinition, class_def: ClassDefinition) Optional[str][source]#

Find the python range value (str, int, etc) for the identifier slot of a class used as a slot range.

If a pyrange value matches a class name, the range of the identifier slot will be returned. If more than one match is found and they don’t match, an exception will be raised.

Parameters:

slot_ranges – list of python range values

generate_python_range(slot_range, slot_def: SlotDefinition, class_def: ClassDefinition) str[source]#

Generate the python range for a slot range value

generatorname: ClassVar[str] = 'pydanticgen.py'#

Name of the generator. Override with os.path.basename(__file__)

generatorversion: ClassVar[str] = '0.0.2'#

Version of the generator. Consider deprecating and instead use overall linkml version

genmeta: bool#
get_class_isa_plus_mixins() Dict[str, List[str]][source]#

Generate the inheritance list for each class from is_a plus mixins :return:

get_class_slot_range(slot_range: str, inlined: bool, inlined_as_list: bool) str[source]#
get_mixin_identifier_range(mixin) str[source]#
get_predefined_slot_values() Dict[str, Dict[str, str]][source]#
Returns:

Dictionary of dictionaries with predefined slot values for each class

pydantic_version: str#
range_class_has_identifier_slot(slot)[source]#

Check if the range class of a slot has an identifier slot, via both slot.any_of and slot.range Should return False if the range is not a class, and also if the range is a class but has no identifier slot

Parameters:

slot – SlotDefinition

Returns:

bool

serialize() str[source]#

Generate output in the required format

Parameters:

kwargs – Generator specific parameters

Returns:

Generated output

sort_classes(clist: List[ClassDefinition]) List[ClassDefinition][source]#

sort classes such that if C is a child of P then C appears after P in the list

Overridden method include mixin classes

TODO: This should move to SchemaView

template_file: str = None#

Path to template

valid_formats: ClassVar[List[str]] = ['pydantic']#

Allowed formats - first format is default

linkml.generators.pydanticgen.default_template(pydantic_ver: str = '1', extra_fields: str = 'forbid') str[source]#

Constructs a default template for pydantic classes based on the version of pydantic

linkml.generators.pythongen module#

class linkml.generators.pythongen.PythonGenerator(schema: ~typing.Union[str, ~typing.TextIO, ~linkml_runtime.linkml_model.meta.SchemaDefinition, ~linkml.utils.generator.Generator], schemaview: ~typing.Optional[~linkml_runtime.utils.schemaview.SchemaView] = None, format: ~typing.Optional[str] = None, metadata: bool = <factory>, useuris: ~typing.Optional[bool] = None, log_level: int = 30, mergeimports: ~typing.Optional[bool] = <factory>, source_file_date: ~typing.Optional[str] = None, source_file_size: ~typing.Optional[int] = None, logger: ~typing.Optional[~logging.Logger] = None, verbose: ~typing.Optional[bool] = None, output: ~typing.Optional[str] = None, namespaces: ~typing.Optional[~linkml_runtime.utils.namespaces.Namespaces] = None, directory_output: bool = False, base_dir: ~typing.Optional[str] = None, metamodel_name_map: ~typing.Optional[~typing.Dict[str, str]] = None, importmap: ~typing.Optional[~typing.Union[str, ~typing.Mapping[str, str]]] = None, emit_prefixes: ~typing.Set[str] = <factory>, metamodel: ~typing.Optional[~linkml.utils.schemaloader.SchemaLoader] = None, stacktrace: bool = False, gen_classvars: bool = <factory>, gen_slots: bool = <factory>, genmeta: bool = <factory>, emit_metadata: bool = <factory>, **_kwargs)[source]#

Bases: Generator

Generates Python dataclasses from a LinkML model

See Python Generator Docs

class_reference_type(slot: SlotDefinition, cls: Optional[ClassDefinition]) Tuple[str, str, str][source]#

Return the type of a slot referencing a class

Parameters:
  • slot – slot to be typed

  • cls – owning class. Used for generating key references

Returns:

Python class reference type, most proximal type, most proximal type name

compile_module(**kwargs) module[source]#

Compiles generated python code to a module :return:

emit_metadata: bool#
end_schema(**_)[source]#

Visited once at the end of generation

@param kwargs: Arguments passed through from CLI – implementation dependent

file_extension: ClassVar[str] = 'py'#
forward_reference(slot_range: str, owning_class: str) bool[source]#

Determine whether slot_range is a forward reference

gen_class_meta(cls: ClassDefinition) str[source]#
static gen_class_reference(rangelist: List[str]) str[source]#

Return a basic or a union type depending on the number of elements in range list

Parameters:

rangelist – List of types from distal to proximal

Returns:

gen_class_variable(cls: ClassDefinition, slot: SlotDefinition, can_be_positional: bool) str[source]#

Generate a class variable declaration for the supplied slot. Note: the can_be_positional attribute works, but it makes tag/value lists unduly complex, as you can’t load them with tag=…, value=… – you HAVE to load positionally. We currently ignore this parameter, meaning that we have a tag/value option for any LinkML element

Parameters:
  • cls – Owning class

  • slot – slot definition

  • can_be_positional – True means that positional parameters are allowed.

Returns:

Initializer string

gen_class_variables(cls: ClassDefinition) str[source]#

Generate the variable declarations for a dataclass.

Parameters:

cls – class containing variables to be rendered in inheritance hierarchy

Returns:

variable declarations for target class and its ancestors

gen_classdef(cls: ClassDefinition) str[source]#

Generate python definition for class cls

gen_classdefs() str[source]#

Create class definitions for all non-mixin classes in the model Note that apply_to classes are transformed to mixins

gen_classvars: bool#
gen_constructor(cls: ClassDefinition) Optional[str][source]#
gen_enum(enum: EnumDefinition) str[source]#

Generate an enum class @param enum: EnumDefinition object to be converted into code @return: python code string

gen_enum_comment(enum: EnumDefinition) str[source]#
gen_enum_definition(enum: EnumDefinition, enum_name: str) str[source]#
gen_enum_description(enum: EnumDefinition, enum_name: str) str[source]#
gen_enumerations() str[source]#
gen_import_list() Dict[str, List[str]][source]#

Generate a list of types to import

Returns:

source file followed by elements to import

gen_imports() str[source]#
gen_inherited_slots(cls: ClassDefinition) str[source]#
gen_namespaces() str[source]#
gen_postinit(cls: ClassDefinition, slot: SlotDefinition) Optional[str][source]#

Generate python post init rules for slot in class

gen_postinits(cls: ClassDefinition) str[source]#

Generate all the typing and existence checks post initialize

gen_pv_constructor(pv: PermissibleValue, indent: int) str[source]#

Generate a permissible value constructor in the form

PermissibleValue(text=”NAME_ONLY”) PermissibleValue(

text=”CODE”, description=”…”, meaning=”…”)

@param pv: Value to be constructed @param indent: number of additional spaces to add on successive lines @return: Permissible value constructor

gen_pvs(enum: EnumDefinition) str[source]#

Generate the python compliant permissible value initializers as a set of class variables @param enum: EnumDefinition object to be converted into class variables @return: string containing the enum declaration

gen_pvs_as_setattrs(enum: EnumDefinition) str[source]#

Generate the non-python compliant permissible value initializers as a set of setattr instructions in the form

@classmethod def _addvals(cls):

setattr(cls, “NAME”,
PermissibleValue(

text=”NAME”, description=”description here”))

@param enum: EnumDefinition object to be converted into code @return: string containing the enum declaration

gen_references() str[source]#

Generate python type declarations for all identifiers (primary keys)

gen_schema() str[source]#
gen_slot(slot: SlotDefinition) str[source]#
gen_slotdefs() str[source]#
gen_slots: bool#
gen_type_meta(typ: TypeDefinition) str[source]#
gen_typedefs() str[source]#

Generate python type declarations for all defined types

generatorname: ClassVar[str] = 'pythongen.py'#

Name of the generator. Override with os.path.basename(__file__)

generatorversion: ClassVar[str] = '0.0.1'#

Version of the generator. Consider deprecating and instead use overall linkml version

genmeta: bool#
is_key_value_class(range_name: DefinitionName) bool[source]#

Return True if range_name references a class with exactly one key and one value

Parameters:

range_name – class definition (name)

Returns:

True if meets the special case

key_name_for(class_name: ClassDefinitionName) Optional[str][source]#
primary_keys_for(cls: ClassDefinition) List[SlotDefinitionName][source]#

Return the primary key for cls.

Note: At the moment we return at most one entry. At some point, keys will be expanded to support

composite keys.

@param cls: class to get keys for @return: List of primary keys or identifiers

process_multiline_string(input: str, prefix_string: str) str[source]#

Process a (potentially multi-line) string, preserving existing formatting

@param input: input string to be formatted @param prefix_string: the text to prefix the first line of the output @return: formatted string

python_uri_for(uriorcurie: Union[str, URIRef]) Tuple[str, Optional[str]][source]#

Return the python form of uriorcurie :param uriorcurie: :return: URI and CURIE form

range_cardinality(slot: SlotDefinition, cls: Optional[ClassDefinition], positional_allowed: bool) Tuple[str, Optional[str]][source]#

Return the range type including initializers, etc. Generate a class variable declaration for the supplied slot. Note: the positional_allowed attribute works, but it makes tag/value lists unduly complex, as you can’t load them with tag=…, value=… – you HAVE to load positionally. We currently ignore this parameter, meaning that we have a tag/value option for any LinkML element

Parameters:
  • slot – slot to generate type for

  • cls – containing class – used to render key slots correctly. If absent, slot is an add-in

  • positional_allowed – True Means that we are in the positional space and defaults are not supplied

Returns:

python property name and initializer (if any)

range_type_name(slot: SlotDefinition) str[source]#

Generate the type name for the slot

uses_schemaloader: ClassVar[bool] = True#

Old-style generator that uses the SchemaLoader and visitor pattern

valid_formats: ClassVar[List[str]] = ['py']#

Allowed formats - first format is default

visit_all_class_slots: ClassVar[bool] = False#

Visitor ClassVar: False means only visit own slots, True means visit all slots

visit_class(cls: ClassDefinition) bool[source]#

Visited once per schema class

@param cls: class being visited @return: Visit slots and end class. False means skip and go on

visit_schema(**kwargs) None[source]#

Visited once at the beginning of generation

@param kwargs: Arguments passed through from CLI – implementation dependent

visit_slot(aliased_slot_name: str, slot: SlotDefinition) None[source]#

Visited once for every slot definition in the schema.

@param aliased_slot_name: Aliased name of the slot. May not be unique @param slot: visited slot

visit_type(typ: TypeDefinition) None[source]#

Visited once for every type definition in the schema

@param typ: Type definition

linkml.generators.rdfgen module#

YAML Schema to RDF Generator

Generate a JSON LD representation of the model

class linkml.generators.rdfgen.RDFGenerator(schema: Union[str, TextIO, linkml_runtime.linkml_model.meta.SchemaDefinition, ForwardRef('Generator')], schemaview: Optional[linkml_runtime.utils.schemaview.SchemaView] = None, format: Optional[str] = None, metadata: bool = <factory>, useuris: Optional[bool] = None, log_level: int = 30, mergeimports: Optional[bool] = <factory>, source_file_date: Optional[str] = None, source_file_size: Optional[int] = None, logger: Optional[logging.Logger] = None, verbose: Optional[bool] = None, output: Optional[str] = None, namespaces: Optional[linkml_runtime.utils.namespaces.Namespaces] = None, directory_output: bool = False, base_dir: str = None, metamodel_name_map: Dict[str, str] = None, importmap: Union[str, Mapping[str, str], NoneType] = None, emit_prefixes: Set[str] = <factory>, metamodel: linkml.utils.schemaloader.SchemaLoader = None, stacktrace: bool = False, emit_metadata: bool = <factory>, context: List[str] = None, **_kwargs)[source]#

Bases: Generator

context: List[str] = None#
emit_metadata: bool#
end_schema(output: Optional[str] = None, context: Optional[str] = None, **_) None[source]#

Visited once at the end of generation

@param kwargs: Arguments passed through from CLI – implementation dependent

generatorname: ClassVar[str] = 'rdfgen.py'#

Name of the generator. Override with os.path.basename(__file__)

generatorversion: ClassVar[str] = '0.1.1'#

Version of the generator. Consider deprecating and instead use overall linkml version

uses_schemaloader: ClassVar[bool] = True#

Old-style generator that uses the SchemaLoader and visitor pattern

valid_formats: ClassVar[List[str]] = ['ttl', 'hext', 'json-ld', 'n3', 'nquads', 'nt', 'nt11', 'ntriples', 'trig', 'trix', 'ttl', 'turtle', 'xml']#

Allowed formats - first format is default

visit_all_class_slots: ClassVar[bool] = False#

Visitor ClassVar: False means only visit own slots, True means visit all slots

linkml.generators.shaclgen module#

class linkml.generators.shaclgen.ShaclGenerator(schema: Union[str, TextIO, linkml_runtime.linkml_model.meta.SchemaDefinition, ForwardRef('Generator')], schemaview: Optional[linkml_runtime.utils.schemaview.SchemaView] = None, format: Optional[str] = None, metadata: bool = <factory>, useuris: Optional[bool] = None, log_level: int = 30, mergeimports: Optional[bool] = <factory>, source_file_date: Optional[str] = None, source_file_size: Optional[int] = None, logger: Optional[logging.Logger] = None, verbose: Optional[bool] = None, output: Optional[str] = None, namespaces: Optional[linkml_runtime.utils.namespaces.Namespaces] = None, directory_output: bool = False, base_dir: str = None, metamodel_name_map: Dict[str, str] = None, importmap: Union[str, Mapping[str, str], NoneType] = None, emit_prefixes: Set[str] = <factory>, metamodel: linkml.utils.schemaloader.SchemaLoader = None, stacktrace: bool = False, closed: bool = <factory>, **_kwargs)[source]#

Bases: Generator

as_graph() Graph[source]#
closed: bool#

True means add ‘sh:closed=true’ to all shapes, except of mixin shapes and shapes, that have parents

file_extension: ClassVar[str] = 'shacl.ttl'#
generate_header()[source]#
generatorname: ClassVar[str] = 'shaclgen.py'#

Name of the generator. Override with os.path.basename(__file__)

generatorversion: ClassVar[str] = '0.0.1'#

Version of the generator. Consider deprecating and instead use overall linkml version

serialize(**args) str[source]#

Generate output in the required format

Parameters:

kwargs – Generator specific parameters

Returns:

Generated output

uses_schemaloader: ClassVar[bool] = True#

Old-style generator that uses the SchemaLoader and visitor pattern

valid_formats: ClassVar[List[str]] = ['ttl']#

Allowed formats - first format is default

visit_all_class_slots: ClassVar[bool] = False#

Visitor ClassVar: False means only visit own slots, True means visit all slots

linkml.generators.shexgen module#

Generate ShEx definition of a model

class linkml.generators.shexgen.ShExGenerator(schema: Union[str, TextIO, linkml_runtime.linkml_model.meta.SchemaDefinition, ForwardRef('Generator')], schemaview: Optional[linkml_runtime.utils.schemaview.SchemaView] = None, format: Optional[str] = None, metadata: bool = <factory>, useuris: Optional[bool] = None, log_level: int = 30, mergeimports: Optional[bool] = <factory>, source_file_date: Optional[str] = None, source_file_size: Optional[int] = None, logger: Optional[logging.Logger] = None, verbose: Optional[bool] = None, output: Optional[str] = None, namespaces: Optional[linkml_runtime.utils.namespaces.Namespaces] = None, directory_output: bool = False, base_dir: str = None, metamodel_name_map: Dict[str, str] = None, importmap: Union[str, Mapping[str, str], NoneType] = None, emit_prefixes: Set[str] = <factory>, metamodel: linkml.utils.schemaloader.SchemaLoader = None, stacktrace: bool = False, shex: ShExJSG.SchemaWithContext.Schema = <factory>, shapes: List = <factory>, shape: Optional[ShExJSG.ShExJ.Shape] = None, list_shapes: List[ShExJSG.ShExJ.IRIREF] = <factory>, **_kwargs)[source]#

Bases: Generator

end_class(cls: ClassDefinition) None[source]#

Visited after visit_class_slots (if visit_class returned true)

@param cls: class being visited

end_schema(output: Optional[str] = None, **_) None[source]#

Visited once at the end of generation

@param kwargs: Arguments passed through from CLI – implementation dependent

file_extension: ClassVar[str] = 'shex.rdf'#
generate_header()[source]#
generatorname: ClassVar[str] = 'shexgen.py'#

Name of the generator. Override with os.path.basename(__file__)

generatorversion: ClassVar[str] = '0.0.2'#

Version of the generator. Consider deprecating and instead use overall linkml version

list_shapes: List[IRIREF]#
shape: Optional[Shape] = None#
shapes: List#
shex: Schema#
uses_schemaloader: ClassVar[bool] = True#

Old-style generator that uses the SchemaLoader and visitor pattern

valid_formats: ClassVar[List[str]] = ['shex', 'json', 'rdf']#

Allowed formats - first format is default

visit_all_class_slots: ClassVar[bool] = False#

Visitor ClassVar: False means only visit own slots, True means visit all slots

visit_class(cls: ClassDefinition) bool[source]#

Visited once per schema class

@param cls: class being visited @return: Visit slots and end class. False means skip and go on

visit_class_slot(cls: ClassDefinition, aliased_slot_name: SlotDefinitionName, slot: SlotDefinition) None[source]#

Visited for each slot in a class. If class level visit_all_slots is true, this is visited once for any class that is inherited (class itself, is_a, mixin, apply_to). Otherwise just the own slots.

@param cls: containing class @param aliased_slot_name: Aliased slot name. May not be unique across all class slots @param slot: slot being visited

visit_schema(**_)[source]#

Visited once at the beginning of generation

@param kwargs: Arguments passed through from CLI – implementation dependent

linkml.generators.sparqlgen module#

class linkml.generators.sparqlgen.SparqlGenerator(schema: ~typing.Union[str, ~typing.TextIO, ~linkml_runtime.linkml_model.meta.SchemaDefinition, ~linkml.utils.generator.Generator], schemaview: ~typing.Optional[~linkml_runtime.utils.schemaview.SchemaView] = None, format: ~typing.Optional[str] = None, metadata: bool = <factory>, useuris: ~typing.Optional[bool] = None, log_level: int = 30, mergeimports: ~typing.Optional[bool] = <factory>, source_file_date: ~typing.Optional[str] = None, source_file_size: ~typing.Optional[int] = None, logger: ~typing.Optional[~logging.Logger] = None, verbose: ~typing.Optional[bool] = None, output: ~typing.Optional[str] = None, namespaces: ~typing.Optional[~linkml_runtime.utils.namespaces.Namespaces] = None, directory_output: bool = False, base_dir: ~typing.Optional[str] = None, metamodel_name_map: ~typing.Optional[~typing.Dict[str, str]] = None, importmap: ~typing.Optional[~typing.Union[str, ~typing.Mapping[str, str]]] = None, emit_prefixes: ~typing.Set[str] = <factory>, metamodel: ~typing.Optional[~linkml.utils.schemaloader.SchemaLoader] = None, stacktrace: bool = False, named_graphs: ~typing.Optional[~typing.List[str]] = None, limit: ~typing.Optional[int] = None, sparql: ~typing.Optional[str] = None, **_kwargs)[source]#

Bases: Generator

Generates SPARQL queries that can be used for delayed validation

generate_sparql(named_graphs=None, limit: Optional[int] = None)[source]#
generatorname: ClassVar[str] = 'sparqlgen.py'#

Name of the generator. Override with os.path.basename(__file__)

limit: Optional[int] = None#
named_graphs: Optional[List[str]] = None#
serialize(directory=None) str[source]#

Generate output in the required format

Parameters:

kwargs – Generator specific parameters

Returns:

Generated output

sparql: Optional[str] = None#
split_sparql(sparql: str) Dict[str, str][source]#
uses_schemaloader: ClassVar[bool] = False#

Old-style generator that uses the SchemaLoader and visitor pattern

valid_formats: ClassVar[List[str]] = ['sparql']#

Allowed formats - first format is default

visit_all_class_slots: ClassVar[bool] = False#

Visitor ClassVar: False means only visit own slots, True means visit all slots

linkml.generators.sparqlgen.materialize_schema(schemaview: SchemaView)[source]#

linkml.generators.sqlddlgen module#

DEPRECATED: Use SQLTableGenerator instead

class linkml.generators.sqlddlgen.Backref(original_column: 'SQLColumn', backref_column: 'SQLColumn', order_by: str = None)[source]#

Bases: object

backref_column: SQLColumn#
order_by: str = None#
original_column: SQLColumn#
class linkml.generators.sqlddlgen.DDLEntity(*args, **kwargs)[source]#

Bases: object

abstract grouping

description: str = None#
class linkml.generators.sqlddlgen.SQLColumn(*args, **kwargs)[source]#

Bases: DDLEntity

represents a Relational Table Column

as_ddlstr()[source]#
base_type: str = None#
foreign_key: Optional[SQLColumn] = None#
is_primary_key()[source]#
is_singular_primary_key: bool = False#
mapped_to: SlotDefinition = None#
mapped_to_alias: str = None#
name: str = None#
table: SQLTable = None#
class linkml.generators.sqlddlgen.SQLDDLGenerator(*args, **kwargs)[source]#

Bases: Generator

A Generator for creating SQL DDL

DEPRECATED: Use SQLTableGenerator instead

The basic algorithm for mapping a linkml schema S is as follows:

  • Each schema S corresponds to one database schema D (see SQLSchema)

  • Each Class C in S is mapped to a table T (see SQLTable)

  • Each slot S in each C is mapped to a column Col (see SQLColumn)

if the direct_mapping attribute is set to true, then no further transformations are applied. Note that this means:

  • inline objects are modeled as Text strings

  • multivalued fields are modeled as single Text strings

this direct mapping is useful for simple spreadsheet/denormalized representations of complex data. however, for other applications, additional transformations should occur. these are:

MULTIVALUED SLOTS

The relational model does not have direct representation of lists. These are normalized as follows.

If the range of the slot is a class, and there are no other slots whose range is this class, and the slot is for a class that has a singular primary key, then a backref is added.

E.g. if we have User 0..* Address, then add a field User_id to Address.

When SQLAlchemy bindings are created, a backref mapping is added

If the range of the slot is an enum or type, then a new linktable is created, and a backref added

E.g. if a class User has a multivalues slot alias whose range is a string, then create a table user_aliases, with two columns (1) alias [a string] and (2) a backref to user

Each mapped slot C.S has a range R

ranges that are types (literals):
  • If R is a type, and the slot is NOT multivalued, do a direct type conversion

  • If R is a type, and the slot is multivalued: * do not include the mapped column * create a new table T_S, with 2 columns: S, and a backref to T

ranges that are classes:

Ref = map_class_to_table(R) - if R is a class, and the slot is NOT multivalued, and Ref has a singular primary key:

  • Col.type = ForeignKey(Ref.PK)

  • if R is a class, and the slot is NOT multivalued, and Ref has NO singular primary key: * add a foreign key C.pk to Ref * add a backref C.S => Ref, C.pk * remove Col from T

  • If R is a class, and the slot IS multivalued

dialect: str#
end_class(cls: ClassDefinition) None[source]#

Visited after visit_class_slots (if visit_class returned true)

@param cls: class being visited

end_schema(**kwargs) None[source]#

Visited once at the end of generation

@param kwargs: Arguments passed through from CLI – implementation dependent

generate_ddl() None[source]#
generate_header()[source]#
generatorname: ClassVar[str] = 'sqlddlgen.py'#

Name of the generator. Override with os.path.basename(__file__)

generatorversion: ClassVar[str] = '0.1.1'#

Version of the generator. Consider deprecating and instead use overall linkml version

get_sql_range(slot: SlotDefinition)[source]#

returns a SQL Alchemy column type

inject_primary_keys: bool = True#
sqlschema: SQLSchema = SQLSchema(description=None, name=None, mapped_to=None, tables={})#
use_inherits: bool = False#
valid_formats: ClassVar[List[str]] = ['sql']#

Allowed formats - first format is default

visit_all_class_slots: bool = True#

Visitor ClassVar: False means only visit own slots, True means visit all slots

visit_class(cls: ClassDefinition) bool[source]#

Visited once per schema class

@param cls: class being visited @return: Visit slots and end class. False means skip and go on

visit_class_slot(cls: ClassDefinition, aliased_slot_name: str, slot: SlotDefinition) None[source]#

Visited for each slot in a class. If class level visit_all_slots is true, this is visited once for any class that is inherited (class itself, is_a, mixin, apply_to). Otherwise just the own slots.

@param cls: containing class @param aliased_slot_name: Aliased slot name. May not be unique across all class slots @param slot: slot being visited

write_sqla_python_imperative(model_path: str) str[source]#

imperative mapping: https://docs.sqlalchemy.org/en/14/orm/dataclasses.html#mapping-dataclasses-using-imperative-mapping

maps to the python classes generated using PythonGenerator

``` output = StringIO() with redirect_stdout(output):

gen.write_sqla_python_imperative()

class linkml.generators.sqlddlgen.SQLSchema(*args, **kwargs)[source]#

Bases: DDLEntity

represents a Relational Schema

add_table(t: SQLTable)[source]#
all_columns() List[SQLColumn][source]#
get_table_by_class_name(cn: ClassDefinitionName) Optional[SQLTable][source]#
mapped_to: SchemaDefinition = None#
name: str = None#
tables: Dict[str, SQLTable]#
class linkml.generators.sqlddlgen.SQLTable(*args, **kwargs)[source]#

Bases: DDLEntity

represents a Relational Table

add_column(c: SQLColumn)[source]#
as_var() str[source]#
backrefs: List[Backref]#
columns: Dict[str, SQLColumn]#
get_singular_primary_key() Optional[SQLColumn][source]#
in_schema: SQLSchema = None#
mapped_to: ClassDefinition = None#
name: str = None#
primary_keys: List[SQLColumn]#
referenced_by: List[SQLColumn]#
remove_column(c)[source]#

linkml.generators.summarygen module#

Generate Summary Spreadsheets

class linkml.generators.summarygen.SummaryGenerator(schema: Union[str, TextIO, linkml_runtime.linkml_model.meta.SchemaDefinition, ForwardRef('Generator')], schemaview: Optional[linkml_runtime.utils.schemaview.SchemaView] = None, format: Optional[str] = None, metadata: bool = <factory>, useuris: Optional[bool] = None, log_level: int = 30, mergeimports: Optional[bool] = <factory>, source_file_date: Optional[str] = None, source_file_size: Optional[int] = None, logger: Optional[logging.Logger] = None, verbose: Optional[bool] = None, output: Optional[str] = None, namespaces: Optional[linkml_runtime.utils.namespaces.Namespaces] = None, directory_output: bool = False, base_dir: str = None, metamodel_name_map: Dict[str, str] = None, importmap: Union[str, Mapping[str, str], NoneType] = None, emit_prefixes: Set[str] = <factory>, metamodel: linkml.utils.schemaloader.SchemaLoader = None, stacktrace: bool = False, dirname: str = None, classtab: Optional[csv.DictWriter] = None, slottab: Optional[csv.DictWriter] = None, dialect: str = <factory>, **_kwargs)[source]#

Bases: Generator

classtab: Optional[DictWriter] = None#
dialect: str#
dirname: str = None#
generatorname: ClassVar[str] = 'summarygen.py'#

Name of the generator. Override with os.path.basename(__file__)

generatorversion: ClassVar[str] = '0.1.1'#

Version of the generator. Consider deprecating and instead use overall linkml version

slottab: Optional[DictWriter] = None#
valid_formats: ClassVar[List[str]] = ['tsv']#

Allowed formats - first format is default

visit_class(cls: ClassDefinition) bool[source]#

Visited once per schema class

@param cls: class being visited @return: Visit slots and end class. False means skip and go on

visit_class_slot(cls: ClassDefinition, aliased_slot_name: str, slot: SlotDefinition) None[source]#

Visited for each slot in a class. If class level visit_all_slots is true, this is visited once for any class that is inherited (class itself, is_a, mixin, apply_to). Otherwise just the own slots.

@param cls: containing class @param aliased_slot_name: Aliased slot name. May not be unique across all class slots @param slot: slot being visited

visit_schema(**_) None[source]#

Visited once at the beginning of generation

@param kwargs: Arguments passed through from CLI – implementation dependent

linkml.generators.terminusdbgen module#

linkml.generators.yamlgen module#

Validate linkml input and optionally emit completely resolved biolink yaml output

class linkml.generators.yamlgen.YAMLGenerator(schema: ~typing.Union[str, ~typing.TextIO, ~linkml_runtime.linkml_model.meta.SchemaDefinition, ~linkml.utils.generator.Generator], schemaview: ~typing.Optional[~linkml_runtime.utils.schemaview.SchemaView] = None, format: ~typing.Optional[str] = None, metadata: bool = <factory>, useuris: ~typing.Optional[bool] = None, log_level: int = 30, mergeimports: ~typing.Optional[bool] = <factory>, source_file_date: ~typing.Optional[str] = None, source_file_size: ~typing.Optional[int] = None, logger: ~typing.Optional[~logging.Logger] = None, verbose: ~typing.Optional[bool] = None, output: ~typing.Optional[str] = None, namespaces: ~typing.Optional[~linkml_runtime.utils.namespaces.Namespaces] = None, directory_output: bool = False, base_dir: ~typing.Optional[str] = None, metamodel_name_map: ~typing.Optional[~typing.Dict[str, str]] = None, importmap: ~typing.Optional[~typing.Union[str, ~typing.Mapping[str, str]]] = None, emit_prefixes: ~typing.Set[str] = <factory>, metamodel: ~typing.Optional[~linkml.utils.schemaloader.SchemaLoader] = None, stacktrace: bool = False, validateonly: bool = <factory>, **_kwargs)[source]#

Bases: Generator

A generator that produces a schema as a YAML Document

generatorname: ClassVar[str] = 'yamlgen.py'#

Name of the generator. Override with os.path.basename(__file__)

generatorversion: ClassVar[str] = '0.1.0'#

Version of the generator. Consider deprecating and instead use overall linkml version

serialize(validateonly: bool = False, **kwargs) str[source]#

Generate output in the required format

Parameters:

kwargs – Generator specific parameters

Returns:

Generated output

uses_schemaloader: ClassVar[bool] = True#

Old-style generator that uses the SchemaLoader and visitor pattern

valid_formats: ClassVar[List[str]] = ['yaml']#

Allowed formats - first format is default

validateonly: bool#

linkml.generators.yumlgen module#

Generate yuml

https://yuml.me/diagram/scruffy/class/samples

class linkml.generators.yumlgen.YumlGenerator(schema: Union[str, TextIO, linkml_runtime.linkml_model.meta.SchemaDefinition, ForwardRef('Generator')], schemaview: Optional[linkml_runtime.utils.schemaview.SchemaView] = None, format: Optional[str] = None, metadata: bool = <factory>, useuris: Optional[bool] = None, log_level: int = 30, mergeimports: Optional[bool] = <factory>, source_file_date: Optional[str] = None, source_file_size: Optional[int] = None, logger: Optional[logging.Logger] = None, verbose: Optional[bool] = None, output: Optional[str] = None, namespaces: Optional[linkml_runtime.utils.namespaces.Namespaces] = None, directory_output: bool = False, base_dir: str = None, metamodel_name_map: Dict[str, str] = None, importmap: Union[str, Mapping[str, str], NoneType] = None, emit_prefixes: Set[str] = <factory>, metamodel: linkml.utils.schemaloader.SchemaLoader = None, stacktrace: bool = False, referenced: Optional[Set[linkml_runtime.linkml_model.meta.ClassDefinitionName]] = None, generated: Optional[Set[linkml_runtime.linkml_model.meta.ClassDefinitionName]] = None, box_generated: Optional[Set[linkml_runtime.linkml_model.meta.ClassDefinitionName]] = None, associations_generated: Optional[Set[linkml_runtime.linkml_model.meta.ClassDefinitionName]] = None, focus_classes: Optional[Set[linkml_runtime.linkml_model.meta.ClassDefinitionName]] = None, gen_classes: Optional[Set[linkml_runtime.linkml_model.meta.ClassDefinitionName]] = None, output_file_name: Optional[str] = None, classes: Set[linkml_runtime.linkml_model.meta.ClassDefinitionName] = None, directory: Optional[str] = None, diagram_name: Optional[str] = None, load_image: bool = <factory>, **_kwargs)[source]#

Bases: Generator

associations_generated: Optional[Set[ClassDefinitionName]] = None#
box_generated: Optional[Set[ClassDefinitionName]] = None#
static cardinality(slot: SlotDefinition, is_attribute: bool = True) str[source]#
class_associations(cn: ClassDefinitionName, must_render: bool = False) str[source]#

Emit all associations for a focus class. If none are specified, all classes are generated

@param cn: Name of class to be emitted @param must_render: True means render even if this is a target (class is specifically requested) @return: YUML representation of the association

class_box(cn: ClassDefinitionName) str[source]#

Generate a box for the class. Populate its interior only if (a) it hasn’t previously been generated and (b) it appears in the gen_classes list

@param cn: @return:

classes: Set[ClassDefinitionName] = None#
diagram_name: Optional[str] = None#
directory: Optional[str] = None#
filtered_cls_slots(cn: ~linkml_runtime.linkml_model.meta.ClassDefinitionName, all_slots: bool = True, filtr: ~typing.Callable[[~linkml_runtime.linkml_model.meta.SlotDefinition], bool] = <function YumlGenerator.<lambda>>) List[SlotDefinition][source]#

Return the set of slots associated with the class that meet the filter criteria. Slots will be returned in defining order, with class slots returned last

@param cn: name of class to filter @param all_slots: True means include attributes @param filtr: Slot filter predicate @return: List of slot definitions

focus_classes: Optional[Set[ClassDefinitionName]] = None#
gen_classes: Optional[Set[ClassDefinitionName]] = None#
generated: Optional[Set[ClassDefinitionName]] = None#
generatorname: ClassVar[str] = 'yumlgen.py'#

Name of the generator. Override with os.path.basename(__file__)

generatorversion: ClassVar[str] = '0.1.1'#

Version of the generator. Consider deprecating and instead use overall linkml version

load_image: bool#
output_file_name: Optional[str] = None#
prop_modifier(cls: ClassDefinition, slot: SlotDefinition) str[source]#
Return the modifiers for the slot:

(i) - inherited (m) - inherited through mixin (a) - injected (pk) - primary ckey

@param cls: @param slot: @return:

referenced: Optional[Set[ClassDefinitionName]] = None#
valid_formats: ClassVar[List[str]] = ['yuml', 'png', 'pdf', 'jpg', 'json', 'svg']#

Allowed formats - first format is default

visit_all_class_slots: ClassVar[bool] = False#

Visitor ClassVar: False means only visit own slots, True means visit all slots

visit_schema(classes: Optional[Set[ClassDefinitionName]] = None, directory: Optional[str] = None, diagram_name: Optional[str] = None, load_image: bool = True, **_) None[source]#

Visited once at the beginning of generation

@param kwargs: Arguments passed through from CLI – implementation dependent

Module contents#

Generators translate between a SchemaDefinition and an alternative representation such as JsonSchema

class linkml.generators.JavaGenerator(schema: ~typing.Union[str, ~typing.TextIO, ~linkml_runtime.linkml_model.meta.SchemaDefinition, Generator], schemaview: ~typing.Optional[~linkml_runtime.utils.schemaview.SchemaView] = None, format: ~typing.Optional[str] = None, metadata: bool = <factory>, useuris: ~typing.Optional[bool] = None, log_level: int = 30, mergeimports: ~typing.Optional[bool] = <factory>, source_file_date: ~typing.Optional[str] = None, source_file_size: ~typing.Optional[int] = None, logger: ~typing.Optional[~logging.Logger] = None, verbose: ~typing.Optional[bool] = None, output: ~typing.Optional[str] = None, namespaces: ~typing.Optional[~linkml_runtime.utils.namespaces.Namespaces] = None, directory_output: bool = False, base_dir: str = None, metamodel_name_map: ~typing.Dict[str, str] = None, importmap: ~typing.Optional[~typing.Union[str, ~typing.Mapping[str, str]]] = None, emit_prefixes: ~typing.Set[str] = <factory>, metamodel: ~linkml.utils.schemaloader.SchemaLoader = None, stacktrace: bool = False, template_file: ~typing.Optional[str] = None, package: str = 'example', generate_records: bool = False, gen_classvars: bool = <factory>, gen_slots: bool = <factory>, genmeta: bool = <factory>, emit_metadata: bool = <factory>, **_kwargs)[source]#

Bases: OOCodeGenerator

Generates java code from a LinkML schema.

Two styles are supported:

  • java classes, using lombok annotations

  • java records

default_value_for_type(typ: str) str[source]#
emit_metadata: bool#
emit_prefixes: Set[str]#

Prefixes to emit, for RDF-based generators

gen_classvars: bool#
gen_slots: bool#
generate_records: bool = False#

If True then use java records (introduced in java 14) rather than classes

generatorname: ClassVar[str] = 'javagen.py'#

Name of the generator. Override with os.path.basename(__file__)

generatorversion: ClassVar[str] = '0.0.1'#

Version of the generator. Consider deprecating and instead use overall linkml version

genmeta: bool#
map_type(t: TypeDefinition, required: bool = False) str[source]#
mergeimports: Optional[bool]#

True means merge non-linkml sources into importing package. False means separate packages

metadata: bool#

True means include date, generator, etc. information in source header if appropriate

schema: Union[str, TextIO, SchemaDefinition, 'Generator']#

metamodel compliant schema. Can be URI, file name, actual schema, another generator, an open file or a pre-parsed schema

serialize(directory: str, **kwargs) None[source]#

Generate output in the required format

Parameters:

kwargs – Generator specific parameters

Returns:

Generated output

template_file: Optional[str] = None#

Path to template

valid_formats: ClassVar[List[str]] = ['java']#

Allowed formats - first format is default

class linkml.generators.JsonSchemaGenerator(schema: ~typing.Union[str, ~typing.TextIO, ~linkml_runtime.linkml_model.meta.SchemaDefinition, ~linkml.utils.generator.Generator], schemaview: ~typing.Optional[~linkml_runtime.utils.schemaview.SchemaView] = None, format: ~typing.Optional[str] = None, metadata: bool = <factory>, useuris: ~typing.Optional[bool] = None, log_level: int = 30, mergeimports: ~typing.Optional[bool] = <factory>, source_file_date: ~typing.Optional[str] = None, source_file_size: ~typing.Optional[int] = None, logger: ~typing.Optional[~logging.Logger] = None, verbose: ~typing.Optional[bool] = None, output: ~typing.Optional[str] = None, namespaces: ~typing.Optional[~linkml_runtime.utils.namespaces.Namespaces] = None, directory_output: bool = False, base_dir: ~typing.Optional[str] = None, metamodel_name_map: ~typing.Optional[~typing.Dict[str, str]] = None, importmap: ~typing.Optional[~typing.Union[str, ~typing.Mapping[str, str]]] = None, emit_prefixes: ~typing.Set[str] = <factory>, metamodel: ~typing.Optional[~linkml.utils.schemaloader.SchemaLoader] = None, stacktrace: bool = False, topClass: ~typing.Optional[str] = None, not_closed: ~typing.Optional[bool] = <factory>, indent: int = 4, inline: bool = False, top_class: ~typing.Optional[~typing.Union[~linkml_runtime.linkml_model.meta.ClassDefinitionName, str]] = None, include_range_class_descendants: bool = <factory>, top_level_schema: ~typing.Optional[~linkml.generators.jsonschemagen.JsonSchema] = None, **_kwargs)[source]#

Bases: Generator

Generates JSONSchema documents from a LinkML SchemaDefinition

  • Each linkml class generates a schema

  • inheritance hierarchies are rolled-down from ancestors

  • Composition not yet implemented

  • Enumerations treated as strings

  • Foreign key references are treated as semantics-free strings

emit_prefixes: Set[str]#

Prefixes to emit, for RDF-based generators

file_extension: ClassVar[str] = 'schema.json'#
generate() dict[source]#
generatorname: ClassVar[str] = 'jsonschemagen.py'#

Name of the generator. Override with os.path.basename(__file__)

generatorversion: ClassVar[str] = '0.0.3'#

Version of the generator. Consider deprecating and instead use overall linkml version

get_subschema_for_anonymous_class(cls: AnonymousClassExpression, properties_required: bool = False) Union[None, JsonSchema][source]#
get_subschema_for_slot(slot: SlotDefinition, omit_type: bool = False) JsonSchema[source]#
get_type_info_for_slot_subschema(slot: AnonymousSlotExpression) Tuple[str, str, Union[str, List[str]]][source]#
get_value_constraints_for_slot(slot: Optional[AnonymousSlotExpression]) JsonSchema[source]#
handle_class(cls: ClassDefinition) None[source]#
handle_class_slot(subschema: JsonSchema, cls: ClassDefinition, slot: SlotDefinition) None[source]#
handle_enum(enum: EnumDefinition) None[source]#
include_range_class_descendants: bool#

If set, use an open world assumption and allow the range of a slot to be any descendant of the declared range. Note that if the range of a slot has a type designator, descendants will always be included.

indent: int = 4#
inline: bool = False#
mergeimports: Optional[bool]#

True means merge non-linkml sources into importing package. False means separate packages

metadata: bool#

True means include date, generator, etc. information in source header if appropriate

not_closed: Optional[bool]#

If not closed, then an open-ended set of attributes can be instantiated for any object

schema: Union[str, TextIO, SchemaDefinition, 'Generator']#

metamodel compliant schema. Can be URI, file name, actual schema, another generator, an open file or a pre-parsed schema

serialize(**kwargs) str[source]#

Generate output in the required format

Parameters:

kwargs – Generator specific parameters

Returns:

Generated output

start_schema(inline: bool = False) JsonSchema[source]#
topClass: Optional[str] = None#
top_class: Optional[Union[ClassDefinitionName, str]] = None#

Class instantiated by the root node of the document tree

top_level_schema: JsonSchema = None#
uses_schemaloader: ClassVar[bool] = False#

Old-style generator that uses the SchemaLoader and visitor pattern

valid_formats: ClassVar[List[str]] = ['json']#

Allowed formats - first format is default

class linkml.generators.OwlSchemaGenerator(schema: ~typing.Union[str, ~typing.TextIO, ~linkml_runtime.linkml_model.meta.SchemaDefinition, ~linkml.utils.generator.Generator], schemaview: ~typing.Optional[~linkml_runtime.utils.schemaview.SchemaView] = None, format: ~typing.Optional[str] = None, metadata: bool = <factory>, useuris: ~typing.Optional[bool] = None, log_level: int = 30, mergeimports: ~typing.Optional[bool] = <factory>, source_file_date: ~typing.Optional[str] = None, source_file_size: ~typing.Optional[int] = None, logger: ~typing.Optional[~logging.Logger] = None, verbose: ~typing.Optional[bool] = None, output: ~typing.Optional[str] = None, namespaces: ~typing.Optional[~linkml_runtime.utils.namespaces.Namespaces] = None, directory_output: bool = False, base_dir: ~typing.Optional[str] = None, metamodel_name_map: ~typing.Optional[~typing.Dict[str, str]] = None, importmap: ~typing.Optional[~typing.Union[str, ~typing.Mapping[str, str]]] = None, emit_prefixes: ~typing.Set[str] = <factory>, metamodel: ~typing.Optional[~linkml.utils.schemaloader.SchemaLoader] = None, stacktrace: bool = False, ontology_uri_suffix: ~typing.Optional[str] = None, metadata_profile: ~typing.Optional[~linkml.generators.owlgen.MetadataProfile] = None, metadata_profiles: ~typing.List[~linkml.generators.owlgen.MetadataProfile] = <factory>, metaclasses: bool = <factory>, add_root_classes: bool = <factory>, add_ols_annotations: bool = <factory>, graph: ~typing.Optional[~rdflib.graph.Graph] = None, top_value_uri: ~typing.Optional[~rdflib.term.URIRef] = None, type_objects: bool = <factory>, assert_equivalent_classes: bool = <factory>, use_native_uris: bool = <factory>, mixins_as_expressions: ~typing.Optional[bool] = None, slot_is_literal_map: ~typing.Mapping[str, ~typing.Set[bool]] = <factory>, node_owltypes: ~typing.Mapping[~typing.Union[~rdflib.term.BNode, ~rdflib.term.URIRef], ~typing.Set[~rdflib.term.URIRef]] = <factory>, simplify: bool = <factory>, use_swrl: bool = <factory>, target_profile: ~linkml.generators.owlgen.OWLProfile = <factory>, metamodel_schemaview: ~linkml_runtime.utils.schemaview.SchemaView = <factory>, **_kwargs)[source]#

Bases: Generator

Generates a schema-oriented OWL representation of a LinkML model

OWL Generator Docs

.

  • LinkML ClassDefinitions are translated to OWL Classes

  • LinkML SlotDefinitions are translated to OWL Properties

  • LinkML Enumerations are translated to OWL Classes

  • LinkML TypeDefinitions are translated to OWL Datatypes

The translation aims to be as faithful as possible. But note that OWL is open-world, whereas LinkML is closed-world

add_class(cls: ClassDefinition) None[source]#

Each ClassDefinition is represented as an OWL class.

  • the OWL Class will instantiate ClassDefinition, if schema.metaclasses is true

  • the OWL Class will be annotated using the same properties as the source ClassDefinition

  • induced slots and their ranges added as OWL restrictions; note this will be under the Open World Assumption

This method works by generating an OWL ontology via populating triples in a graph. To understand how the RDF-level operations here related to the OWL representation, consult https://www.w3.org/TR/owl2-mapping-to-rdf/

Parameters:

cls

Returns:

add_constraints(element: Union[SlotDefinition, AnonymousSlotExpression, TypeDefinition, AnonymousTypeExpression], is_literal: Optional[bool] = None) Tuple[List[BNode], Set[URIRef]][source]#
add_enum(e: EnumDefinition) None[source]#
add_metadata(e: Definition, uri: URIRef) None[source]#

Add annotation properties.

Set the profile attribute to the appropriate OWL profile.

Parameters:
  • e – schema element

  • uri – URI representation of schema element

Returns:

add_ols_annotations: bool#
add_root_classes: bool#
add_slot(slot: SlotDefinition, attribute=False) None[source]#
add_type(typ: TypeDefinition) None[source]#
as_graph() Graph[source]#

Generate an rdflib Graph from the LinkML schema.

Returns:

assert_equivalent_classes: bool#

If True, assert equivalence between definition_uris and class_uris

emit_prefixes: Set[str]#

Prefixes to emit, for RDF-based generators

file_extension: ClassVar[str] = 'owl'#
generatorname: ClassVar[str] = 'owlgen.py'#

Name of the generator. Override with os.path.basename(__file__)

generatorversion: ClassVar[str] = '0.1.1'#

Version of the generator. Consider deprecating and instead use overall linkml version

graph: Optional[Graph] = None#

Mutable graph that is being built up during OWL generation.

has_profile(profile: MetadataProfile, default=False) bool[source]#

Determine if a metadata profile is active.

Parameters:
  • profile – profile to check

  • default – True if the configured profiles include the specified profile

Returns:

mergeimports: Optional[bool]#

True means merge non-linkml sources into importing package. False means separate packages

metaclasses: bool#

if True, include OWL representations of ClassDefinition, SlotDefinition, etc. Introduces punning

metadata: bool#

True means include date, generator, etc. information in source header if appropriate

metadata_profile: MetadataProfile = None#

Deprecated - use metadata_profiles.

metadata_profiles: List[MetadataProfile]#

By default, use the linkml metadata profile, this allows for overrides.

metamodel_schemaview: SchemaView#
mixins_as_expressions: bool = None#

EXPERIMENTAL: If True, use OWL existential restrictions to represent mixins

node_owltypes: Mapping[Union[BNode, URIRef], Set[URIRef]]#

rdfs:Datatype, owl:Thing

ontology_uri_suffix: str = None#

Suffix to add to the schema name to create the ontology URI, e.g. .owl.ttl

schema: Union[str, TextIO, SchemaDefinition, 'Generator']#

metamodel compliant schema. Can be URI, file name, actual schema, another generator, an open file or a pre-parsed schema

serialize(**kwargs) str[source]#

Serialize the OWL triple graph to a standard RDF serialization format.

Parameters:

kwargs

Returns:

simplify: bool#

Reduce complex expressions to simpler forms

slot_is_literal_map: Mapping[str, Set[bool]]#

DEPRECATED: use node_owltypes

slot_node_owltypes(slot: Union[SlotDefinition, AnonymousSlotExpression]) Set[URIRef][source]#
slot_owl_type(slot: SlotDefinition) URIRef[source]#
target_profile: OWLProfile#

Target OWL profile. Currently the only distinction is between DL and Full

top_value_uri: Optional[URIRef] = None#

If metaclasses=True, then this property is used to connect object shadows to literals

transform_class_expression(cls: Union[ClassDefinition, AnonymousClassExpression], quantifier_predicate: URIRef = rdflib.term.URIRef('http://www.w3.org/2002/07/owl#allValuesFrom')) BNode[source]#

Transform a LinkML class expression into an OWL expression.

If the class includes boolean expressions, then these are recursively transformed (each such inner expression is an anonymous expression)

Parameters:

cls – LinkML class expression (anonymous if called recursively)

Returns:

blank node representing the OWL expression

transform_class_slot_expression(cls: Optional[Union[ClassDefinition, AnonymousClassExpression]], slot: Union[SlotDefinition, AnonymousSlotExpression], main_slot: Optional[SlotDefinition] = None, owl_types: Optional[Set[URIRef]] = None) Union[BNode, URIRef][source]#

Take a ClassExpression and SlotExpression combination and transform to a node.

Parameters:
  • cls

  • slot

  • main_slot

Returns:

type_objects: bool#

if True, represents types as classes (and thus all slots are object properties); typed object classes effectively shadow the main xsd literal types. The purpose of this is to allow a uniform ObjectProperty representation for all slots, without having to commit to being either Data or Object property (OWL-DL does not allow a property to be both.

use_native_uris: bool#

If True, use the definition_uris, otherwise use class_uris.

use_swrl: bool#

Use of SWRL is experimental

uses_schemaloader: ClassVar[bool] = False#

Old-style generator that uses the SchemaLoader and visitor pattern

valid_formats: ClassVar[List[str]] = ['owl', 'ttl', 'json-ld', 'xml', 'n3', 'turtle', 'ttl', 'ntriples', 'nt', 'nt11', 'nquads', 'trix', 'trig', 'hext']#

Allowed formats - first format is default

class linkml.generators.PydanticGenerator(schema: ~typing.Union[str, ~typing.TextIO, ~linkml_runtime.linkml_model.meta.SchemaDefinition, Generator], schemaview: ~typing.Optional[~linkml_runtime.utils.schemaview.SchemaView] = None, format: ~typing.Optional[str] = None, metadata: bool = <factory>, useuris: ~typing.Optional[bool] = None, log_level: int = 30, mergeimports: ~typing.Optional[bool] = <factory>, source_file_date: ~typing.Optional[str] = None, source_file_size: ~typing.Optional[int] = None, logger: ~typing.Optional[~logging.Logger] = None, verbose: ~typing.Optional[bool] = None, output: ~typing.Optional[str] = None, namespaces: ~typing.Optional[~linkml_runtime.utils.namespaces.Namespaces] = None, directory_output: bool = False, base_dir: str = None, metamodel_name_map: ~typing.Dict[str, str] = None, importmap: ~typing.Optional[~typing.Union[str, ~typing.Mapping[str, str]]] = None, emit_prefixes: ~typing.Set[str] = <factory>, metamodel: ~linkml.utils.schemaloader.SchemaLoader = None, stacktrace: bool = False, template_file: str = None, package: str = 'example', pydantic_version: str = <factory>, extra_fields: str = <factory>, gen_mixin_inheritance: bool = <factory>, gen_classvars: bool = <factory>, gen_slots: bool = <factory>, genmeta: bool = <factory>, emit_metadata: bool = <factory>, **_kwargs)[source]#

Bases: OOCodeGenerator

Generates Pydantic-compliant classes from a schema

This is an alternative to the dataclasses-based Pythongen

compile_module(**kwargs) module[source]#

Compiles generated python code to a module :return:

default_value_for_type(typ: str) str[source]#
emit_metadata: bool#
emit_prefixes: Set[str]#

Prefixes to emit, for RDF-based generators

extra_fields: str#
file_extension: ClassVar[str] = 'py'#
gen_classvars: bool#
gen_mixin_inheritance: bool#
gen_slots: bool#
generate_collection_key(slot_ranges: List[str], slot_def: SlotDefinition, class_def: ClassDefinition) Optional[str][source]#

Find the python range value (str, int, etc) for the identifier slot of a class used as a slot range.

If a pyrange value matches a class name, the range of the identifier slot will be returned. If more than one match is found and they don’t match, an exception will be raised.

Parameters:

slot_ranges – list of python range values

generate_python_range(slot_range, slot_def: SlotDefinition, class_def: ClassDefinition) str[source]#

Generate the python range for a slot range value

generatorname: ClassVar[str] = 'pydanticgen.py'#

Name of the generator. Override with os.path.basename(__file__)

generatorversion: ClassVar[str] = '0.0.2'#

Version of the generator. Consider deprecating and instead use overall linkml version

genmeta: bool#
get_class_isa_plus_mixins() Dict[str, List[str]][source]#

Generate the inheritance list for each class from is_a plus mixins :return:

get_class_slot_range(slot_range: str, inlined: bool, inlined_as_list: bool) str[source]#
get_mixin_identifier_range(mixin) str[source]#
get_predefined_slot_values() Dict[str, Dict[str, str]][source]#
Returns:

Dictionary of dictionaries with predefined slot values for each class

mergeimports: Optional[bool]#

True means merge non-linkml sources into importing package. False means separate packages

metadata: bool#

True means include date, generator, etc. information in source header if appropriate

pydantic_version: str#
range_class_has_identifier_slot(slot)[source]#

Check if the range class of a slot has an identifier slot, via both slot.any_of and slot.range Should return False if the range is not a class, and also if the range is a class but has no identifier slot

Parameters:

slot – SlotDefinition

Returns:

bool

schema: Union[str, TextIO, SchemaDefinition, 'Generator']#

metamodel compliant schema. Can be URI, file name, actual schema, another generator, an open file or a pre-parsed schema

serialize() str[source]#

Generate output in the required format

Parameters:

kwargs – Generator specific parameters

Returns:

Generated output

sort_classes(clist: List[ClassDefinition]) List[ClassDefinition][source]#

sort classes such that if C is a child of P then C appears after P in the list

Overridden method include mixin classes

TODO: This should move to SchemaView

template_file: str = None#

Path to template

valid_formats: ClassVar[List[str]] = ['pydantic']#

Allowed formats - first format is default

class linkml.generators.PythonGenerator(schema: ~typing.Union[str, ~typing.TextIO, ~linkml_runtime.linkml_model.meta.SchemaDefinition, ~linkml.utils.generator.Generator], schemaview: ~typing.Optional[~linkml_runtime.utils.schemaview.SchemaView] = None, format: ~typing.Optional[str] = None, metadata: bool = <factory>, useuris: ~typing.Optional[bool] = None, log_level: int = 30, mergeimports: ~typing.Optional[bool] = <factory>, source_file_date: ~typing.Optional[str] = None, source_file_size: ~typing.Optional[int] = None, logger: ~typing.Optional[~logging.Logger] = None, verbose: ~typing.Optional[bool] = None, output: ~typing.Optional[str] = None, namespaces: ~typing.Optional[~linkml_runtime.utils.namespaces.Namespaces] = None, directory_output: bool = False, base_dir: ~typing.Optional[str] = None, metamodel_name_map: ~typing.Optional[~typing.Dict[str, str]] = None, importmap: ~typing.Optional[~typing.Union[str, ~typing.Mapping[str, str]]] = None, emit_prefixes: ~typing.Set[str] = <factory>, metamodel: ~typing.Optional[~linkml.utils.schemaloader.SchemaLoader] = None, stacktrace: bool = False, gen_classvars: bool = <factory>, gen_slots: bool = <factory>, genmeta: bool = <factory>, emit_metadata: bool = <factory>, **_kwargs)[source]#

Bases: Generator

Generates Python dataclasses from a LinkML model

See Python Generator Docs

class_reference_type(slot: SlotDefinition, cls: Optional[ClassDefinition]) Tuple[str, str, str][source]#

Return the type of a slot referencing a class

Parameters:
  • slot – slot to be typed

  • cls – owning class. Used for generating key references

Returns:

Python class reference type, most proximal type, most proximal type name

compile_module(**kwargs) module[source]#

Compiles generated python code to a module :return:

emit_metadata: bool#
emit_prefixes: Set[str]#

Prefixes to emit, for RDF-based generators

end_schema(**_)[source]#

Visited once at the end of generation

@param kwargs: Arguments passed through from CLI – implementation dependent

file_extension: ClassVar[str] = 'py'#
forward_reference(slot_range: str, owning_class: str) bool[source]#

Determine whether slot_range is a forward reference

gen_class_meta(cls: ClassDefinition) str[source]#
static gen_class_reference(rangelist: List[str]) str[source]#

Return a basic or a union type depending on the number of elements in range list

Parameters:

rangelist – List of types from distal to proximal

Returns:

gen_class_variable(cls: ClassDefinition, slot: SlotDefinition, can_be_positional: bool) str[source]#

Generate a class variable declaration for the supplied slot. Note: the can_be_positional attribute works, but it makes tag/value lists unduly complex, as you can’t load them with tag=…, value=… – you HAVE to load positionally. We currently ignore this parameter, meaning that we have a tag/value option for any LinkML element

Parameters:
  • cls – Owning class

  • slot – slot definition

  • can_be_positional – True means that positional parameters are allowed.

Returns:

Initializer string

gen_class_variables(cls: ClassDefinition) str[source]#

Generate the variable declarations for a dataclass.

Parameters:

cls – class containing variables to be rendered in inheritance hierarchy

Returns:

variable declarations for target class and its ancestors

gen_classdef(cls: ClassDefinition) str[source]#

Generate python definition for class cls

gen_classdefs() str[source]#

Create class definitions for all non-mixin classes in the model Note that apply_to classes are transformed to mixins

gen_classvars: bool#
gen_constructor(cls: ClassDefinition) Optional[str][source]#
gen_enum(enum: EnumDefinition) str[source]#

Generate an enum class @param enum: EnumDefinition object to be converted into code @return: python code string

gen_enum_comment(enum: EnumDefinition) str[source]#
gen_enum_definition(enum: EnumDefinition, enum_name: str) str[source]#
gen_enum_description(enum: EnumDefinition, enum_name: str) str[source]#
gen_enumerations() str[source]#
gen_import_list() Dict[str, List[str]][source]#

Generate a list of types to import

Returns:

source file followed by elements to import

gen_imports() str[source]#
gen_inherited_slots(cls: ClassDefinition) str[source]#
gen_namespaces() str[source]#
gen_postinit(cls: ClassDefinition, slot: SlotDefinition) Optional[str][source]#

Generate python post init rules for slot in class

gen_postinits(cls: ClassDefinition) str[source]#

Generate all the typing and existence checks post initialize

gen_pv_constructor(pv: PermissibleValue, indent: int) str[source]#

Generate a permissible value constructor in the form

PermissibleValue(text=”NAME_ONLY”) PermissibleValue(

text=”CODE”, description=”…”, meaning=”…”)

@param pv: Value to be constructed @param indent: number of additional spaces to add on successive lines @return: Permissible value constructor

gen_pvs(enum: EnumDefinition) str[source]#

Generate the python compliant permissible value initializers as a set of class variables @param enum: EnumDefinition object to be converted into class variables @return: string containing the enum declaration

gen_pvs_as_setattrs(enum: EnumDefinition) str[source]#

Generate the non-python compliant permissible value initializers as a set of setattr instructions in the form

@classmethod def _addvals(cls):

setattr(cls, “NAME”,
PermissibleValue(

text=”NAME”, description=”description here”))

@param enum: EnumDefinition object to be converted into code @return: string containing the enum declaration

gen_references() str[source]#

Generate python type declarations for all identifiers (primary keys)

gen_schema() str[source]#
gen_slot(slot: SlotDefinition) str[source]#
gen_slotdefs() str[source]#
gen_slots: bool#
gen_type_meta(typ: TypeDefinition) str[source]#
gen_typedefs() str[source]#

Generate python type declarations for all defined types

generatorname: ClassVar[str] = 'pythongen.py'#

Name of the generator. Override with os.path.basename(__file__)

generatorversion: ClassVar[str] = '0.0.1'#

Version of the generator. Consider deprecating and instead use overall linkml version

genmeta: bool#
is_key_value_class(range_name: DefinitionName) bool[source]#

Return True if range_name references a class with exactly one key and one value

Parameters:

range_name – class definition (name)

Returns:

True if meets the special case

key_name_for(class_name: ClassDefinitionName) Optional[str][source]#
mergeimports: Optional[bool]#

True means merge non-linkml sources into importing package. False means separate packages

metadata: bool#

True means include date, generator, etc. information in source header if appropriate

primary_keys_for(cls: ClassDefinition) List[SlotDefinitionName][source]#

Return the primary key for cls.

Note: At the moment we return at most one entry. At some point, keys will be expanded to support

composite keys.

@param cls: class to get keys for @return: List of primary keys or identifiers

process_multiline_string(input: str, prefix_string: str) str[source]#

Process a (potentially multi-line) string, preserving existing formatting

@param input: input string to be formatted @param prefix_string: the text to prefix the first line of the output @return: formatted string

python_uri_for(uriorcurie: Union[str, URIRef]) Tuple[str, Optional[str]][source]#

Return the python form of uriorcurie :param uriorcurie: :return: URI and CURIE form

range_cardinality(slot: SlotDefinition, cls: Optional[ClassDefinition], positional_allowed: bool) Tuple[str, Optional[str]][source]#

Return the range type including initializers, etc. Generate a class variable declaration for the supplied slot. Note: the positional_allowed attribute works, but it makes tag/value lists unduly complex, as you can’t load them with tag=…, value=… – you HAVE to load positionally. We currently ignore this parameter, meaning that we have a tag/value option for any LinkML element

Parameters:
  • slot – slot to generate type for

  • cls – containing class – used to render key slots correctly. If absent, slot is an add-in

  • positional_allowed – True Means that we are in the positional space and defaults are not supplied

Returns:

python property name and initializer (if any)

range_type_name(slot: SlotDefinition) str[source]#

Generate the type name for the slot

schema: Union[str, TextIO, SchemaDefinition, 'Generator']#

metamodel compliant schema. Can be URI, file name, actual schema, another generator, an open file or a pre-parsed schema

uses_schemaloader: ClassVar[bool] = True#

Old-style generator that uses the SchemaLoader and visitor pattern

valid_formats: ClassVar[List[str]] = ['py']#

Allowed formats - first format is default

visit_all_class_slots: ClassVar[bool] = False#

Visitor ClassVar: False means only visit own slots, True means visit all slots

visit_class(cls: ClassDefinition) bool[source]#

Visited once per schema class

@param cls: class being visited @return: Visit slots and end class. False means skip and go on

visit_schema(**kwargs) None[source]#

Visited once at the beginning of generation

@param kwargs: Arguments passed through from CLI – implementation dependent

visit_slot(aliased_slot_name: str, slot: SlotDefinition) None[source]#

Visited once for every slot definition in the schema.

@param aliased_slot_name: Aliased name of the slot. May not be unique @param slot: visited slot

visit_type(typ: TypeDefinition) None[source]#

Visited once for every type definition in the schema

@param typ: Type definition

class linkml.generators.SQLAlchemyGenerator(schema: ~typing.Union[str, ~typing.TextIO, ~linkml_runtime.linkml_model.meta.SchemaDefinition, ~linkml.utils.generator.Generator], schemaview: ~typing.Optional[~linkml_runtime.utils.schemaview.SchemaView] = None, format: ~typing.Optional[str] = None, metadata: bool = <factory>, useuris: ~typing.Optional[bool] = None, log_level: int = 30, mergeimports: ~typing.Optional[bool] = <factory>, source_file_date: ~typing.Optional[str] = None, source_file_size: ~typing.Optional[int] = None, logger: ~typing.Optional[~logging.Logger] = None, verbose: ~typing.Optional[bool] = None, output: ~typing.Optional[str] = None, namespaces: ~typing.Optional[~linkml_runtime.utils.namespaces.Namespaces] = None, directory_output: bool = False, base_dir: ~typing.Optional[str] = None, metamodel_name_map: ~typing.Optional[~typing.Dict[str, str]] = None, importmap: ~typing.Optional[~typing.Union[str, ~typing.Mapping[str, str]]] = None, emit_prefixes: ~typing.Set[str] = <factory>, metamodel: ~typing.Optional[~linkml.utils.schemaloader.SchemaLoader] = None, stacktrace: bool = False, template: ~typing.Optional[~linkml.generators.sqlalchemygen.TemplateEnum] = None, original_schema: ~typing.Optional[~typing.Union[str, ~linkml_runtime.linkml_model.meta.SchemaDefinition]] = None, **_kwargs)[source]#

Bases: Generator

Generates SQL Alchemy classes

See also: SQLTableGenerator

add_safe_aliases(schema: SchemaDefinition) None[source]#
compile_sqla(compile_python_dataclasses=False, pydantic=False, model_path=None, template: TemplateEnum = 'imperative', **kwargs) module[source]#

Generates and compiles SQL Alchemy bindings

  • If template is DECLARATIVE, then a single python module with classes is generated

  • If template is IMPERATIVE, only mappings are generated
    • if compile_python_dataclasses is True then a standard datamodel is generated

Parameters:
  • compile_python_dataclasses – (default False)

  • model_path

  • template

  • kwargs

Returns:

file_extension: ClassVar[str] = 'py'#
generate_sqla(model_path: Optional[str] = None, no_model_import=False, template: Optional[TemplateEnum] = None, foreign_key_policy: Optional[ForeignKeyPolicy] = None, **kwargs) str[source]#
generatorname: ClassVar[str] = 'sqlalchemygen.py'#

Name of the generator. Override with os.path.basename(__file__)

generatorversion: ClassVar[str] = '0.1.1'#

Version of the generator. Consider deprecating and instead use overall linkml version

order_classes_by_hierarchy(sv: SchemaView) List[ClassDefinitionName][source]#
original_schema: Union[SchemaDefinition, str] = None#
serialize(**kwargs) str[source]#

Generate output in the required format

Parameters:

kwargs – Generator specific parameters

Returns:

Generated output

skip(cls: ClassDefinition) bool[source]#
template: TemplateEnum = None#
uses_schemaloader: ClassVar[bool] = False#

Old-style generator that uses the SchemaLoader and visitor pattern

valid_formats: ClassVar[List[str]] = ['sqla']#

Allowed formats - first format is default

class linkml.generators.SQLTableGenerator(schema: ~typing.Union[str, ~typing.TextIO, ~linkml_runtime.linkml_model.meta.SchemaDefinition, ~linkml.utils.generator.Generator], schemaview: ~typing.Optional[~linkml_runtime.utils.schemaview.SchemaView] = None, format: ~typing.Optional[str] = None, metadata: bool = <factory>, useuris: ~typing.Optional[bool] = None, log_level: int = 30, mergeimports: ~typing.Optional[bool] = <factory>, source_file_date: ~typing.Optional[str] = None, source_file_size: ~typing.Optional[int] = None, logger: ~typing.Optional[~logging.Logger] = None, verbose: ~typing.Optional[bool] = None, output: ~typing.Optional[str] = None, namespaces: ~typing.Optional[~linkml_runtime.utils.namespaces.Namespaces] = None, directory_output: bool = False, base_dir: ~typing.Optional[str] = None, metamodel_name_map: ~typing.Optional[~typing.Dict[str, str]] = None, importmap: ~typing.Optional[~typing.Union[str, ~typing.Mapping[str, str]]] = None, emit_prefixes: ~typing.Set[str] = <factory>, metamodel: ~typing.Optional[~linkml.utils.schemaloader.SchemaLoader] = None, stacktrace: bool = False, use_inherits: bool = False, dialect: str = <factory>, inject_primary_keys: bool = <factory>, use_foreign_keys: bool = <factory>, rename_foreign_keys: bool = <factory>, direct_mapping: bool = <factory>, relative_slot_num: bool = <factory>, **_kwargs)[source]#

Bases: Generator

A Generator for creating SQL DDL

The basic algorithm for mapping a linkml schema S is as follows:

  • Each schema S corresponds to one database schema D (see SQLSchema)

  • Each Class C in S is mapped to a table T (see SQLTable)

  • Each slot S in each C is mapped to a column Col (see SQLColumn)

if the direct_mapping attribute is set to true, then no further transformations are applied. Note that this means:

  • inline objects are modeled as Text strings

  • multivalued fields are modeled as single Text strings

this direct mapping is useful for simple spreadsheet/denormalized representations of complex data. however, for other applications, additional transformations should occur. these are:

MULTIVALUED SLOTS

The relational model does not have direct representation of lists. These are normalized as follows.

If the range of the slot is a class, and there are no other slots whose range is this class, and the slot is for a class that has a singular primary key, then a backref is added.

E.g. if we have User 0..* Address, then add a field User_id to Address.

When SQLAlchemy bindings are created, a backref mapping is added

If the range of the slot is an enum or type, then a new linktable is created, and a backref added

E.g. if a class User has a multivalues slot alias whose range is a string, then create a table user_aliases, with two columns (1) alias [a string] and (2) a backref to user

Each mapped slot C.S has a range R

ranges that are types (literals):
  • If R is a type, and the slot is NOT multivalued, do a direct type conversion

  • If R is a type, and the slot is multivalued: * do not include the mapped column * create a new table T_S, with 2 columns: S, and a backref to T

ranges that are classes:

Ref = map_class_to_table(R) - if R is a class, and the slot is NOT multivalued, and Ref has a singular primary key:

  • Col.type = ForeignKey(Ref.PK)

  • if R is a class, and the slot is NOT multivalued, and Ref has NO singular primary key: * add a foreign key C.pk to Ref * add a backref C.S => Ref, C.pk * remove Col from T

  • If R is a class, and the slot IS multivalued

dialect: str#
direct_mapping: bool#
file_extension: ClassVar[str] = 'sql'#
generate_ddl(naming_policy: Optional[SqlNamingPolicy] = None, **kwargs) str[source]#
generatorname: ClassVar[str] = 'sqltablegen.py'#

Name of the generator. Override with os.path.basename(__file__)

generatorversion: ClassVar[str] = '0.1.1'#

Version of the generator. Consider deprecating and instead use overall linkml version

get_foreign_key(cn: str, sv: SchemaView) str[source]#
get_sql_range(slot: SlotDefinition, schema: Optional[SchemaDefinition] = None)[source]#

returns a SQL Alchemy column type

inject_primary_keys: bool#
relative_slot_num: bool#
rename_foreign_keys: bool#
serialize(**kwargs) str[source]#

Generate output in the required format

Parameters:

kwargs – Generator specific parameters

Returns:

Generated output

use_foreign_keys: bool#
use_inherits: bool = False#
uses_schemaloader: ClassVar[bool] = False#

Old-style generator that uses the SchemaLoader and visitor pattern

valid_formats: ClassVar[List[str]] = ['sql']#

Allowed formats - first format is default

class linkml.generators.ShExGenerator(schema: Union[str, TextIO, linkml_runtime.linkml_model.meta.SchemaDefinition, ForwardRef('Generator')], schemaview: Optional[linkml_runtime.utils.schemaview.SchemaView] = None, format: Optional[str] = None, metadata: bool = <factory>, useuris: Optional[bool] = None, log_level: int = 30, mergeimports: Optional[bool] = <factory>, source_file_date: Optional[str] = None, source_file_size: Optional[int] = None, logger: Optional[logging.Logger] = None, verbose: Optional[bool] = None, output: Optional[str] = None, namespaces: Optional[linkml_runtime.utils.namespaces.Namespaces] = None, directory_output: bool = False, base_dir: str = None, metamodel_name_map: Dict[str, str] = None, importmap: Union[str, Mapping[str, str], NoneType] = None, emit_prefixes: Set[str] = <factory>, metamodel: linkml.utils.schemaloader.SchemaLoader = None, stacktrace: bool = False, shex: ShExJSG.SchemaWithContext.Schema = <factory>, shapes: List = <factory>, shape: Optional[ShExJSG.ShExJ.Shape] = None, list_shapes: List[ShExJSG.ShExJ.IRIREF] = <factory>, **_kwargs)[source]#

Bases: Generator

emit_prefixes: Set[str]#

Prefixes to emit, for RDF-based generators

end_class(cls: ClassDefinition) None[source]#

Visited after visit_class_slots (if visit_class returned true)

@param cls: class being visited

end_schema(output: Optional[str] = None, **_) None[source]#

Visited once at the end of generation

@param kwargs: Arguments passed through from CLI – implementation dependent

file_extension: ClassVar[str] = 'shex.rdf'#
generate_header()[source]#
generatorname: ClassVar[str] = 'shexgen.py'#

Name of the generator. Override with os.path.basename(__file__)

generatorversion: ClassVar[str] = '0.0.2'#

Version of the generator. Consider deprecating and instead use overall linkml version

list_shapes: List[IRIREF]#
mergeimports: Optional[bool]#

True means merge non-linkml sources into importing package. False means separate packages

metadata: bool#

True means include date, generator, etc. information in source header if appropriate

schema: Union[str, TextIO, SchemaDefinition, 'Generator']#

metamodel compliant schema. Can be URI, file name, actual schema, another generator, an open file or a pre-parsed schema

shape: Optional[Shape] = None#
shapes: List#
shex: Schema#
uses_schemaloader: ClassVar[bool] = True#

Old-style generator that uses the SchemaLoader and visitor pattern

valid_formats: ClassVar[List[str]] = ['shex', 'json', 'rdf']#

Allowed formats - first format is default

visit_all_class_slots: ClassVar[bool] = False#

Visitor ClassVar: False means only visit own slots, True means visit all slots

visit_class(cls: ClassDefinition) bool[source]#

Visited once per schema class

@param cls: class being visited @return: Visit slots and end class. False means skip and go on

visit_class_slot(cls: ClassDefinition, aliased_slot_name: SlotDefinitionName, slot: SlotDefinition) None[source]#

Visited for each slot in a class. If class level visit_all_slots is true, this is visited once for any class that is inherited (class itself, is_a, mixin, apply_to). Otherwise just the own slots.

@param cls: containing class @param aliased_slot_name: Aliased slot name. May not be unique across all class slots @param slot: slot being visited

visit_schema(**_)[source]#

Visited once at the beginning of generation

@param kwargs: Arguments passed through from CLI – implementation dependent

class linkml.generators.ShaclGenerator(schema: Union[str, TextIO, linkml_runtime.linkml_model.meta.SchemaDefinition, ForwardRef('Generator')], schemaview: Optional[linkml_runtime.utils.schemaview.SchemaView] = None, format: Optional[str] = None, metadata: bool = <factory>, useuris: Optional[bool] = None, log_level: int = 30, mergeimports: Optional[bool] = <factory>, source_file_date: Optional[str] = None, source_file_size: Optional[int] = None, logger: Optional[logging.Logger] = None, verbose: Optional[bool] = None, output: Optional[str] = None, namespaces: Optional[linkml_runtime.utils.namespaces.Namespaces] = None, directory_output: bool = False, base_dir: str = None, metamodel_name_map: Dict[str, str] = None, importmap: Union[str, Mapping[str, str], NoneType] = None, emit_prefixes: Set[str] = <factory>, metamodel: linkml.utils.schemaloader.SchemaLoader = None, stacktrace: bool = False, closed: bool = <factory>, **_kwargs)[source]#

Bases: Generator

as_graph() Graph[source]#
closed: bool#

True means add ‘sh:closed=true’ to all shapes, except of mixin shapes and shapes, that have parents

emit_prefixes: Set[str]#

Prefixes to emit, for RDF-based generators

file_extension: ClassVar[str] = 'shacl.ttl'#
generate_header()[source]#
generatorname: ClassVar[str] = 'shaclgen.py'#

Name of the generator. Override with os.path.basename(__file__)

generatorversion: ClassVar[str] = '0.0.1'#

Version of the generator. Consider deprecating and instead use overall linkml version

mergeimports: Optional[bool]#

True means merge non-linkml sources into importing package. False means separate packages

metadata: bool#

True means include date, generator, etc. information in source header if appropriate

schema: Union[str, TextIO, SchemaDefinition, 'Generator']#

metamodel compliant schema. Can be URI, file name, actual schema, another generator, an open file or a pre-parsed schema

serialize(**args) str[source]#

Generate output in the required format

Parameters:

kwargs – Generator specific parameters

Returns:

Generated output

uses_schemaloader: ClassVar[bool] = True#

Old-style generator that uses the SchemaLoader and visitor pattern

valid_formats: ClassVar[List[str]] = ['ttl']#

Allowed formats - first format is default

visit_all_class_slots: ClassVar[bool] = False#

Visitor ClassVar: False means only visit own slots, True means visit all slots