


image::https://specifications.openehr.org/images/openEHR_logo_RGB.svg["openEHR logo",align="center"]

# Data Types Information Model





## Acknowledgements

### Editor

* Thomas Beale, Ars Semantica (UK); openEHR Foundation Management Board.

### Contributors

This specification benefited from wide formal and informal input from the openEHR and wider health informatics community. The openEHR Foundation would like to recognise the following people for their contributions.

* Silje Ljosland Bakke, RN, Nasjonal IKT HF, Norway
* Pieter Bos, Senior Software Engineer, Nedap, Netherlands
* Rong Chen MD, PhD, Cambio Healthcare Systems, Sweden
* Matthew Darlinson, PhD, CHIME, UCL, UK
* Heath Frankel, CTO Ocean Informatics, Australia
* Peter Gummer, senior developer, Ocean Informatics, Australia
* Andrew Goodchild, PhD, senior research scientist DSTC, Australia
* Grahame Grieve, Kestral Systems, Australia
* Sam Heard MD, Ocean Informatics, Australia
* Sebastian Iancu, Architect, Code24, Netherlands
* Dipak Kalra MD, PhD, Professor Health Informatics, CHIME, UCL, UK
* Bostjan Lah, Architect, Marand, Slovenia
* Heather Leslie MD, FRACGP, FACHI, GAICD, Atomica Informatics, Australia
* David Lloyd (ret), CHIME, UCL, UK
* Kristoffer Lundberg, chief architect, Cambio, Sweden
* Chunlan Ma PhD, MD, Ocean Informatics, Australia
* Jan Mewes, KS-plus.org, India/Germany
* Bjørn Næss, DIPS, Norway
* Pablo Pazos Gutierrez, CaboLabs, Uruguay
* Peter Schloeffel MD, Ocean Informatics, Australia
* Erik Sundvall PhD, Linkoping University, Sweden
* Bert Verhees, Senior developer, Netherlands
* Zar zar Tun, DSTC, Australia

### Support

The work reported in this paper has been funded in part by the following organisations:

* University College London - Centre for Health Informatics and Multi-professional Education (CHIME);
* Ocean Informatics; 
* Distributed Systems Technology Centre (DSTC), under the Cooperative Research Centres Program through the Department of the Prime Minister and Cabinet of the Commonwealth Government of Australia.

Special thanks to David Ingram, Emeritus Professor of Health Informatics at UCL, who provided a vision and collegial working environment ever since the days of GEHR (1992).




ifdef::package_qualifiers[]
endif::[]

# Preface

## Purpose

This document defines the openEHR Data Types Information Model, used throughout the openEHR Reference Model.

The intended audience includes:

* Standards bodies producing health informatics standards;
* Academic groups using openEHR;
* The open source healthcare community;
* Solution vendors;
* Medical informaticians and clinicians interested in health information.
* Health data managers.

## Related Documents

Prerequisite documents for reading this document include:

* The {openehr_overview}[openEHR Architecture Overview^];
* The {openehr_rm_support}[openEHR Support Information Model^].

## Status

This specification is in the STABLE state. The development version of this document can be found at {openehr_rm_latest_data_types}[{openehr_rm_latest_data_types}^].

Known omissions or questions are indicated in the text with a 'to be determined' paragraph, as follows:
*TBD*: (example To Be Determined paragraph)

## Feedback

Feedback may be provided on the https://discourse.openehr.org/c/specifications/rm[openEHR RM specifications forum^].

Issues may be raised on the https://specifications.openehr.org/components/{component}/open_issues[specifications Problem Report tracker^].

To see changes made due to previously reported issues, see the https://specifications.openehr.org/components/{component}/history[{component} component Change Request tracker^].

## Conformance

Conformance of a data or software artifact to an openEHR specification is determined by a formal test of that artifact against the relevant openEHR Implementation Technology Specification(s) (ITSs), such as an IDL interface or an XML-schema. Since ITSs are formal derivations from underlying models, ITS conformance indicates model conformance.


# Background

## Scope

The data type specification presented here defines the clinical/scientific data types which are used in
other openEHR models. Harmonisation of data types between information models used by related
services in a health information infrastructure is essential to reducing the conversion work and potential
for errors between these services. Accordingly, the openEHR data type specification is intended to
work not only for the EHR, but also for other models defined by openEHR, such as the openEHR
demographic and terminological models.

The types described here have been derived from data types used in Good Electronic Health Record cite:[GeHR_Aus2001], the Synapses project 
cite:[Synapses_Req_A], and various standards {iso_13606-1}[ISO 13606-1^], {iso_13606-3}[ISO 13606-3^] and {hl7v3_data_types}[HL7v3 Data Types^].

## Design Criteria

Over and above the need to satisfy the functional requirements of clinical data, three concerns have
driven the design of the openEHR data types:

. clarity of expression
. ease of implementation
. interoperability with data types from other standards

The first of these has led to models which try to clearly convey the semantics of types required by the
clinical domain. The use of constraints (pre- and post-conditions and class invariants) and a comprehensible
class structure ensures formal self-consistency, correct type-substitutability and implementability
in object-oriented formalisms. Types have been designed so as not to clash with norms of
object-oriented languages and libraries, in particular, class names and the inbuilt types. Accordingly,
all types presented here have a logical name commencing with `DV_`, ensuring that there is no clash
with a type in the implementation formalism, hence the type `DV_DATE` presented here will not be confused
with the type `DATE` which appears in many programming languages or libraries.

Object-oriented languages which have been considered include IDL, C++, Java, C#, Eiffel, Delphi
and Python. Each of these languages obeys some variant of the well-known semantics of classes,
encapsulation, typing and inheritance. The data types described here follow the tenets of object-orientation
defined in UML most closely, while being careful not to invalidate their implementation in
any language. The models have all been validated by implementation in the Eiffel language, the closest
available semantic fit for UML, and currently the most powerful of mainstream object-oriented
formalisms.

Implementability in XML-schema has also been an important design criterion, and the current data
types remove many of the problems which the GEHR and CEN data types presented for XMLschema.
There has been no attempt to support XML-DTD, since it has no type system, and cannot
reliably be reasoned about in an object-oriented way.

To simplify implementation in all object-oriented formalisms, including IDL, programming languages
and XML-schema, multiple inheritance has generally been avoided (where it is used, only one
branch corresponds to substitutability). Generic classes have been used, since they significantly clarify
the model. Type genericity is available in Java, C#, Eiffel, C++, and some other languages. For
languages not having it, there is a well-known transformation from models containing generic classes
to classes for non-generic types systems.

Implementability in relational databases has also been considered, and appears relatively straightforward,
since only the data view of the types needs to be represented. Many implementations are likely
to use only a single String or XML string to represent each entire data instance, which significantly
simplifies things.

## Prior Work

Four other type systems for clinical data, namely the GEHR data types, the HL7 v3 data types, the
{iso_13606-1}[ISO 13606-1^] data item types, and the {omg_corbamed}[OMG Corbamed^] data types were carefully scrutinised in order to
ensure a) that all needed types were covered in the openEHR specification, and b) that data conversion
will be possible. Concepts from all three are cross-referenced throughout this specification where
possible.

Because the {hl7v3_data_types}[HL7v3 data type specification^] is a widely available and comprehensive specification for
clinican data types, particular attention has been paid to incorporating its semantics, as well as fixing
errors or shortcomings. While there are differences both in design approach and in detail, a significant
debt must be recognised to the authors of this work, from which many ideas in the present specification
were drawn. A detailed discussion is found in <<Comparison with HL7v3 Types>>.


# Introduction

## Overview

This specification describes a set of types suitable for use in scientific, clinical and related information
structures. In order for such types to exist, a set of primitive types is assumed, namely `Integer`,
`Real`, `Boolean`, `Character`, `Octet`, `String`, `List<T>`, `Set<T>`, and `Array<T>`. These have
standard definitions in the OMG object model used in UML, OCL, and are available in almost all
type systems. The exact assumptions are described in the openEHR Support Information Model. A
number of symbolic definitions (similar to constants in programming) are also described in the Support
IM.

The data types described here are named with the class prefix `DV_`, and inherit from the class
`DATA_VALUE`. They have two distinct uses in reference models. Firstly, they may be used as 'data
values' in reference model structures wherever the `DATA_VALUE` class appears, for example, in the
EHR Reference Model via the `ELEMENT`.`_value_` attribute. Additionally, specific subtypes of the data
types described here can also be used as attribute types in other classes in reference models, such as
date/times, coded terms and so on. The difference is that in the former case, only subtypes of
`DATA_VALUE` may be used, whilst in the latter case, other types may be used as well, from the
assumed set of basic types.

## Package Structure

The package structure of the openEHR data types is illustrated below.

.rm.data_types packages
image::UML/diagrams/RM-data_types-packages.svg[id=rm_data_types_packages, align="center"]


# Basic Package

## Overview

The `data_types.basic` package, illustrated below, contains types for the concepts of bistate,
state (in a state machine) and real-world entity identifiers (see the openEHR Common IM for a
discussion on identifier types).

.rm.data_types.basic package
image::UML/diagrams/RM-data_types.basic.svg[id=rm_data_types_basic, align="center"]

### Requirements

#### Bi-state Values
One of the most basic types of data is boolean or bi-state data. The need here is for a type which both
includes a boolean value, and which inherits from the type `DATA_VALUE`, enabling it to be used as an
`ELEMENT`.`_value_`.

#### State Machine States

A type is required to represent state values of a state machine. In a simple system of data types, a simple
integer would appear sufficient to perform this job. However, in an archetyped framework, a distinct
type is required, so that it can be archetyped not by the constraints used for integers, but by a
state machine definition instead. The type `DV_STATE` is provided for this purpose. An example of a
state machine which models the lifecycle of a medication order is illustrated in the figure below. This definition
would appear in an archetype; the values of a `DV_STATE` object are then restricted to the values
of the states in the definition.

.Example State Machine for Medication Orders
image::{doc_name}/diagrams/state_machine.png[id=state_machine_med_order, align="center", width=80%]

#### Real-world Entity Identification

Real world entities (RWEs) such as people, car engines, invoices, and appointments may all be
assigned identifiers. Although many of these are designed to be unique within a jurisdiction or issuing
space, they are often not, due to data entry errors, bad design (ids which are too small or incorporate
some non-unique characteristic of the identified entities), bad process (e.g. non-synchronised id issuing
points); identity theft (e.g. via theft of documents of proof or hacking). In general, while some real
world identifiers (RWIs) are 'nearly unique', none can be guaranteed so. Therefore, from a strict
computatoinal point of view, RWIs are not treated as reliable identifiers, but as attributes of their
owning objects, in the same ways as names and addresses for example.

Examples of RWE identifiers which are intended to be unique within the space of the issuing authority
or organisation include:

* driver's licence id
* social security number
* passport number
* prescription id

The defining logical characteristic of RWE ids is that they continue to identify the entities in question,
regardless of how they change in time; for example a social security number does not change
when someone changes their hair colour or even their gender (both of which attributes may be
recorded in the database). In general it should be the case that if two RWE ids are equal, they refer to
the same RWE.

At a practical level, RWE identifiers differ from information entity (IE) identifiers in that the former
are generally not assigned by the computing infrastructure that uses them - that is to say, in the production
computing system, such identifiers are no different from other characteristics of the entity,
such as names or addresses.

Note: Some messaging standards make use of a "time validity" or similar attribute on identifier datatypes. 
The recommended way of representing validity timespans of identifiers in openEHR is to model this using archetypes
and templates so that regional or use-case specific needs can be better represented.

### Design

The model defined here in the `DV_IDENTIFIER` class allows the recording of three things as part of identifying an item of interest:

* the identifier given to the item of interest (mandatory).
* the issuing authority of the kind of id used (e.g. it might be the federal department of health) (optional);
* the assigner of the id to the item being identified. This is usually the organisation which created the item being identified (optional);

In addition, a type of item being identified can also be recorded, such as 'driver's licence' or 'Medicare card'. All fields are text fields, rather than coded, as no definitive vocabularies are available. However, some useful sources of terms exists, such as https://www.hl7.org/fhir/v2/0203/index.html[HL7v2 Table 0203^] for the `type` field. If using the latter, it is recommended to use the 'description', not the code.

Only the `identifier` field is mandatory to allow for use cases in which the other fields cannot be populated. However it is strongly recommended to populate the `type` and `issuer` fields where possible. In many cases the `issuer` and `assigner` have the same value, however two fields allow for the situation in which a central issuer provides blocks of identifiers (typically on some kind of form or other paperwork) to other organisations who then assign them to individuals, as is often done with prescription identifiers.

See the {openehr_rm_support}#_identification_package[Support IM specification^] for a further discussion of RWEs and IEs, and the definition of IEs in openEHR.

## Class Descriptions





# Text Package

## Overview

The `rm.data_types.text` package contains classes for representing all textual values in the health record, including plain text, coded terms, and narrative text. It is illustrated below.

.rm.data_types.text package
image::UML/diagrams/RM-data_types.text.svg[id=rm_data_types_text, align="center"]

### Requirements

The sections below describe the requirements of text data types. Two overriding principles should be noted at the outset with regard to text.

. Regardless of what terminologies are (or are not) available to the clinician and/or the software, the primary requirement is that in all cases clinicians are able to record exactly what they want to say. This means that if they want to record something very general, such as "cold" or a very specific term such as "Ross River virus infection" they should be able to, whether or not the appropriate coded terms are available. However, the facility should be available to additionally code any such textual item, at the time or indeed at some later time, so as to satisfy reporting or other needs.
. It is assumed that any client of terminology, such as the EHR, uses a terminology service which provides a complete interface to the terminology. The design of the `DV_CODED_TEXT` type reflects this. Accordingly, there is no concept of "post-coordination" outside the terminology environment allowed by the data types described here: the only thing that is available from the terminology service is a key which refers to a lexical entity, which may be a single term or a code phrase, and which may be part of a reference terminology and/or linked to element(s) of underlying ontologies. It is also assumed that there is no direct access to any particular terminology; access to all terminologies (whether simple coded lexicons or large semantic networks) is via the same abstract interface.

Terminology Ids are likely to be of various types.

. Terminology Id = `"local"`: this constant value means that the origin of allowable values is described within the archetype. This is coded to allow translation. The local archetype then only needs the set of codes and the local translation. The archetype may contain a translation table if required.
. Terminology Id = `"[authority]"`. This might be `"openehr"`, `"centc251"`, `"hl7"`, etc;
. The variant Terminology Id = `"[authority]:[Domain value set]"` could also be supported, although it should not generally be necessary, since all codes should be unique within a given issuing authority. Examples might be `"openehr:event math function"`, `"hl7:gender"`;
. Terminology Id = `"SNOMED-CT"`, `"ICD10AM"`, etc. Identifiers of this kind must be unique values in an accepted set of terminologies from an authoritative source. These MUST be universally known. In openEHR, names from the US National Library of Medicine's UMLS terminology name list are used. See the `terminology` package in the {openehr_rm_support}#_terminology_package[Support IM specification^] for details.

#### Narrative Text

Narrative text items are used in the EHR in a number of cases, including:

* values of coded attributes in the reference model;
* recording of subjective or imprecise patient responses, particularly quantities or dates not deemed sufficiently precise to be represented using structured quantitative or date/time date types;
* recording of narrative statements, e.g. visual observations;
* recording of tracts of prose, e.g. overall findings and conclusions, prognoses;
* recording of values that would normally be coded, but for which no code and/or no terminology service is available.

While narrative text items themselves are not themselves coded, they may have code phrases associated
with them, as described below under Mappings, and may be mixed within a paragraph with
coded items.

#### Terminological Entities

Textual entities available in a terminology service are used in the health record to enable processing,
from simple queries to decision support. Reasons for using terminology include the following.

* To guarantee interoperability of meaning. For instance, if the term "cold" is recorded in plain text, it could be interpreted as "feeling cold", "C.O.L.D" (chronic obstructive lung disease), "rhinorrhoea", "coryza" or "U.R.T.I. (upper respiriatory tract infection), among others. If, however, it is coded from a terminology such as {who_icd}[ICD10^] or {snomed_ct}[SNOMED CT^], any party reading the data (including software) knows the intention, since the meaning of the code in the terminology is unambiguous.
* To standardise textual renderings of terms and avoid informal shorthand. For example, practitioners wanting to write "systolic blood pressure" write things like "systolic BP", "systolic bp", "sys. BP." and so on; use of coded terms ensures that such abbreviations are either avoided, or associated with an unambiguous meaning.
* For unambiguous naming of problems, medications or diagnoses for support of knowledgebased tools such as prescribing packages and other decision support applications.
* For standardised names of things in the record e.g. a heading of "Physical examination" or an entry such as "Differential diagnosis".
* For finite sets of values ('value sets'), e.g. Blood Group = 'A|B|AB|O'.
* For classifying other data for the purpose of statistical studies, e.g. by putting ICD disease group classifiers on actual disease names entered in health records.

A basic requirement for interoperability of text items, coded using terms (i.e. where the text is the
official rubric for the code), is that both the rubric and the code (or 'code-phrase') must be recorded,
to ensure the originally intended text is retained for receivers of EHR information who do not have
access to the terminologies used at the origin. However, where a terminology service is available, the
key can be used to unambiguously locate the string value of the term, and can also be used to find
translations in other languages. (Note that these comments do not apply to mappings, which are
described below).

In some terminologies, there are semantic networks of links emanating from most coded terms,
which classify them or relate them to other terms. Such links provide a means for decision support to
make inferences about specific things found in the record. For instance if the term "pneumonia" is
found, queries to the terminology service can be made in order to deduce that the patient has both a
"infection" and a "disease of the respiratory system" (assuming pneumonia is classified under these more
general terms in the terminology).

This specification assumes the existence of a terminology service which is responsible for interrogating
actual terminologies and performing _validated coordination_ of terms, i.e. creating combinations
deemed valid by the underlying source terminology, potentially without even assigning a new code to
the result. All validated coordination is carried out inside the terminology service, and any 'term'
made available by the service is already 'coordinated'. The difference between 'pre-coordinated' and
'post-coordinated' terms is that the former have a single code, whereas the latter have a code phrase,
or expression that is interpretable by the terminology. For example, the coordination "foot, left" (a
shorthand way of writing the relationship "foot has-laterality left") could be created by the terminology
service from the source terms "foot", "left" and "has-laterality" from a terminology such as
SNOMED CT. Any such coordination must be valid within the source terminology, i.e. correspond to
valid relationships defined therein.

The semantics attached to post-coordinations of terms may differ. Two categories of coordination
described in the literature are 'qualification' and 'modification'. A common definition of the first is
that qualification 'narrows meaning' - i.e. creates a new term whose possible real world instances are
within the set denoted by the original root term. Modification on the other hand changes the meaning
of a root term. Various cases are described below under Meaning Modification. Both coordination
types are assumed to be managed by the terminology service.

Coded terms may also be mapped to terms from other terminologies, which may be intended as
equivalents, classifiers, or something in between. The section below on Mappings deals with these.

#### Integration Scenarios

In cases where openEHR data is used to represent data originally represented in other formats, one common requirement is to be able to represent both the term chosen by the user at data capture time, and also the corresponding preferred term, where the two are different. This allows both the user's specific choice and the 'standard term' to be captured.

Secondly, where term mappings are represented it is useful to be able to capture not just the code or code-phrase of the mapped term, but the preferred term or expression text, in order to make the mapped term self-standing in the data.

#### Text Formatting

In modern information systems in all industries, the ability to visually format text exists. EHR systems are no different, and authors of narrative text parts of the health record expect to be able to create longer tracts of text that include paragraphs, bolding, bullet lists and other typical structures, as well as simple atoms of text. Generally speaking, the text associated with a coded term is a simple string, devoid of formatting or newlines, and if the text is a direct copy of the rubric (i.e. term) from a terminology, this will almost always be the case. However there is no guarantee that this will not change in the future, with perhaps newlines and e.g. bolding being used in 'rich text' rubrics.

Clinicians need the freedom to maximise clarity of any text they write, and therefore should be able to include a reasonable level of formatting in text.

### Design

All atomic text items are either instances of the type `DV_TEXT` or of `DV_CODED_TEXT`. The type `DV_TEXT` should be used wherever a coded or non-coded text item is allowed, while the type `DV_CODED_TEXT` should be used wherever a text item must be coded. The former allows the representation of text (`_value_` attribute) with optional formatting and hyperlinking (see <<_formatting_and_hyperlinking>> below). The latter class `DV_CODED_TEXT` captures the association of two things:

* the code of a term known in the terminology service, recorded in the `_defining_code_` attribute of type `CODE_PHRASE`;
* the text rubric of the term, recorded in the `_value_` attribute (inherited from `DV_TEXT`).

The attribute `CODE_PHRASE._code_string_` records a term code or code expression which may be used as an argument to a retrieval function in the terminology service interface to obtain the definition of the term or expression.

The model of `DV_CODED_TEXT` is designed to capture the _actual_ term chosen by the user or software at runtime, i.e. preferred term or synonym (for terminologies supporting synonyms), or a post-coordination of underlying distinct terms if an expression was chosen as the term (such as an expression supported by SNOMED CT). A `DV_CODED_TEXT` instance is used if the final textual value chosen by the user is the exact term text (preferred or other) returned by the terminology service for the key (i.e. `_code_string_` value). If the user makes even the slightest modification during data entry, a mapping (see <<Mappings>>) to a `DV_TEXT` should be used instead.

*Deprecated*: The type `DV_PARAGRAPH` was used to represent larger tracts of text built from lists of `DV_TEXT` instances, i.e. instances of `DV_TEXT` and `DV_CODED_TEXT`. Such text is now represented as plain text with new lines or markdown text, [as described below](#_formatting_and_hyperlinking).

### Qualification

Qualification is the process of making a term more specific through the post-coordination of additional
terms. It occurs when a terminology defines relationships between a primary term and other
terms that qualify the primary. For example a coordination using the term "bronchitis" which creates
a qualified term might be 'acute bronchitis'; all real world instances of the latter are also instances of
the former.

### Meaning Modification

Terms that change the meaning of other terms are often known as 'modifiers'. The difference
between modification and qualification is that modifiers change the meaning so that the modifed term
as a whole does _not_ refer to instances of the unmodified term. We describe below the particular types
of modifiers and how they are represented using the text data types.

#### Mode-changing Terms

One class of modifers is exemplified by the addition of words like 'risk of', 'fear of', 'history of'
and so on. These are sometimes called _mode-changing_ terms, since they change the 'mode' of the
root term from the present to the past ('history of'), a potential future ('risk of') or some other possible
reality. Terms which are modified in this way should never be matched in queries searching for
the root term; for example, a query for 'coronary diease' (of the patient) should not match 'family
history of coronary disease'.

#### Context Sensitivity

There are many terms whose meaning is changed by the context in which they are stated, such as
within a certain kind of note or test result. Consider the following:

* a blood sugar level after a 75gm oral loading has a different meaning than a fasting blood sugar;
* a systolic blood pressure in the pulmonary artery has a different meaning than a systemic arterial blood pressure;
* 'total hip replacement' in the context of a 'planned procedure';
* 'meningitis' in the context of a 'differential diagnosis'.

#### Negation

Negation is a special kind of mode change and has been a serious design challenge in the past,
because modifiers like 'not' or 'no' only make sense when attached to some terms, and create nonsensical
values or ambiguities by arbitrarily association with other terms.

#### Representation of Meaning-Modifying Terms

Rather than provide explicit features for representing modifier terms within `DV_CODED_TEXT`, the
general principle underlying representation of all post-coordinations other than qualifications, is that
a higher-level, archetyped structure such as an `ENTRY` (defined in the EHR RM), is a _minimal indivisible
unit of information_. Such higher-level entities can have internal structure, and it is possible (and
desirable) to achieve the effect of combinations of terms through this structure. In the case of `ENTRY`,
it will be via structuring of `CLUSTER`/`ELEMENT` objects. The general rule is: to obtain the full meaning
of any terms found in the record, all of the node names in any `ENTRY` (coded or not) must be considered
from the root to the relevant leaf. Conversely, the "final" meaning of any term in the record
cannot be known in isolation from the rest of the terms in the structure.

Accordingly, the concept "family history of coronary disease" is represented as an `ENTRY` whose root
is named (for example) "subject family history", and which includes further structure, which may be
in greater of lesser detail; the coded term "coronary disease" would appear somewhere in this structure.
The actual structure is completely defined by appropriate archetypes. Contrary to some perceptions,
there is no general way to represent concepts such as "family history of coronary disease",
since it will vary depending on how much detail is recorded. Where some GPs routinely record just
the simplest form, others may record the details of which family members had heart problems and
exactly what they were.

The same approach is used for context-dependent terms. Archetypes defining contexts such as
"planned procedures" or "differential diagnosis" will use these terms as their root nodes; as a result,
the meaning of any term appearing below the root can only be understood by including the root. Once
again, the exact structures are completely dependent upon archetyping, and may be simple or quite
sophisticated.

Negations are more complex than might first be apparent and are best handled by good archetype
design. Terminologies might provide a term such as "No known allergies" which is helpful. But if
someone has an allergy of some sort, the medicolegal requirement might be to record that the person
has no known allergies to penicillin or another class of medication that is being prescribed. The often 
proposed approach of using a generic negation 'modifier' to deal with such issues results in further
problems. Consider the use of negation with liver - "no liver", "no palpable liver", "no liver disease",
"no history of liver disease", "no liver function", "no liver function tests". The meaning of negated
terms may be non-sensical and difficult to interpret.

A basic principle of dealing with negatives is to realise that most naïve suggested use cases are quite
ambiguous as stated. Does "no allergies" mean "no reported episode of allergy", "no allergic reactions
ever", "no known allergies to medication" or something else? Does it mean that these statements
are taken as given by the patient, or determined by tests? Like all medical phenomena, allergies
must be described in some detail for the EHR to be of any real use. Almost inevitably, this precludes
the use of negated terms. Since the actual information structure will be determined in advance by
archetype designers, clinicians will almost never be in the situation of having to negate a term. However,
if the need does arise, it should be dealt with by a negative or quantitative answer, i.e. a value
rather than a name. For example, in any `ENTRY` describing current problems, the clinician may record
the name/value pair "allergies: NONE". Here, "allergies" will be a `DV_CODED_TEXT`, and "NONE"
will be either a `DV_CODED_TEXT` or a `DV_TEXT`; the two will be associated by a containing object,
such as an instance of the `ELEMENT` class from the EHR RM. There is no explicit model of negation in the openEHR Reference Model. Negation statements are normally solved by specific 'exclusion' archetypes.

### Mappings

In a number of circumstances, both plain text and coded text items are mapped to terms from other
terminologies. In theory, this should never occur, since it means that relationships between terms
which should only be knowable in the knowledge base (in the form of the terminology service, or
something else) are being created and transmitted as part of EHR information, potentially invalidating
or overriding the knowledge base. Where mappings are required, the proper approach is to create thesauri
within the knowledge environment, and map through them. Unfortunately, in some cases, activities
in the real world do not respect the information/knowledge boundary, hence the model described
here includes an explicit mapping concept, which itself includes a "purpose" and a "match" indicator.
Matching corresponds to the categories described below.

#### Classification (Broader Terms)

Any text item, whether coded or not, may be classified with a coded term, for research, reporting and
decision support purposes. For example, a GP working in tropical Australia may wish to write "Ross
River infection", and be working with ICD9, which does not contain this term (although ICD9-CM
does). He or she will use a plain text item, but will still be able to map it to an ICD9 classifier, such as
the code for "arbovirus infection NOS". The same approach can be used for adding a classifying term
to a coded text item. The utility of classifier terms is various: they allow decision support to make
more powerful inferences; in situations where the available terminologies do not provide the classification
inbuilt, and where it is known that not all users of EHR data will have terminologies available.
In data terms, classification mapping can be visualised as illustrated below.

.Plain Text and Coded Text with Classifier(s)
image::{doc_name}/diagrams/coded_text_mappings.png[id=coded_text_mappings, align="center", width=70%]

Classifying mappings are represented by adding a term to the mappings list of the original term. Each
mapping is explicitly represented with an instance of `TERM_MAPPING`, which indicates both the term
being associated with the original text item, and a value of '>' for the match attribute, which indicates
that the mapping is "broader". The possible values of the match attribute are '>' (broader), '<' (narrower),
and '=' (equivalent); they are taken from the ISO standards {iso_2788}[ISO 2788 - Guide to Establishment and development of monolingual thesauri^] and {iso_5964}[ISO 5964 - Guide to Establishment and development of multilingual thesauri^].

#### Equivalent / Synonymous Terms

Data from pathology laboratories has often been coded using a terminology local to the laboratory,
due to lack of or economic unfeasibility of using existing widespread terminologies for the job. However,
some laboratories also supply a nearest equivalent code from a well-known terminology such as
{loinc}[LOINC], to enable the receiver of the data to process it in a more standard fashion. Here, "equivalence"
is taken to mean a term of the same meaning but from a different vocabulary.

Another instance where equivalent terms might be supplied is to effect the translation of terms across
specialist vocabularies such as nursing vocabularies when sharing EHRs across jurisdictions.

In theory, the cleanest way for senders and receivers of data coded with both a local and a more standard
equivalent to deal with the mapping problem is for the originator of the local terminology to provide
a complete thesaurus of translations into one or more recognised terminologies. However, in
practice, laboratories using the HL7 v2.x messaging standard usually encode a primary term and
equivalents with the HL7 CE data type, meaning that equivalents are included only with the term they
are used with. A similar pragmatic approach to mapping equivalent terms in the EHR is likely to be
used with the data types described here, and can be effected with the same mapping approach as for
classification.

A further situation in which text values - this time plain text - is mapped to equivalent terms is when
natural language processing is used to generate coded terms for existing free-text prose. The aim of
such processing is to detect word phrases and associate them with a coded term of the same meaning,
without obliterating the original text. In terms of the model described here, a `CODE_PHRASE` is associated
with a `DV_TEXT` instance via the mappings attribute.

In all cases with equivalents, the value of the match attribute is '=', indicating that the mapping is a
synonym.

#### More Specific Mappings (Narrower Terms)

Occasionally, there is a need to create a mapping to a term of narrower meaning than the original text
item. Circumstances in which this occurs include when a clinician wants to record a syndrome such as
"croup" or "influenza", but the terminology does not contain these general terms, although it does
contain more specific terms, e.g. "viral laryngo-tracheitis" or "influenza type A". Clearly the clinician
should be allowed to record what he/she wants (as plain text if necessary), but it should also be possible
to add a mapping to the more precise term. For mappings to narrower terms, the value of the
match attribute is '<'.

#### The Unified Medical Language System (UMLS)

It has been argued in GEHR cite:[GeHR_Aus2001] that UMLS reference terms should also be supplied with occurrences
of coded terms, in the form of the UMLS concept unique identifier, or "CUI". UMLS is a way
of encoding terms developed at the National Library of Medicine in the United States, and consists of
a meta-thesaurus, in which terms from any extant term set (such as {who_icd}[ICDx^], {snomed_ct}[SNOMED CT^], READ) can be
cross-referenced. UMLS CUIs could turn out to be extremely useful for decision support and reporting.

The proper use of UMLS is that terms from particular terminologies are passed to a UMLS interface
and a CUI + rubric received in response. However, the mapping approach described above could also
be used to map UMLS CUIs to existing text or terms in an EHR; in this case, a `DV_CODED_TEXT` is
constructed for each UMLS "term", where the code is the CUI and the rubric is the text rendering of
the CUI (guaranteed unique in UMLS). The same approach can be used for any other thesaurus
which becomes available in the future.

#### Legacy Mapping Scenarios

In cases where legacy data has to be converted to openEHR-compliant data, and only codes are available,
e.g. ICD or ICPC codes, the following approach is recommended:

* create a new `DV_TEXT` whose value is "(not available)"
* add a mapping to the `DV_TEXT`, with:
** `_purpose_` = `"legacy conversion"`
** `_match_` = `"="`
** `_target_` = `CODE_PHRASE` object whose `_code_string_` and `_terminology_id_` are set to correspond to the available code in the legacy data.

This expresses the reality that no text was ever recorded in the legacy system; rather a code was recorded directly in the data field. In the converted data, this code is more correctly considered a mapping.

### Language Translations

In most cases the natural language of a text object is known from the enclosing Entry (i.e. Observation)
or other enclosing context. Where it is different (e.g. a German sentence within an English language
diagnosis), or there is no enclosing context, the `DV_TEXT._language_` attribute can be set to
indicate the language of the text item.

### Formatting and Hyperlinking

Formatted text is represented by `DV_TEXT` and `DV_CODED_TEXT` instances. In versions _prior to RM Release 1.0.4_, `DV_PARAGRAPH` was provided as a way to represent larger tracts of text containing newlines and formatting of sub-sections, with each subsection being represented by one `DV_TEXT` or `DV_CODED_TEXT`.

WARNING: `DV_PARAGRAPH` is now deprecated, and all text should be represented using the `DV_TEXT` or `DV_CODED_TEXT`. For legacy reasons, `DV_PARAGRAPH` remains legal, and should be supported in at least a basic way.

Formatting of the text in the `_value_` field of `DV_TEXT` and `DV_CODED_TEXT` instances may be indicated via the optional `_formatting_` attribute. How this attribute is used has changed from initial versions of the openEHR Reference Model.

WARNING: Additionally, the `_value_` field was assumed to contain no newlines. This assumption is no longer made starting from RM Release 1.0.4, since `DV_PARAGRAPH` is no longer used to represent paragraphs.

A common model of text processing is of a processing pipeline that consumes readable text containing markings, which is then rendered into HTML, PDF or some other rendering format, and then displayed by a tool such as a web browser that consumes the latter format. Historical approaches to marking text were known as 'markup', such as nroff, troff, Latek, and then more recently, numerous formats whose base syntax is XML. These formats all have the disadvantages of poor human readability in raw form, and being specific to particular rendering engines, and are starting to fall out of favour for uses involving human reading of the raw text. Another common approach to formatting text is to use the _output format_, usually HTML, to express e.g. fonts, bolding etc. This is also problematic for human readability, being complicated by the use of CSS classes in tags, which then need to be defined.

*Deprecated*: This was the original approach assumed for the `DV_TEXT._formatting_` attribute in openEHR, which was defined in versions _prior to RM Release 1.0.4_ as containing CSS font strings to apply to the whole of the `DV_TEXT._value_`. This usage is now deprecated, while remaining legal in order to allow for legacy systems and data.

The current trend (emerging mainly for documentation in software) is to use 'markdown', which consists of markings in the text that visually indicate the intention: literal newlines, bolding via asterisks etc. No explicit CSS classes are needed, and conversion to rendering form is assumed to be done by an industry-standard markdown-to-HTML or other such converter. This is the approach taken by this specification, and is applied as follows.

The `_formatting_` attribute may contain one of the following values, with the associated meaning.

* `Void`:  if no value is supplied, no formatting marks are assumed to exist in the text, other than newlines, and it may safely be passed in a 'straight-through' fashion to a display device with no further processing, if desired;
* `"markdown"`: the text is assumed to be markdown format, strongly recommended use of the {commonmark_spec}[CommonMark^] form of markdown, and should preferably be rendered via conversion to HTML in the usual way, but _may_ be passed straight through to display if unavoidable, since markdown is acceptably human-readable;
* `"plain"`: the text is treated as in the unformatted (`Void`) case above (newlines are allowed); this option is used to enable archetype-based modelling tools to clearly require a text object to be unformatted;
* `"plain_no_newlines"`: as for the plain case, but newlines are not allowed - the text is a simple 'atom';
* (legacy - deprecated): for legacy purposes, it remains legal to use a string of the form `"name:value; name:value…"` , e.g. `"font-weight : bold; font-family : Arial; font-size : 12pt;"`.

Related to the question of formatting, a second optional attribute, `DV_TEXT._hyperlink_` of type `DV_URI`, exists to specify a web link associated with the whole text represented by the `DV_TEXT` instance. Similarly to the case of formatting, the more modern markdown approach to using the `_value_` field is also more flexible with regards to links, since multiple instances of the latter may be used within a single text.

*Deprecated*: Starting at RM Release 1.0.4, the use of the `_hyperlink_` field is deprecated in favour of inline link(s) in the `_value_` field, represented using markdown; in CommonMark, the basic form of a link is `[text](uri)`.

Not all CommonMark features are allowed in the `_value_` field, if it contains markdown. The following should not be used:

* HTML 'blocks';
* raw HTML;
* images - these may be included in openEHR content via the `DV_MULTIMEDIA` types.

#### Usage in DV_TEXT Instances

In a concrete instance of `DV_TEXT`, the following are the likely usages of the `_value_` and `_formatting_` attributes. The `_hyperlink_` is assumed to be Void in all non-legacy cases.

|===
|Requirement|`_value_` attribute|`_formatting_` attribute|Legacy form

|Plain text 'atom' +
 (no formatting, no newlines)
|plain text string
|`Void` or `"plain_no_newlines"`
|(same)

|Plain text 'atom' with a hyperlink +
 (no formatting, no newlines)
|text string of form `[text](uri)` or other CommonMark link variant
|`"markdown"`
|`_value_` = plain text; `_hyperlink_` = URI/URL

|Plain text paragraphs, +
 no other formatting
|plain text string with newlines
|`Void` or `"plain"`
|`DV_PARAGRAPH` instance(s) containing plain legacy text atom form `DV_TEXTs`

|Formatted text with paragraphs, bolding, italics, bullet lists, links etc
|CommonMark text string
|`"markdown"`
|`DV_PARAGRAPH` instance(s) containing legacy form `DV_TEXTs` with CSS formatting and/or values in `_hyperlink_`

|===

#### Usage in DV_CODED_TEXT Instances

In a concrete instance of `DV_CODED_TEXT`, the following are the likely usages of the `_value_` and `_formatting_` attributes. The `_hyperlink_` is assumed to be Void in all non-legacy cases.

|===
|Requirement|`_value_` attribute|`_formatting_` attribute|Legacy form

|Plain text of coded term
|plain text string
|`Void`
|(same)

|Plain text of coded term with a hyperlink
|text string of form `[text](uri)` or other CommonMark link variant
|`"markdown"`
|`_value_` = plain text; `_hyperlink_` = URI/URL

|Plain text of coded term or other text, containing newlines
|Plain formatted text
|Void or `"plain"`
|(not applicable)

|===

## Class Descriptions






# Quantity Package

## Overview
The `data_types.quantity` package is illustrated below. Dates and Times are found in the next section.

.rm.data_types.quantity package
image::UML/diagrams/RM-data_types.quantity.svg[id=rm_data_types_quantity, align="center"]

### Requirements

#### Scores and Scales

Medicine is a domain in which symbols representing relative magnitudes are commonly used, without exact values being used. The main purpose is usually to classify patients into groups for which different decisions might be made. Such classifications are typically known as _scores_ or _scales_. For example the characterisation of pain as 'mild', 'medium', 'severe', or the reflex response to tendon percussion as pass:["-", "+/-", "+", "++", "+++", "++++"]. Many scores such as the Apgar Score, Glasgow Coma Scale (GCS), and Barthel Index are globally known and used.

In some cases, there may be no way (or need) to precisely quantify such values because they reflect a subjective experience of the patient or informal judgment by the clinician. However, they are understood as being ordered, e.g. pass: [`++`] is arithmetically greater than pass:[`+`].

Similarly, even though the symbolic values for haemolysed blood in a urinalysis have approximate
ranges stated for them, as shown below, these 'values' are not usable in the same way as true quantities.

* `"neg"`, `"trace"` (10 cells/&#956;l)
* `"small"` (<25 cells/&#956;l)
* `"moderate"` (<80 cells/&#956;l)
* `"large"` (>200 cells/&#956;l)

A second requirement for score and scale values is that in many cases there is a need to associate numeric values values with the symbols, in order to facilitate ordered comparison, and also to enable longitudinal comparison across results of the same kind (e.g. pain, protein). The majority of scores and scales are limited to Integer values, but some use Real numbers interspersed with Integers e.g. the https://www.researchgate.net/publication/228089364_Proposing_a_standardized_method_for_evaluating_patient_report_of_the_intensity_of_dyspnea_during_exercise_testing_in_COPD[Borg CR 10 scale] for perceived exertion. In both cases, values may be negative, zero or positive.

NOTE: an argument sometimes put forward for recording all ordinals in a more precise way is that comparisons might want to be made between the values quoted by two laboratories for the same symbol (e.g. 'moderate'). There are a number of counter-arguments. Firstly, such comparisons are a poor attempt at normalisation, an activity which is the business of pathologists, not EHR users. Secondly, the symbolic values are often arrived at by the tester making a judgement of colour on a strip, which while an adequate (and cost-effective) approach for classifying, is not a valid means of quantifying a value. Lastly, in most cases, if a quantified point value or range is desired, or available, then it will be used - meaning that the appropriate quantitative data type can be used, rather than an the ordinal type.

#### Countable Things

A common kind of data value in medicine is the dimensionless countable quantity, e.g.

* number of doses: 2;
* number of previous pregnancies: 1;
* number of tablets: 3.

Values of this type are always integral. Countable values need to be convertible to real numbers for statistical purposes, for example for a study of average number of pregnancies per couple.

Some countable entities such as tablets are divisible into major fractions, typically halves and occasionally quarters.

#### Dimensioned Quantities

The most common kind of quantity is a measured, dimensioned quantity. Anything which is measurable
(rather than countable) involves a number of data aspects, namely:

* a magnitude whose value is a real number;
* the physical property being measured, with the appropriate units;
* a concept of precision, i.e. to what number of decimal places the value is recorded;
* a concept of accuracy, i.e. the known or assumed error in the measurement due to instrumentation or human judgement.

Examples of dimensioned quantities include:

* systolic BP: 110 mmHg
* height: 178 cm
* rate of asthma attacks: 7 /week
* weight loss: 2.5 kg

#### Ratios and Proportions

A common quantitative type in science and medicine is the proportion, or ratio, which is used in situations like the following:

* 1:128 (a titer);
* Na:K concentration ratio (unitary denominator);
* albumin:creatinine ratio;
* % e.g. red cell distribution width (RDW) which is the width of a distribution of RBC widths.

In general ratios have real number values, even if many examples appear to be integer ratios. Proportions with unitary denominator and % (denominator = 100) are common.

#### Formulations

A concept superficially similar to proportions and ratios is formulations of materials, such as a solid in a liquid e.g.:

* 250 mg / 500 ml (solute/solvent)

Although a single solute/single solvent formulation appears to have the same form as a ratio, the general form is for any number of substances to be mixed together, usually according to a particular procedure. Formulations are therefore not candidates for direct modelling as fine-grained quantities, but instead are constructed by archetyping a higher-level structure, each leaf element of which contains the required kind of Quantity.

#### Quantity Ranges

Quantity ranges are ubiquitous in science and medicine, and may be defined for any kind of measured
phenomenon. Examples include:

* healthy weight range, e.g. 48kg - 60kg
* normal range for urinalysis in pregnancy - protein, e.g. "nil" - "trace"

#### Reference Ranges

A reference range is a quantity range attached to a measured value, and is common for laboratory
result values. The typical form of a reference range found in a pathology result indicates what is considered
the 'normal' range for a measured value. Examples of reference ranges:

* normal range for serum Na is 135 - 145 mmol/L.
* desirable total cholesterol: < 5.5 mmol/L (strictly this probably should be 2.0 - 5.5 mmol/L, but is not usually quoted this way as low cholesterol is not considered a problem.)

Ranges can also be quoted for drug administrations, in which case they are usually thought of as the 'therapeutic' range. For example, the anticonvulsant drug Carbamazepine has a therapeutic range of 20 - 40 &#956;Mol/L. In some cases, there are multiple ranges associated with a drug, for example, Salicylate has a therapeutic range of 1.0 - 2.5 mmol/L and a toxic range > 3.6 mmol/L

Various examples occur in which multiple ranges may be stated, including the following.

* The administration recomendations for drugs which depend on the particular patient state. For example, the therapeutic range of Cyclosporin (an immunosuppresant) is a function of time post-transplant for the affected organ, e.g. kidney: < 6 months: 250 - 350 &#956;g/L, > 6 months: 100 - 200 &#956;g/L.
* Normal ranges for blood IgG, IgA, IgM which vary significantly with the age in months from birth.
* Progesterone and pituitary hormones have ranges which are different for different phases of the menstrual cycle and for menopause. This may result in 4 or 5 ranges given for one result. Only one will apply to any particular patient - but the exact phase of the cycle may be unknown - so the ranges may need to be associated with the value with no 'normal' range.

Where there are multiple ranges, the important question is: _which range information is relevant to the actual data being recorded for the patient?_ In theory, only the range corresponding to the particular patient situation should be used, i.e. the range which applies after taking into account sex, age, smoking status, "professional athlete", organ transplanted, etc. In most cases, this is a single "normal" range, or a pair of ranges, typically "therapeutic" and "critical". However, practical factors complicate things. Firstly, data is sometimes supplied from pathology labs along with some or all of the applicable reference ranges, even though only some could possibly apply. This is particularly the case if the laboratory has no other data on the patient, and cannot evaluate which range applies. The requirement for faithfulness of recording might be extended to reference data supplied by laboratories, regardless of how irrelevant or arbitrarily chosen the reference data is, meaning that such data has to be stored in the record anyway. Secondly, there may be circumstances in which physicians want a number of reference ranges, even while knowing that only one range is applicable to the datum. Ranges above and below the relevant one might be useful to a physician wishing to determine how far out of range the datum is.

#### Normal Range and Status in Laboratory data

It is quite common for laboratories to include a normal range with each measured value, and/or a normal 'status', which indicates where the value lies with respect to the normal range. The latter will commonly take the form of markers like "HHH" (critically high), HH (abnormally high), H (borderline high), L, LL, LLL in HL7v2 messaging, although other schemes are undoubtedly used.

### Design

#### Basic Semantics

In order to make sense of the requirements in a systematic way, a proper typology for quantities is needed. The most basic characteristic of all values typically called 'quantities' is that they are ordered, meaning that the operator "<" (less-than) is defined between any two values in the domain. An ancestor class for all quantities called `DV_ORDERED` is accordingly defined. This type is subtyped into ordinals, scales and true quantities, represented by the classes `DV_ORDINAL`, `DV_SCALE` and `DV_QUANTIFIED` respectively.

`DV_ORDINAL` and `DV_SCALE` are used for scores and scales as described in the requirements above. `DV_ORDINAL` represents data values whose values are Integers, and which have symbolic or text names instead, such as pass:["+", "++", "+++"], or `"mild"`, `"medium"`, `"severe"`. Each symbol can be assigned any Integer value, providing a basis for computable comparison. Typical uses for `DV_ORDINAL` include representing values from the Apgar and Glasgow Coma Scales, e.g. `0｜heart rate absent｜`, `4｜withdraws from pain｜`. `DV_SCALE` is similar to `DV_ORDINAL`, and was introduced to support scales / scores containing Real values as well as Integers.

In contrast to `DV_ORDINAL` and `DV_SCALE`, instances of `DV_QUANTIFIED` and all its subtypes have precise numeric magnitudes. Accordingly, `DV_QUANTIFIED` introduces the properties `_magnitude_` and `_magnitude_status_`. The `_magnitude_` attribute is guaranteed to be available on any `DV_QUANTIFIED`, carrying the effective value, regardless of the particular subtype. The optional `_magnitude_status_` attribute can be used to provide a non-quantified indication of accuracy, and takes the following values:

* `"="` : magnitude is a point value
* `"<"` : value is < magnitude
* `">"` : value is > magnitude
* `"\<="` : value is \<= magnitude
* `">="` : value is >= magnitude
* `"~"` : value is approximately magnitude

If not present, the meaning is `"="`.

Logically, an accuracy attribute should also be included in `DV_QUANTIFIED`, but as its modelling is different in the subtypes in a way that does not easily lend itself to a common ancestor, it is only included in the subtypes.

The `DV_QUANTIFIED` class has two subtypes: `DV_AMOUNT` and `DV_ABSOLUTE_QUANTITY`. The former corresponds to relative 'amounts' of something, either a physical property (such as mass) or items (e.g. cigarettes). Mathematically, the `+` and `-` operators (as well as `*` and `/`) are defined in the same way as for the real numbers (or any other mathematical 'field'), with the semantics that adding two relative quantities measuring the same thing (i.e. with the same units) produces another relative quantity of the same kind; while the semantics of subtraction are that one relative quantity subtracted from another generates a third.

The second subtype of `DV_QUANTIFIED`, `DV_ABSOLUTE_QUANTITY`, models quantities whose values are absolute along a line having a defined origin. The main example of absolute quantities are the temporal concepts date, time and date/time. These are distinguished from relative quantities in that the normal addition and subtraction operations don't apply. Instead, the semantics of such operators are based on the idea of the difference between absolute values being a relative amount. For example, two dates can be subtracted, but the result is a duration, not another date. For this reason, the operations `_add_`, `_subtract_` and `_diff_` are defined rather than `+` or `-`. Date/time types, as well as the relative concept duration, are defined in <<_date_time_package>>.

Subtypes of `DV_AMOUNT` are `DV_PROPORTION`, `DV_QUANTITY`, `DV_COUNT`, and `DV_DURATION` (see date_time package). The type `DV_COUNT` has an integer magnitude and is used to record naturally countable things such as number of previous pregnancies, number of steps taken by a recovering stroke victim and so on. There are no units or precision in a `DV_COUNT`. Countable quantities can be used to create instances of `DV_QUANTITY`, such as during a statistical study which average tobacco
consumption over a time period. Such a computation might cause the creation of `DV_QUANTITY` objects representing values like {magnitude = 5.85, units = '/ week'}

`DV_QUANTITY` is used to represent amounts of measurable things, and has a real number magnitude, precision, units and accuracy. The `_units_` attribute contains the scientific unit in a parsable form defined by default by the {ucum}[Unified Code for Units of Measure (UCUM)^] (case-sensitive form), or by another system or terminology specified in the `_units_system_` attribute. In some cases, such as metric units, the UCUM code and the display form are the same, e.g. 'kg'. However this is not the general case, and many common units have different display and code forms, e.g. degrees Celcius:  '°C' and 'Cel'. In general the unit display name should be looked up if it is not known in context that the code is directly displayable. The `_units_display_name_` attribute may be used if the displayable form of the units is required in the data, and/or terminology lookup is not available or desirable. Unit names may be language dependent, particularly older units.

A valid units string always implies a measured _property_, such as force or pressure. If unit strings are compared in the application environment to determine if they measure the same property (e.g. `"bar"` and `"kPa"` are both units of 'pressure'), which enables the `_is_strictly_comparable_to()_` function defined on `DV_ORDERED` to be properly specified on `DV_QUANTITY`.

NOTE: while these semantics will allow comparison of e.g. two pressures recorded in `mbar and mmHg, or even two accelerations whose units are `"m.s^-2"` and `"m/s^2"`, they provide no guarantee that this is a sensible thing to do in terms of domain semantics: comparing a blood pressure to an atmospheric pressure for example may or may not make any sense. It is not within the scope of the quantity package to express such semantics - this is up to application software which uses Quantities found in specific places in the data.

#### Accuracy and Uncertainty

Theoretically it might be argued that accuracy should not be included in a model for quantified values, because it is an artifact of a measuring process and/or device, not of a quantity itself. For example, a weight of "82 kg &#177;5%" can be represented in two parts. The "82 kg" is represented as a `DV_QUANTITY`, while the "&#177;5%" could be included in the protocol description of the weighing instrument, since this is where the error comes from. For practical purposes however, (in)accuracy in a measured quantity corresponds to a range of possible values. In realistic computing in health, it is quite likely that the accuracy will be required in computations on quantities, especially for statistical population queries in which measurement error must be disambiguated from true correlation.

Accuracy is therefore introduced as the abstract feature accuracy of the `DV_QUANTIFIED` class. It is defined concretely in the two descendants, `DV_AMOUNT`, where it is of type Real, and `DV_ABSOLUTE_QUANTITY`, where it is of a differential type defined by subtypes. A value of 0 in either case indicates 100% accuracy, i.e. no error in measurement. Where accuracy is not recorded in a quantity, it is represented by a special value. In `DV_AMOUNT`, a value of -1 for the accuracy attribute
is used for this purpose, and the constant unknown_accuracy_value = -1 is provided within the class to give a symbolic name for the special value. In the `DV_ABSOLUTE_QUANTITY` class, `_accuracy_unknown_` is represented by a Void (i.e. null) value for the accuracy attribute. An abstract Boolean feature `_accuracy_unknown_` is defined in the parent class `DV_QUANTIFIED` to provide a logical test of accuracy being absent, and is implemented in the respective  descendants by concrete functions that check for the special values.

In addition, the class `DV_AMOUNT`, provides a feature `_accuracy_is_percent_: Boolean` to indicate if accuracy value is to be understood as a percentage, or an absolute value.

When two compatible quantities are added or subtracted using the + or - operators (`DV_AMOUNT` descendants) or add and substract (`DV_ABSOLUTE_QUANTITY` class), accuracy behaves in the following way:

* if accuracies are present in both quantities, they are added in the result, for both addition and subtraction operations;
* if either or both quantities has an unknown accuracy, the accuracy of the result is also unknown;
* if two `DV_AMOUNT` descendants are added or subtracted, and only one has `_accuracy_is_percent_` = True, accuracy is expressed in the result in the form used in the larger of the two quantities.

The related notion of 'uncertainty' is understood as a subjective judgement made by the clinician, indicating that he/she is not certain of a particular statement. It is not the same as accuracy: uncertainty may apply to non-quantified values, such as subjective statements, and it is not an aspect of objective measurement processes, but of human confidence. Where the uncertainty is due to subjective memory e.g. "I think my grandfather was 56 when he died", the uncertainty is simply recorded as another value, along with the main data item being recorded. Uncertainty is therefore not directly modelled in the openEHR data types, but appears instead in particular archetypes.

#### Quantity Ranges

Ranges are modelled by the generic type `DV_INTERVAL<T:DV_ORDERED>` which enables a range of any of the other quantity types (except ratio) to be constructed. This allows any subtype of `DV_ORDERED` to occur as a range as well.

#### Proportions

The `DV_PROPORTION` type is provided for representing true ratios, i.e. relative values, and consists of numerator and denominator Real values, and a magnitude function which is computed as the result of the numerator/denominator division. The type attribute is used to indicate the logical type of the proportion. Supported types include:

* _percent_: denominator is 100; usual presentation is "numerator %"
* _unitary_: denominator is 1; usual presentation is "numerator"
* _fraction_: numerator and denominator are both integer values; usual presentation is n/d, e.g. such as ½ or ¾, 1/2, 3/4 etc;
* _integer_fraction_: numerator and denominator are both integer values; usual presentation is n/d; if numerator > denominator, display as "a b/c", i.e. the integer part followed by the remaining fraction part, e.g. 1½; this is the most likely form for expressing a number of tablets;
* _ratio_: numerator and denominator can take any value; usual presentation is "numerator: denominator"

Lastly, the `_is_integral_` function indicates that the numerator and denominator are both integer values; this is used for fractions (the fraction and integer_fraction types above) and other commonly occurring ratios where both parts are always integer values.

#### Normal and Reference Ranges

Normal range for any of the quantity types (i.e. any instance of a subtype of `DV_ORDERED`) can be included via the attribute `DV_ORDERED`.`_normal_range_`, of type `REFERENCE_RANGE`. Other reference ranges (e.g. sub-critical, critical etc) can be included via the attribute `DV_ORDERED`.`_other_reference_ranges_`. The separation of normal and other reference range attributes is used because the former constitute the vast majority of ranges quoted for quantitative data.

Normal status can be included via the attribute `DV_ORDERED`.`_normal_status_`, which takes the form of a `DV_ORDINAL`, whose symbol attribute is coded according to the openEHR terminology group "normal status", and takes values "HHH" (critically high), "HH" (abnormally high), "H" (borderline high)", "N" (normal), "L" ... "LLL".

#### Recording Time

Time can be recorded in two ways. Absolute times in the social time domain, such as dates and time of day are recorded using the types in the date_time package. Fine-grained 'time', which is a duration rather than a time, is recorded using a `DV_QUANTITY` with units = 's' or another temporal unit ('h', 'ms', 'ns' etc).

## Class Descriptions













## Syntaxes

### Units Syntax

The BNF syntax specification of the units string, adapted from {ucum}[UCUM^] (case-sensitive form) is as follows:  

```ebnf
units = '/' exp_units | units '.' exp_units | units '/' exp_units | exp_units ;
exp_units = unit_group exponent | unit_group ;
unit_group = PREFIX annot_unit | annot_unit | '(' exp_units ')' | factor ;
annot_unit = unit_name [ '{' ANNOTATION '}' ] | '{' ANNOTATION '}' ;
factor = Integer ;
exponent = [ SIGN ] Integer ;

PREFIX = 'Y' |'Z' | 'E' | 'P' | 'T' | 'G' | 'M' | 'k' | 'h' | 'da' | 'd' | 'c' | 'm' | 'μ' | 'n' | 'p' | 'f' | 'a' | 'z' | 'y' ;
UNIT_NAME = ? [a-zA-Z_%]+ ?;   (* replace regex with values from unit tables *)
ANNOTATION = ? [a-zA-Z'.]+ ?;  (* replace regex with values from unit tables *)
SUFFIX = ? [a-zA-Z0-9'_]+ ?;   (* replace regex with values from unit tables *)
SIGN = '+' | '-' ;
Integer = ? [0-9]+ ?;          (* regex *)
```

This proposal is comprehensive, covering all useful unit systems, including SI, various imperial, customary mesaures, and some obscure measures, as well as clinically specific additions. Metric prefixes, meaning-changing textual suffixes (e.g. "[Hg]" in "mm[Hg]") and non-meaning-changing annotations (e.g. "kg {total}") are recognised. With this syntax, units can be simply expressed in strings such as:

```
"kg/m^2", "m.s^-1", "km/h", "mm[Hg]"
```

and so on.


# Date Time Package

## Overview

The `data_types.quantity.date_time` package includes three absolute date/time concepts:
`DV_DATE`, `DV_TIME`, `DV_DATE_TIME`, and a relative concept: `DV_DURATION`. The representations of
all of these are {iso_8601}[ISO 8601:2004] compatible date/time strings. They also include the ISO 8601 semantics
for partial dates and times. The `quantity.date_time` package is illustrated below.

.rm.data_types.quantity.date_time package
image::UML/diagrams/RM-data_types.quantity.date_time.svg[id=rm_data_types_quantity_date_time, align="center"]

### Requirements

#### Standard Date/Times

The basic requirement is for types which represent the following concepts.

* _Date_: a type which records year, month and day in month. Examples include date of birth, date of onset of a problem.
* _Time_: a type which records hour, minute, second, and timezone. Examples include time of meal, time of day when a problem recurs. Timezone is required in a shared EHR repository so that times of clinical events which occurred in different timezones are comparable; this includes specialised pathology tests which might be done in another country.
* _Date_time_: a type which records year, month, day, hour, minute, second, and timezone. Examples include date & time of death, timestamp of any observation. Timezone is required for the same reason as in Time.
* _Duration_: a type which records duration of an event or (in)activity, as days, hours, minutes, and seconds. A duration is understood as being relative to an unstated origin point (such as birth), and may take a negative value, indicating prior to the origin.

#### Partial Date/Times

Partial or uncertain date/times have to be supported in clinical medicine. It is common for patients to
be unsure about dates and durations. Requirements for partial date/times include the following.

* For dates, one of the following rules applies to any instance:
** only the year is known
** only the year and month are known
** If not even the year is known, then the date is obviously extremely approximate and it would
probably be unsafe to represent it computationally. However, if computatable representation
was needed in this case, a date interval can be used. A pedantic example which breaks these
rules is someone who claims to be born on "a Monday at the start of May in 1934" (i.e. day
but not date unknown). Either the clinician determines what date the first Monday in May
1934 actually was and record that (assuming the patient's way of accurately remembering
just happens to be via day rather than date), or else records a partial date of the form "May
1934" (in ISO 8601 form, `"1934-05"`) if they determine that the patient really is unsure.
* Sometimes incomplete times are recorded, which follow the same rule that either the hours
or both the hours and minutes are present. Examples:
** recordings by instruments which only generate hh:mm values (i.e. no seconds);
** recordings by patients who report approximate times of events;
** recordings by clinicians who use approximate times in administrations, e.g. "take insulin at 8am" really means something like 8 am +/- 30 mins.
* Imprecise durations such as '2 - 3 hrs' need to be recordable in a computable form.

To satisfy the faithfulness requirement for health record recording it should always be possible to
record the narrative form of the datum provided by the patient as well as the formal form.

### Design

#### General Approach

Date/time values are somewhat special in the realm of data types in that they are expressed in their
'customary' form, in which the standard structure of `{value, unit}` and metric relationships between
orders of magnitude do not hold. The customary form is what we are used to using in the social time
domain, such as births, deaths, ages, and times and durations of events which we remember. In all
these cases it is expressed using the familiar year/month/date/hour/minute/second system, in which
the relationships between each successive unit of time is non-metric. The customary form can be converted
to a magnitude since an origin point, and many date/time libraries do this in order to implement
various operations, particularly comparison.

The date/time types fall into two categories: _absolute_ and _relative_. The absolute category comprises
the Date, Date/time and Time concepts, each of which measure time from a known origin. Date and
Date/time measure calendrical time from the date `0001-01-01`, while Time measures clock time from
midnight. Both Date/time and Time can include timezone information, ensuring that their instances
are correctly situated on the same timeline. All absolute time types inherit from the `DV_TEMPORAL`
type, which provides the appropriate signature for the `_diff()_` function.

The relative category contains only the Duration concept, which expresses elapsed time between two
time points. The `DV_DURATION` class is used for expressing durations of clinical phenomena and differences
between absolute times.

With two exceptions, all four concepts conform to the {iso_8601_official}[ISO 8601:2019 standard^], which is accordingly used as the primary definitional basis of the openEHR date/time types. The two exceptions are as follows:

* a negative sign may be used before a Duration, for example '-P10D', meaning '10 days before [origin]', where the 'origin' is a timepoint understood as the origin for the duration;
* the  W' designator may be mixed with other designators. 

The first exception allows the expression of negative durations, indicating an elapsed time prior to an origin point. An example from clinical medicine is the notion of 'adjusted age', whereby the true developmental age of a very premature newborn is computed with respect to the origin point of birth after a nominal gestation period (usually 9 months). A baby born at 6 months would therefore have an adjusted age of '-3 months', or '-P3M' in the format used by the `DV_DURATION` type. The use of the negative enables correctly computed developmental age comparisons of newborns, regardless of prematurity. Negation for ISO 8601 durations is also supported by {w3c_xml_schema}[W3C XML-schema^] and various programming languages.

See the {openehr_foundation_types}#_time_types[Time Types section in the openEHR Foundation Types specification^] for conformance details.

#### Partial Date/Times

The types defined in this specification support the notion of partially specified dates and times. The
modelling approach used here takes into account the known needs for representing partial date/time
data, while balancing that with the need to avoid incomprehensibly complex types whose generality
would only apply to a tiny percent of difficult cases. Thus, the basis for modelling incomplete
date/times is as follows.

* The modelling problem relates only to date/time quantities that need to be computable. For extremely imprecise date/times, if the clinician feels the need, she can record it as narrative text.
* For imprecise durations, an interval should be used, i.e. `DV_INTERVAL<DV_DURATION>`. In this way durations like '2 - 3 hrs' can be represented, and still be computable.

Based on the above considerations, the requirements for partial types are satisfied by the semantics of
ISO 8601:2004 for 'reduced accuracy' date/times, in which parts of a date, time or date/time can be
missing from the right hand end of the string. This models the reasonable situation where e.g. day
may be unknown in a date, but a date cannot have month unknown and day known.

#### Calendars

A comment on calendars is in order. In this specification, all date/time types currently modelled are
Gregorian calendar based. This is the same assumption made by ISO 8601, and most technical
computing systems today in many parts of the world. At first glance this may seem like a culturally
insensitive approach, but in fact it makes sense in computational terms, for both users of the Gregorian and other calendars, e.g. Julian, Islamic, Baha'i, etc. Arguments against trying to use the
date/time classes defined here to represent date/times from any calendar include the following:

* Almost all dates on computer systems, including in regions such as the Indian sub-continent,
Turkey and the middle east, where alternate calendars are in use, are in the Gregorian system.
This is likely to be the case for some time, and may always be the case, regardless of
the continued use of other calendars for religious or other purposes (outside of health);
* If a calendar indicator were used in date quantities, all software, to be correct, would have to
check the value to verify that it is in the expected calendar system, and to do something special
if it is not - an added cost which is a possible source of bugs and which would rarely be
used. The reality is that most software produced in the western world, India etc (possibly
excepting open source software) would automatically assume the Gregorian calendar, and
would be in error if ever it did receive EHR data containing dates from alternate calendars.
* If/when other calendars are used in EHR or related systems, the users of those calendars will
be aware of it, and include the appropriate conversion logic between Gregorian dates and
their own, limiting the extra software work and quality issues to those users who actually
need alternate calendars. If EHRs from such places are sent to a health care facility where
Gregorian is the default, nothing special is needed to ensure that those records will contain
dates comprehensible to the receiver.
* The detailed model of date/times in some other calendars is not the same as in the Gregorian
calendar, so they would require different classes anyway - the classes defined here would
not necessarily function correctly simply by adding a calendar field.

For users requiring non-Gregorian dates in EHR and other health systems there are two approaches.
One is to treat non-Gregorian dates as a localisation issue, to be handled inside the application and
GUI environment. The other is to actually add further sibling packages to the openEHR date/time
package, for each new calendar or calendar group required. Conversion algorithms would most likely
be needed in and out of the Gregorian types to enable interoperability of information drawn from different
applications or sources. This approach may require a substantial modelling effort.

Algorithms for conversion between the Egyptian, Armenian, Khwarizmian, Persian, Ethiopian, Coptic,
Republican, Macedonian, Syrian, Julian Roman, Gregorian, Islamic A, Islamic B, Baha'i and
Saka calendars are described by cite:[Richards1998] and are based on the work of D. A. Hatcher (1986).

#### Representation

All of the date/time classes described here are defined so as to have an attribute called value of type
String, in the form of an {iso_8601_official}[ISO 8601:2019] string, with the two above-described deviations allowed. ISO 8601 is convenient for this purpose, as it is a simple
syntax, and covers not only all four variants of fully-specified date/time described here, but also
the partial varieties. The deviations support common use cases in healthcare, without compromising the semantics. Using a single string attribute significantly simplifies persistence as well as mapping
to XML-based formalisms, which use a mostly ISO 8601 compliant date/time representation.
The ISO 8601 semantics assumed by EHR are defined in classes found in the classes
`Iso8601_date`, `Iso8601_time`, `Iso8601_date_time`, `Iso8601_duration`, from the
{openehr_foundation_types}#_time_types[`base.foundation_types.time` package]. These classes are inherited into the corresponding classes
defined below.

NOTE: it is strongly recommended that where possible, the _extended_ form of the ISO 8601 date/time syntax is used, i.e. the use of dashes in dates (e.g. `2018-03-14` rather than `20180314`) and colons for times (i.e. `14:24:00` instead of `142400`). This greatly aids human readability, and reduces the need for special date/time display rendering.

## Class Descriptions






# Time_specification Package

## Overview
Time specification is about potentiality rather than actuality, and needs its own types. The openEHR
`data_types.time_specification` package provides such types, based on the HL7 types of the
same names, and is illustrated below.

.rm.data_types.time_specification package
image::UML/diagrams/RM-data_types.time_specification.svg[id=rm_data_types_time_specification, align="center"]

### Requirements
One of the difficulties with time is expressing future times, since potential occurrences, durations,
repetitions cannot be expressed in the same way as actual time. Complicating the problem is the fact
that humans tend to use very customary (i.e. calendar-anchored) ways of specifying time, such as
"every second Tuesday", or "the first Sunday of the month". In clinical medicine, future time is most
commonly used to express when medications or other therapies are intended to take place. They are
often anchored to the calendar, and can easily include repetitions.

As with other time types, there are both simple and complex cases to consider. One of the most common
examples of time in the future is the timing for drug administrations, e.g. "once every four
hours". This could be represented as a simple periodic specification, consisting of a start point in
time, a period, and a number of repetitions. The specification for taking blood sugar levels during a
glucose test could be represented as a simple aperiodic series, e.g. ".5hr, 1hr, 2hr". However, even
common specifications for prescriptions e.g. "three times a day for seven days" start to become quite
complex, for example, because "three times a day" might not mean literally 8 hours apart.

Some of the factors to consider in timing specifications are:

* period of repetition
* duration of activity being specified
* possible alignment to the calendar, e.g. "every 5th of the month"
* possible alignment to real world events e.g. "after meals"
* fuzziness

Because time is inherently "messy" (months do not all have the same number of days, leap years
change the number of days in some years etc), and because the relationship we have with time can
also be arbitrary (e.g. anchored to mealtimes etc), specifying linguistically obvious specifications formally
is quite challenging.

### Design

The HL7 version 3 data types for time specification appear to allow for all of the required possibilities.
The syntax is based on the {iso_8601}[ISO 8601 standard^]. It provides types which express:

* Periodic intervals (HL7v3 - `PIVL<T:TS>`) - allows period, duration, and calendar linking to
be specified.
* Event-linked periodic intervals (HL7v3 - `EIVL<T:TS>`) - allows PIVLs to be linked to realworld
events like meals.
* General timing specification (HL7v3 - GTS) - allows any time specification to be expressed,
using a syntax which is equivalet to a series of `IVL<TS>` (i.e. intervals of `DATE_TIME`).

The HL7 syntax for time specification is encapsulated in equivalent openEHR types described here.

## Class Descriptions




## Syntaxes

### Phase-linked Time Specification Syntax

The syntactic form of phase-linked periodic time specifications (derived from the `PIVL<T>` spec
HL7v3 ballot) is as follows.

```
"[" interval "]" "/" "(" difference ")" [ "@" alignment ] [ "IST" ]
```

Examples include:

```
* [200004181100;200004181110]/(7d)@DW = every Tuesday from 11:00 to 11:10 AM.
* [200004181100;200004181110]/(1mo)@DM" = every 18th of the month 11:00 to 11:10 AM.
```

A parse specification is as follows:

```ebnf
phase_linked_time_spec = pure_phase_linked_time_spec [ "IST" ] ;
pure_phase_linked_time_spec = phase [ "@" alignment ] ;
phase = interval "/" "(" difference ")" ;
alignment = "DW" | etc ;                  (* terms from "HL7::CalendarCycle" domain *)
difference =  ;                           (* ISO 8601 for time difference *)
interval = "[" interval_spec "]" ;
interval_spec = ";" | ";" date_time | date_time ";" date_time | date_time ";" ;
date_time = (* ISO 8601 for date/time string yyyymmdd[hh[mm[ss]]] *) ;
```

### Event-linked Periodic Time Specification Syntax
Examples of event-linked periodic time specifications include:

* "PC+[1h;1h]" = one hour after meal
* "HS-[50min;1h]" = one hour before bedtime for 10 minutes

The following parse specification defines the syntax for event-related periodic time specifications.

```ebnf
event_linked_time_spec = event | event offset ;
event = "AC" | "ACD" | etc ;             (* HL7 domain "HL7::TimingEvent" *)
offset = ( "+" | "-" ) dur_interval ;
dur_interval = ;                         (* ISO 8601 for duration interval *)
```

### General Time Specification Syntax
The class is the same structurally as the `DV_TIME_SPECIFICATION` parent. The syntax is the HL7
GTS syntax, defined by the following parse specification:

```ebnf
general_time_spec = symbol | union | exclusion ;
union = intersection  [";" union ] ;
exclusion = exclusion "\" intersection ;
intersection = factor intersection | factor ;
hull = factor [ ".." hull ] ;
factor = interval | phase_linked_time_spec | event_linked_time_spec | "(" general_time_spec ")" ;
```


# Encapsulated Package

## Overview
The `data_types.encapsulated` package contains classes representing data values whose internal
structure is defined outside the EHR model, such as multimedia and parsable data. It is illustrated below.

.rm.data_types.encapsulated package
image::UML/diagrams/RM-data_types.encapsulated.svg[id=rm_data_types_encapsulated, align="center"]

### Requirements
There is a need to be able to include content in the EHR whose interior structure is not modelled in
the EHR reference model, but instead documented by sufficient meta-data attributes for specific tools
to process the data. Types of content in this category are as follows.

* Images, including images which are themselves a compressed version of one image from a
high-resolution image set stored elsewhere. Such images may be in any of the well-known
compressed or uncompressed formats, and may have their own thumbnail image attached, to
facilitate web-viewing.
* Bio-signal data series, such as a set of values representing a diagnostic part of an ECG trace.
This might be represented as DICOM content.
* Content which is textual (or nearly so) which is essentially a parsable language file of some
kind. This includes all XML instance, HTML, and any other EHR content which happens to
be represented in syntax form - such as the unit strings used in quantities. The name of the
formalism should be stored as meta-data.
* Binary content which is processed by a work processor or other dedicated tool.
* Digital signatures.

Sufficient meta-data must be included with all of these types to enable a way for the content to be
processed, typically by indicating either its type (e.g. "jpeg", "word document") or the name of a tool
which can be used to process it. Important meta-data include:

* size of the content;
* natural language, if any.

Any encapsulated data item may be a summary, "thumbnail" or otherwise reduced form of an original
content item found outside the EHR, in some other system or file-system.
Checksums must be expressible for those items for which a checksum is available, or for which the
system generates checksums to improve the quality of its internal data transmissions.

### Design
The design approach used here is based on the following analysis.

. Any encapsulated data item may be in some particular language, even if it is an image or other graphic form such as a biosignal with axis markings in a particular language;
. The general structure of encapsulated content data items includes a block of bytes or characters representing the content, and various meta-data as appropriate, including:
** size
** character encoding
** compression type/algorithm
** name of formalism for parsable content
. For encapsulated items that have a counterpart in another system, the standard means of portable address is the W3C URI;
. For items may that have an associated integrity checksum, the checksum is itself a series of bytes, and the type of checksum must also be specified, e.g. "md5".

These observations lead naturally to an abstract `DV_ENCAPSULATED` class, with two subtypes,
`DV_PARSABLE`, for all content which is syntactic in nature, and `DV_MULTIMEDIA` for everything else.
Note that it is possible to imagine parsable content items which are large, stored in compressed form,
and are themselves a summary of another item elsewhere on the web; such items can for practical
purposes be represented as instances of `DV_MULTIMEDIA`, rather than `DV_PARSABLE`. The vast
majority of parsable encapsulated data are expected to be short and stored in native textual form, e.g.
fragments of XML or HTML.

The formal model of the classes `DV_ENCAPSULATED` and `DV_MULTIMEDIA` are closely based on the
ED type from the HL7v3 data types specification.

### Examples

The following examples show how to use the classes to represent some common encapsulated data types.

|===
|Data format            |Class              |Attributes

|inline JSON            |`DV_PARSABLE`      |`_value_` = JSON string +
                                             `_formalism_ = "json"`

|inline JSON, minified +
 (white space removed)  |`DV_PARSABLE`      |`_value_` = minified JSON string +
                                             `_formalism_ = "json"`
 
|JSON document          |`DV_MULTIMEDIA`    |`_uri_` = URI at which document is located +
                                             `_media_type_ = "IANA::application/json"` +
                                             `_size_` = Integer indicating number of bytes of target.

|inline JPG             |`DV_MULTIMEDIA`    |`_data_` = byte array carrying JPG +
                                             `_media_type_ = "IANA::image/jpeg"` +
                                             `_size_` = Integer indicating number of bytes of `_data_`.

|inline JPG, Base64 +
 encoded                |`DV_MULTIMEDIA`    |`_data_` = byte array carrying Base64 string of JPG +
                                             `_media_type_ = "IANA::image/jpeg;base64"` +
                                             `_size_` = Integer indicating number of bytes of `_data_`.

|inline JPG with +
 SHA-2 hash             |`DV_MULTIMEDIA`    |`_data_` = byte array carrying JPG +
                                             `_media_type_ = "IANA::image/jpeg"` +
                                             `_integrity_check_` = byte array containing SHA-2 hash +
                                             `_integrity_check_algorithm_ = "openehr::SHA-2"` +
                                             `_size_` = Integer indicating number of bytes of `_data_`.                                             

|===

## Class Descriptions




# Uri Package

## Overview

The `data_types.uri` package includes two types used for referring to information resources. The
`DV_URI` type allows data values which are references to objects on the world wide web to be created.
Its specialisation, `DV_EHR_URI`, enables any element in an openEHR record to be identified in the
same way as other objects on the web. The `DV_EHR_URI` type is convenient, because it is a string,
like any other URI, and is therefore easily transportable and processable. Because it has its own
scheme space, 'ehr', instances can be globally unique, as long as EHR identification is globally
unique. `DV_EHR_URIs` are used to express all runtime paths in the EHR. The `uri` Package is illustrated
below.

.rm.data_types.uri package
image::UML/diagrams/RM-data_types.uri.svg[id=rm_data_types_uri, align="center"]

### Requirements

This package meets the requirement for a `DATA_VALUE` subtype which represents a W3C Uniform
Resource Identifier (URI). A common example of where this might be used is to represent a reference
to a clinical guideline or other justifying document associated with an intervention or treatment plan
recorded in the EHR.

URIs are a superset of Uniform Resource Locators (URLs) (although the two are often confused,
even within the W3C), and can be used to specify the location of any information item, regardless of
its type, location or storage method, as long as a URI "scheme" exists for that type of information.

There is an additional requirement for a kind of URI that can point at an EHR data item, either inside
the same EHR containing the link, or in another EHR. This is the basis of implementing logical references
in the EHR and between EHRs.

### Design

A simple design approach is used whereby a URI is represented as a String, and appropriate functions are defined to extract the various parts according to the syntax of URIs defined by Tim Berners-Lee ({rfc3986}[IETF RFC 3986^]). An EHR specific subtype is defined, whose scheme is 'ehr', and which contains further attributes enabling the instances of the type to record what kind of object they are referring to.

So-called 'plain-text URIs' that contain RFC-3986 forbidden characters such as spaces etc, are allowed on the basis of human readability, but must be RFC-3986 encoded prior to use in e.g. REST APIs or other contexts relying on machine-level conformance.

## Definitions

The following symbolic definitions are used in the classes below.

* `_Ehr_scheme_`: `String` = "ehr"

## Class Descriptions



## Syntaxes

### DV_EHR_URI Syntax

The syntax of a `DV_EHR_URI` is an openEHR path, inside the 'ehr' URI scheme-space, and is one of the forms:

```
ehr://system_id/ehr_id/top_level_structure_locator/path_inside_top_level_structure
ehr:/ehr_id
ehr:/ehr_id/top_level_structure_locator
ehr:/ehr_id/top_level_structure_locator/path_inside_top_level_structure 
```

The syntax is described in more detail in the {openehr_overview}#_ehr_uris[openEHR Architecture Overview]. `DV_EHR_URIs` are used as a mechanism for referencing in the EHR, ensuring readability by humans, as well as validity when extracts are transmitted elsewhere: even if the target of a path is not present, the path can be used to locate the missing item on demand.

# Implementation Strategies

## Overview
This section notes a few of the general challenges for mapping the openEHR data types to implementation
technologies such as programming languages and XML. For specific guidelines, Implementation
Technology Specification (ITS) document for each target formalism should be consulted.

## Quantities and Ordered_numeric
In the quantity package, the type `DV_QUANTIFIED` is shown having an abstract property of type
Ordered_numeric. This is intended to indicate that the type `DV_QUANTIFIED` is distinguished by
the magnitude property (compared to say `DV_ORDERED`, which describes ordered things without having
magnitudes). The type Ordered_numeric be mapped to various types in implementation technologies
as follows:

* Java: `java.lang.Number`
* C#: `System.IComparable`
* Eiffel: `NUMERIC`

All of these type systems currently suffer from not having a single type whose meaning is both
"ordered" (having the function '<') and "numeric" (having the functions '+', '-', '*', '/') but in practice
it does not matter much. For type systems with no convenient supertype of the numeric concrete
types `Real`, `Integer`, `Double`, the `_magnitude_` property can safely be left out of `DV_QUANTIFIED`;
the only drawback is that code cannot call `DV_QUANTIFIED`.`_magnitude_` polymorphically, e.g. in a
statistical application processing `DV_QUANTITY` and `DV_COUNT` objects.

## Unicode
Unicode is supported in various ways in different languages. In Java, since JDK 1.1, unicode support
is implicit in the base classes. From the documentation:

    the classes java.io.InputStreamReader, java.io.OutputStreamWriter, and
    java.lang.String can convert between Unicode and a number of other character
    encodings. More information is available at:
    http://java.sun.com/j2se/1.3/docs/guide/intl/encoding.doc.html.

In the C# language, conversion can be done between Unicode and other codepages using the System.
`Text.UnicodeEncoding` (for UTF-16) and `System.Text.UTF8Encoding` (for UTF-8) classes.

In XML unicode is handled by specifying the encoding of the document in the XML declaration, e.g.
`<?xml version="1.0" encoding="UTF-16"?>`.

In the Eiffel language, unicode is available in the Gobo public domain library (see
http://www.gobosoft.com), in the `UC_STRING` class, which inherits from the String class.
The support in other languages varies, and may require a special type like the `UC_STRING` used in
Eiffel.

## Dates and Times

In some formalisms, dates and times are represented using a single calendar-like class. This is not
considered to be good practice from the point of specification, since it is more difficult to state proper
invariants for such a class used to represent a particular logical type such as a `DATE` or `TIME`, however,
its utility in implementation is recognised.

Where implementors want to use such a class (call it `CALENDAR` here for the sake of discussion) the
recommended approach is to wrap the class `CALENDAR` with classes representing the types described
in this specification, i.e. `DATE` etc. This enables the addition of any necessary functionality in the
wrapper for example, for serialising and deserialising in and out of XML.

# Comparison with HL7v3 Types

## Scope
Some HL7v3 types are not modelled in openEHR. HL7v3 V3DT types which are assumed by
openEHR to exist in the underlying type system of any implementation technology include:

* Integer (`INT`)
* Real (`REAL`)
* Set (`SET`)
* List (`LIST`)
* Bag (`BAG`)

HL7v3 types which are not modelled here because they are almost always too volatile for concrete
modelling, and can be created with archetyped generic information structures are as follows (even in
HL7 they are really data structures rather than data types):

* Postal address (`AD`)
* Entity name (`EN`)
* Person name (`PN`)
* Organisation name (`ON`)
* Trivial name (`TN`)

These types are all modelled by archetyped spatial data structures in openEHR (equivalent to subtypes
of Structure in the CDA specification).
HL7v3 types which may need to be modelled in the future include:

* Uncertain value probabilistic (`UVP`)
* Non-parametric probability distribution (`NPPD`)
* Parametric probability distribution (`PPD`)

Types which are provided by openEHR but not supported directly by HL7 include:

* state variable (`DV_STATE`);
* ordinal values (`DV_ORDINAL`);
* explicit partial date and time types (`DV_DATE`, `DV_TIME`);
* explicit time duration (`DV_DURATION`).

Types in the latter two categories may be implementable with the `TS` (timestamp) type.

## Design Differences
There are some significant differences in design approach between the openEHR data types and the
HL7v3 data types, described in the following sections.

### Naming
All types in the HL7 specification have two names, one short and one long. For example the type representing
physical quantities is known both as "PhysicalQuantity" and "PQ". While short names may
be reasonable for often-used types, someshort names are not obvious, e.g. "EN", "ON", "TN",
"NPPD" etc. Short names certainly have benefits for drawing tools such as Rational Rose or other
UML tools, however, it is questionable whether a formal model should include concept names chosen
on the basis of visual appearance in such tools (one might argue that such tools should provide aliases
for visual purposes, without changing the actual model). Another problem is that UML does not
include the concept of class name aliases, nor do most programming languages.

The openEHR model uses one name only for each class.

### Identification
The HL7 V3DT includes the types `II`, `UID`, `OID` and `UUID`. The `II` type is claimed to be for identifying
all kinds of entities, which we here classify as real-world entities ("RWEs") (such as people, vehicle
registrations, invoices) and informational entities ("IEs") - which in general are snapshots of data
representing an RWE in a computer system. One problem with RWE identification schemes is that
some are known (e.g. social security number) to produce fallible identifiers or situations where multiple
RWEs have the same identifier, or no identifier at all. Conversely, with well-controlled and internationally
agreed ways of issuing/generating information system identifiers (e.g. GUID, ISO OID) it
is thought that such identifiers can be made reliable, and indeed correspond 1:1 with their intended
IEs. However, a problem with IEs is that there are often duplicates and also multiple versions in time,
each intended to represent the same RWE (such as a particular person, observation or composition).

As far as can be ascertained currently, there is no standard analysis taking into account the existence
of IEs and RWEs, and recognising the fact that multiple versions and/or duplicates may refer to the
same RWE.

The approach taken in openEHR with respect to identifiers is currently as follows.

* RWE identifiers such as social security numbers, licence numbers, etc are modelled with the
type `DV_IDENTIFIER`, which has the attributes:
** `_issuer_`: `String`
** `_id_`: `String`
** `_type_`: `String`
The attributes listed above are nearly the same as for the HL7 II type, indicating that the two
types may be compatible.
* Identification of IEs is done using the type `OBJECT_ID`, which is not a data type, and is documented
in the Support Information Model. The `OBJECT_ID` type takes into account the
fact that there may be multiple IEs referring to the same underlying RWE by adding a version
identifier (assumed to be a timestamp).

### Archetyping

The openEHR data types are defined on the assumption of archetype-based systems. While they will
work perfectly well in systems which know nothing about archetyping, some types are not defined
because archetypable structures built from more basic entities are assumed instead, rather than concretely
modelled data types. These include 'types' for Address and PersonName which are found in
HL7v3 and ISO 13606.

### Treatment of Inbuilt Types
The HL7v3 data types do not make any assumptions about the existence of types typically built-in to
most object and relational formalisms, such as the basic types `String`, `Integer`, `Boolean`, `Real`,
`Double`, and the generic types `Set<T>`, `Bag<T>` and `Array<T>`. Hence, the types `ST`, `INT`, `REAL`,
`BL`, `SET<T>`, `BAG<T>` and so on are redefined by HL7. The supposed advantage of this approach is
that the semantics of all types in the HL7 system, right down to atomic data items are self-contained
in the definition, and do not rely on external semantics. Possible problems with this approach include
the following.

* The HL7 definitions diverge from the OMG IDL and ISO 11404 definitions of the basic data
types, which could cause unexpected problems in software development and data processing
which is done in typical development technologies (object-oriented and relational).
* The HL7 types `INT` and `REAL` are defined as subtypes of the `QTY` type, a relationship that
does not exist in any object-oriented formalism for these types (in particular, there is no substitutability
of a type called Integer or Real for a type called Qty built in to any object language).
The definitions of `INT` and `REAL` are also different from those found in most object
formalisms. This might cause some difficulty in implementation.
* The binary data type `BIN` is represented as a `List<BL>` (where each item can be True, False, null), whereas it would normally be expected to be something like `Array<Octet>` (i.e. an array of bytes) in most software environments. There does not appear to be any utility in defining it as `List<BL>`, since binary data is almost without exception represented and processed as contiguous arrays of machine bytes.
* The string type `ST` inherits from the encapsulated data type `ED`, which in turn inherits from the binary data type `BIN`. The result of this is that an instance of `ST` contains numerous data attributes relating to multi-media data, and the content is presumably represented as a `List<BL>`. This is a major departure from the standard understanding of a string in computer sciences, which is usually simply an array of characters.
* The HL7 boolean type `BL` is a three-valued logic type due to the null marker approach (see below), not the usual two-valued type found in the Boolean concept in programming languages. The same is true of `INT` and `REAL:` due to the null marker design, "null" is a possible return value of an integer or real as well as true integer and real values.

In general, where differences exist between same-named types in HL7 and an underlying formalism
such as a programming language, there is likely to be some confusion in implementation. Further,
there is likely to be confusion in how to process instances of basic types which contain numerous
(and sometimes recursive) fields which are not used in the standard specifications of basic types.
The openEHR approach with respect to inbuilt types is to assume only those types found in the mainstream
object-oriented programming languages, and in particular, definitive formalisms like OMG
IDL and XML. While this means there there is in theory less control over these types than in the HL7
approach, the number of types involved is quite small, and the problem of bindings to the basic types
of object formalisms is well understood. Additionally, since it is recognised that some data types
defined by openEHR could clash with types found in some languages and libraries, all data type class
names are prefaced with "DV_" to avoid naming confusion, and to allow implementations of
openEHR types to co-exist with existing types in implementation formalisms.

### Use of Null Markers

All HL7 data types inherit from the `ANY` class (equivalent to the `DATA_VALUE` class in openEHR)
which contains the attributes:

```
BL nonNull;
CS nullFlavor;
BL isNull;
```

The purpose of these attributes is to indicate whether a datum is Null, and for what reason. Since
some data type classes also appear as the attributes of other data types, the Null markers also indicate
whether any part of a datum is null. Thus, in the class Interval<T> shown below, all attributes have
the possibility of containing a Null marker.

```java
type Interval<T> alias IVL<T> extends Set<T>
{
    T low;
    BL lowClosed;
    T high;
    BL highClosed;
    T.diff width;
    T center;
    IVL<T> hull(IVL<T> x);
    literal ST;
    promotion IVL<T> (T x);
    demotion T;
};
```

For example, this allows an interval with missing ends and width to exist as a structured type. The
consequence of the approach is that the entire model is essentially a model of "partial" data types;
_any attribute and any function call may return a Null value, as well as the true values of its type_ (in
fact, in the specification, Null values are defined to be valid values of all data types). This design
decision was taken in HL7 so that any datum, no matter how unknown, would be structurally representable
in the same way as completely known data, enabling it to be processed in the same way as all
other instances of the same type.

However, an important object-oriented design principle has been ignored in this approach. In the
proper design of classes, properties and class invariants are stated. Invariants are statements which
describe the correctness conditions of instances of the class; the general rule is that the post-condition
of a creation routine (constructor) of a class must be that the invariants are satisfied. For example, an
invariant of the HL7 `IVL<T>` class could be:

```
(exists(low) and exists(high)) or else
(exists(low) and exists(width)) or else
(exists(width) and exists(high))
```

When an instance of this class is created, this condition should be satisfied, and remain satisfied for
the life of the instance. To do otherwise is to create instances of data which other software can make
no assumptions about, and is forced to check every single field, and then determine what to do in an
ad hoc way. (See citenp:[Meyer_OOSC2] p366, citenp:[Booch1994] p43, citenp:[Kilov1994] p29 for detailed explanations of the invariant concept).
Possible consequences of the built-in Null marker design approach include:

* since even HL7's basic types `ST`, `INT`, `REAL`, `LIST<>`, `SET<>` include null markers, processing
of null values will be pervasive at the lowest level;
* software will be more complex, both implementations of the data types, and of software
which handle them. This is because the software always has to deal with the possibility of
calls to routines and attributes returning Null values. Most clinical information systems to
date have taken the approach that a datum is either represented as an instance of a formal
type if fully known, or else as narrative text if only partial;
* data may not be always be safely processable, since some software may not properly handle
the null values associated with attributes of partially known data items. Essentially, all software
which processes the data has to be "null-value aware", and make no assumptions at all
about whether a particular data instance is valid or not.

The HL7 data type model is in contrast with simpler approaches such as used in CEN, GEHR, and
openEHR, where data types are formal models of types such as Coded_term, Quantity and so on.
Rather than build the possibility of null markers into every attribute and class in the data types, a single
null marker is defined in relevant containing classes. This decision is based on the principle that
data types should be defined independently of their context of use. Hence, where data types are used
as data values, such as in the value attribute of the class `ELEMENT` from the openEHR EHR reference
model, the parallel features is_null and null_flavour are also defined. However, where data types
appear as attributes elsewhere in the model and there is no possibility of them being null, no null
markers are used. The figure below shows visually the difference between the two approaches.

.HL7 and Typical Null value approaches
image::{doc_name}/diagrams/HL7_null_value.png[id=HL7_null_value, align="center", width=65%]

The consequences of the standard software-engineering approach include:

* data types can be more easily formally specified, since the semantics of invariants, attributes and operations do not need to include the possibility of null values;
* software implementations are simpler;
* data are always guaranteed to be safely processable for decision support and general querying, since no instance of a formal type will be created in the first place if the datum is very unreliable;
* null markers only appear in models where they are relevent, rather than everywhere data types are used;
* however, the openEHR data types do not automatically deal with missing or unknown internal attribute values (such as missing high and low values for an interval, partial dates etc).

In order to deal with the last possibility, various approaches are used in openEHR:

* for most data which is not fully known, no data type instance is created, and a null marker is created. Depending on the design of the revelant archetypes, there will usually be the possibility of recording the datum in narrative form;
* `ENTRYs` in the openEHR EHR reference model include a certainty:Boolean attribute, for recording a level of doubt;
* for particular data types which are often partial, special features are defined. The main types affected are `DV_DATE`, `DV_TIME`, and `DV_DATE_TIME`; the properties month_unknown, day_unknown, minute_unknown, and second_unknown (based on ISO 8601 semantics) are used to define explicitly the semantics of dates with a missing day, times with missing seconds and so on;
* Intervals of date/time types include types generated when the parameter type is one of the partial classes, thus, types `DV_INTERVAL<DV_DATE>` (where one or both ends has an unknown part) are possible. This covers the need for intervals in which some date is missing from the end date/times, while not allowing intervals with completely missing items to be created;
* for expressing uncertainy more precisely, probability distribution data types (based on the types defined in HL7) can be used.

A consequence of the HL7 model is that data instances represented in XML or another structured text
format will be structurally the same regardless of whether there are Null values or not. A structured
form for partially known data (which would normally break the invariants of its class) may well be
useful for representing the data as part of a text field, making it easier to use for whatever processing
is possible later on.

### Terminology Approach
The approach in openEHR is to assume the existence of a Terminology Server which is the sole
authoritative interface with terminologies of any kind, and is the only entity which can assume
responsibility for querying, post-coordination or other manipulations of terms. No allowance is made
for coordination of "modifiers", "qualifiers" or any other terms outside the service. As a consequence,
there are no coordination facilities in the type `DV_CODED_TEXT`, a departure from earlier versions of
the specification - any term provided from the terminology service must already be "coordinated",
either by the terminology service, or by one of the terminologies it accesses. This places the responsibility
of combining terms firmly in the knowledge part of the system, and prevents unsanctioned,
unvalidated combinations being created elsewhere.

### Date/Time Approach
The HL7 specification uses a single `TS` type to represent all logical dates, times, date/times, and partial
versions thereof. The openEHR specification defines distinct types for each, since these are the
types which occur in the real world, and it is easier to specify correctness constraints with this
approach. It is recognised that a single type may be used by some implementors (depending on what
is available in the language being used), however, the recommended practice is to wrap any such
types with the logical types described in this specification. This approach reduces the possibility for
any errors in transmitted data (since no strange combinations of year, ... , second can occur not explicitly
described in the type definitions).

### Time Specification Types
The HL7 approach for time specification appears to cover all reasonable requirements, but has some
minor problems, including:

* the types `PIVL` and `EIVL` are declared as being generic types (i.e. `PIVL<T:TS>`,
`EIVL<T:TS>`), when there appears to be no reason for this;
* the `PIVL`.`_phase_` attribute is used to represent an interval during which a activity occurs,
example given is "2 minutes every 8 hours". However, the "2 mins" is almost always part of
a therapeutic prescription of some kind, not part of the timing specification as such. Therapeutic 
prescriptions have the form "do X every Y time", where the X describes what to do,
and how long to do it for (e.g. 40 mins massage, administer a drug slowly over 10 mins). In
fact, what we are really interested in with a timing specification is the specification of the
starting points in time of some activity, not a time-based graph of on/off points, whch is
effectively what the `PIVL` type is now.

### Type Conversions
The HL7v3 data types specification allows various type conversions, as follows:

    Three kinds of type conversions are defined: promotion, demotion, and character string literals.
    Type conversions can be implicit or explicit. Implicit type conversion occurs when a certain
    type is expected (e.g. as an argument to a statement) but a different type is actually provided.

One notable kind of conversion possible in HL7 is of a value of any type `T` into an instance of
`Set<T>`, `List<T>`, `Bag<T>` or `IVL<T>` containing the value.
The openEHR model does not provide for any type conversions other than those automatically available
between inbuilt basic numeric types such as Integer, Float and Double, and between types
related by inheritance, as supported by all object-oriented languages.



:sectnums!:
## References

bibliography::[]
