FHIR Chat · FHIR primitives · python

Stream: python

Topic: FHIR primitives


view this post on Zulip Eric Haas (Dec 19 2018 at 19:55):

I tried to created a FHIRString class or FHIRPrimitive class, I can create the object ( e.g. _text inheriets id and extension) and can use as_json(), but I can't get it to hang off a larger object such as CodeableConcept.text. This is my first foray into python class inheritance and I am not sure why the FHIRprimitive class is not working like the Element Class and adding new element Properties ( id and extension) to the base. I've looked at the Swift code but trying to map that to Python has not been easy.

here is some code...

view this post on Zulip Eric Haas (Dec 19 2018 at 20:02):

I tried just extending the Element class which did not work and now I think I know why

I think the add'l properties need to define in the abstract base class

view this post on Zulip Eric Haas (Dec 19 2018 at 20:05):

It tried using a separate FHIRPrimitive class too which was patterned after the Element class.

view this post on Zulip Eric Haas (Dec 19 2018 at 20:07):

(deleted)

view this post on Zulip Eric Haas (Dec 20 2018 at 02:25):

OK I got it to work .. sort of.... here is my code:

FHIRPrimitive Class:

import logging
from . import element


class FHIRPrimitive(element.Element):
    """ FHIR Primitive Class - is just an empty class for now
    """

    resource_type = "FHIRPrimitive"

    def __init__(self, jsondict=None, strict=True):
        """ Initialize all valid properties.

        :raises: FHIRValidationError on validation errors, unless strict is False
        :param dict jsondict: A JSON dictionary to use for initialization
        :param bool strict: If True (the default), invalid variables will raise a TypeError
        """

        # setattr(self,sunder_name,None)  # how do I get the name

        super(FHIRPrimitive, self).__init__(jsondict=jsondict, strict=strict)

view this post on Zulip Eric Haas (Dec 20 2018 at 02:31):

CodeableConcpept Class: notice I hardcoded '_text' to init and elementProperties.. I tried to do this dynamically but was not successful.

import logging
from . import element


class CodeableConcept(element.Element):
    """ Concept - reference to a terminology or just  text.

    A concept that may be defined by a formal reference to a terminology or
    ontology or may be provided by text.
    """

    resource_type = "CodeableConcept"

    def __init__(self, jsondict=None, strict=True):
        """ Initialize all valid properties.

        :raises: FHIRValidationError on validation errors, unless strict is False
        :param dict jsondict: A JSON dictionary to use for initialization
        :param bool strict: If True (the default), invalid variables will raise a TypeError
        """
        self.coding = None
        """ Code defined by a terminology system.
        List of `Coding` items (represented as `dict` in JSON). """

        self.text = None
        """ Plain text representation of the concept.
        Type `str`. """

        self._text = None
        """ addon for text id and extension. """

        super(CodeableConcept, self).__init__(jsondict=jsondict, strict=strict)

    def elementProperties(self):
        from . import coding
        from . import fhirprimitive
        js = super().elementProperties()
        js.extend([
            ("coding", "coding", coding.Coding, True, None, False),
            ("text", "text", str, False, None, False),
            ('_text', '_text', fhirprimitive.FHIRPrimitive, False, None, False)
        ])
        logging.info("elementProperties for CodeableConcept returning js")
        return js

view this post on Zulip Eric Haas (Dec 20 2018 at 02:34):

so....

from json import dumps, loads
from fhirr4models import codeableconcept as C
from fhirr4models import fhirprimitive as FP
from fhirr4models import extension as X

my_c = C.CodeableConcept()
my_c.text = "foo"
_text = FP.FHIRPrimitive()
_text.id = '123'
my_extension = X.Extension({"url":"http://example.org/fhir/StructureDefinition/text","valueString":"Easter 1970"})
_text.extension = [my_extension]
my_c._text = _text
print(my_c.as_json())

view this post on Zulip Eric Haas (Dec 20 2018 at 02:35):

returns....

{'text': 'foo', '_text': {'extension': [{'url': 'http://example.org/fhir/StructureDefinition/text', 'valueString': 'Easter 1970'}], 'id': '123'}}

view this post on Zulip Eric Haas (Dec 20 2018 at 02:38):

so the question is do we try to initialize the Class and all the primitives on the fly or just regenerate the class definitions with all the '_name' element for all the primitives? ( except for id and extension)?

view this post on Zulip Eric Haas (Dec 20 2018 at 17:05):

I wlll take a look at the class generator to see If I can add this.

view this post on Zulip Geoff Low (Dec 20 2018 at 22:54):

could you use the my_c.update_with_json({'extension': [{'url': 'http://example.org/fhir/StructureDefinition/text', 'valueString': 'Easter 1970'}]}) ? The Element already holds a collection for extension

view this post on Zulip Eric Haas (Dec 21 2018 at 00:59):

I tried but for primitive extensions really are adding an element to the class or a new name value pair to the dict. So I am just regenerating the models to include all these elements.

view this post on Zulip Eric Haas (Dec 21 2018 at 01:01):

for example:

for Patient I just generated this... ( have not tested fully for side effects)

#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
#  Generated from FHIR 3.6.0-bd605d07 (http://hl7.org/fhir/StructureDefinition/Patient) on 2018-12-20.
#  2018, SMART Health IT.


from . import domainresource

class Patient(domainresource.DomainResource):
    """ Information about an individual or animal receiving health care services.

    Demographics and other administrative information about an individual or
    animal receiving care or other health-related services.
    """

    resource_type = "Patient"

    def __init__(self, jsondict=None, strict=True):
        """ Initialize all valid properties.

        :raises: FHIRValidationError on validation errors, unless strict is False
        :param dict jsondict: A JSON dictionary to use for initialization
        :param bool strict: If True (the default), invalid variables will raise a TypeError
        """

        self.active = None

        """ Whether this patient's record is in active use.
        Type `bool`. """

        self._active = None

        """ extension for fhir primitive  active"""

        self.address = None

        """ An address for the individual.
        List of `Address` items (represented as `dict` in JSON). """



        self.birthDate = None

        """ The date of birth for the individual.
        Type `FHIRDate` (represented as `str` in JSON). """



        self.communication = None

        """ A language which may be used to communicate with the patient about
        his or her health.
        List of `PatientCommunication` items (represented as `dict` in JSON). """



        self.contact = None

        """ A contact party (e.g. guardian, partner, friend) for the patient.
        List of `PatientContact` items (represented as `dict` in JSON). """



        self.deceasedBoolean = None

        """ Indicates if the individual is deceased or not.
        Type `bool`. """

        self._deceasedBoolean = None

        """ extension for fhir primitive  deceasedBoolean"""

        self.deceasedDateTime = None

        """ Indicates if the individual is deceased or not.
        Type `FHIRDate` (represented as `str` in JSON). """



        self.gender = None

        """ male | female | other | unknown.
        Type `str`. """

        self._gender = None

        """ extension for fhir primitive  gender"""

        self.generalPractitioner = None

        """ Patient's nominated primary care provider.
        List of `FHIRReference` items (represented as `dict` in JSON). """



        self.identifier = None

        """ An identifier for this patient.
        List of `Identifier` items (represented as `dict` in JSON). """



        self.link = None

        """ Link to another patient resource that concerns the same actual
        person.
        List of `PatientLink` items (represented as `dict` in JSON). """



        self.managingOrganization = None

        """ Organization that is the custodian of the patient record.
        Type `FHIRReference` (represented as `dict` in JSON). """



        self.maritalStatus = None

        """ Marital (civil) status of a patient.
        Type `CodeableConcept` (represented as `dict` in JSON). """



        self.multipleBirthBoolean = None

        """ Whether patient is part of a multiple birth.
        Type `bool`. """

        self._multipleBirthBoolean = None

        """ extension for fhir primitive  multipleBirthBoolean"""

        self.multipleBirthInteger = None

        """ Whether patient is part of a multiple birth.
        Type `int`. """

        self._multipleBirthInteger = None

        """ extension for fhir primitive  multipleBirthInteger"""

        self.name = None

        """ A name associated with the patient.
        List of `HumanName` items (represented as `dict` in JSON). """



        self.photo = None

        """ Image of the patient.
        List of `Attachment` items (represented as `dict` in JSON). """



        self.telecom = None

        """ A contact detail for the individual.
        List of `ContactPoint` items (represented as `dict` in JSON). """



        super(Patient, self).__init__(jsondict=jsondict, strict=strict)

    def elementProperties(self):
        js = super(Patient, self).elementProperties()
        js.extend([
            ("active", "active", bool, False, None, False),
            ("_active", "_active",fhirprimitive.FHIRPrimitive, False, None, False),
            ("address", "address", address.Address, True, None, False),
            ("birthDate", "birthDate", fhirdate.FHIRDate, False, None, False),
            ("communication", "communication", PatientCommunication, True, None, False),
            ("contact", "contact", PatientContact, True, None, False),
            ("deceasedBoolean", "deceasedBoolean", bool, False, "deceased", False),
            ("_deceasedBoolean", "_deceasedBoolean",fhirprimitive.FHIRPrimitive, False, None, False),
            ("deceasedDateTime", "deceasedDateTime", fhirdate.FHIRDate, False, "deceased", False),
            ("gender", "gender", str, False, None, False),
            ("_gender", "_gender",fhirprimitive.FHIRPrimitive, False, None, False),
            ("generalPractitioner", "generalPractitioner", fhirreference.FHIRReference, True, None, False),
            ("identifier", "identifier", identifier.Identifier, True, None, False),
            ("link", "link", PatientLink, True, None, False),
            ("managingOrganization", "managingOrganization", fhirreference.FHIRReference, False, None, False),
            ("maritalStatus", "maritalStatus", codeableconcept.CodeableConcept, False, None, False),
            ("multipleBirthBoolean", "multipleBirthBoolean", bool, False, "multipleBirth", False),
            ("_multipleBirthBoolean", "_multipleBirthBoolean",fhirprimitive.FHIRPrimitive, False, None, False),
            ("multipleBirthInteger", "multipleBirthInteger", int, False, "multipleBirth", False),
            ("_multipleBirthInteger", "_multipleBirthInteger",fhirprimitive.FHIRPrimitive, False, None, False),
            ("name", "name", humanname.HumanName, True, None, False),
            ("photo", "photo", attachment.Attachment, True, None, False),
            ("telecom", "telecom", contactpoint.ContactPoint, True, None, False),
        ])
        return js


from . import backboneelement

class PatientCommunication(backboneelement.BackboneElement):
    """ A language which may be used to communicate with the patient about his or
    her health.
    """

    resource_type = "PatientCommunication"

    def __init__(self, jsondict=None, strict=True):
        """ Initialize all valid properties.

        :raises: FHIRValidationError on validation errors, unless strict is False
        :param dict jsondict: A JSON dictionary to use for initialization
        :param bool strict: If True (the default), invalid variables will raise a TypeError
        """

        self.language = None

        """ The language which can be used to communicate with the patient
        about his or her health.
        Type `CodeableConcept` (represented as `dict` in JSON). """



        self.preferred = None

        """ Language preference indicator.
        Type `bool`. """

        self._preferred = None

        """ extension for fhir primitive  preferred"""

        super(PatientCommunication, self).__init__(jsondict=jsondict, strict=strict)

    def elementProperties(self):
        js = super(PatientCommunication, self).elementProperties()
        js.extend([
            ("language", "language", codeableconcept.CodeableConcept, False, None, True),
            ("preferred", "preferred", bool, False, None, False),
            ("_preferred", "_preferred",fhirprimitive.FHIRPrimitive, False, None, False),
        ])
        return js


class PatientContact(backboneelement.BackboneElement):
    """ A contact party (e.g. guardian, partner, friend) for the patient.
    """

    resource_type = "PatientContact"

    def __init__(self, jsondict=None, strict=True):
        """ Initialize all valid properties.

        :raises: FHIRValidationError on validation errors, unless strict is False
        :param dict jsondict: A JSON dictionary to use for initialization
        :param bool strict: If True (the default), invalid variables will raise a TypeError
        """

        self.address = None

        """ Address for the contact person.
        Type `Address` (represented as `dict` in JSON). """



        self.gender = None

        """ male | female | other | unknown.
        Type `str`. """

        self._gender = None

        """ extension for fhir primitive  gender"""

        self.name = None

        """ A name associated with the contact person.
        Type `HumanName` (represented as `dict` in JSON). """



        self.organization = None

        """ Organization that is associated with the contact.
        Type `FHIRReference` (represented as `dict` in JSON). """



        self.period = None

        """ The period during which this contact person or organization

view this post on Zulip Eric Haas (Dec 21 2018 at 01:02):

Then they are avaiable when needed for use other wise the primitives behave normally.

view this post on Zulip Eric Haas (Dec 21 2018 at 03:14):

I could not figure out how to access the subclass element name in the superclass so I regenerated all the classes instead.

view this post on Zulip Eric Haas (Dec 23 2018 at 19:44):

OK so I'm ready to do a PR. there are two systemic unit test warnings....
one for unit tests on FHIRReference

e.g...

WARNING:fhirparser:Unknown property "patient.reference" in unit test on FHIRReference in downloads/claimresponse-example-unsolicited-preauth.json

view this post on Zulip Eric Haas (Dec 23 2018 at 19:45):

and one for Resource

e..g,...

WARNING:fhirparser:Unknown property "contained[0].status" in unit test on Resource in downloads/plandefinition-example-kdn5-simplified.json

view this post on Zulip Eric Haas (Dec 23 2018 at 19:46):

Could not figure out what the unit test was testing and why these errors arise @Pascal Pfiffner ?

view this post on Zulip Eric Haas (Dec 23 2018 at 21:05):

(deleted)


Last updated: Apr 12 2022 at 19:14 UTC