Mostrando entradas con la etiqueta FHIR. Mostrar todas las entradas
Mostrando entradas con la etiqueta FHIR. Mostrar todas las entradas

lunes, 11 de mayo de 2020

Generating FHIR Logical Models from archetypes: Transform and roll out!

Transforming archetypes to specific resources (like Observation or Questionnaire) can be useful for quick integrations. However, most of the remaining Resources are not as generic, and thus a specific transformation will not always be reusable enough to justify an specific transformation process. For this case, one thing we can do is to generate FHIR Logical Models. These are not intented to represent new Resources, but could be used to represent any archetype or template in a way that FHIR tooling can understand.

Generating Logical Models from archetypes or templates is a direct process, but in the end generation process differs a little from the already defined transformations to Observation or Questionnaire.

One of the main differences is that while the Observation transformation is based in generating the 'differential' part of the StructureDefinition, for Logical Models we actually generate the 'snapshot' part of the StructureDefinition.1

Another interesting thing is that this transformation process works regardless of the input archetype reference model. This is because process in completely based on the Archetype Object Model (AOM). 2

What this means is that this process can generate Logical Models not only from openEHR EHR Reference Model, but also from openEHR demographic model, ISO13606, HL7 CDA, or even CDISC ODM. In principle, generating archetypes works for any standard or local structures that are expressed as either XML Schemas or BMM and has the notion of "building block". The only real development needed to support a new reference model is to define a set of data types equivalences.

It is also worth noticing that this will work also for any kind of artifact that LinkEHR can import (OPT, OET, and even ADL2 archetypes), as they are all transformed to AOM structures in the end.

Process is quite straightforward:
  • As similar to other StructureDefinition generation, first the metadata part of the Logical Model is generated from the archetype/template.
  • Nodes in the archetype are traversed in order to generate the corresponding id, path, short text, definition, and min/max occurrences. Other attributes such as mustSupport, isModifier, and isSummary are also added.
  • Archetype internal references are transformed to contentReference
  • For types of Element and above, their type is transformed to BackboneElement.
  • Objects of type Element and their corresponding data type are fused as a single entity with the text, description, etc. of the Element and type of the transformed data type. 
  • Data type alternatives are added to the element path to create unique paths. Probably an invariant would be needed to show that they are actually alternatives.
There is still a few useful things missing in this transformation that could be added:
  • Probably mappings to the actual archetype paths can be defined, like it's already included in the Observation profiles. Currently they could be reverse engineered from the generated FHIR paths, but there is no reason to not include them as mappings (or even bindings).
  • Multilinguality is lost in this transformation. This probably differs quite a bit between STU3 and R4. Needs more examples on how it is usually done in FHIR.
  • Add the option to complete with reference model: Archetypes also define some kind of 'differential' view over the reference model, but it's easy to complete the archetype with the underlying reference model to get all constraints.
  • ArchetypeSlots are a completely different approach to using References to profiles. As far as I know, References can only be defined to point to specific profiles, while archetypes typical use case includes pointing to multiple ones (e.g. a given archetype or any of its specializations). This means that there is no direct mechanism to transform ArchetypeSlots for the moment.
All this process was already available on last week's LinkEHR release. Support to more data types has been added in this week's release. All feedback is welcome.
1. This wasn't always the case, as the original intent for Observation transformation was to let users choose if they wanted to define the differential or the snapshot+differential. This second option was discarded because it was really time consuming and FHIR tools can already generate the snapshot+differential from the differential
2. For FHIR Observation transformation the input could also be a ISO13606 archetype, but this was possible because the process looked for specific openEHR or ISO13606 classes.

lunes, 27 de abril de 2020

Generating FHIR Questionnaire resources

These days of quarantine (we are literally more than 40 days now here in Spain) have not been the most productive days of all, but I wanted to put a little effort in helping in the great effort that is the COVID openEHR template. Seriously, take a lot at it, it's impressive the quality and how fast deployment in real systems has been.

In any case, as I don't have a clinical background, I couldn't help much other than translating some not-so-clinical archetypes (occupation record, etc.) to Spanish. But one thing I could do was to finally work on another idea of generating Questionnaire instances from a given template/archetype. For that, openEHR COVID template seemed like the perfect use case: It would require fast iterations and no (human) time should be spent in the generation of the equivalent FHIR Questionnaire for each revision.

With that in mind, I looked at the available FHIR Questionnaire examples and took the common meta attributes and tried to relate them to the archetype ones. Some are always put as constants in any case (e.g. even if it was a published archetype, the autogenerated questionnaire always should be a 'draft').

After that two main big tasks were detected:

  1. Transform a given object in the archetype to the corresponding item in the questionnaire instance.
  2. Flatten the archetype hierarchy as much as possible to obtain all possible questions

For 1) the process was more or less direct: Generate a linkid from the template/archetype path, get the text from archetype, get the object occurrences to give value to the repeat attribute if necessary and finally transform the archetype rmtype to the corresponding questionnaire item type. For this, it was assumed that any remaining hierarchy objects should be treated as questionnaire "group". Data types are translated to the closest type. If an implicit value set is defined in a coded text of the archetype, the corresponding FHIR ValueSet is generated and the item points to it. In this case the type "choice" is selected.

For 2) an specific traverse algorithm for openEHR Reference model was designed. This algorithm traverses the template tree and only generates the items that are interesting (e.g. it avoids generating the History, Item_tree, etc. levels). This process also merges both Element and data type objects, so the same FHIR question item can have a question text and a data type.


Snippet of openEHR COVID-19 Pneumonia Diagnosis and Treatment (7th edition) template transformed into a FHIR Questionnaire



Besides these tasks, there were a few little challenges:
  • Even if you usually create profiles for each Resource, in case of questionnaires you define an instance of Questionnaire resource. Then your QuestionnaireResponse instances relate to that instance of the Questionnaire resource. This does not make the process more difficult, but means that not all the already developed methods to deal with the transformation of an archetype to a FHIR Observation Resource could be reused directly (e.g. different data types being allowed as parts of Observation and Questionnaire, which has already been discussed by Thomas Beale in the past).
  • Another thing that was available for the FHIR Observation transformation that is not available for Questionnaires is the mapping part. It should be very interesting to point to the exact archetype paths where a question comes from, but as far as I know this is not possible in vanilla questionnaires.
  • As already happened with the FHIR Observation transformation, FHIR doesn't really support the alternatives in monovaluated attributes. This is also true for FHIR Questionnaries and is also present in the COVID template (e.g. having an data value alternative of DV_TEXT and DV_CODED_TEXT, or DV_DURATION and DV_CODED_TEXT). As far as I see it there isn't a satisfactory solution to this yet, so for the moment only one of the alternatives is generated.
  • Archetype slots provide a challenge as they potentially reference an open set of archetypes, which as far as I understand the FHIR Reference Resource cannot handle. For the time being, ArchetypeSlots will be ignored in the transformation.
  • In case of openEHR COVID template, having the Symptom/Sign name as another element complicated things a little, as this should end merged with the corresponding values or presence absence. Luckily it was a pattern that could be easily implemented in step 2.
  • Archetypes are multilingual, but Questionnaires are not (maybe there is one extension out there that deals with it). In any case, getting the texts from a given language in the archetype vocabulary should be trivial, so multilingual questionnaires could easily become a reality with very little effort.
This functionality is part of LinkEHR since 2020-04-22. Try it and suggest improvements if you want :)

Next blog post will talk about the other new functionality introduced in that LinkEHR version, the generation of FHIR Logical Models from archetypes

jueves, 28 de noviembre de 2019

Extracting (all) CKM ValueSets

A derived results from the latest developments on the openEHR -> FHIR transformation is that I end up developing a method to analyze all the contents of an archetype to identify potential elements to end in a profile, regardless of the source class of the archetype. With that method developed, there was only a sensible thing to do...


Based on the CKM github mirror I applied the process to generate the profiles for each archetype, which in the end generates the ValueSets for each DV_CODED_TEXT, DV_ORDINAL, and even DV_QUANTITY units.

So this is the result. A set of 1023 ValueSet profiles where generated. This shows how much knowledge and effort has been put into developing CKM archetypes. For example, "location of measurement" ValueSet provides a set of 15 terms translated to 15 languages, which is something I've never seen before in a given subset.

Extract from locationofmeasurement ValueSet




I plan on regenerating this from time to time, so check the date for getting the latest version.

(and as a remainder, unless stated otherwise everything I put in this website has a CC-BY-SA license, so take it, try to break it and tell me if it actually breaks ;)

miércoles, 30 de octubre de 2019

Using LinkEHR to generate FHIR Observation profiles

After my last 'summer challenge' post one of the missing things was to make it publicly available in a simple way. This post shows how that algorithm was actually implemented in LinkEHR. This functionality is available in LinkEHR version that can be downloaded from linkehr.com

The process is quite straightforward:
  1. Open a given archetype (or import OPT)
    1. Process is NOT limited to openEHR Observation archetypes, any archetype can be feed as an input. Output will always be FHIR observation profile/s
  2. Launch the wizard in Advanced utilities -> Transform openEHR to FHIR observation
  3. Select an output path
  4. Select the archetype paths to be exported
    1. The process lists all paths with a leaf node, regardless of where are they included in the archetype (data, protocol, etc.)
  5. Select the type of the element in the FHIR profile (as Observation.component, as Observation.value or as a new extension)
  6. Check the suitable options from the bottom and press Finish



Process should provide a observation profile + a set of ValueSets coming from the coded values of the archetype. It also provides the Extension profiles from nodes selected as extension (if any)


What is currently supported via UI

  • Add translations to ValueSets
  • Support to OPTs as input 
    • Presented OPT paths are not as readable as in normal archetypes, but the process should work Ok anyway
  • Generate mapping file
    • Creates a LinkEHR mapping file containing the mapping the openEHR source paths to the target FHIR XML paths
  • Generate empty FHIR archetype
    • This creates an empty FHIR archetype for being use with the above mapping file. This allows the automatic generation of an XQuery program to transform openEHR data instances into FHIR data instances

 What is currently supported by code (hopefully soon in the UI)

  • Generate a set of observation profiles from a single openEHR archetype. 
    • Still evaluating how to create a simple UI for this functionality
  • Deal with underlying openEHR Reference Model
    • Some RM attributes are probably interesting to be included in profiles, which means some kind of merge of RM + archetype must be done
  • Generating STU3 profiles
    • It is supported to generate both R4 and STU3 "flavours"of FHIR. However, needs more testing to ensure everything is still correct after latest changes.

Currently working on

  • Dealing with DV_IDENTIFIER. 
    • No support for Identifier type in Observation.component.value[x] means that either identifiers are put in some specific paths in the FHIR profile or we create extensions. Trying to identify all these possible paths to ask users what they want to do with them

Potential improvements

  • Support other reference models
    • ISO 13606 would be almost trivial, but probably other RM such as HL7 CDA are interesting to tackle
  • Create Bundles to group the observations
  • Evaluate other classes (openEHR Composition with FHIR Composition resource)

Please tell me any doubt, problem, or error you found with the process so I can fix it. Probably best channel is by twitter (@yampeku)

PS: This functionality has actually been a month included in the tool, but only a few selected people knew it was already there to get their feedback

miércoles, 10 de julio de 2019

openEHR Observations to FHIR profiles, my 2019 summer challenge

This personal challenge started with a tweet from @siljelb asking for tooling for transforming openEHR archetypes to FHIR profiles. This was something I've always wanted to prove, so why not turn this into a personal summer challenge?

FHIR to openEHR 

 

My first thought was to generate an archetype from all the different components and extensions included in a FHIR profile. The rationale being that we already have systems capable of supporting arbitrary archetypes and archetypes have little problems when you want to include an unknown/big set of data values. After a little bit of profile analysis and a little trial and error I ended with a method that received an observation profile (with all the definitions of the extension it contained) and outputted a single observation archetype. As an example, here is the algorithm applied to the genomics profile.


Original genomics profile

Output observation archetype



(I would found later on that this particular example is not really accurate of how complex observations should be modeled in FHIR, but algorithm should stay more or less the same).

Although it seemed like a good idea at first, this transformation has a big issue: Two slightly different profiles will give us two different archetypes that will have to rely fully on terminology bindings to know they are talking about the same, which kind of goes against the philosophy of one archetype per concept. Archetypes are supposed to represent a universal use case (aiming to a max data set instead of a 80/20). These FHIR to openEHR transformations could work well enough in isolation or a single project but not a CKM-type environment. FHIR embraces local profiles and extensions, which could make their governance quite an issue.

openEHR to FHIR


One important lesson to get from this first experience is that a set of profiles will transform into a single archetype, but also a single archetype will end as a set of profiles! So while the FHIR → openEHR way only generates a single archetype and doesn't need any further user input besides choosing the set of profiles, the openEHR → FHIR transformation needs more information. Specifically, we need to tell the algorithm three things:
  • Select the Element that would go into the value part of the Observation profile (if any)
  • Select the list of elements that will end as components (they can go without value, they can also be an empty list)
  • Select which Elements of the original archetype are suitable to be transformed into extensions.
For first two, openEHR Clusters can give an idea of pieces of an observation that make sense as a group. So from there users should be able to choose what constitutes the value and what parts constitute the components. Clusters in Clusters are an interesting use case that probably needs that users choose directly how it should be generated. If we consider that every part in the archetype is equally important, then everything could end in profiles with values constraint to [0..0] and every archetype part modeled as components, which could make this process completely automatic.

For knowing what could be an extension, archetype slots provide an excellent indication. We could also analyze all archetypes in one go and create the different parts that could be reused as extensions (Can we create some default Protocol-like profiles? Do we need to take into account default parts from RM and always include them as extensions?)

Once we decide that, the generation of the Observation, Extension, and even ValueSet profiles is quite straightforward. For data types equivalences, I built this transformation based on the openEHR wiki page about data types equivalence. For the moment only the most usual data types have been translated (namely DV_TEXT, DV_CODED_TEXT, DV_DATE_TIME and DV_QUANTITY), but adding new ones should be easy (with maybe the exception of DV_ORDINAL alternatives).

Snippet of State of Dress valueset


The profile differences between STU3 and R4 aren't too many, so I've included support for both generations. User can choose which one generate as a parameter.

The generated profiles were adjusted thanks to the Hammer tool, so they should be correct for STU3. After a bit of tweaking I got rid of the unknown error that was preventing me to import them into Forge R4, so they should also be R4 compliant.

Weight profile from openEHR weight observation archetype


What's next

  • More testing! 
    • Do you have any archetype you want to test?
    • Could be interesting to process all CKM in one go? (at least for ValueSets)
  • Should we put all generated ValueSets in our FHIR terminology service?
  • More data types!
    • Some data types are still missing. I think that it is possible that some data types, such as openEHR Ordinals alternatives will provide bigger challenge if they have additional optional elements.
  • Make it more configurable, e.g. change base uris, etc.
  • Put the algorithm into LinkEHR Editor and provide a minimal user interface to ease the element selection process.
  • Use the process to generate the mapping that will generate automatically a transformation program to generate the different FHIR Observation instances.
    • Mapping seems that could be bidirectional, as it seems that all mappings are atomic.

Lessons learned

  • It is feasible to create a semiautomatic translation from openEHR to FHIR. We can make global assumptions to make this process automatic.
  • FHIR to openEHR transformation is straightforward, however to take advantage of the big amount of high quality clinical models already avaliable in openEHR it seems preferable to use openEHR archetypes as a basis and generate profiles for them.
  • The differences in StructureDefinition between STU3 and R4 that matter to this transformation are manageable.

Bonus for those of you getting to the end, the good ol' Blood pressure archetype as a FHIR observation profile

miércoles, 9 de mayo de 2018

Using SNQuery to test FHIR subsets

When defining Snomed CT subsets, the most common approach is to define them in an extensional way. This is also the case for national bodies or subsets defined in FHIR specifications. These extensional subsets definition have several potential problems, such as missing out concepts out of the subset or the existence of homograph words that cause the choosing of wrong terms. There is a missing opportunity for the use of Snomed Expressions Constraints for subset definitions. We will use SNQuery to demonstrate how we can create or validate existing subsets in an easy way.

Subsets with logical definition (is-a)


The first example, is those subsets which also contain a logical definition with "is-a" relationships such as medication codes valueset or body site valueset
For medication codes valueset, the definition is as follows:

This definition can be easily translated to Expression Constraint Language like this
<< 410942007 |Drug or medicament (substance)| OR << 373873005 |Pharmaceutical / biologic product (product)| OR << 106181007 |Immunologic substance (substance)|
 This expression in the latest substrate available (20180131) contains 28928 concepts

Lists of codes


Several FHIR subsets are defined as sets of codes (such as bodysite relative location). The main problem with this approach is that subsets may be incomplete, or be potentially wrong, as hand picked words could have several meanings (e.g. the same term can be used to represent the procedure and the tissue where the procedure is made). These errors are revealed easily by looking to some graphs. In case of the bodysite relative location, the equivalent expression is the following one:
419161000 or 419465000 or 51440002 or 261183002 or 261122009 or 255561001 or 49370004 or 264217000 or 261089000 or 255551008 or 351726001 or 352730000






This graph shows where most of the concepts fall. In this case, all bodysite relative locations are qualifier values, which seems correct.

These kinds of visualizations become more useful, the more concepts the subset has. For example facility codes subset, which contains 79 concepts.





The last graph can be interpreted as follows: Of the 79 concepts contained in the subset  94% (74 out of 79) are a 'site of care', with 4 of the remaining ones being 'community environment' and a single one is a 'hospital environment'. With this kind of visualization, some questions can be raised: That single code in the hospital environment subtree should be referring to itself and all the allowed children? Could we get away with simplifying the subset to the expression "< 276339004 |Environment (environment)|" which contains all the environments known in Snomed? Do the terms annotated in the original FHIR subset with "--OTHER--NOT LISTED" should always be translated into a children or self operation?

Validating subsets

One of the advantages of this approach is that the graphical representation also allows for a quick review of the quality of the proposed subset. As an example the specimen collection method, which can be defined with the expression constraint

119295008 |Specimen obtained by aspiration| OR 413651001 |Bioptics| OR 360020006 |Extirpation - action| OR 430823004 |Examination of midstream urine specimen| OR 16404004 |Induced| OR 67889009 |Irrigation| OR 29240004 |Autopsy examination| OR 45710003 |Sputum| OR 7800008 |Punctate| OR 258431006 |Scrapings| OR 20255002 |Blushing| OR 386147002 |Smear procedure| OR 278450005 |Finger stick|

This subset contains 13 concepts, and shows the following graph:




One thing that can be quickly seen is that the focus concept (which can be interpreted as the minimum common ancestor) is the Snomed CT root concept. This means that concepts in the subset have no other common parent aside from the Snomed root concept. This serves as a sign that subset definition has potential problems.

A more detailed analysis shows that:
  • 5 / 12 concepts are in the procedure hierarchy, which seems fitting as we are talking about collection methods.
  • 3 / 12 concepts are in the qualifier value hierarchy
  • 2/ 12 concepts are in the specimen hierarchy
  • 1 / 12 concept is in the substance hierarchy
  • 1 / 12 concept is in the observable entity hierarchy 
  • 1 concept is inactive and shouldn't be used

 Taking a careful look at the concepts not in procedure hierarchy, some problems become apparent:
  • The concept "45710003 |Sputum (substance)|", which refers to the substance, is used to refer to the method of collection. In this case, the concept "37705003 |Collection of sputum (procedure)|" seems way more fitting to the purpose of the subset
  • The concept "20255002 |Blushing, function (observable entity)|"refers to an observable entity. It seems that the correct concept could be "225063006 | Flushing cannula (procedure) |"
  • Similar to the last one, "258431006 |Scrappings (specimien)|" and "Specimen obtained by aspiration (specimen)" seem to be unfitting for the purpose of the subset. Probably, "56757003 |Scraping (procedure)|" and "14766002 | Aspiration (procedure) |" should be used instead. 
  • The inactive concept "386147002 | Smear procedure (procedure) |" was made inactive because it was ambiguous. By reviewing the code in the Snomed Browser (see RefSet tab) we can see that code should be "448895004 | Sampling for smear (procedure) |" or "448938001 | Preparation of smear (procedure) |" (or both).
  • Regarding the selected qualifier values, the correct approach shouldn't be to add these qualifiers to the set, but to allow the procedures that use this qualifier value. This can be expressed as 71388002|Procedure (procedure)| which 260686004 |Method (attribute)| is any of the three qualifier values. Formally, the expression for these qualifier values would end as:
 <71388002|Procedure (procedure)|:260686004 |Method (attribute)|=(16404004 |Induced (qualifier value)| OR 360020006 |Extirpation - action (qualifier value)| OR 7800008 |Punctate (qualifier value)|)
Note: Even if Induced and Punctuate terms are not currently used as destination of any attribute in Snomed CT, this expression constraint allows to validate the post-coordination of procedures that use these methods
In addition to validating the subset we should also ask ourselves again if there is some expression that could be used to group terms, and by doing so, simplify the expression.

Conclusion 

As the examples show, these subsets' visualizations could help clinical experts in the subset definition, validation, and curation. Extensional subsets may seem easy to define, but could led to potential problems if the hierarchy is not taken into account when defining the subset. Even if (arguably) one of the advantages of defining extensional subsets is to limit the possible inputs in a form, official provided subsets should always try to include all and every term useful for the subset to ease interoperability. When implementing the subset in a given organization is always better to further refine a subset than to extend it with terms not originally included in it.




jueves, 16 de marzo de 2017

Archetyping FHIR

As Thomas Beale said in his excelent piece about openEHR and FHIR, the semantic coverage of FHIR Resources is hard to determine (are they like archetypes? like a reference model? something in between?). Personally my opinion is that they are something in between: Some resources like AllergyIntolerance, NutritionOrder, or ReferralRequest are closer to the level of semantics included in archetypes; On the other hand, resources such as Observation, Patient, Questionnaire or even Bundle feel more like reference model classes that could be archetyped in the end.

With this basis, using some of these resources as if they were reference model classes to be used in archetype definition tools seems like a good experiment.

The FHIR Reference Model

Luckily for us, even if FHIR 'source of truth' are 'Excel spreadsheets saved as XML plus a variety of ini, html and XML files', FHIR also provides a set of XML Schemas for validation purposes and code generation. We can use these XML Schemas as a way of importing FHIR Reference Model (RM) into LinkEHR Studio

LinkEHR reference model manager


With this, we can create new archetypes based on FHIR RM (at least from the one it makes sense to do that). Having everything else in the RM is also helpful to create mappings between these resources and other RM (e.g. HL7 CDA, openEHR, ISO13606, CDISC ODM...) in order to generate transformation programs for them.

FHIR profile as archetype


There are probably two drawbacks to this approach, and both are due to non-technical reasons (and probably related): There are already a couple of tools for profiling in FHIR, and most people from FHIR community doesn't see the benefits of using archetypes for profile definition. So what else can be done to ease these concerns? Two come to mind: Integrate into FHIR workflow by providing means of going from profiles to archetypes, and provide added value to attract people to use the tooling.

From Profiles to Archetypes (& Added Value)

Luckily, the definition of profiles themselves follows a known structure (StructureDefinition resource) and can be easily parsed to generate archetypes from them. We added LinkEHR the ability to import FHIR profiles.

Importing a FHIR profile as an archetype


Right off the bat, these FHIR archetypes provide some advantages, such as multilinguality, solving profile consistency, and reuse of semantic artifacts (archetype slots, internal references, and semantic patterns)(More about this on [1]). In addition to that, they also allow the use of our tooling to derive from these FHIR archetypes interesting reference materials such as mindmaps, schematron rules, Json Schema, implementation guides, and more importantly, automatic generation of transformation programs from mapping definitions.

Furthermore, FHIR StructureDefinitions also contain mappings definitions to several standards and terminologies. Terminology mappings (Loinc, etc.) can be added as archetype terminology bindings. Mappings to other standards such as HL7 CDA can be used to create mapping definitions that LinkEHR can understand.

FHIR archetype with mapping imported from profile definition

These mapping definitions can be then automatically compiled into an XQuery program to transform CDA data instances into FHIR data instances. Notice that users do not need to provide any additional mappings for this automatic generation (but they can if needed, of course).

Automatic generation of XQuery

Testing the XQuery

What is Next?

With this, we have generated a one way import process from profiles to archetypes. The other way around (archetypes to profiles/StructureDefinition) seems like the obvious next step, and shouldn't be too hard.



[1] Combining Archetypes with Fast Health Interoperability Resources in Future-proof Health Information Systems
MIE presentation

martes, 7 de febrero de 2017

FHIR comparado con openEHR

El siguiente post es una traducción al castellano del magnífico artículo de Thomas Beale "FHIR compared to openEHR". Me parece que deja bastante claras las cosas así que espero que con esta traducción pueda llegar a más gente.


--------------------

Cada vez más personas y organizaciones se hacen la vieja pregunta de cómo se comparan estándares entre ellos, hoy en día en la forma de: ¿Cómo se comparan o se relacionan HL7 FHIR y openEHR?

Siempre es entretenido revisar esta cuestión cada cierto tiempo, especialmente cuando algunos de los que preguntan son lo suficientemente jóvenes y afortunados para no conocer demasiado la historia de los estándares en salud. Para entender la pregunta hace falta revisar unos cuantos conceptos básicos de la informática médica. Este texto trata de ser lo más objetivo posible, pero es obvio que conozco con mucho más detalle openEHR que FHIR.



¿Cómo se soluciona la necesidad de interoperabilidad?

La respuesta traditional, y la base de HL7, EDIFACT, etc. es decir que no podemos controlar lo que hay en los sistemas, por lo que necesitamos imponer estándares en el flujo de datos entre sistemas (esto es, mensajes). Esto ha funcionado de modo satisfactorio por muchos años para cierto tipo de datos bien definidos, particularmente resultados de pruebas de laboratorio y prescripciones. De hecho muchos sistemas todavía bombean millones de HL7v2.3 o v2.5 mientras escribimos esto.

Sin embargo, diría (y creo que la mayoría de la comunidad de openEHR, 13606 y HL7 CIMI están de acuerdo) que:

  • En los últimos 20 años, el rango de la semántica y datos que necesitan ser compartidos para permitir una historia de salud electrónica es mucho mayor que el que puede ser acomodado por mensajes que capturan conjuntos de datos específicos, y de hecho el tamaño y la complejidad de esta semántica es tal que es simplemente insostenible tenerlos descritos o bien dentro de productos de comerciales específicos (en forma de formularios en pantalla) o incluso en formatos de mensaje específicos, lo que implicaría tener que volver a expresarlos para cada nuevo formato (interfaces de usuario, captura de datos en dispositivos móviles, varios formatos de documento, etc.) y tecnología (diferentes tipos de bases de datos, Javascript, etc.).
  • A diferencia de hace 20 años cuando muchas soluciones no eran más que pantallas sobre tablas en una base de datos, los creadores de sistemas de hoy en día son muy conscientes de la semántica que necesitan en el interior de sus sistemas.
  • La gente que entiende la semántica del dominio no son el personal de IT, son profesionales del dominio y expertos en informática médica con un conocimiento profundo del dominio (aquí otro artículo tratando este punto).

Mi punto de vista es que el único modo escalable para crear especificaciones con semántica es que éstos sean artefactos externos tanto para los productos comerciales como para formatos específicos de comunicación. Esto conlleva una aproximación basada en modelos comunes, con los modelos existiendo en su propio formalismo, herramientas y comunidades. Ejemplos de estos ‘modelos’ incluyen terminologías como CIE (ICD), SNOMED, CIF (ICF), etc.; arquetipos y plantillas de openEHR y de otros grupos como HL7 CIMI, guías clínicas, diccionarios de medicamentos y así sucesivamente. Todos estos modelos diferentes (incluyendo los de openEHR) tienen dos características claves:

  • Son creados directamente por personas que entienden la semántica del dominio.
  • Pueden ser transformados por computadoras en cualquier formato razonable, incluyendo formatos de mensajes.
     


Este artículo sobre escalabilidad semántica proporciona algunas figuras sobre la necesidad de esta aproximación a un modelo común de base.



Teoría de mensaje frente a teoría de sistema

La aproximación anterior puede ser llamada la teoría de sistema de la interoperabilidad: La semántica es formalizada por el dominio y convertida automáticamente a formatos concretos (como por ejemplo XSD, formatos basados en JSON, etc.) usables por sistemas y aplicaciones, incluyendo mensajería u otras serializaciones.

En la teoría de mensaje de la interoperabilidad, el contenido del mensaje (no solamente estructuras genéricas o protocolos de comunicación) se estandariza y se convierte en un/el requisito de conformidad para los sistemas, o cuanto menos para alguno de sus canales de comunicación.
Esto está potencialmente bien desde el punto de vista de al menos algunos de los consumidores de datos de esos sistemas, pero para sistemas que quieren exportar su semántica nativa o basada en modelos, se convierte en casi un escollo. Esto es porque para comunicarse en un canal de mensajería preestandarizado, se tienen que ingeniar transformaciones entre sus datos y las estructuras requeridas por los mensajes. Estos pueden ser bastante diferentes y el mapeo requerido puede no ser trivial - y siempre que existe un mapeo hay riesgos de pérdida de rendimiento, corrección y seguridad del paciente. Si el conjunto de datos del mensaje es pequeño y simple, habrá pocos problemas, pero si ampliamos la casuística para permitir ‘comunicar cualquier cosa’, entonces podemos estar ante un grave problema.

Sin embargo, seguimos necesitando ser capaces de serializar datos y enviarlos a distintos lugares. La teoría de sistema aborda estos problemas definiendo primero los modelos – para nosotros, plantillas de openEHR, que incluyen enlace terminológico – y para generar automáticamente definiciones de mensajes de ellas. Hoy en día esta es una operación trivial, y de hecho lo ha sido desde los tiempos del RPCgen. Consecuentemente, los ecosistemas basados en modelos no necesitan mensajes, solamente necesitan una tecnología genérica de mensajería. Cabe destacar que en esta aproximación, no hay un único formato posible: puede ser cualquier tipo de XML genérico, JSON, binario o incluso formatos de documento como PDF, openDoc, etc.

Por tanto en estas dos aproximaciones teóricas a la interoperabilidad, los modelos están en dos lugares diferentes. En la aproximación de ‘sistema’, que es la que usa openEHR, los modelos están fuera de los productos y formatos concretos de comunicación. Por otro lado, en la aproximación de mensaje están incluídos en un formato de comunicación particular.
Hacerlo basado en sistemas es más difícil técnicamente, pero mucho más escalable y a prueba de futuro. Hacerlo basado en mensajes produce resultados más rápidos, pero se encontrarán problemas cuando el mensaje necesita cambiarse o el tamaño del espacio de contenidos es crece hasta ser demasiado grande.

Más sobre las limitaciones de la aproximación basada en mensajes en este artículo reciente.

El mundo ideal – modelos universales

Una aproximación ideal al mundo de la salud digital sería desarrollar un conjunto universal de modelos clínicos (como antes, ‘modelos’ incluye terminología, subsets, arquetipos, plantillas, guías, etc.) y herramientas que pueden convertirlos en artefactos usables para la creación de componentes del sistema, bases de datos, mensajes, etc. Este mundo ideal fue claramente descrito por el Dr Stan Huff en la creación de CIMI en 2011. Ha sido nuestro ideal desde finales de los 90 y desde siempre de Stan en Intermountain Healthcare. (desde entonces, CIMI ha pasado a convertirse en un comité técnico de HL7, pero creo que todavía persigue los mismos objetivos).

En una realidad alternativa, la aproximación a ‘hacer mensajes’ debería de haber sido ‘hacer modelos’ y entonces generar cualquier tipo de mensaje u otro formato de serialización que se ajuste a circunstancias específicas.

Sin embargo, politiqueos en los estándares internacionales, diferentes necesidades, restricciones temporales y muchas otras presiones lo han impedido, incluso siendo técnicamente posible y estando ya implementado (aunque no de forma universal).

Añadiré que la forma ideal de este tipo de trabajo no es vía diseño por comité (design-by-committee) tal y como se hace en las organizaciones de desarrollos de estándares (SDO) tradicionales, sino vía ingeniería, desarrollada en un estilo de proyecto ampliamente open source (o un conjunto de dichos proyectos en cooperación). Esta es la aproximación que tomamos en openEHR.

El mundo real

En el mundo real en el que vivimos, las cosas son más complicadas. Por un lado la gente intenta resolver diferentes problemas. Uno de los problemas – sin dudas estadísticamente todavía el más prevalente – es extraer datos de sistemas opacos que no quieren darlos (generalmente por razones contractuales o de IP) y contienen interfaces propietarias muy limitadas o incluso simples tablas relacionales en bruto. Otro caso distinto es el de construir una nueva generación de sistemas y componentes que encarnan una comprensión moderna de la semántica sanitaria, esto es, información, procesos, reglas de negocio, CDS, etc. Estos retos corresponden a diferentes aproximaciones.

En el mundo de los estándares sanitarios, HL7 aparcó el esfuerzo invertido en HL7 v3 tras 15 años (demasiado complejo, poco adaptado a las nuevas tecnologías, HL7v2 funcionaba bastante bien) y empezó a trabajar en FHIR alrededor de 2012.

Nosotros por nuestra parte en openEHR continuamos con la aproximación de ‘sistemas’ descrita anteriormente. La norma relacionada ISO13606 y más recientemente la comunidad CIMI han trabajado usando la misma base, como lo han hecho, tácitamente, IHTSDO, editores de bases de datos de medicamentos, algunos emisores de guías clínicas, etc. (i.e., dichas organizaciones producen artefactos cuyo contenido es independiente de los productos particulares de cualquier vendedor y de formatos de comunicación concretos).


¿Cómo se compara FHIR a openEHR?

El principal objetivo de FHIR es solucionar la comunicación de sistema-a-sistema (B2B) y sistema-a-aplicación (B2C), sin hacer ninguna asunción sobre los sistemas. La parte B2B es básicamente la aproximación de la mensajería para el siglo 21; La parte de B2C supone la creación de unas APIs adecuadas para los programas y aborda una necesidad primordial – hacer sencillo construir aplicaciones modernas sanitarias. El reto está en que lo segundo claramente hace asunciones sobre la lógica de negocio y el contenido que incluyen los sistemas subyacentes. 

La intención principal de openEHR es resolver el reto de los de salud de los pacientes – un historial de paciente longevo, versionado, distribuido y computable – y hacerlo de un modo robusto a los cambios futuros, exponiendo la semántica usando una arquitectura de plataforma. Vemos la interoperabilidad como una consecuencia técnica natural de una plataforma basada en una semántica formalizada. Por supuesto, openEHR en si misma solo propone algunos elementos de dicha plataforma – necesita ser usado en conjunción con terminologías, ontologías, bases de datos de medicamentos, interfaces de servicio y demás.

Representación Técnica

FHIR se define a partir de una biblioteca de ‘recursos’ (micro-formatos de datos de la red) y una aproximación técnica al desarrollo de ‘perfiles’ y ‘extensiones’ para soportar la localización (estos términos están todos definidos en el sitio web de FHIR). En otras palabras, hay un cierto nivel de ‘modelado clínico’, pero está dentro del formalismo principal XML de FHIR. Los recursos están diseñados para ser instanciados y accedidos mediante APIs REST.

En openEHR usamos un Modelo de Referencia estándar, y varias capas de modelos sobre él, incluyendo arquetipos, plantillas y subconjuntos terminológicos. El Modelo de Referencia de openEHR es estándar para todo el mundo, y todo los datos basados en openEHR, no importa dónde estén o de dónde vengan lo siguen al pie de la letra. En openEHR y otras comunidades basadas en ADL, los modelos están al margen de la mensajería o de los micro-formatos web y en su lugar son transformados de forma automática a cualquiera de esas formas cuando sea necesario. Esto claramente significa más herramientas: por ejemplo, herramientas para generar XML, JSON, el protocolo de buffer de Google, o cualquier otro, pero la realidad es que estos formatos concretos cambian continuamente – en los 5 años que lleva existiendo FHIR la preferencia principal ya ha evolucionado de XML a JSON.

Los arquetipos openEHR se representan en Archetype Definition Language (ADL) / Archetype Object Model (AOM, un estándar ISO). ADL is también la representación de los modelos de HL7 CIMI. Soporta la composición, especialización y redefinición, permitiendo adaptar los modelos generales en otros más específicos y localizados.

También hay diferencias en el estilo de los modelos que se construyen. En openEHR y tecnologías relacionadas, generalmente son construidos por comunidades de expertos en el dominio clínico, basado en requisitos (‘como nos gustaría que fuera’). En FHIR, la estrategia es producir cada recurso FHIR como un superset de los datos que se pueden encontrar en sistemas legacy, y así satisfacer las necesidades de los desarrolladores. Esto lleva a diferentes resultados – Los modelos FHIR son usables directamente por los desarrolladores, pero difícilmente serán reusables en diferentes tecnologías, como por ejemplo generar formularios en una interfaz de usuario. OpenEHR usa herramientas para generar XSD, JSON, Xforms y otros formatos que los desarrolladores puedan querer. 

Además, en openEHR tenemos una base teórica para la HCE bastante extensa, que nutre al Modelo de Referencia sobre los que se construyen. No soy consciente de que exista algo equivalente en FHIR. Creo que esto importará en gran manera en la interoperabilidad de procesos clínicos entre infraestructuras de e-Salud..

Hay más detalles para los fans de FHIR sobre openEHR en otro post reciente, base técnica de openEHR para usuarios de  HL7 y FHIR.

Alcance de la plataforma

Si estamos de acuerdo en la idea general que una plataforma técnica consiste en modelos de información, modelos semánticos, APIs y consultas, podemos establecer comparativas adicionales.

openEHR tiene una cobertura extensiva de la información de paciente (su Modelo de Referencia define numerosos tipos de estructuras), una cobertura significativa del área de modelos semánticos (creemos que quizás sobre el 25% de la medicina general), y una cobertura limitada en el área de APIs de aplicación (ejemplo), aunque con algunas buenas herramientas, aún sin estandarizar. Esta es una de las principales áreas en las que estamos trabajando durante 2017, junto con una nueva especificación de procesos (acaba de proponerse para comentarios una nueva especificación para la planificación de tareas).

La cobertura de APIs en FHIR es sustancialmente mayor, siendo como es una de sus especialidades, y de hecho el proyecto FHIR podría seguramente afirmar haber hecho un trabajo innovador y pionero en cómo construir APIs para datos complejos e interacciones.

Sin embargo, su cobertura de la semántica del dominio y los modelos de información es más difícil de determinar – depende sobre todo de lo que uno piense que son los recursos FHIR – ¿algo como los arquetipos?¿un tipo de Modelo de Referencia?¿quizás algo intermedio?. Mi lectura particular es que son como una biblioteca de plantillas de openEHR, que disponen de reuso y especialización para la extensión, más un conjunto de recursos genéricos para identificadores, tipos de datos, estructuras genéricas, recursos demográficos y otros tipos para infraestructura. Una diferencia entre los dos es que recursos más complejos, como por ejemplo el recurso Risk Assessment, es su propia estructura de datos, mientras en openEHR  Health risk assessment es un arquetipo de la clase Evaluación del Modelo de Referencia. Añadir un nuevo contenido clínico en openEHR acaba siendo simplemente añadir un nuevo arquetipo (i.e. no es necesario cambiar el Modelo de Referencia); en FHIR necesita nuevos recursos, o si no crear un perfil sobre un recurso existente. Esto implica nuevo software para cada nuevo recurso.

Un área que creo que openEHR tiene bien cubierta son las consultas semánticas, para lo cual usa un lenguaje portátil de query, AQL. En mi conocimiento, FHIR no tiene nada equivalente a esto. Las queries portátiles son potentes porque son completamente independientes de los esquemas del almacenamiento físico y su tecnología – solo dependen de los arquetipos.

El diferente grado de cobertura de elementos esenciales de la plataforma hace más interesante uno u otro ecosistema para diferentes tipos de desarrolladores, pero mucho de lo que usar y cómo se basa al fin y al cabo en el problema que se intenta solucionar.

Hype contra Realidad

Probablemente valga la pena mencionar brevemente el problema del ‘hype’ (altas expectativas) aunque solo sea para alertar a los desprevenidos. FHIR ha sido altamente ‘hypeado’, incluso algunos dirían ‘sobrehypeado’ como en este artículo. Esto no significa que sea culpa del proyecto FHIR, sino más bien debido a la combinación de algo común en los humanos normales como la psicología de la bala de plata (la creencia irracional que una única solución arreglará todos los problemas) y un cierto grado de desespero por encontrar un reemplazo a HL7v3 entre las agencias como la ONC. La mayoría el ‘hype’ ha sido creado por gente con alto grado de optimismo pero un conocimiento ingenuo de las restricciones y dificultades con las que las tecnologías de eSalud tienen que lidiar.

Mi recomendación aquí es simplemente el considerar cuidadosamente los requisitos e intentar entender los paradigmas que se quieren utilizar para resolverlos – por ejemplo, si quieres usar una aproximación tal como una arquitectura de plataforma que usa semántica avanzada, una solución multiusos comercial, o alguna otra aproximación. Entonces aprende cuál es el ámbito de aplicación de las distintas tecnologías disponibles – ¿qué es lo que solucionan?¿qué no solucionan? Cualquier persona racional sabe que ninguna tecnología soluciona por sí misma todos los problemas, y esto es cierto tanto para HL7 FHIR como para openEHR.

¿Pueden openEHR y FHIR trabajar conjuntamente?

Hay respuestas triviales y no triviales a esta pregunta. Si el requisito es hacer los datos de grandes sistemas legacy comerciales disponibles a aplicaciones y permitir ciertos tipos de comunicaciones B2B, FHIR es atractivo porque ese es exactamente el problema para el que fue diseñado, y puede que sea todo lo que necesitas.

Sin embargo, si el fin es construir una plataforma abierta y longeva  de salud, donde la organización proveedora quiere control sobre los datos, interfaces sobre los componentes principales y control sobre las elecciones compras y tiempos, será necesario mucho más. Bajo esta visión, la Historia Clínica Electrónica no es un producto que compras, es una capacidad que creas para gestionar los datos que posees.

Este es el escenario para el que openEHR fue diseñado – ser parte de una infrastuctura de plataforma abierta, tal y como se describe en el White Paper de openEHR. Normalmente este tipo de entorno incluye grandes sistemas legacy y EMRs (esto depende mucho del país), por tanto uno de las tareas principales que una solución openEHR tiene que realizar es la de implementar ‘puentes’ de datos e importación de mensajes, de modo que se pueda convertir las fuentes de datos necesarias en datos semánticos de gran calidad basados en modelos.

El siguiente desafío es cómo implementar unas APIs on la plataforma de modo que se permita la construcción de aplicaciones. Históricamente, la visión de las APIs en openEHR ha sido mas cercana a la de IHE y los servicios de la OMG, como por ejemplo IHE PIX, PDQ, ATNA y OMG EIS y RLUS. De un tiempo a esta parte hemos estado trabajando en una interfaz ligera REST, tanto a nivel de especificación como con herramientas como EhrScape. Esto proporciona unas APIs nativas e interfaces de mensajes en un entorno openEHR.

Si una organización quiere implementar FHIR sobre un entorno openEHR como un añadido a sus interfaces nativas será necesario un esfuerzo. Hay dos aproximaciones. La primera es la ingenua: esencialmente la misma como si se hiciera un canal de exportación del sistema en  HL7v2 o CDA, que es decir que cada recurso FHIR + API requerida, construir una interfaz a medida y un proceso base que use AQL para sacar datos de un sistema openEHR. Los costes de este tipo de aproximación son abiertos, pues cada nueva API requiere más trabajo, pero es probable que sea lo suficientemente sostenible para muchos usuarios.

Una aproximación más potente y escalable sería permitir nuevas ‘particiones de recursos’ en la plataforma de comunicación genérica de FHIR, por ejemplo para acomodar las definiciones de contenido de openEHR, ISO 13606, CDISC o cualquier otro modelo abierto. Esta aproximación se describe en detalle en el post ’Making FHIR work for Everybody’ de hace unos meses (que todo sea dicho, se encontró con una resistencia dentro de HL7 bastante fuerte). La gran ventaja de esta aproximación es que permite a los programadores hablar a openEHR (o ISO 13606, o CDISC BRIDG…) en estilo de FHIR, y usar la aproximación al desarrollo de aplicaciones de FHIR, pero con la interfaz de contenido siendo derivada automaticamente de los modelos relevantes de la fuente en lugar de los recursos nativos de FHIR – lo mejor de ambos mundos.

Mi creencia personal es que esto representa la mejor esperanza de traer juntos estos dos mundos, pero falta ver si HL7 puede convencerse del potencial de esta idea.

Espero que este artículo proporcione un contexto adecuado para aquellos que intentan entender openEHR y FHIR, y especialmente sobre cómo se pueden usar conjuntamente.

Epílogo

Me he dado cuenta de un  pensamiento implícito relevante en mi discusión debería haber de haber sido incluido al final, y es como sigue: Creo que el principal reto para los que trabajamos en eSalud (y de hecho en cualquier cualquier dominio que tenga una complejidad semántica inherente) continua siendo el desarrollo de una biblioteca universal de modelos de esa semántica. De nuevo, la palabra 'modelos' se refiere a su definición más amplia – cualquier expresión formalizada de la semántica del dominio, pero expresada de modo diferente según los productos o tecnologías de implementación con durabilidad limitada.

Algunos dirán que es imposible, porque la gente no se pondrá nunca de acuerdo. Pero existen diferentes niveles de acuerdos. Considera que los 'modelos' son en realidad formalizaciones de teorías sobre algún fenómeno (como describe este artículo). Las teorías se gestan en las mentes de unos pocos, son discutidas, desarrolladas, probadas, reformuladas y así sucesivamente, hasta que finalmente mueren o sobreviven, pero en las mentes de muchos. Los modelos no son mas que expresiones de teorías de comprensión, y el nivel de acuerdo refleja como de ampliamente esa comprensión es compartida.

Hacia donde las tecnologías en sanidad deben de evolucionar es a una completa separación de los modelos de significado (semántica) en salud y las tecnología usadas para implementar soluciones en un momento dado