Debian Codegraph @

docs/gallery/plot_term_set.py

raw
1 """
2 TermSet
3 =======
4
5 This is a user guide for interacting with the
6 :py:class:`~hdmf.term_set.TermSet` and :py:class:`~hdmf.term_set.TermSetWrapper` classes.
7 The :py:class:`~hdmf.term_set.TermSet` and :py:class:`~hdmf.term_set.TermSetWrapper` types
8 are experimental and are subject to change in future releases. If you use these types,
9 please provide feedback to the HDMF team so that we can improve the structure and
10 overall capabilities.
11
12 Introduction
13 -------------
14 The :py:class:`~hdmf.term_set.TermSet` class provides a way for users to create their own
15 set of terms from brain atlases, species taxonomies, and anatomical, cell, and
16 gene function ontologies.
17
18 Users will be able to validate their data and attributes to their own set of terms, ensuring
19 clean data to be used inline with the FAIR principles later on.
20 The :py:class:`~hdmf.term_set.TermSet` class allows for a reusable and sharable
21 pool of metadata to serve as references for any dataset or attribute.
22 The :py:class:`~hdmf.term_set.TermSet` class is used closely with
23 :py:class:`~hdmf.common.resources.HERD` to more efficiently map terms
24 to data.
25
26 In order to actually use a :py:class:`~hdmf.term_set.TermSet`, users will use the
27 :py:class:`~hdmf.term_set.TermSetWrapper` to wrap data and attributes. The
28 :py:class:`~hdmf.term_set.TermSetWrapper` uses a user-provided :py:class:`~hdmf.term_set.TermSet`
29 to perform validation.
30
31 :py:class:`~hdmf.term_set.TermSet` is built upon the resources from LinkML, a modeling
32 language that uses YAML-based schema, giving :py:class:`~hdmf.term_set.TermSet`
33 a standardized structure and a variety of tools to help the user manage their references.
34
35 How to make a TermSet Schema
36 ----------------------------
37 Before the user can take advantage of all the wonders within the
38 :py:class:`~hdmf.term_set.TermSet` class, the user needs to create a LinkML schema (YAML) that provides
39 all the permissible term values. Please refer to https://linkml.io/linkml/intro/tutorial06.html
40 to learn more about how LinkML structures their schema.
41
42 1. The name of the schema is up to the user, e.g., the name could be "Species" if the term set will
43 contain species terms.
44 2. The prefixes will be the standardized prefix of your source, followed by the URI to the terms.
45 For example, the NCBI Taxonomy is abbreviated as NCBI_TAXON, and Ensemble is simply Ensemble.
46 As mentioned prior, the URI needs to be to the terms; this is to allow the URI to later be coupled
47 with the source id for the term to create a valid link to the term source page.
48 3. The schema uses LinkML enumerations to list all the possible terms. To define the all the permissible
49 values, the user can define them manually in the schema, transfer them from a Google spreadsheet,
50 or pull them into the schema dynamically from a LinkML supported source.
51
52 For a clear example, please view the
53 `example_term_set.yaml <https://github.com/hdmf-dev/hdmf/blob/dev/docs/gallery/example_term_set.yaml>`_
54 for this tutorial, which provides a concise example of how a term set schema looks.
55
56 .. note::
57 For more information regarding LinkML Enumerations, please refer to
58 https://linkml.io/linkml/intro/tutorial06.html.
59
60 .. note::
61 For more information on how to properly format the Google spreadsheet to be compatible with LinkMl, please
62 refer to https://linkml.io/schemasheets/#examples.
63
64 .. note::
65 For more information how to properly format the schema to support LinkML Dynamic Enumerations, please
66 refer to https://linkml.io/linkml/schemas/enums.html#dynamic-enums.
67 """
68 from hdmf.common import DynamicTable, VectorData
69 import os
70 import numpy as np
71
72 try:
73 import linkml_runtime # noqa: F401
74 except ImportError as e:
75 raise ImportError("Please install linkml-runtime to run this example: pip install linkml-runtime") from e
76 from hdmf.term_set import TermSet, TermSetWrapper
77
78 try:
79 dir_path = os.path.dirname(os.path.abspath(__file__))
80 yaml_file = os.path.join(dir_path, 'example_term_set.yaml')
81 schemasheets_folder = os.path.join(dir_path, 'schemasheets')
82 dynamic_schema_path = os.path.join(dir_path, 'example_dynamic_term_set.yaml')
83 except NameError:
84 dir_path = os.path.dirname(os.path.abspath('.'))
85 yaml_file = os.path.join(dir_path, 'gallery/example_term_set.yaml')
86 schemasheets_folder = os.path.join(dir_path, 'gallery/schemasheets')
87 dynamic_schema_path = os.path.join(dir_path, 'gallery/example_dynamic_term_set.yaml')
88
89 # Use Schemasheets to create TermSet schema
90 # -----------------------------------------
91 # The :py:class:`~hdmf.term_set.TermSet` class builds off of LinkML Schemasheets, allowing users to convert between
92 # a Google spreadsheet to a complete LinkML schema. Once the user has defined the necessary LinkML metadata within the
93 # spreadsheet, the spreadsheet needs to be saved as individual tsv files, i.e., one tsv file per spreadsheet tab. Please
94 # refer to the Schemasheets tutorial link above for more details on the required syntax structure within the sheets.
95 # Once the tsv files are in a folder, the user simply provides the path to the folder with ``schemasheets_folder``.
96 termset = TermSet(schemasheets_folder=schemasheets_folder)
97
98 # Use Dynamic Enumerations to populate TermSet
99 # --------------------------------------------
100 # The :py:class:`~hdmf.term_set.TermSet` class allows user to skip manually defining permissible values, by pulling from
101 # a LinkML supported source. These sources contain multiple ontologies. A user can select a node from an ontology,
102 # in which all the elements on the branch, starting from the chosen node, will be used as permissible values.
103 # Please refer to the LinkMl Dynamic Enumeration tutorial for more information on these sources and how to setup Dynamic
104 # Enumerations within the schema. Once the schema is ready, the user provides a path to the schema and set
105 # ``dynamic=True``. A new schema, with the populated permissible values, will be created in the same directory.
106 termset = TermSet(term_schema_path=dynamic_schema_path, dynamic=True)
107
108 ######################################################
109 # Viewing TermSet values
110 # ----------------------------------------------------
111 # :py:class:`~hdmf.term_set.TermSet` has methods to retrieve terms. The :py:func:`~hdmf.term_set.TermSet.view_set`
112 # method will return a dictionary of all the terms and the corresponding information for each term.
113 # Users can index specific terms from the :py:class:`~hdmf.term_set.TermSet`. LinkML runtime will need to be installed.
114 # You can do so by first running ``pip install linkml-runtime``.
115 terms = TermSet(term_schema_path=yaml_file)
116 print(terms.view_set)
117
118 # Retrieve a specific term
119 terms['Homo sapiens']
120
121 ######################################################
122 # Validate Data with TermSetWrapper
123 # ----------------------------------------------------
124 # :py:class:`~hdmf.term_set.TermSetWrapper` can be wrapped around data.
125 # To validate data, the user will set the data to the wrapped data, in which validation must pass
126 # for the data object to be created.
127 data = VectorData(
128 name='species',
129 description='...',
130 data=TermSetWrapper(value=['Homo sapiens'], termset=terms)
131 )
132
133 ######################################################
134 # Validate Compound Data with TermSetWrapper
135 # ----------------------------------------------------
136 # :py:class:`~hdmf.term_set.TermSetWrapper` can be wrapped around compound data.
137 # The user will set the field within the compound data type that is to be validated
138 # with the termset.
139 c_data = np.array([('Homo sapiens', 24)], dtype=[('species', 'U50'), ('age', 'i4')])
140 data = VectorData(
141 name='species',
142 description='...',
143 data=TermSetWrapper(value=c_data, termset=terms, field='species')
144 )
145
146 ######################################################
147 # Validate Attributes with TermSetWrapper
148 # ----------------------------------------------------
149 # Similar to wrapping datasets, :py:class:`~hdmf.term_set.TermSetWrapper` can be wrapped around any attribute.
150 # To validate attributes, the user will set the attribute to the wrapped value, in which validation must pass
151 # for the object to be created.
152 data = VectorData(
153 name='species',
154 description=TermSetWrapper(value='Homo sapiens', termset=terms),
155 data=['Human']
156 )
157
158 ######################################################
159 # Validate on append with TermSetWrapper
160 # ----------------------------------------------------
161 # As mentioned prior, when using a :py:class:`~hdmf.term_set.TermSetWrapper`, all new data is validated.
162 # This is true for adding new data with append and extend.
163 data = VectorData(
164 name='species',
165 description='...',
166 data=TermSetWrapper(value=['Homo sapiens'], termset=terms)
167 )
168
169 data.append('Ursus arctos horribilis')
170 data.extend(['Mus musculus', 'Myrmecophaga tridactyla'])
171
172 ######################################################
173 # Validate Data in a DynamicTable
174 # ----------------------------------------------------
175 # Validating data for :py:class:`~hdmf.common.table.DynamicTable` is determined by which columns were
176 # initialized with a :py:class:`~hdmf.term_set.TermSetWrapper`. The data is validated when the columns
177 # are created and modified using ``DynamicTable.add_row``.
178 col1 = VectorData(
179 name='Species_1',
180 description='...',
181 data=TermSetWrapper(value=['Homo sapiens'], termset=terms),
182 )
183 col2 = VectorData(
184 name='Species_2',
185 description='...',
186 data=TermSetWrapper(value=['Mus musculus'], termset=terms),
187 )
188 species = DynamicTable(name='species', description='My species', columns=[col1,col2])
189
190 ##########################################################
191 # Validate new rows in a DynamicTable with TermSetWrapper
192 # --------------------------------------------------------
193 # Validating new rows to :py:class:`~hdmf.common.table.DynamicTable` is simple. The
194 # :py:func:`~hdmf.common.table.DynamicTable.add_row` method will automatically check each column for a
195 # :py:class:`~hdmf.term_set.TermSetWrapper`. If a wrapper is being used, then the data will be
196 # validated for that column using that column's :py:class:`~hdmf.term_set.TermSet` from the
197 # :py:class:`~hdmf.term_set.TermSetWrapper`. If there is invalid data, the
198 # row will not be added and the user will be prompted to fix the new data in order to populate the table.
199 species.add_row(Species_1='Mus musculus', Species_2='Mus musculus')
200
201 #############################################################
202 # Validate new columns in a DynamicTable with TermSetWrapper
203 # -----------------------------------------------------------
204 # To add a column that is validated using :py:class:`~hdmf.term_set.TermSetWrapper`,
205 # wrap the data in the :py:func:`~hdmf.common.table.DynamicTable.add_column`
206 # method as if you were making a new instance of :py:class:`~hdmf.common.table.VectorData`.
207 species.add_column(name='Species_3',
208 description='...',
209 data=TermSetWrapper(value=['Ursus arctos horribilis', 'Mus musculus'], termset=terms),)