def createobservation(cls, valueString=str, code=None, codesystem=None, codedisplay=None, date=None): from . import fhirutils obs = observation.Observation() # Date fdate = fhirdate.FHIRDate() fdate.date = date or datetime.datetime.utcnow() obs.effectiveDateTime = fdate # Ontology if code is not None and codesystem is not None: obs.code = fhirutils.FHIRUtils.codeableconcept( code, codesystem, codedisplay) # status obs.status = 'final' # Value obs.valueString = valueString or None return obs
def patient(id): # https://{FHIR Base URL}/Observation? # patient={Patient Id}& # category={category}& # code={code1,code2,code3...}& # date={date}& # _format=json # TODO: query params # patient_id = request.args.get('patient', None) # TODO: connect to database to search patient result = db.engine.execute("SELECT 1") names = [] for row in result: pass # dummy data with open( os.path.join(app.config['FHIR_RESOURCES'], 'observation-example-body-height.json')) as f: data = json.load(f) obs = ob.Observation(data) # TODO: update observation resource print(obs.as_json()) return jsonify(result=obs.as_json())
def gen_obs(patient_id_ref, patient_name, patient_dob): # set up observation structure from model for i in range(len(observation_list)): # performer, age_mos, wt_lbs, ht_in, bmi = observation_list[i] performer, age_mos, age_wks, wt_lbs, ht_in = observation_list[i] o = observation.Observation() o.status = 'final' o.subject = {"reference": patient_id_ref, "display": patient_name} o.encounter = [{"display": performer}] o.performer = [{"display": performer}] date_seen = patient_dob + relativedelta( months=age_mos) + relativedelta(weeks=age_wks) o.effectiveDateTime = date_seen.isoformat() o.code = coding_weight o.valueQuantity = {"value": lbs_to_kg(wt_lbs), "unit": "kg"} with open( os.path.join('json_data', 'ob-kara', 'ob-kara-wt-' + str(i) + '.json'), 'w') as f: print(json.dumps(OrderedDict(o.as_json()), indent=4, separators=(',', ': ')), file=f) o.code = coding_height o.valueQuantity = {"value": in_to_cm(ht_in), "unit": "cm"} with open( os.path.join('json_data', 'ob-kara', 'ob-kara-ht-' + str(i) + '.json'), 'w') as f: print(json.dumps(OrderedDict(o.as_json()), indent=4, separators=(',', ': ')), file=f)
def create_sleep_observations(patient_ref): form_data = repo.generate_patient_sleep_data() for measurement in form_data.items(): # (date, val) date = measurement[0] value = measurement[1] observation = obs.Observation() observation.status = "registered" # <code> ref_patient = fhirref.FHIRReference() ref_patient.reference = "Patient/" + str(patient_ref) observation.subject = ref_patient observation.code = models.codeableconcept.CodeableConcept() code = models.coding.Coding() code.system = "SNOMED CT" code.code = "248263006" code.display = "Sleep Duration" observation.code.coding = [code] quantity = models.quantity.Quantity() quantity.value = value quantity.unit = "h" quantity.system = "http://unitsofmeasure.org" quantity.code = "h" observation.valueQuantity = quantity observation.effectiveDateTime = fhirdate.FHIRDate(date) result = observation.create(smart.server) print(result)
def annotate(self, obsid): obs = o.Observation() obs.uuid = uuid.uuid4().urn observation = o.Observation.read(obsid, self.smart.server) obs.specimen = observation.specimen obs.related = observation.related obs.basedOn = observation.basedOn obs.code = observation.code obs.component = observation.component obs.method = observation.method seq_id = observation.related[0].target.reference.split("/")[1] seq = s.Sequence.read(seq_id, self.smart.server) obseverved_seq = seq.observedSeq annotation = self.gfeapi.annotate_get(obseverved_seq, imgthla_version="3.31.0") gfe = annotation.gfe bodysite3 = cc.CodeableConcept() bodySiteCoding3 = mkCoding(system='http://act.b12x.org', code='261063000', version="0.0.5") bodysite3.coding = [bodySiteCoding3] bodysite3.text = gfe obs.valueCodeableConcept = bodysite3 obs.status = 'final' obs.subject = observation.subject return obs
def to_fhir_obj(self): observation = o.Observation(base_observation) #observation.subject_reference = self.subject_reference observation.subject.reference = self.subject_reference observation.performer[0].reference = self.subject_reference observation.effectiveDateTime = fd.FHIRDate(str(datetime.utcnow().isoformat())) observation.issued = fd.FHIRDate(str(datetime.utcnow().isoformat())) observation.valueString = self.sexual_orientation return observation
def gen_obs(patient_id_ref, patient_name, patient_dob): # data for generation (provided by Aly) # Boy Smith 2-5 yr # Visit Age(mos) Wt(lbs) Ht(in) BMI(kg/m2) observation_list = [ ["MD", 24, 30., 34.5, 17.7], ["WIC", 24, 30., 34.5, 17.7], ["WIC", 30, 34., 36.25, 18], ["WIC", 36, 36., 38., 17.5], ["MD", 39, 38., 38.25, 18], ["WIC", 48, 44., 40., 19], ["MD", 51, 44., 40., 19], ["WIC", 52, 44., 40., 19], ["WIC", 54, 46., 40.25, 19.9], ["WIC", 57, 46.5, 40.5, 19.9], ["WIC", 60, 48., 42., 19.1], ] # set up observation structure from model for i in range(len(observation_list)): performer, age_mos, wt_lbs, ht_in, bmi = observation_list[i] o = observation.Observation() o.status = 'final' o.subject = {"reference": patient_id_ref, "display": patient_name} o.encounter = [{"display": performer}] o.performer = [{"display": performer}] date_seen = patient_dob + relativedelta(months=age_mos) o.effectiveDateTime = date_seen.isoformat() o.code = coding_weight o.valueQuantity = {"value": lbs_to_kg(wt_lbs), "unit": "kg"} with open( os.path.join('json_data', 'ob-clark', 'ob-clark-wt-' + str(i) + '.json'), 'w') as f: print(json.dumps(OrderedDict(o.as_json()), indent=4, separators=(',', ': ')), file=f) o.code = coding_height o.valueQuantity = {"value": in_to_cm(ht_in), "unit": "cm"} with open( os.path.join('json_data', 'ob-clark', 'ob-clark-ht-' + str(i) + '.json'), 'w') as f: print(json.dumps(OrderedDict(o.as_json()), indent=4, separators=(',', ': ')), file=f) o.code = coding_bmi o.valueQuantity = {"value": bmi, "unit": "kg/m2"} with open( os.path.join('json_data', 'ob-clark', 'ob-clark-bmi-' + str(i) + '.json'), 'w') as f: print(json.dumps(OrderedDict(o.as_json()), indent=4, separators=(',', ': ')), file=f)
def get_result(self): self.__model = ob.Observation(self.init_value()) self.__model.meta = self.meta() self.__model.category = self.category() self.__model.subject = self.subject() self.__model.effectiveDateTime = self.effective_date_time() self.__model.device = self.device() self.__model.valueQuantity = self.value() return self.__model
def get_result(self): self.__model = ob.Observation(self.init_value()) self.__model.meta = self.meta() self.__model.category = self.category() self.__model.subject = self.subject() self.__model.effectiveDateTime = self.effective_date_time() self.__model.performer = self.performer() self.__model.component = self.component() self.__model.device = self.device() return self.__model
def update_patients_sexuality(patient_id, sexual_orientation): base_observation = { "resourceType": "Observation", "status": "final", "category": [ { "coding": [ { "system": "http://terminology.hl7.org/CodeSystem/observation-category", "code": "social-history", "display": "social-history" } ] } ], "code": { "coding": [ { "system": "http://loinc.org", "code": "76690-7", "display": "Sexual orientation" } ], "text": "Sexual orientation" }, "subject": { "reference": "" }, "performer": [{"reference": ""}], "valueString": "" } settings = { 'app_id': 'LGBTQCovidReporting', 'api_base': 'https://r4.smarthealthit.org' } smart = client.FHIRClient(settings=settings) #id = str(datetime.utcnow().date()) + "pgood7userobservation" + "1" subject_reference = "Patient/" + patient_id #date = datetime.utcnow().isoformat() #sexual_orientations = ['Bisexual', 'Heterosexual', 'Homosexual', 'Other', 'Asked but unknown', 'Unknown'] observation = o.Observation(base_observation) #observation.subject_reference = subject_reference observation.subject.reference = subject_reference observation.performer[0].reference = subject_reference observation.effectiveDateTime = fd.FHIRDate(str(datetime.utcnow().isoformat())) observation.issued = fd.FHIRDate(str(datetime.utcnow().isoformat())) observation.valueString = sexual_orientation new_observation = observation.create(smart.server) if(new_observation): return 200 else: return 400
def get_result(self): self.__model = ob.Observation(self.init_value()) self.__model.meta = self.meta() self.__model.category = [self.category()] self.__model.valueCodeableConcept = self.value_codeable_concept() self.__model.subject = self.subject() self.__model.effectiveDateTime = self.effective_date_time() self.__model.performer = self.performer() self.__model.device = self.device() self.__model.code = self.code() return self.__model
def get_result(self): self.__model = ob.Observation(self.init_value()) self.__model.meta = self.meta() self.__model.category = self.category() self.__model.subject = self.subject() self.__model.effectiveDateTime = self.effective_date_time() self.__model.performer = self.performer() self.__model.device = self.device() self.__model.referenceRange = self.ref_range() self.__model.interpretation = self.interpretation() self.__model.valueQuantity = self.value() return self.__model
def add_phased_relationship_obv(self): patient_reference = reference.FHIRReference( {"reference": "Patient/" + self.patientID}) self.sequence_rels \ = get_sequence_relation(self.phased_rec_map) for index in self.sequence_rels.index: siduid = "sid-" + uuid4().hex[:13] self.result_ids.append(siduid) observation_sid = observation.Observation() observation_sid.resource_type = "Observation" observation_sid.id = siduid observation_sid.meta = meta.Meta({ "profile": [("http://hl7.org/fhir/uv/" + "genomics-reporting/" + "StructureDefinition/" + "sequence-phase-relationship")] }) observation_sid.status = "final" observation_sid.category = [ concept.CodeableConcept({ "coding": [{ "system": ("http://terminology.hl7.org/" + "CodeSystem/observation-category"), "code": "laboratory" }] }) ] observation_sid.code = concept.CodeableConcept({ "coding": [{ "system": "http://loinc.org", "code": "82120-7", "display": "Allelic phase" }] }) observation_sid.subject = patient_reference observation_sid.valueCodeableConcept = concept.CodeableConcept({ "coding": [{ "system": ("http://hl7.org/fhir/uv/" + "genomics-reporting/" + "CodeSystem/seq-phase-relationship"), "code": self.sequence_rels.at[index, 'Relation'], "display": self.sequence_rels.at[index, 'Relation'] }] }) self.report.contained.append(observation_sid)
def observation_to_phenotypic_feature(obj): """ FHIR Observation to Phenopackets PhenotypicFeature. """ observation = obs.Observation(obj) codeable_concept = observation.code # CodeableConcept phenotypic_feature = { # id is an integer AutoField, store legacy id in description # TODO change "description": observation.id, "pftype": { "id": f"{codeable_concept.coding[0].system}:{codeable_concept.coding[0].code}", "label": codeable_concept.coding[0].display # TODO collect system info in metadata } } if observation.specimen: # FK to Biosample phenotypic_feature["biosample"] = observation.specimen.reference phenotypic_feature["extra_properties"] = observation.as_json() return phenotypic_feature
def postObservation(measurement, value, patient, time): print measurement, value obs = o.Observation({ 'code': { 'coding': [{ 'system': 'http://hl7.org/fhir/observation-category', 'code': 'fakecode', 'display': measurement }] }, 'status': 'activeYo', "subject": { "reference": "Patient/" + patient }, "effectiveDateTime": time, "valueQuantity": { "value": value } }) # "effectiveDateTime": time }) result = o.Observation.create(obs, smart.server)
def write(server_url, system, code, patient, value): observation = o.Observation() observation.status = "final" observation.subject = fr.FHIRReference() observation.subject.reference = ("Patient/%s" % patient) observation.code = cc.CodeableConcept() tmp = c.Coding() tmp.system = system tmp.code = code observation.code.coding = [tmp] observation.valueString = str(value) observation.effectiveDateTime = fd.FHIRDate("2017-11-28T00:00:00+00:00") #write json obj json_obj = observation.as_json() json_obj["resourceType"] = "Observation" print(json.dumps(json_obj)) requests.post(server_url + "Observation", json=json_obj)
def addObservationToServer(self, patient_id, value_code, value_unit, value_quantity, coding_code, coding_display, coding_system, timestamp): observation = o.Observation() # Create Value Quantity quantity = q.Quantity() quantity.code = value_code quantity.unit = value_unit quantity.value = value_quantity observation.valueQuantity = quantity # Create Coding code = cc.CodeableConcept() coding_item = c.Coding() coding_item.code = coding_code coding_item.display = coding_display coding_item.system = coding_system coding_list = [coding_item] code.coding = coding_list observation.code = code # Create Subject reference = r.FHIRReference() reference.reference = self.getPatientById(patient_id).relativePath() observation.subject = reference # Create Status observation.status = 'final' # Create Issued/EffectiveDateTime observation.effectiveDateTime = d.FHIRDate(timestamp) # Write the observation result_json = observation.create(self.smart.server) observation.id = self.getCreatedId(result_json) return observation.id
def ObservationCreate(client, patID): print("create") jsondict = { "resourceType": "Observation", "text": { "status": "generated" #, # "div": "<div>Ryan Audit Test</div>" }, "identifier": [{ "use": "official", "system": "http://www.bmc.nl/zorgportal/identifiers/observations", "value": "632555" }], "status": "final", "code": { "coding": [{ "system": "http://loinc.org", "code": "11557-6", "display": "Carbon dioxide in blood" }] }, "subject": { "reference": "Patient/" + patID }, ## "effectivePeriod": { ## "start": "2013-04-02T10:30:10+01:00", ## "end": "2013-04-05T10:30:10+01:00" ## }, ## "issued": "2013-04-03T15:30:10+01:00", "performer": [{ "reference": "Practitioner/f005", "display": "A. Langeveld" }], "valueQuantity": { "value": 6.2, "unit": "kPa", "system": "http://unitsofmeasure.org", "code": "kPa" }, "interpretation": [{ "coding": [{ "system": "http://terminology.hl7.org/CodeSystem/v3-ObservationInterpretation", "code": "H", "display": "High" }] }], "referenceRange": [{ "low": { "value": 4.8, "unit": "kPa", "system": "http://unitsofmeasure.org", "code": "kPa" }, "high": { "value": 6.0, "unit": "kPa", "system": "http://unitsofmeasure.org", "code": "kPa" } }] } return O.Observation(jsondict, strict=False).create(client.server)
def add_observation(self, patient_id, observation_data): # This is the common structure for observations # Values of None will be filled in later observation_template = { 'id': '', 'status': 'final', 'category': { 'coding': [ { 'system': 'http://hl7.org/fhir/observation-category', 'code': None } ] }, 'code': None, 'subject': { 'reference': 'Patient/' + str(patient_id) }, 'effectiveDateTime': observation_data['datetime'], 'issued': observation_data['datetime'], 'valueQuantity': { 'value': None, 'unit': None, 'system': 'http://unitsofmeasure.org/', 'code': None } } # Fill in value based on observation type (name) if observation_data['name'] == 'a1c': category_coding_code = 'laboratory' code = { 'coding': [ { 'system': 'http://loinc.org', 'code': '4548-4', 'display': 'Hemoglobin A1c/Hemoglobin.total in Blood' } ], 'text': 'Hemoglobin A1c/Hemoglobin.total in Blood' } value_quantity = { 'value': observation_data['value'], 'unit': observation_data['unit'], 'system': 'http://unitsofmeasure.org/', 'code': observation_data['unit'] } observation_template['category']['coding'][0]['code'] = category_coding_code observation_template['code'] = code observation_template['valueQuantity'] = value_quantity elif observation_data['name'] == 'bmi': category_coding_code = 'vital-signs' code = { 'coding': [ { 'system': 'http://loinc.org', 'code': '39156-5', 'display': 'Body Mass Index' } ], 'text': 'Body Mass Index' } value_quantity = { 'value': observation_data['value'], 'unit': observation_data['unit'], 'system': 'http://unitsofmeasure.org/', 'code': observation_data['unit'] } observation_template['category']['coding'][0]['code'] = category_coding_code observation_template['code'] = code observation_template['valueQuantity'] = value_quantity elif observation_data['name'] == 'bp': category_coding_code = 'vital-signs' code = { 'coding': [ { 'system': 'http://loinc.org', 'code': '55284-4', 'display': 'Blood Pressure' } ] } component = [ { 'code': { 'coding': [ { 'system': 'http://loinc.org', 'code': '8480-6', 'display': 'Systolic Blood Pressure' } ], 'text': 'Systolic Blood Pressure' }, 'valueQuantity': { 'value': observation_data['value'][0], 'unit': observation_data['unit'], 'system': 'http://unitsofmeasure.org/', 'code': observation_data['unit'] } }, { 'code': { 'coding': [ { 'system': 'http://loinc.org', 'code': '8462-4', 'display': 'Diastolic Blood Pressure' } ], 'text': 'Diastolic Blood Pressure' }, 'valueQuantity': { 'value': observation_data['value'][1], 'unit': observation_data['unit'], 'system': 'http://unitsofmeasure.org/', 'code': observation_data['unit'] } } ] observation_template['category']['coding'][0]['code'] = category_coding_code observation_template['code'] = code observation_template['component'] = component else: print 'No valid observation specified' return observation = o.Observation(observation_template) print observation.as_json() o.Observation.create(observation, self.smart.server) print 'Finished adding ' + observation_data['name'] + ' observation'
def __init__(self,observation_dict,dt=datetime.datetime.now(),Patient=None, Practitioner=None): """ Creates, validates, and posts an Observation FHIR _generate_patient_fhir_object. :param observation_dict: dictionary of observations :param dt: datetime of observation. Default is now. :param Patient: Patient FHIR object. :param Practitioner: Practioner FHIR object. :returns: GenerateObservation object that has Observation as an attribute. """ self.dt = dt if Patient is None: self.Patient = generatepatient.GeneratePatient().Patient else: self.Patient = Patient if Practitioner is None: self.Practitioner = generatepractitioner.GeneratePractitioner().Practitioner else: self.Practitioner = Practitioner # if Patient is not None and Encounter is not None and Practitioner is not None: # if Patient.id != Encounter.Patient.id: # raise ValueError('Patient.id must equal Encounter.Patient.id') # if Encounter.Practitioner.id != Practitioner.id: # raise ValueError('Encounter.Practitioner.id must equal Practitioner.id') # self.Patient = Patient # self.Encounter = Encounter # self.Practitioner = Practitioner # elif Patient is not None and Encounter is not None and Practitioner is None: # if Patient.id != Encounter.Patient.id: # raise ValueError('Patient.id must be the same as Encounter.Patient.id') # self.Patient = Patient # self.Encounter = Encounter # self.Practitioner = Encounter.Practitioner # elif Patient is not None and Encounter is None and Practitioner is not None: # self.Patient = Patient # self.Practitioner = Practitioner # self.Encounter = generateencounter.GenerateEncounter(Patient=self.Patient,Practitioner=self.Practitioner).Encounter # elif Patient is not None and Encounter is None and Practitioner is None: # self.Patient = Patient # self.Encounter = generateencounter.GenerateEncounter(Patient=self.Patient).Encounter # self.Practitioner = self.Encounter.Practitioner # elif Patient is None and Encounter is not None and Practitioner is None: # self.Encounter = Encounter # self.Patient = self.Encounter.Patient # self.Practitioner = self.Encounter.Practitioner # elif Patient is None and Encounter is None and Practitioner is not None: # self.Practitioner = Practitioner # self.Encounter = generateencounter.GenerateEncounter(Practitioner=self.Practitioner).Encounter # self.Patient = self.Encounter.Patient # elif Patient is None and Encounter is not None and Practitioner is not None: # if Encounter.Practitioner.id != Practitioner.id: # raise ValueError('Encounter.Practitioner.id must equal Practitioner.id') # self.Encounter = Encounter # self.Patient = self.Encounter.Patient # self.Practitioner = Practitioner # elif Patient is None and Encounter is None and Practitioner is None: # self.Encounter = generateencounter.GenerateEncounter().Encounter # self.Patient = self.Encounter.Patient # self.Practitioner = self.Encounter.Practitioner # else: # raise ValueError('Error with Patient, Encounter, and Practitioner values.') # self.Patient = generatepatient.GeneratePatient().Patient self.observation_dict = observation_dict if not isinstance(self.observation_dict,dict): raise ValueError('observation_dict needs to be a dictionary of observations') for obs,value in self.observation_dict.items(): self.obs = obs Observation = o.Observation() Observation.code = self._create_FHIRCodeableConcept(code=value['code'], system=value['system'], display=value['display']) Observation.status = 'final' Observation.subject = self._create_FHIRReference(self.Patient) Observation.performer = [self._create_FHIRReference(self.Practitioner)] Observation = self._add_value(Observation,value) Observation.effectiveDateTime = self._create_FHIRDate(self.dt) self._validate(Observation) self.response = self.post_resource(Observation) Observation.id = self._extract_id() self.Observation = Observation print(self)
def import_observation(self, res, options): """Import a single observation""" verbosity = options['verbosity'] strict = options['strict'] force = options['force'] f_observation = obs.Observation(res, strict=strict) logger.info(f'Importing {f_observation}') if f_observation.component is None: logger.debug('No components. Importing as single observation.') d_observation = None if f_observation.valueQuantity is not None: d_observation = Observation( code=self.get_codeableconcept(f_observation.code), category=self.get_codeableconcept( next(iter(f_observation.category))) if f_observation.category is not None else None, comment=f_observation.comment if f_observation.comment is not None else '', effective_datetime=f_observation.effectiveDateTime.date, value_quantity_value=f_observation.valueQuantity.value, value_quantity_unit=CodeableConcept( f_observation.valueQuantity.code, f_observation.valueQuantity.system, f_observation.valueQuantity.unit), # See: https://docs.djangoproject.com/en/2.1/topics/db/optimization/#use-foreign-key-values-directly subject_id=f_observation.subject.reference[ 9:] # Remove urn:uuid: prefix ) if d_observation is not None: try: d_observation.save() except IntegrityError as err: logger.error( 'Saving single observation to database failed', exc_info=True) else: logger.debug( 'Multiple components. Importing as compound observation with children.' ) cc_observation = CompoundObservation( code=self.get_codeableconcept(f_observation.code)) try: cc_observation.save() except IntegrityError as err: logger.error(f'Saving compound observation to database failed', exc_info=True) for a_component in f_observation.component: # pylint: disable=E1133 d_observation = None d_observation = Observation( code=self.get_codeableconcept(a_component.code), category=self.get_codeableconcept( next(iter(f_observation.category))) if f_observation.category is not None else None, comment=f_observation.comment if f_observation.comment is not None else '', effective_datetime=f_observation.effectiveDateTime.date, value_quantity_value=a_component.valueQuantity.value, value_quantity_unit=CodeableConcept( a_component.valueQuantity.code, a_component.valueQuantity.system, a_component.valueQuantity.unit), # See: https://docs.djangoproject.com/en/2.1/topics/db/optimization/#use-foreign-key-values-directly subject_id=f_observation.subject. reference[9:], # Remove urn:uuid: prefix compound_observation=cc_observation) try: d_observation.save() except IntegrityError as err: logger.error( f'Saving child observation to database failed', exc_info=True)
def phenotypic_feature_to_fhir(obj): """Converts Phenotypic feature to FHIR Observation. :param obj: PhenotypicFeature json :return: FHIR Observation json """ schema_path = os.path.join(SCHEMA_PATH, 'phenotypic_feature_schema.json') try: validate_schema(schema_path, obj) except jsonschema.exceptions.ValidationError: raise Exception("The phenotypic feature object is not valid.") observation = obs.Observation() if 'description' in obj: observation.note = [] annotation = a.Annotation() annotation.text = obj.get('description', None) observation.note.append(annotation) observation.code = fhir_codeable_concept(obj['type']) # required by FHIR specs but omitted by phenopackets, for now set for unknown observation.status = 'unknown' if 'negated' in obj: observation.interpretation = fhir_codeable_concept({ "label": "Positive", "id": "POS" }) else: observation.interpretation = fhir_codeable_concept({ "label": "Negative", "id": "NEG" }) observation.extension = [] concept_extensions = codeable_concepts_fields( ['severity', 'modifier', 'onset'], 'phenotypicFeature', obj) for c in concept_extensions: observation.extension.append(c) if 'evidence' in obj: evidence = extension.Extension() evidence.url = PHENOPACKETS_ON_FHIR_MAPPING['phenotypicFeature'][ 'evidence']['url'] evidence.extension = [] evidence_code = extension.Extension() evidence_code.url = PHENOPACKETS_ON_FHIR_MAPPING['phenotypicFeature'][ 'evidence']['evidenceCode'] evidence_code.valueCodeableConcept = fhir_codeable_concept( obj['evidence']['evidenceCode']) evidence.extension.append(evidence_code) if 'reference' in obj['evidence']: evidence_reference = extension.Extension() evidence_reference.url = PHENOPACKETS_ON_FHIR_MAPPING[ 'externalReference']['url'] evidence_reference.extension = [] evidence_reference_id = extension.Extension() evidence_reference_id.url = PHENOPACKETS_ON_FHIR_MAPPING[ 'externalReference']['idUrl'] evidence_reference_id.valueUri = obj['evidence']['reference']['id'] evidence_reference.extension.append(evidence_reference_id) if 'description' in obj['evidence']['reference']: evidence_reference_desc = extension.Extension() evidence_reference_desc.url = PHENOPACKETS_ON_FHIR_MAPPING[ 'externalReference']['descriptionUrl'] evidence_reference_desc.valueString = obj['evidence'][ 'reference'].get('description', None) evidence_reference.extension.append(evidence_reference_desc) evidence.extension.append(evidence_reference) observation.extension.append(evidence) if 'biosample' in obj: observation.specimen = fhirreference.FHIRReference() observation.specimen.reference = obj.get('biosample', None) return observation.as_json()
def fhir_observation(obj): """ Converts phenotypic feature to FHIR Observation. """ observation = obs.Observation() if 'description' in obj.keys(): observation.note = [] annotation = a.Annotation() annotation.text = obj.get('description', None) observation.note.append(annotation) observation.code = fhir_codeable_concept(obj['type']) # required by FHIR specs but omitted by phenopackets, for now set for unknown observation.status = 'unknown' if 'negated' in obj.keys(): observation.interpretation = fhir_codeable_concept({ "label": "Positive", "id": "POS" }) else: observation.interpretation = fhir_codeable_concept({ "label": "Negative", "id": "NEG" }) observation.extension = [] concept_extensions = codeable_concepts_fields( ['severity', 'modifier', 'onset'], 'phenotypic_feature', obj) for c in concept_extensions: observation.extension.append(c) if 'evidence' in obj.keys(): evidence = extension.Extension() evidence.url = PHENOPACKETS_ON_FHIR_MAPPING['phenotypic_feature'][ 'evidence']['url'] evidence.extension = [] evidence_code = extension.Extension() evidence_code.url = PHENOPACKETS_ON_FHIR_MAPPING['phenotypic_feature'][ 'evidence']['evidence_code'] evidence_code.valueCodeableConcept = fhir_codeable_concept( obj['evidence']['evidence_code']) evidence.extension.append(evidence_code) if 'reference' in obj['evidence'].keys(): evidence_reference = extension.Extension() evidence_reference.url = PHENOPACKETS_ON_FHIR_MAPPING[ 'external_reference']['url'] evidence_reference.extension = [] evidence_reference_id = extension.Extension() evidence_reference_id.url = PHENOPACKETS_ON_FHIR_MAPPING[ 'external_reference']['id_url'] # GA$GH guide requires valueURL but there is no such property evidence_reference_id.valueUri = obj['evidence']['reference']['id'] evidence_reference.extension.append(evidence_reference_id) if 'description' in obj['evidence']['reference'].keys(): evidence_reference_desc = extension.Extension() evidence_reference_desc.url = PHENOPACKETS_ON_FHIR_MAPPING[ 'external_reference']['description_url'] evidence_reference_desc.valueString = obj['evidence'][ 'reference'].get('description', None) evidence_reference.extension.append(evidence_reference_desc) evidence.extension.append(evidence_reference) observation.extension.append(evidence) if 'biosample' in obj.keys(): observation.specimen = fhirreference.FHIRReference() observation.specimen.reference = obj.get('biosample', None) return observation.as_json()
def add_regionstudied_obv(self, ref_seq, reportable_query_regions, nocall_regions): if reportable_query_regions.empty and nocall_regions.empty: return patient_reference = reference.FHIRReference( {"reference": "Patient/" + self.patientID}) contained_uid = "rs-" + uuid4().hex[:13] self.result_ids.append(contained_uid) # Region Studied Obeservation observation_rs = observation.Observation() contained_rs = observation_rs contained_rs.id = contained_uid observation_rs.resource_type = "Observation" contained_rs.meta = meta.Meta({ "profile": [("http://hl7.org/fhir/uv/" + "genomics-reporting/" + "StructureDefinition/region-studied")] }) observation_rs.code = concept.CodeableConcept({ "coding": [{ "system": "http://loinc.org", "code": "53041-0", "display": "DNA region of interest panel" }] }) observation_rs.status = "final" observation_rs.category = [ concept.CodeableConcept({ "coding": [{ "system": ("http://terminology.hl7.org/" + "CodeSystem/observation-category"), "code": "laboratory" }] }) ] observation_rs.subject = patient_reference observation_rs_component2 = observation.ObservationComponent() observation_rs_component2.code = concept.CodeableConcept({ "coding": [{ "system": "http://loinc.org", "code": "92822-6", "display": "Genomic coord system" }] }) observation_rs_component2\ .valueCodeableConcept = concept.CodeableConcept( { "coding": [ { "system": "http://loinc.org", "code": "LA30102-0", "display": "1-based character counting" } ] } ) observation_rs_component3 = observation.ObservationComponent() observation_rs_component3.code = concept.CodeableConcept({ "coding": [{ "system": "http://loinc.org", "code": "48013-7", "display": "Genomic reference sequence ID" }] }) observation_rs_component3\ .valueCodeableConcept = concept.CodeableConcept( { "coding": [ { "system": "http://www.ncbi.nlm.nih.gov/nuccore", "code": ref_seq } ] } ) observation_rs_components = self._get_region_studied_component( reportable_query_regions, nocall_regions) observation_rs.component = [ observation_rs_component2, observation_rs_component3 ] + observation_rs_components # Observation structure : described-variants self.report.contained.append(contained_rs)
def getFhirJSON(cleanVcf, nextelem, patientID, refSeq, noCall=False, gender="M"): dvuids = {} siduids = [] alleles = getAllelicState(cleanVcf, nextelem, gender) sequenceRels = getSequenceRelation(cleanVcf, nextelem) noCallRegion, queryRange = getNoCallableData(NO_CALL_FILE, QUERY_RANGE_FILE) nocallRows = len(noCallRegion.index) start = queryRange.at[0, "START"] end = queryRange.at[0, "END"] if not noCallRegion.empty: if noCallRegion['START'].iloc[0] <= queryRange['START'].iloc[0]: noCallRegion['START'].iloc[0] = queryRange['START'].iloc[0] if noCallRegion['END'].iloc[-1] >= queryRange['END'].iloc[0]: noCallRegion['END'].iloc[-1] = queryRange['END'].iloc[0] else: noCall = False contained_uid = uuid4().hex[:13] patient_reference = reference.FHIRReference( {"reference": "Patient/" + patientID}) variant_reference = reference.FHIRReference( {"reference": "#rs-" + contained_uid}) report = dr.DiagnosticReport() report.id = "dr-" + uuid4().hex[:13] report.meta = meta.Meta({ "profile": [ "http://hl7.org/fhir/uv/genomics-reporting/StructureDefinition/genomics-report" ] }) report.status = "final" report.code = concept.CodeableConcept({ "coding": [{ "system": "http://loinc.org", "code": "81247-9", "display": "Master HL7 genetic variant reporting panel" }] }) report.subject = patient_reference report.issued = date.FHIRDate(Utilities.getFhirDate()) observation_rs = observation.Observation() contained_rs = observation_rs contained_rs.id = "rs-" + contained_uid observation_rs.resource_type = "Observation" contained_rs.meta = meta.Meta({ "profile": [ "http://hl7.org/fhir/uv/genomics-reporting/StructureDefinition/region-studied" ] }) observation_rs.code = concept.CodeableConcept({ "coding": [{ "system": "http://loinc.org", "code": "53041-0", "display": "DNA region of interest panel" }] }) observation_rs.status = "final" observation_rs.category = [ concept.CodeableConcept({ "coding": [{ "system": "http://terminology.hl7.org/CodeSystem/observation-category", "code": "laboratory" }] }) ] observation_rs.subject = patient_reference observation_rs_component1 = observation.ObservationComponent() observation_rs_component1.code = concept.CodeableConcept({ "coding": [{ "system": "http://loinc.org", "code": "51959-5", "display": "Range(s) of DNA sequence examined" }] }) observation_rs_component1.valueRange = valRange.Range({ "low": { "value": int(start) }, "high": { "value": int(end) } }) observation_rs_component2 = observation.ObservationComponent() observation_rs_component2.code = concept.CodeableConcept({ "coding": [{ "system": "http://loinc.org", "code": "92822-6", "display": "Genomic coord system" }] }) observation_rs_component2.valueCodeableConcept = concept.CodeableConcept({ "coding": [{ "system": "http://loinc.org", "code": "LA30102-0", "display": "1-based character counting" }] }) observation_rs_component3 = observation.ObservationComponent() observation_rs_component3.code = concept.CodeableConcept({ "coding": [{ "system": "http://loinc.org", "code": "48013-7", "display": "Genomic reference sequence ID" }] }) observation_rs_component3.valueCodeableConcept = concept.CodeableConcept({ "coding": [{ "system": "http://www.ncbi.nlm.nih.gov/nuccore", "code": refSeq }] }) if noCall: #component Region-studied (No call region) nocallComponents = [] for i in range(nocallRows): nocallComponents.append('observation_rs_component' + str(i + 4)) observation_rs_components = [] for (index, i) in zip(noCallRegion.index, nocallComponents): i = observation.ObservationComponent() i.code = concept.CodeableConcept({ "coding": [{ "system": "http://loinc.org", "code": "TBD-noCallRegion", "display": "No call region" }] }) observation_rs_components.append(i) observation_rs.component = [ observation_rs_component2, observation_rs_component3 ] + observation_rs_components else: observation_rs.component = [ observation_rs_component2, observation_rs_component3 ] # Observation structure : described-variants obsContained = [contained_rs] for index in alleles.index: dvuid = uuid4().hex[:13] dvuids.update({str(alleles.at[index, 'POS']): dvuid}) observation_dv = observation.Observation() observation_dv.resource_type = "Observation" observation_dv.id = "dv-" + dvuid observation_dv.meta = meta.Meta({ "profile": [ "http://hl7.org/fhir/uv/genomics-reporting/StructureDefinition/variant" ] }) observation_dv.status = "final" observation_dv.category = [ concept.CodeableConcept({ "coding": [{ "system": "http://terminology.hl7.org/CodeSystem/observation-category", "code": "laboratory" }] }) ] observation_dv.code = concept.CodeableConcept({ "coding": [{ "system": "http://loinc.org", "code": "69548-6", "display": "Genetic variant assessment" }] }) observation_dv.subject = patient_reference observation_dv.valueCodeableConcept = concept.CodeableConcept({ "coding": [{ "system": "http://loinc.org", "code": "LA9633-4", "display": "present" }] }) observation_dv_component1 = observation.ObservationComponent() observation_dv_component1.code = concept.CodeableConcept({ "coding": [{ "system": "http://loinc.org", "code": "62374-4", "display": "Human reference sequence assembly version" }] }) observation_dv_component1.valueCodeableConcept = concept.CodeableConcept( { "coding": [{ "system": "http://loinc.org", "code": "LA14029-5", "display": "GRCh37" }] }) observation_dv_component2 = observation.ObservationComponent() observation_dv_component2.code = concept.CodeableConcept({ "coding": [{ "system": "http://loinc.org", "code": "48013-7", "display": "Genomic reference sequence ID" }] }) observation_dv_component2.valueCodeableConcept = concept.CodeableConcept( { "coding": [{ "system": "http://www.ncbi.nlm.nih.gov/nuccore", "code": refSeq }] }) observation_dv_component3 = observation.ObservationComponent() observation_dv_component3.code = concept.CodeableConcept({ "coding": [{ "system": "http://loinc.org", "code": "53034-5", "display": "Allelic state" }] }) observation_dv_component3.valueCodeableConcept = concept.CodeableConcept( { "coding": [{ "system": "http://loinc.org", "code": alleles.at[index, 'CODE'], "display": alleles.at[index, 'ALLELE'] }] }) observation_dv_component4 = observation.ObservationComponent() observation_dv_component4.code = concept.CodeableConcept({ "coding": [{ "system": "http://loinc.org", "code": "69547-8", "display": "Genomic Ref allele [ID]" }] }) observation_dv_component4.valueString = alleles.at[index, 'REF'] observation_dv_component5 = observation.ObservationComponent() observation_dv_component5.code = concept.CodeableConcept({ "coding": [{ "system": "http://loinc.org", "code": "69551-0", "display": "Genomic Alt allele [ID]" }] }) observation_dv_component5.valueString = alleles.at[index, 'ALT'] observation_dv_component6 = observation.ObservationComponent() observation_dv_component6.code = concept.CodeableConcept({ "coding": [{ "system": "http://loinc.org", "code": "92822-6", "display": "Genomic coord system" }] }) observation_dv_component6.valueCodeableConcept = concept.CodeableConcept( { "coding": [{ "system": "http://loinc.org", "code": "LA30102-0", "display": "1-based character counting" }] }) observation_dv_component7 = observation.ObservationComponent() observation_dv_component7.code = concept.CodeableConcept({ "coding": [{ "system": "http://hl7.org/fhir/uv/genomics-reporting/CodeSystem/tbd-codes", "code": "exact-start-end", "display": "Variant exact start and end" }] }) observation_dv_component7.valueRange = valRange.Range( {"low": { "value": int(alleles.at[index, 'POS']) }}) observation_dv.component = [ observation_dv_component1, observation_dv_component2, observation_dv_component3, observation_dv_component4, observation_dv_component5, observation_dv_component6, observation_dv_component7 ] obsContained.append(observation_dv) # Obesrvation structure: sequence-phase relatons siduids = [] for index in sequenceRels.index: dvRef1 = dvuids.get(str(sequenceRels.at[index, 'POS1'])) dvRef2 = dvuids.get(str(sequenceRels.at[index, 'POS2'])) siduid = uuid4().hex[:13] siduids.append(siduid) observation_sid = observation.Observation() observation_sid.resource_type = "Observation" observation_sid.id = "sid-" + siduid observation_sid.meta = meta.Meta({ "profile": [ "http://hl7.org/fhir/uv/genomics-reporting/StructureDefinition/sequence-phase-relationship" ] }) observation_sid.status = "final" observation_sid.category = [ concept.CodeableConcept({ "coding": [{ "system": "http://terminology.hl7.org/CodeSystem/observation-category", "code": "laboratory" }] }) ] observation_sid.code = concept.CodeableConcept({ "coding": [{ "system": "http://loinc.org", "code": "82120-7", "display": "Allelic phase" }] }) observation_sid.subject = patient_reference observation_sid.valueCodeableConcept = concept.CodeableConcept({ "coding": [{ "system": "http://hl7.org/fhir/uv/genomics-reporting/CodeSystem/seq-phase-relationship", "code": sequenceRels.at[index, 'Relation'], "display": sequenceRels.at[index, 'Relation'] }] }) obsContained.append(observation_sid) report.contained = obsContained reportResult = [variant_reference] for pos, uid in dvuids.items(): reportResult.append( reference.FHIRReference({"reference": "#dv-" + uid})) for uid in siduids: reportResult.append( reference.FHIRReference({"reference": "#sid-" + uid})) report.result = reportResult response = report.as_json() od = OrderedDict() od["resourceType"] = response['resourceType'] od["id"] = response['id'] od["meta"] = response['meta'] od["contained"] = response['contained'] od["status"] = response['status'] od["code"] = response['code'] od["subject"] = response['subject'] od["issued"] = response['issued'] od["result"] = response['result'] odCodeCoding = OrderedDict() odCodeCoding["system"] = od["code"]["coding"][0]["system"] odCodeCoding["code"] = od["code"]["coding"][0]["code"] odCodeCoding["display"] = od["code"]["coding"][0]["display"] od["code"]["coding"][0] = odCodeCoding sidIndex = 0 for index, fhirReport in enumerate(od['contained']): if (fhirReport['id'].startswith('sid-')): sidIndex = index break for index, (sequenceRel, fhirReport) in enumerate( zip(sequenceRels.index, od['contained'][sidIndex:])): dvRef1 = dvuids.get(str(sequenceRels.at[index, 'POS1'])) dvRef2 = dvuids.get(str(sequenceRels.at[index, 'POS2'])) if (fhirReport['id'].startswith('sid-')): derivedFromDV1 = {} derivedFromDV2 = {} derivedFromDV1['reference'] = "#dv-" + dvRef1 derivedFromDV2['reference'] = "#dv-" + dvRef2 derivedFrom = [derivedFromDV1, derivedFromDV2] fhirReport['derivedFrom'] = derivedFrom for k, i in enumerate(od['contained']): if (i['category'][0]['coding'][0]): odCategoryCoding = OrderedDict() odCategoryCoding["system"] = i['category'][0]['coding'][0][ "system"] odCategoryCoding["code"] = i['category'][0]['coding'][0]["code"] od['contained'][k]['category'][0]['coding'][0] = odCategoryCoding if (i['code']['coding'][0]): odCodeCoding = OrderedDict() odCodeCoding["system"] = i['code']['coding'][0]["system"] odCodeCoding["code"] = i['code']['coding'][0]["code"] odCodeCoding["display"] = i['code']['coding'][0]["display"] od['contained'][k]['code']['coding'][0] = odCodeCoding if 'valueCodeableConcept' in i.keys(): odValueCodeableConceptCoding = OrderedDict() odValueCodeableConceptCoding["system"] = i['valueCodeableConcept'][ 'coding'][0]["system"] odValueCodeableConceptCoding["code"] = i['valueCodeableConcept'][ 'coding'][0]["code"] odValueCodeableConceptCoding["display"] = i[ 'valueCodeableConcept']['coding'][0]["display"] od['contained'][k]['valueCodeableConcept']['coding'][ 0] = odValueCodeableConceptCoding if ((i['id'].startswith('dv-')) or (i['id'].startswith('rs-'))): for l, j in enumerate(i['component']): odComponentCodeCoding = OrderedDict() if j['code']['coding'][0]["system"]: odComponentCodeCoding["system"] = j['code']['coding'][0][ "system"] if j['code']['coding'][0]["code"]: odComponentCodeCoding["code"] = j['code']['coding'][0][ "code"] if j['code']['coding'][0]["display"]: odComponentCodeCoding["display"] = j['code']['coding'][0][ "display"] if od['contained'][k]['component'][l]['code']['coding'][0]: od['contained'][k]['component'][l]['code']['coding'][ 0] = odComponentCodeCoding odComponentvalueCodeableConcept = OrderedDict() if 'valueCodeableConcept' in j.keys(): odComponentvalueCodeableConcept["system"] = j[ 'valueCodeableConcept']['coding'][0]["system"] if 'code' in j['valueCodeableConcept']['coding'][0].keys(): odComponentvalueCodeableConcept["code"] = j[ 'valueCodeableConcept']['coding'][0]["code"] if 'display' in j['valueCodeableConcept']['coding'][ 0].keys(): odComponentvalueCodeableConcept["display"] = j[ 'valueCodeableConcept']['coding'][0]["display"] od['contained'][k]['component'][l]['valueCodeableConcept'][ 'coding'][0] = odComponentvalueCodeableConcept if (i['id'].startswith('rs-')): odRS = OrderedDict() odRS["resourceType"] = i['resourceType'] odRS["id"] = i['id'] odRS["meta"] = i['meta'] odRS["status"] = i['status'] odRS["category"] = i['category'] odRS["code"] = i['code'] odRS["subject"] = i['subject'] odRS["component"] = i['component'] od['contained'][k] = odRS if (i['id'].startswith('dv-')): odDV = OrderedDict() odDV["resourceType"] = i['resourceType'] odDV["id"] = i['id'] odDV["meta"] = i['meta'] odDV["status"] = i['status'] odDV["category"] = i['category'] odDV["code"] = i['code'] odDV["subject"] = i['subject'] odDV["valueCodeableConcept"] = i['valueCodeableConcept'] odDV["component"] = i['component'] od['contained'][k] = odDV if (i['id'].startswith('sid-')): odSID = OrderedDict() odSID["resourceType"] = i['resourceType'] odSID["id"] = i['id'] odSID["meta"] = i['meta'] odSID["status"] = i['status'] odSID["category"] = i['category'] odSID["code"] = i['code'] odSID["subject"] = i['subject'] odSID["valueCodeableConcept"] = i['valueCodeableConcept'] odSID["derivedFrom"] = i['derivedFrom'] od['contained'][k] = odSID with open(FHIR_JSON_RESULT + 'fhir.json', 'w') as fp: json.dump(od, fp, indent=4) return FHIR_JSON_RESULT
def add_variant_obv(self, record, ref_seq, ratio_ad_dp): # collect all the record with similar position values, # to utilized later in phased sequence relationship self._add_phase_records(record) patient_reference = reference.FHIRReference( {"reference": "Patient/" + self.patientID}) alleles = get_allelic_state(record, ratio_ad_dp) dvuid = "dv-" + uuid4().hex[:13] self.fhir_report.update({str(record.POS): dvuid}) self.result_ids.append(dvuid) observation_dv = observation.Observation() observation_dv.resource_type = "Observation" observation_dv.id = dvuid observation_dv.meta = meta.Meta({ "profile": [("http://hl7.org/fhir/uv/" + "genomics-reporting/StructureDefinition/variant")] }) observation_dv.status = "final" observation_dv.category = [ concept.CodeableConcept({ "coding": [{ "system": ("http://terminology.hl7.org/" + "CodeSystem/observation-category"), "code": "laboratory" }] }) ] observation_dv.code = concept.CodeableConcept({ "coding": [{ "system": "http://loinc.org", "code": "69548-6", "display": "Genetic variant assessment" }] }) observation_dv.subject = patient_reference observation_dv.valueCodeableConcept = concept.CodeableConcept({ "coding": [{ "system": "http://loinc.org", "code": "LA9633-4", "display": "present" }] }) observation_dv.component = [] observation_dv_component1 = observation.ObservationComponent() observation_dv_component1.code = concept.CodeableConcept({ "coding": [{ "system": "http://loinc.org", "code": "62374-4", "display": "Human reference sequence assembly version" }] }) observation_dv_component1\ .valueCodeableConcept = concept.CodeableConcept( { "coding": [ { "system": "http://loinc.org", "code": "LA14029-5", "display": "GRCh37" } ] } ) observation_dv.component.append(observation_dv_component1) observation_dv_component2 = observation.ObservationComponent() observation_dv_component2.code = concept.CodeableConcept({ "coding": [{ "system": "http://loinc.org", "code": "48013-7", "display": "Genomic reference sequence ID" }] }) observation_dv_component2\ .valueCodeableConcept = concept.CodeableConcept( { "coding": [ { "system": "http://www.ncbi.nlm.nih.gov/nuccore", "code": ref_seq } ] } ) observation_dv.component.append(observation_dv_component2) if alleles['CODE'] != "" or alleles['ALLELE'] != "": observation_dv_component3 = observation.ObservationComponent() observation_dv_component3.code = concept.CodeableConcept({ "coding": [{ "system": "http://loinc.org", "code": "53034-5", "display": "Allelic state" }] }) observation_dv_component3\ .valueCodeableConcept = concept.CodeableConcept( { "coding": [ { "system": "http://loinc.org", "code": alleles['CODE'], "display": alleles['ALLELE'] } ] } ) observation_dv.component.append(observation_dv_component3) observation_dv_component4 = observation.ObservationComponent() observation_dv_component4.code = concept.CodeableConcept({ "coding": [{ "system": "http://loinc.org", "code": "69547-8", "display": "Genomic Ref allele [ID]" }] }) observation_dv_component4.valueString = record.REF observation_dv.component.append(observation_dv_component4) observation_dv_component5 = observation.ObservationComponent() observation_dv_component5.code = concept.CodeableConcept({ "coding": [{ "system": "http://loinc.org", "code": "69551-0", "display": "Genomic Alt allele [ID]" }] }) observation_dv_component5.valueString = record.ALT[0].sequence observation_dv.component.append(observation_dv_component5) observation_dv_component6 = observation.ObservationComponent() observation_dv_component6.code = concept.CodeableConcept({ "coding": [{ "system": "http://loinc.org", "code": "92822-6", "display": "Genomic coord system" }] }) observation_dv_component6\ .valueCodeableConcept = concept.CodeableConcept( { "coding": [ { "system": "http://loinc.org", "code": "LA30102-0", "display": "1-based character counting" } ] } ) observation_dv.component.append(observation_dv_component6) observation_dv_component7 = observation.ObservationComponent() observation_dv_component7.code = concept.CodeableConcept({ "coding": [{ "system": ("http://hl7.org/fhir/uv/" + "genomics-reporting/CodeSystem/tbd-codes"), "code": "exact-start-end", "display": "Variant exact start and end" }] }) observation_dv_component7.valueRange = valRange.Range( {"low": { "value": int(record.POS) }}) observation_dv.component.append(observation_dv_component7) self.report.contained.append(observation_dv)
def getEmptyFhirJSON(patientID, start, end, refSeq, nocall=False): logging.info("[FHIR: Converting XML to JSON]") noCallRegion, queryRange = getNoCallableData(NO_CALL_FILE, QUERY_RANGE_FILE) nocallRows = len(noCallRegion.index) start = queryRange.at[0, "START"] end = queryRange.at[0, "END"] if not noCallRegion.empty: if noCallRegion['START'].iloc[0] <= queryRange['START'].iloc[0]: noCallRegion['START'].iloc[0] = queryRange['START'].iloc[0] if noCallRegion['END'].iloc[-1] >= queryRange['END'].iloc[0]: noCallRegion['END'].iloc[-1] = queryRange['END'].iloc[0] else: nocall = False contained_uid = uuid4().hex[:13] patient_reference = reference.FHIRReference( {"reference": "Patient/" + patientID}) variant_reference = reference.FHIRReference( {"reference": "#rs-" + contained_uid}) report = dr.DiagnosticReport() report.id = "dr-" + uuid4().hex[:13] report.meta = meta.Meta({ "profile": [ "http://hl7.org/fhir/uv/genomics-reporting/StructureDefinition/diagnosticreport" ] }) report.code = concept.CodeableConcept({ "coding": [{ "system": "http://loinc.org", "code": "53041-0", "display": "DNA region of interest panel" }] }) report.status = "final" report.subject = patient_reference report.issued = date.FHIRDate(Utilities.getFhirDate()) report.result = [variant_reference] observation_rs = observation.Observation() contained_rs = observation_rs observation_dv = observation.Observation() contained_dv = observation_dv observation_sid = observation.Observation() contained_sid = observation_sid contained_rs.id = "rs-" + contained_uid observation_rs.resource_type = "Observation" contained_rs.meta = meta.Meta({ "profile": [ "http://hl7.org/fhir/uv/genomics-reporting/StructureDefinition/obs-region-studied" ] }) observation_rs.code = concept.CodeableConcept({ "coding": [{ "system": "http://loinc.org", "code": "53041-0", "display": "DNA region of interest panel" }] }) observation_rs.status = "final" observation_rs.category = [ concept.CodeableConcept({ "coding": [{ "system": "http://terminology.hl7.org/CodeSystem/observation-category", "code": "laboratory" }] }) ] observation_rs.subject = patient_reference observation_rs_component1 = observation.ObservationComponent() observation_rs_component1.code = concept.CodeableConcept({ "coding": [{ "system": "http://loinc.org", "code": "51959-5", "display": "Range(s) of DNA sequence examined" }] }) observation_rs_component1.valueRange = valRange.Range({ "low": { "value": int(start) }, "high": { "value": int(end) } }) observation_rs_component2 = observation.ObservationComponent() observation_rs_component2.code = concept.CodeableConcept({ "coding": [{ "system": "http://loinc.org", "code": "tbd-coordinate system", "display": "Genomic coordinate system" }] }) observation_rs_component2.valueCodeableConcept = concept.CodeableConcept({ "coding": [{ "system": "http://hl7.org/fhir/uv/genomics-reporting/CodeSystem/genetic-coordinate-system", "code": "1" }] }) observation_rs_component3 = observation.ObservationComponent() observation_rs_component3.code = concept.CodeableConcept({ "coding": [{ "system": "http://loinc.org", "code": "48013-7", "display": "Genomic reference sequence ID" }] }) observation_rs_component3.valueCodeableConcept = concept.CodeableConcept({ "coding": [{ "system": "http://www.ncbi.nlm.nih.gov/nuccore", "code": refSeq }] }) if nocall: #component Region-studied (No call region) nocallComponents = [] for i in range(nocallRows): nocallComponents.append('observation_rs_component' + str(i + 4)) observation_rs_components = [] for (index, i) in zip(noCallRegion.index, nocallComponents): i = observation.ObservationComponent() i.code = concept.CodeableConcept({ "coding": [{ "system": "http://loinc.org", "code": "TBD-noCallRegion", "display": "No call region" }] }) observation_rs_components.append(i) if nocall: observation_rs.component = [ observation_rs_component2, observation_rs_component3 ] + observation_rs_components else: observation_rs.component = [ observation_rs_component2, observation_rs_component3 ] response = report.as_json() od = OrderedDict() od["resourceType"] = response['resourceType'] od["id"] = response['id'] od["meta"] = response['meta'] od["contained"] = response['contained'] od["status"] = response['status'] od["code"] = response['code'] od["subject"] = response['subject'] od["issued"] = response['issued'] od["result"] = response['result'] with open(FHIR_JSON_RESULT + 'fhir.json', 'w') as fp: json.dump(od, fp, indent=4) return FHIR_JSON_RESULT