def addMedList(self):
      """Adds a MedList to a patient's graph"""

      g = self.g
      if not self.pid in Med.meds: return  # No meds for this patient
      for m in Med.meds[self.pid]:
        mNode = BNode()
        g.add((mNode,RDF.type,SP['Medication']))
        g.add((mNode,SP['drugName'],self.codedValue(SPCODE["RxNorm_Semantic"], RXN_URI%m.rxn,m.name,RXN_URI%"",m.rxn)))
        g.add((mNode,SP['startDate'],Literal(m.start)))
        if len(m.end) > 0:
            g.add((mNode,SP['endDate'],Literal(m.end))) 
        g.add((mNode,SP['instructions'],Literal(m.sig))) 
        if m.qtt:
          g.add((mNode,SP['quantity'],self.valueAndUnit(m.qtt,m.qttunit)))
        if m.freq:
          g.add((mNode,SP['frequency'],self.valueAndUnit(m.freq,m.frequnit)))

        self.addStatement(mNode)

        # Now,loop through and add fulfillments for each med
        for fill in Refill.refill_list(m.pid,m.rxn):
          rfNode = BNode()
          g.add((rfNode,RDF.type,SP['Fulfillment']))
          g.add((rfNode,DCTERMS['date'],Literal(fill.date)))
          g.add((rfNode,SP['quantityDispensed'], self.valueAndUnit(fill.q,"{tab}")))

          g.add((rfNode,SP['dispenseDaysSupply'],Literal(fill.days)))

          g.add((rfNode,SP['medication'],mNode)) # create bidirectional links
          g.add((mNode,SP['fulfillment'],rfNode))
          self.addStatement(rfNode)
Esempio n. 2
0
   def addMedList(self):
      """Adds a MedList to a patient's graph"""

      g = self.g
      if not self.pid in Med.meds: return  # No meds for this patient
      for m in Med.meds[self.pid]:
        mNode = BNode()
        g.add((mNode,RDF.type,SP['Medication']))
        g.add((mNode,SP['drugName'],self.codedValue(SPCODE["RxNorm_Semantic"], RXN_URI%m.rxn,m.name,RXN_URI%"",m.rxn)))
        g.add((mNode,SP['startDate'],Literal(m.start)))
        g.add((mNode,SP['instructions'],Literal(m.sig))) 
        if m.qtt:
          g.add((mNode,SP['quantity'],self.valueAndUnit(m.qtt,m.qttunit)))
        if m.freq:
          g.add((mNode,SP['frequency'],self.valueAndUnit(m.freq,m.frequnit)))

        self.addStatement(mNode)

        # Now,loop through and add fulfillments for each med
        for fill in Refill.refill_list(m.pid,m.rxn):
          rfNode = BNode()
          g.add((rfNode,RDF.type,SP['Fulfillment']))
          g.add((rfNode,DCTERMS['date'],Literal(fill.date)))
          g.add((rfNode,SP['dispenseQuantity'], self.valueAndUnit(fill.q,"{tab}")))

          g.add((rfNode,SP['dispenseDaysSupply'],Literal(fill.days)))

          g.add((rfNode,SP['medication'],mNode)) # create bidirectional links
          g.add((mNode,SP['fulfillment'],rfNode))
          self.addStatement(rfNode)
Esempio n. 3
0
 def set_meds(self, bundle, prefix=None):
     """Generates and appends a MedicationRequest entry to the transaction"""
     if GENERATION_MAP["Meds"]:
         if self.pid in Med.meds:
             for o in Med.meds[self.pid]:
                 bundle["entry"].append(o.toJSON(prefix))
                 for f in Refill.refill_list(o.pid, o.rxn):
                     bundle["entry"].append(f.toJSON(o, prefix))
     return bundle
Esempio n. 4
0
   def addMedList(self):
      """Adds a MedList to a patient's graph"""

      g = self.g
      if not self.pid in Med.meds: return  # No meds for this patient
      for m in Med.meds[self.pid]:
        mNode = BNode()
        g.add((mNode,RDF.type,SP['Medication']))
        g.add((mNode,SP['drugName'],self.codedValue(RXN_URI%m.rxn,m.name,RXN_URI%"",m.rxn)))
        g.add((mNode,SP['startDate'],Literal(m.start)))
        g.add((mNode,SP['instructions'],Literal(m.sig))) 
        if m.qtt:
          g.add((mNode,SP['quantity'],self.valueAndUnit(m.qtt,m.qttunit)))
        if m.freq:
          g.add((mNode,SP['frequency'],self.valueAndUnit(m.freq,m.frequnit)))

        # Now,loop through and add fulfillments for each med
        for fill in Refill.refill_list(m.pid,m.rxn):
          rfNode = BNode()
          g.add((rfNode,RDF.type,SP['Fulfillment']))
          g.add((rfNode,DC['date'],Literal(fill.date)))
          g.add((rfNode,SP['dispenseQuantity'],Literal(fill.q))) 
          g.add((rfNode,SP['dispenseDaysSupply'],Literal(fill.days)))
          g.add((mNode,SP['fulfillment'],rfNode))
Esempio n. 5
0
   print >>f, g.toRDF()


def displayPatientSummary(pid):
   """writes a patient summary to stdout"""
   if not pid in Patient.mpi: return
   print Patient.mpi[pid].asTabString()
   print "PROBLEMS: ",
   if not pid in Problem.problems: print "None",
   else: 
     for prob in Problem.problems[pid]: print prob.name+"; ",
   print "\nMEDICATIONS: ",
   if not pid in Med.meds: print "None",
   else:
     for med in Med.meds[pid]: 
       print med.name+"{%d}; "%len(Refill.refill_list(pid,med.rxn)),
   print "\nLABS: ",
   if not pid in Lab.results: print "None",
   else:
     print "%d results"%len(Lab.results[pid])
   print "\n"

if __name__=='__main__':

  parser = argparse.ArgumentParser(description='Test Data Generator')
  group = parser.add_mutually_exclusive_group()
  group.add_argument('--summary', metavar='pid',nargs='?', const="all", 
     help="displays patient summary (default is 'all')")
  group.add_argument('--rdf', metavar='pid', nargs='?', const='1520204',
     help='display RDF for a patient (default=1520204)')
  group.add_argument('--write', metavar='dir', nargs='?', const='.',
Esempio n. 6
0
    def writePatientData(self):

        pfile = open(os.path.join(self.path, "patient-%s.fhir-bundle.xml" % self.pid), "w")
        p = Patient.mpi[self.pid]

        now = datetime.datetime.now().isoformat()
        base_url = self.base_url

        if self.pid == "99912345":
            vpatient = generate_patient()
            p.dob = vpatient["birthday"]
            VitalSigns.loadVitalsPatient(vpatient)

        print >> pfile, """<?xml version="1.0" encoding="UTF-8"?>
<Bundle xmlns="http://hl7.org/fhir">
    <type value="transaction"/>
"""

        if self.pid in Document.documents:
            for d in [doc for doc in Document.documents[self.pid] if doc.type == "photograph"]:
                data = fetch_document(self.pid, d.file_name)
                d.content = data["base64_content"]
                d.size = data["size"]
                d.hash = data["hash"]
                b = d
                id = uid("Binary", "%s-photo" % d.id)
                d.binary_id = id
                template = template_env.get_template("binary.xml")
                print >> pfile, template.render(dict(globals(), **locals()))
                p.photo_code = d.mime_type
                p.photo_binary_id = d.binary_id
                p.photo_size = d.size
                p.photo_hash = d.hash
                p.photo_title = d.title

        id = "Patient/%s" % self.pid
        pid = id
        template = template_env.get_template("patient.xml")
        print >> pfile, template.render(dict(globals(), **locals()))

        bps = []
        othervitals = []

        if self.pid in VitalSigns.vitals:
            encounters = []
            for v in VitalSigns.vitals[self.pid]:
                encounter_id = None
                e = [i for i in encounters if i["date"] == v.start_date and i["type"] == v.encounter_type]
                if len(e) > 0:
                    encounter_id = e[0]["id"]
                else:
                    encounter_id = uid("Encounter", v.id)
                    encounters.append({"date": v.start_date, "type": v.encounter_type, "id": encounter_id})
                    id = encounter_id
                    template = template_env.get_template("encounter.xml")
                    print >> pfile, template.render(dict(globals(), **locals()))
                for vt in VitalSigns.vitalTypes:
                    try:
                        othervitals.append(getVital(v, vt, encounter_id))
                    except:
                        pass
                try:
                    systolic = getVital(v, VitalSigns.systolic, encounter_id)
                    diastolic = getVital(v, VitalSigns.diastolic, encounter_id)
                    bp = systolic
                    bp["systolic"] = int(systolic["value"])
                    bp["diastolic"] = int(diastolic["value"])
                    bp["site"] = v.bp_site
                    bp["id"] = v.id
                    if bp["site"]:
                        for pc in VitalSigns.bpPositionCodes:
                            if pc["name"] == bp["site"]:
                                bp["site_code"] = pc["code"]
                                bp["site_system"] = pc["system"]
                    bp["method"] = v.bp_method
                    if bp["method"]:
                        for pc in VitalSigns.bpPositionCodes:
                            if pc["name"] == bp["method"]:
                                bp["method_code"] = pc["code"]
                                bp["method_system"] = pc["system"]
                    bp["position"] = v.bp_position
                    if bp["position"]:
                        for pc in VitalSigns.bpPositionCodes:
                            if pc["name"] == bp["position"]:
                                bp["position_code"] = pc["code"]
                                bp["position_system"] = pc["system"]
                    bps.append(bp)
                except:
                    pass

        for bp in bps:
            systolicid = uid("Observation", "%s-systolic" % bp["id"])
            diastolicid = uid("Observation", "%s-diastolic" % bp["id"])
            id = uid("Observation", "%s-bp" % bp["id"])
            template = template_env.get_template("blood_pressure.xml")
            print >> pfile, template.render(dict(globals(), **locals()))

            id = systolicid
            o = {
                "date": bp["date"],
                "code": "8480-6",
                "name": "Systolic blood pressure",
                "scale": "Qn",
                "value": bp["systolic"],
                "units": "mm[Hg]",
                "unitsCode": "mm[Hg]",
                "categoryCode": "vital-signs",
                "categoryDisplay": "Vital Signs",
            }
            template = template_env.get_template("observation.xml")
            print >> pfile, template.render(dict(globals(), **locals()))

            id = diastolicid
            o = {
                "date": bp["date"],
                "code": "8462-4",
                "name": "Diastolic blood pressure",
                "scale": "Qn",
                "value": bp["diastolic"],
                "units": "mm[Hg]",
                "unitsCode": "mm[Hg]",
                "categoryCode": "vital-signs",
                "categoryDisplay": "Vital Signs",
            }
            template = template_env.get_template("observation.xml")
            print >> pfile, template.render(dict(globals(), **locals()))

        template = template_env.get_template("observation.xml")
        for o in othervitals:
            id = uid("Observation", "-".join((o["id"], o["name"].lower().replace(" ", "").replace("_", ""))))
            if "units" in o.keys():
                o["unitsCode"] = o["units"]
                o["categoryCode"] = "vital-signs"
                o["categoryDisplay"] = "Vital Signs"
            print >> pfile, template.render(dict(globals(), **locals()))

        if self.pid in Lab.results:
            for o in Lab.results[self.pid]:
                id = uid("Observation", "%s-lab" % o.id)
                o.categoryCode = "laboratory"
                o.categoryDisplay = "Laboratory"
                print >> pfile, template.render(dict(globals(), **locals()))

        medtemplate = template_env.get_template("medication.xml")
        dispensetemplate = template_env.get_template("medication_dispense.xml")
        if self.pid in Med.meds:
            for m in Med.meds[self.pid]:
                medid = id = uid("MedicationOrder", m.id)
                print >> pfile, medtemplate.render(dict(globals(), **locals()))

                for f in Refill.refill_list(m.pid, m.rxn):
                    id = uid("MedicationDispense", f.id)
                    print >> pfile, dispensetemplate.render(dict(globals(), **locals()))

        template = template_env.get_template("condition.xml")
        if self.pid in Problem.problems:
            for c in Problem.problems[self.pid]:
                id = uid("Condition", c.id)
                print >> pfile, template.render(dict(globals(), **locals()))

        template = template_env.get_template("procedure.xml")
        if self.pid in Procedure.procedures:
            for w in Procedure.procedures[self.pid]:
                id = uid("Procedure", w.id)
                print >> pfile, template.render(dict(globals(), **locals()))

        template = template_env.get_template("immunization.xml")
        if self.pid in Immunization.immunizations:
            for i in Immunization.immunizations[self.pid]:
                id = uid("Immunization", i.id)
                i.cvx_system, i.cvx_id = i.cvx.rsplit("cvx", 1)
                i.cvx_system += "cvx"
                print >> pfile, template.render(dict(globals(), **locals()))

        template = template_env.get_template("family_history.xml")
        if self.pid in FamilyHistory.familyHistories:
            for fh in FamilyHistory.familyHistories[self.pid]:
                id = uid("FamilyHistory", fh.id)
                print >> pfile, template.render(dict(globals(), **locals()))

        template = template_env.get_template("smoking_status.xml")
        if self.pid in SocialHistory.socialHistories:
            t = SocialHistory.socialHistories[self.pid]
            t.smokingStatusText = SMOKINGCODES[t.smokingStatusCode]
            id = uid("Observation", "-".join((t.id, "smokingstatus")))
            print >> pfile, template.render(dict(globals(), **locals()))

        if p.gestage:
            template = template_env.get_template("observation.xml")
            o = {
                "date": p.dob,
                "code": "18185-9",
                "name": "Gestational age at birth",
                "scale": "Qn",
                "value": p.gestage,
                "units": "weeks",
                "unitsCode": "wk",
                "categoryCode": "exam",
                "categoryDisplay": "Exam",
            }
            id = uid("Observation", "%s-gestage" % self.pid)
            print >> pfile, template.render(dict(globals(), **locals()))

        if self.pid in Allergy.allergies:
            for al in Allergy.allergies[self.pid]:
                if al.statement == "positive":
                    if al.type == "drugClass":
                        al.typeDescription = "medication"
                        al.system = "http://rxnav.nlm.nih.gov/REST/Ndfrt"
                    elif al.type == "drug":
                        al.typeDescription = "medication"
                        al.system = "http://www.nlm.nih.gov/research/umls/rxnorm"
                    elif al.type == "food":
                        al.typeDescription = "food"
                        al.system = "http://fda.gov/UNII/"
                    elif al.type == "environmental":
                        al.typeDescription = "environment"
                        al.system = "http://fda.gov/UNII/"
                    if al.reaction:
                        if al.severity.lower() == "mild":
                            al.severity = "mild"
                            al.criticality = "CRITL"
                        elif al.severity.lower() == "severe":
                            al.severity = "severe"
                            al.criticality = "CRITH"
                        elif al.severity.lower() == "life threatening" or al.severity.lower() == "fatal":
                            al.severity = "severe"
                            al.criticality = "CRITH"
                        elif al.severity.lower() == "moderate":
                            al.severity = "moderate"
                            al.criticality = "CRITU"
                        else:
                            al.severity = None
                    id = uid("AllergyIntolerance", al.id)
                    template = template_env.get_template("allergy.xml")
                    print >> pfile, template.render(dict(globals(), **locals()))
                elif al.statement == "negative" and al.type == "general":
                    if al.code == "160244002":
                        template = template_env.get_template("no_known_allergies.xml")
                        id = uid("List", al.id)
                        al.loinc_code = "52473-6"
                        al.loinc_display = "Allergy"
                        al.text = "No known allergies"
                        print >> pfile, template.render(dict(globals(), **locals()))
                    elif al.code == "409137002":
                        template = template_env.get_template("no_known_allergies.xml")
                        id = uid("List", al.id)
                        al.loinc_code = "11382-9"
                        al.loinc_display = "Medication allergy"
                        al.text = "No known history of drug allergy"
                        print >> pfile, template.render(dict(globals(), **locals()))
                    else:
                        template = template_env.get_template("general_observation.xml")
                        o = {
                            "date": al.start,
                            "system": "http://snomed.info/sct",
                            "code": al.code,
                            "name": al.allergen,
                            "categoryCode": "exam",
                            "categoryDisplay": "Exam",
                        }
                        id = uid("Observation", "%s-allergy" % al.id)
                        print >> pfile, template.render(dict(globals(), **locals()))

        addedPractitioner = False

        if self.pid in ClinicalNote.clinicalNotes:
            id = "Practitioner/1234"
            template = template_env.get_template("practitioner.xml")
            print >> pfile, template.render(dict(globals(), **locals()))
            addedPractitioner = True
            for d in ClinicalNote.clinicalNotes[self.pid]:
                if d.mime_type == "text/plain":
                    data = fetch_document(self.pid, d.file_name)
                    d.content = data["base64_content"]
                    b = d
                    id = uid("Binary", "%s-note" % d.id)
                    d.binary_id = id
                    template = template_env.get_template("binary.xml")
                    print >> pfile, template.render(dict(globals(), **locals()))
                    id = uid("DocumentReference", "%s-note" % d.id)
                    d.system = "http://loinc.org"
                    d.code = "34109-9"
                    d.display = "Note"
                    template = template_env.get_template("document.xml")
                    print >> pfile, template.render(dict(globals(), **locals()))

        if self.pid in Document.documents:
            if not addedPractitioner:
                id = "Practitioner/1234"
                template = template_env.get_template("practitioner.xml")
                print >> pfile, template.render(dict(globals(), **locals()))
            for d in [doc for doc in Document.documents[self.pid] if doc.type != "photograph"]:
                data = fetch_document(self.pid, d.file_name)
                d.content = data["base64_content"]
                d.size = data["size"]
                d.hash = data["hash"]
                b = d
                id = uid("Binary", "%s-document" % d.id)
                d.binary_id = id
                template = template_env.get_template("binary.xml")
                print >> pfile, template.render(dict(globals(), **locals()))
                id = uid("DocumentReference", "%s-document" % d.id)
                d.system = "http://smarthealthit.org/terms/codes/DocumentType#"
                d.code = d.type
                d.display = d.type
                template = template_env.get_template("document.xml")
                print >> pfile, template.render(dict(globals(), **locals()))

        if self.pid in ImagingStudy.imagingStudies:
            st = {}
            for img in ImagingStudy.imagingStudies[self.pid]:
                data = fetch_document(self.pid, img.image_file_name)
                img.mime_type = "application/dicom"
                img.content = data["base64_content"]
                img.size = data["size"]
                img.hash = data["hash"]
                b = img
                id = uid("Binary", "%s-dicom" % img.id)
                img.binary_id = id
                template = template_env.get_template("binary.xml")
                print >> pfile, template.render(dict(globals(), **locals()))
                if img.study_oid not in st.keys():
                    st[img.study_oid] = {
                        "id": img.id,
                        "title": img.study_title,
                        "date": img.study_date,
                        "accession_number": img.study_accession_number,
                        "modality": img.study_modality,
                        "oid": img.study_oid,
                        "series_count": 0,
                        "images_count": 0,
                        "series": {},
                    }
                series = st[img.study_oid]["series"]
                if img.series_oid not in series.keys():
                    st[img.study_oid]["series_count"] += 1
                    series[img.series_oid] = {
                        "number": st[img.study_oid]["series_count"],
                        "title": img.series_title,
                        "oid": img.series_oid,
                        "images_count": 0,
                        "images": [],
                    }
                st[img.study_oid]["images_count"] += 1
                series[img.series_oid]["images_count"] += 1
                series[img.series_oid]["images"].append(
                    {
                        "title": img.image_title,
                        "date": img.image_date,
                        "file_name": img.image_file_name,
                        "oid": img.image_oid,
                        "binary_id": img.binary_id,
                        "sop": img.image_sop,
                        "number": series[img.series_oid]["images_count"],
                    }
                )

            for i in st:
                s = st[i]
                id = uid("ImagingStudy", s["id"])
                template = template_env.get_template("imagingstudy.xml")
                print >> pfile, template.render(dict(globals(), **locals()))

        print >> pfile, "\n</Bundle>"
        pfile.close()
Esempio n. 7
0
    def addMeds(self):
        """ Add medications to the patient's data. """
        if self.pid in Med.meds:
            for m in Med.meds[self.pid]:

                # build the fills, setting some defaults
                subs = {
                    'qunit': {
                        'qunit': '{tab}'
                    },
                    'pbm': {
                        'pbm': 'T00000000001011'
                    },
                    'ncpdp': {
                        'ncpdp': '5235235'
                    },
                    'pharm_org': {
                        'pharm_org': 'CVS #588'
                    },
                    'pharm_co': {
                        'pharm_co': 'Australia'
                    },
                    'pharm_ci': {
                        'pharm_ci': 'Wonder City'
                    },
                    'pharm_pc': {
                        'pharm_pc': '5555'
                    },
                    'pharm_st': {
                        'pharm_st': '111 Lake Drive'
                    },
                    'pharm_re': {
                        'pharm_re': 'West Australia'
                    },
                    'prov_dea': {
                        'prov_dea': '325555555'
                    },
                    'prov_npi': {
                        'prov_npi': '5235235'
                    },
                    'prov_email': {
                        'prov_email': '*****@*****.**'
                    },
                    'prov_fn': {
                        'prov_fn': 'Joshua'
                    },
                    'prov_ln': {
                        'prov_ln': 'Mandel'
                    },
                    'prov_tel': {
                        'prov_tel': '1-234-567-8910'
                    },
                }
                fills_str = ''
                for f in Refill.refill_list(self.pid, m.rxn):
                    self._set_default_attrs(f, subs)
                    fills_str = '\n'.join([
                        fills_str,
                        FULFILLMENT.sub({
                            'date': f.date,
                            'days': f.days,
                            'pbm': f.pbm,
                            'ncpdp': f.ncpdp,
                            'pharm_org': f.pharm_org,
                            'pharm_co': f.pharm_co,
                            'pharm_ci': f.pharm_ci,
                            'pharm_pc': f.pharm_pc,
                            'pharm_st': f.pharm_st,
                            'pharm_re': f.pharm_re,
                            'prov_dea': f.prov_dea,
                            'prov_npi': f.prov_npi,
                            'prov_email': f.prov_email,
                            'prov_fn': f.prov_fn,
                            'prov_ln': f.prov_ln,
                            'prov_tel': f.prov_tel,
                            'quantity': f.q,
                            'quantityUnits': f.qunit
                        }).done()
                    ])

                # build the med, setting some defaults
                subs = {
                    'qtt': {
                        'qtt': 30,
                        'qttunit': '{tab}'
                    },
                    'freq': {
                        'freq': 2,
                        'frequnit': '/d'
                    },
                    'prov': {
                        'prov': 'Derived by prescription',
                        'prov_id': 'prescription'
                    },
                    'end': {
                        'end': '2010-04-09'
                    },
                }
                self._set_default_attrs(m, subs)
                med_data = {
                    'name': m.name,
                    'rxnorm': m.rxn,
                    'endDate': m.end,
                    'frequencyValue': m.freq,
                    'frequencyUnits': m.frequnit,
                    'instructions': m.sig,
                    'provenance': m.prov,
                    'provenance_id': m.prov_id,
                    'quantityValue': m.qtt,
                    'quantityUnits': m.qttunit,
                    'startDate': m.start,
                }
                med_str = MEDICATION.sub(med_data).sub({
                    'fills': fills_str
                },
                                                       escape=False).done()
                self.data.append(
                    SDMX.sub({
                        'models': med_str
                    }, escape=False).done())
Esempio n. 8
0
  def writePatientData(self):

    pfile = open(os.path.join(self.path, "patient-%s.fhir-bundle.xml"%self.pid), "w")
    p = Patient.mpi[self.pid]

    now = datetime.datetime.now().isoformat()
    
    if self.pid == '99912345':
        vpatient = generate_patient()
        p.dob = vpatient["birthday"]
        VitalSigns.loadVitalsPatient(vpatient)

    print >>pfile, """<?xml version="1.0" encoding="UTF-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
  <title>SMART patient bundle for transactional posting</title>
  <id>urn:uuid:%s</id>
  <updated>%s</updated>
"""%(uid(), now)

    if self.pid in Document.documents:
        for d in [doc for doc in Document.documents[self.pid] if doc.type == 'photograph']:
            data = fetch_document (self.pid, d.file_name)
            d.content = data['base64_content']
            d.size = data['size']
            d.hash = data['hash']
            b = d
            id = uid("Binary", "%s-photo" % d.id)
            d.binary_id = id
            template = template_env.get_template('binary.xml')
            print >>pfile, template.render(dict(globals(), **locals()))
            p.photo_code = d.mime_type
            p.photo_binary_id = d.binary_id
            p.photo_size = d.size
            p.photo_hash = d.hash
            p.photo_title = d.title

    id = "Patient/%s"%self.pid
    pid = id
    template = template_env.get_template('patient.xml')
    print >>pfile, template.render(dict(globals(), **locals()))

    bps = []
    othervitals = []

    if self.pid in VitalSigns.vitals:
      encounters = []
      for v in  VitalSigns.vitals[self.pid]:
          encounter_id = None
          e = [i for i in encounters if i['date'] == v.start_date and i['type'] == v.encounter_type]
          if len(e) > 0:
              encounter_id = e[0]['id']
          else:
              encounter_id = uid("Encounter", v.id)
              encounters.append ({'date': v.start_date, 'type': v.encounter_type, 'id': encounter_id})
              id = encounter_id
              template = template_env.get_template('encounter.xml')
              print >>pfile, template.render(dict(globals(), **locals()))
          for vt in VitalSigns.vitalTypes:
              try: 
                  othervitals.append(getVital(v, vt, encounter_id))
              except: pass
          try: 
              systolic = getVital(v, VitalSigns.systolic, encounter_id)
              diastolic = getVital(v, VitalSigns.diastolic, encounter_id)
              bp = systolic
              bp['systolic'] = int(systolic['value'])
              bp['diastolic'] = int(diastolic['value'])
              bp['site'] = v.bp_site
              bp['id'] = v.id
              if bp['site']:
                for pc in VitalSigns.bpPositionCodes:
                    if pc['name'] == bp['site']:
                        bp['site_code'] = pc['code']
                        bp['site_system'] = pc['system']
              bp['method'] = v.bp_method
              if bp['method']:
                for pc in VitalSigns.bpPositionCodes:
                    if pc['name'] == bp['method']:
                        bp['method_code'] = pc['code']
                        bp['method_system'] = pc['system']
              bp['position'] = v.bp_position
              if bp['position']:
                for pc in VitalSigns.bpPositionCodes:
                    if pc['name'] == bp['position']:
                        bp['position_code'] = pc['code']
                        bp['position_system'] = pc['system']
              bps.append(bp)
          except: pass
          
    for bp in bps:
        systolicid = uid("Observation", "%s-systolic" % bp['id'])
        diastolicid = uid("Observation", "%s-diastolic" % bp['id'])
        id = uid("Observation", "%s-bp" % bp['id'])
        template = template_env.get_template('blood_pressure.xml')
        print >>pfile, template.render(dict(globals(), **locals()))

        id = systolicid
        o = {
                "date": bp['date'],
                "code": "8480-6",
                "name": "Systolic blood pressure",
                "scale": "Qn",
                "value": bp['systolic'],
                "units": "mm[Hg]",
                "unitsCode": "mm[Hg]"
        }
        template = template_env.get_template('observation.xml')
        print >>pfile, template.render(dict(globals(), **locals()))

        id = diastolicid
        o = {
                "date": bp['date'],
                "code": "8462-4",
                "name": "Diastolic blood pressure",
                "scale": "Qn",
                "value": bp['diastolic'],
                "units": "mm[Hg]",
                "unitsCode": "mm[Hg]"
        }
        template = template_env.get_template('observation.xml')
        print >>pfile, template.render(dict(globals(), **locals()))
        
    template = template_env.get_template('observation.xml')
    for o in othervitals:
        id = uid("Observation", '-'.join((o["id"], o["name"].lower().replace(' ', '').replace('_', ''))))
        if "units" in o.keys():
           o["unitsCode"] = o["units"]
        print >>pfile, template.render(dict(globals(), **locals()))

    if self.pid in Lab.results:  
      for o in Lab.results[self.pid]:
        id = uid("Observation", "%s-lab" % o.id)
        print >>pfile, template.render(dict(globals(), **locals()))

    medtemplate = template_env.get_template('medication.xml')
    dispensetemplate = template_env.get_template('medication_dispense.xml')
    if self.pid in Med.meds:  
      for m in Med.meds[self.pid]:
        medid = id = uid("MedicationPrescription", m.id)
        print >>pfile, medtemplate.render(dict(globals(), **locals()))

        for f in Refill.refill_list(m.pid, m.rxn):
          id = uid("MedicationDispense", f.id)
          print >>pfile, dispensetemplate.render(dict(globals(), **locals()))

    template = template_env.get_template('condition.xml')
    if self.pid in Problem.problems:  
      for c in Problem.problems[self.pid]:
        id = uid("Condition", c.id)
        print >>pfile, template.render(dict(globals(), **locals()))
        
    template = template_env.get_template('procedure.xml')
    if self.pid in Procedure.procedures:  
      for w in Procedure.procedures[self.pid]:
        id = uid("Procedure", w.id)
        print >>pfile, template.render(dict(globals(), **locals()))
        
    template = template_env.get_template('immunization.xml')
    if self.pid in Immunization.immunizations:  
      for i in Immunization.immunizations[self.pid]:
        id = uid("Immunization", i.id)
        i.cvx_system, i.cvx_id = i.cvx.rsplit("cvx",1)
        i.cvx_system += "cvx"
        print >>pfile, template.render(dict(globals(), **locals()))

    template = template_env.get_template('family_history.xml')
    if self.pid in FamilyHistory.familyHistories:  
      for fh in FamilyHistory.familyHistories[self.pid]:
        id = uid("FamilyHistory", fh.id)
        print >>pfile, template.render(dict(globals(), **locals()))
        
    template = template_env.get_template('smoking_status.xml')
    if self.pid in SocialHistory.socialHistories: 
        t = SocialHistory.socialHistories[self.pid]
        t.smokingStatusText = SMOKINGCODES[t.smokingStatusCode]
        id = uid("Observation", '-'.join((t.id,"smokingstatus")))
        print >>pfile, template.render(dict(globals(), **locals()))
    
    if p.gestage:
        template = template_env.get_template('observation.xml')
        o = {
            "date": p.dob,
            "code": "18185-9",
            "name": "Gestational age at birth",
            "scale": "Qn",
            "value": p.gestage,
            "units": "weeks",
            "unitsCode": "wk"
        }
        id = uid("Observation", "%s-gestage" % self.pid)
        print >>pfile, template.render(dict(globals(), **locals()))

    if self.pid in Allergy.allergies:
        for al in Allergy.allergies[self.pid]:
            if al.statement == 'positive':
                id = uid("Substance", '-'.join((al.system.lower(), al.code)))
                al.substance_id = id
                template = template_env.get_template('substance.xml')
                if al.type == 'drugClass':
                    al.typeDescription = 'drug class'
                    al.system = "http://rxnav.nlm.nih.gov/REST/Ndfrt"
                elif al.type == 'drug':
                    al.typeDescription = 'drug'
                    al.system = "http://www.nlm.nih.gov/research/umls/rxnorm"
                elif al.type == 'food':
                    al.typeDescription = 'food',
                    al.system = "http://fda.gov/UNII/"
                elif al.type == 'environmental':
                    al.typeDescription = 'environmental substance',
                    al.system = "http://fda.gov/UNII/"
                print >>pfile, template.render(dict(globals(), **locals()))
                if al.reaction:
                    if al.severity.lower() == 'mild':
                        al.severity = 'minor'
                        al.criticality = 'low'
                    elif al.severity.lower() == 'severe':
                        al.severity = 'severe'
                        al.criticality = 'high'
                    elif al.severity.lower() == 'life threatening' or al.severity.lower() == 'fatal':
                        al.severity = 'severe'
                        al.criticality = 'fatal'
                    elif al.severity.lower() == 'moderate':
                        al.severity = 'moderate'
                        al.criticality = 'medium'
                    else:
                        al.severity = None
                    id = uid("AdverseReaction", al.id)
                    al.reaction_id = id
                    template = template_env.get_template('adverse_reaction.xml')
                    print >>pfile, template.render(dict(globals(), **locals()))
                id = uid("AllergyIntolerance", al.id)
                template = template_env.get_template('allergy.xml')
                print >>pfile, template.render(dict(globals(), **locals()))
            elif al.statement == 'negative' and al.type == 'general':
                if al.code == '160244002':
                    template = template_env.get_template('no_known_allergies.xml')
                    id = uid("List", al.id)
                    al.loinc_code = '52473-6'
                    al.loinc_display = 'Allergy'
                    al.text = 'No known allergies'
                    print >>pfile, template.render(dict(globals(), **locals()))
                elif al.code == '409137002':
                    template = template_env.get_template('no_known_allergies.xml')
                    id = uid("List", al.id)
                    al.loinc_code = '11382-9'
                    al.loinc_display = 'Medication allergy'
                    al.text = 'No known history of drug allergy'
                    print >>pfile, template.render(dict(globals(), **locals()))
                else:
                    template = template_env.get_template('general_observation.xml')
                    o = {
                        "date": al.start,
                        "system": "http://snomed.info/sct",
                        "code": al.code,
                        "name": al.allergen
                    }
                    id = uid("Observation", "%s-allergy" % al.id)
                    print >>pfile, template.render(dict(globals(), **locals()))

    addedPractitioner = False
                    
    if self.pid in ClinicalNote.clinicalNotes:
        id = 'Practitioner/1234'
        template = template_env.get_template('practitioner.xml')
        print >>pfile, template.render(dict(globals(), **locals()))
        addedPractitioner = True
        for d in ClinicalNote.clinicalNotes[self.pid]:
            if d.mime_type == 'text/plain':
                data = fetch_document (self.pid, d.file_name)
                d.content = data['base64_content']
                b = d
                id = uid("Binary", "%s-note" % d.id)
                d.binary_id = id
                template = template_env.get_template('binary.xml')
                print >>pfile, template.render(dict(globals(), **locals()))
                id = uid("DocumentReference", "%s-note" % d.id)
                d.system = "http://loinc.org"
                d.code = '34109-9'
                d.display = 'Note'
                template = template_env.get_template('document.xml')
                print >>pfile, template.render(dict(globals(), **locals()))
                
    if self.pid in Document.documents:
        if not addedPractitioner:
            id = 'Practitioner/1234'
            template = template_env.get_template('practitioner.xml')
            print >>pfile, template.render(dict(globals(), **locals()))
        for d in [doc for doc in Document.documents[self.pid] if doc.type != 'photograph']:
            data = fetch_document (self.pid, d.file_name)
            d.content = data['base64_content']
            d.size = data['size']
            d.hash = data['hash']
            b = d
            id = uid("Binary", "%s-document" % d.id)
            d.binary_id = id
            template = template_env.get_template('binary.xml')
            print >>pfile, template.render(dict(globals(), **locals()))
            id = uid("DocumentReference", "%s-document" % d.id)
            d.system = 'http://smarthealthit.org/terms/codes/DocumentType#'
            d.code = d.type
            d.display = d.type
            template = template_env.get_template('document.xml')
            print >>pfile, template.render(dict(globals(), **locals()))
    
    if self.pid in ImagingStudy.imagingStudies:
        st = {}
        for img in ImagingStudy.imagingStudies[self.pid]:
            data = fetch_document (self.pid, img.image_file_name)
            img.mime_type = "application/dicom"
            img.content = data['base64_content']
            img.size = data['size']
            img.hash = data['hash']
            b = img
            id = uid("Binary", "%s-dicom" % img.id)
            img.binary_id = id
            template = template_env.get_template('binary.xml')
            print >>pfile, template.render(dict(globals(), **locals()))
            if img.study_oid not in st.keys():
                st[img.study_oid] = {
                    'id': img.id,
                    'title': img.study_title,
                    'date': img.study_date,
                    'accession_number': img.study_accession_number,
                    'modality': img.study_modality,
                    'oid': img.study_oid,
                    'series_count': 0,
                    'images_count': 0,
                    'series': {}
                }
            series = st[img.study_oid]['series']
            if img.series_oid not in series.keys():
                st[img.study_oid]['series_count'] += 1
                series[img.series_oid] = {
                    'number': st[img.study_oid]['series_count'],
                    'title': img.series_title,
                    'oid': img.series_oid,
                    'images_count': 0,
                    'images': []
                }
            st[img.study_oid]['images_count'] += 1
            series[img.series_oid]['images_count'] += 1
            series[img.series_oid]['images'].append({
                'title': img.image_title,
                'date': img.image_date,
                'file_name': img.image_file_name,
                'oid': img.image_oid,
                'binary_id': img.binary_id,
                'sop': img.image_sop,
                'number': series[img.series_oid]['images_count']
            })

            
        for i in st:
            s = st[i]
            id = uid("ImagingStudy", s['id'])
            template = template_env.get_template('imagingstudy.xml')
            print >>pfile, template.render(dict(globals(), **locals()))

    print >>pfile, "\n</feed>"
    pfile.close()
Esempio n. 9
0
  def writePatientData(self):

    pfile = open(os.path.join(self.path, "patient-%s.fhir-bundle.xml"%self.pid), "w")
    p = Patient.mpi[self.pid]

    now = datetime.datetime.now().isoformat()
    id = "Patient/%s"%self.pid
    pid = id

    print >>pfile, """<?xml version="1.0" encoding="UTF-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
  <title>SMART patient bundle for transactional posting</title>
  <id>urn:uuid:%s</id>
  <updated>%s</updated>
"""%(uid(), now)

    template = template_env.get_template('patient.xml')
    print >>pfile, template.render(dict(globals(), **locals()))

    bps = []
    othervitals = []

    if self.pid in VitalSigns.vitals:
      for v in  VitalSigns.vitals[self.pid]:
          for vt in VitalSigns.vitalTypes:
              try: 
                  othervitals.append(getVital(v, vt))
              except: pass
          try: 
              systolic = getVital(v, VitalSigns.systolic)
              diastolic = getVital(v, VitalSigns.diastolic)
              bp = systolic
              bp['systolic'] = int(systolic['value'])
              bp['diastolic'] = int(diastolic['value'])
              bps.append(bp)
          except: pass

    for bp in bps:
        systolicid = uid("Observation")
        diastolicid = uid("Observation")
        id = uid("Observation")
        template = template_env.get_template('blood_pressure.xml')
        print >>pfile, template.render(dict(globals(), **locals()))

        id = systolicid
        o = {
                "date": bp['date'],
                "code": "8480-6",
                "name": "Systolic blood pressure",
                "scale": "Qn",
                "value": bp['systolic'],
                "units": "mm[Hg]",
                "unitsCode": "mm[Hg]"
        }
        template = template_env.get_template('observation.xml')
        print >>pfile, template.render(dict(globals(), **locals()))

        id = diastolicid
        o = {
                "date": bp['date'],
                "code": "8462-4",
                "name": "Diastolic blood pressure",
                "scale": "Qn",
                "value": bp['diastolic'],
                "units": "mm[Hg]",
                "unitsCode": "mm[Hg]"
        }
        template = template_env.get_template('observation.xml')
        print >>pfile, template.render(dict(globals(), **locals()))
        
    template = template_env.get_template('observation.xml')
    for o in othervitals:
        id = uid("Observation")
        if "units" in o.keys():
           o["unitsCode"] = o["units"]
        print >>pfile, template.render(dict(globals(), **locals()))

    if self.pid in Lab.results:  
      for o in Lab.results[self.pid]:
        id = uid("Observation")
        print >>pfile, template.render(dict(globals(), **locals()))

    medtemplate = template_env.get_template('medication.xml')
    dispensetemplate = template_env.get_template('medication_dispense.xml')
    if self.pid in Med.meds:  
      for m in Med.meds[self.pid]:
        medid = id = uid("MedicationPrescription")
        print >>pfile, medtemplate.render(dict(globals(), **locals()))

        for f in Refill.refill_list(m.pid, m.rxn):
          id = uid("MedicationDispense")
          print >>pfile, dispensetemplate.render(dict(globals(), **locals()))

    template = template_env.get_template('condition.xml')
    if self.pid in Problem.problems:  
      for c in Problem.problems[self.pid]:
        id = uid("Condition")
        print >>pfile, template.render(dict(globals(), **locals()))
        
    template = template_env.get_template('procedure.xml')
    if self.pid in Procedure.procedures:  
      for w in Procedure.procedures[self.pid]:
        id = uid("Procedure")
        print >>pfile, template.render(dict(globals(), **locals()))
        
    template = template_env.get_template('immunization.xml')
    if self.pid in Immunization.immunizations:  
      for i in Immunization.immunizations[self.pid]:
        id = uid("Immunization")
        i.cvx_system, i.cvx_id = i.cvx.rsplit("#",1)
        i.cvx_system += "#"
        print >>pfile, template.render(dict(globals(), **locals()))

    template = template_env.get_template('family_history.xml')
    if self.pid in FamilyHistory.familyHistories:  
      for fh in FamilyHistory.familyHistories[self.pid]:
        id = uid("FamilyHistory")
        print >>pfile, template.render(dict(globals(), **locals()))
        
    template = template_env.get_template('smoking_status.xml')
    if self.pid in SocialHistory.socialHistories: 
        t = SocialHistory.socialHistories[self.pid]
        t.smokingStatusText = SMOKINGCODES[t.smokingStatusCode]
        id = uid("SocialHistory")
        print >>pfile, template.render(dict(globals(), **locals()))
    
    if p.gestage:
        template = template_env.get_template('observation.xml')
        o = {
            "date": p.dob,
            "code": "18185-9",
            "name": "Gestational age at birth",
            "scale": "Qn",
            "value": p.gestage,
            "units": "weeks",
            "unitsCode": "wk"
        }
        id = uid("Observation")
        print >>pfile, template.render(dict(globals(), **locals()))

    print >>pfile, "\n</feed>"
    pfile.close()
Esempio n. 10
0
    def addMeds(self):
        """ Add medications to the patient's data. """
        if  self.pid in Med.meds: 
            for m in Med.meds[self.pid]:

                # build the fills, setting some defaults
                subs = {
                    'qunit': {'qunit': '{tab}'},
                    'pbm': {'pbm': 'T00000000001011'},
                    'ncpdp': {'ncpdp': '5235235'},
                    'pharm_org': {'pharm_org': 'CVS #588'},
                    'pharm_co': {'pharm_co': 'Australia'},
                    'pharm_ci': {'pharm_ci': 'Wonder City'},
                    'pharm_pc': {'pharm_pc': '5555'},
                    'pharm_st': {'pharm_st': '111 Lake Drive'},
                    'pharm_re': {'pharm_re': 'West Australia'},
                    'prov_dea': {'prov_dea': '325555555'},
                    'prov_npi': {'prov_npi': '5235235'},
                    'prov_email': {'prov_email': '*****@*****.**'},
                    'prov_fn': {'prov_fn': 'Joshua'},
                    'prov_ln': {'prov_ln': 'Mandel'},
                    'prov_tel': {'prov_tel': '1-234-567-8910'},
                    }
                fills_str = ''
                for f in Refill.refill_list(self.pid, m.rxn):
                    self._set_default_attrs(f, subs)
                    fills_str = '\n'.join([fills_str, FULFILLMENT.sub({
                                    'date': f.date,
                                    'days': f.days,
                                    'pbm': f.pbm,
                                    'ncpdp': f.ncpdp,
                                    'pharm_org': f.pharm_org,
                                    'pharm_co': f.pharm_co,
                                    'pharm_ci': f.pharm_ci,
                                    'pharm_pc': f.pharm_pc,
                                    'pharm_st': f.pharm_st,
                                    'pharm_re': f.pharm_re,
                                    'prov_dea': f.prov_dea,
                                    'prov_npi': f.prov_npi,
                                    'prov_email': f.prov_email,
                                    'prov_fn': f.prov_fn,
                                    'prov_ln': f.prov_ln,
                                    'prov_tel': f.prov_tel,
                                    'quantity': f.q,
                                    'quantityUnits': f.qunit}).done()])

                # build the med, setting some defaults
                subs = {
                    'qtt': {'qtt': 30, 'qttunit': '{tab}'},
                    'freq': {'freq':2, 'frequnit': '/d'},
                    'prov': {'prov': 'Derived by prescription', 'prov_id': 'prescription'},
                    'end': {'end': '2010-04-09'},
                    }
                self._set_default_attrs(m, subs)
                med_data = {
                    'name': m.name,
                    'rxnorm': m.rxn,
                    'endDate': m.end,
                    'frequencyValue': m.freq,
                    'frequencyUnits': m.frequnit,
                    'instructions': m.sig,
                    'provenance': m.prov,
                    'provenance_id': m.prov_id,
                    'quantityValue': m.qtt,
                    'quantityUnits': m.qttunit,
                    'startDate': m.start,
                    }
                med_str = MEDICATION.sub(med_data).sub({'fills':fills_str}, escape=False).done()                                          
                self.data.append(SDMX.sub({'models':med_str}, escape=False).done())
Esempio n. 11
0
    def writePatientData(self, prefix=None):

        pfile = open(
            os.path.join(self.path, "patient-%s.fhir-bundle.xml" % self.pid),
            "w")
        p = Patient.mpi[self.pid]

        now = datetime.datetime.now().isoformat()
        base_url = self.base_url
        tag = self.tag

        if self.pid == '99912345':
            vpatient = generate_patient()
            p.dob = vpatient["birthday"]
            VitalSigns.loadVitalsPatient(vpatient)

        print >> pfile, """<?xml version="1.0" encoding="UTF-8"?>
<Bundle xmlns="http://hl7.org/fhir">
    <type value="transaction"/>
"""

        if self.pid in Document.documents:
            for d in [
                    doc for doc in Document.documents[self.pid]
                    if doc.type == 'photograph'
            ]:
                data = fetch_document(self.pid, d.file_name)
                d.content = data['base64_content']
                d.size = data['size']
                d.hash = data['hash']
                b = d
                id = uid("Binary", "%s-photo" % d.id, prefix)
                d.binary_id = id
                template = template_env.get_template('binary.xml')
                print >> pfile, template.render(dict(globals(), **locals()))
                p.photo_code = d.mime_type
                p.photo_binary_id = d.binary_id
                p.photo_size = d.size
                p.photo_hash = d.hash
                p.photo_title = d.title

        if (prefix == None):
            id = "Patient/%s" % self.pid
        else:
            id = "Patient/%s-%s" % (prefix, self.pid)
        pid = id

        template = template_env.get_template('patient.xml')
        print >> pfile, template.render(dict(globals(), **locals()))

        bps = []
        othervitals = []

        if self.pid in VitalSigns.vitals:
            encounters = []
            for v in VitalSigns.vitals[self.pid]:
                encounter_id = None
                e = [
                    i for i in encounters if i['date'] == v.start_date
                    and i['type'] == v.encounter_type
                ]
                if len(e) > 0:
                    encounter_id = e[0]['id']
                else:
                    encounter_id = uid("Encounter", v.id, prefix)
                    encounters.append({
                        'date': v.start_date,
                        'type': v.encounter_type,
                        'id': encounter_id
                    })
                    id = encounter_id
                    template = template_env.get_template('encounter.xml')
                    print >> pfile, template.render(dict(
                        globals(), **locals()))
                for vt in VitalSigns.vitalTypes:
                    try:
                        othervitals.append(getVital(v, vt, encounter_id))
                    except:
                        pass
                try:
                    systolic = getVital(v, VitalSigns.systolic, encounter_id)
                    diastolic = getVital(v, VitalSigns.diastolic, encounter_id)
                    bp = systolic
                    bp['systolic'] = int(systolic['value'])
                    bp['diastolic'] = int(diastolic['value'])
                    bp['site'] = v.bp_site
                    bp['id'] = v.id
                    if bp['site']:
                        for pc in VitalSigns.bpPositionCodes:
                            if pc['name'] == bp['site']:
                                bp['site_code'] = pc['code']
                                bp['site_system'] = pc['system']
                    bp['method'] = v.bp_method
                    if bp['method']:
                        for pc in VitalSigns.bpPositionCodes:
                            if pc['name'] == bp['method']:
                                bp['method_code'] = pc['code']
                                bp['method_system'] = pc['system']
                    bp['position'] = v.bp_position
                    if bp['position']:
                        for pc in VitalSigns.bpPositionCodes:
                            if pc['name'] == bp['position']:
                                bp['position_code'] = pc['code']
                                bp['position_system'] = pc['system']
                    bps.append(bp)
                except:
                    pass

        for bp in bps:
            systolicid = uid("Observation", "%s-systolic" % bp['id'], prefix)
            diastolicid = uid("Observation", "%s-diastolic" % bp['id'], prefix)
            id = uid("Observation", "%s-bp" % bp['id'], prefix)
            template = template_env.get_template('blood_pressure.xml')
            print >> pfile, template.render(dict(globals(), **locals()))

            id = systolicid
            o = {
                "date": bp['date'],
                "code": "8480-6",
                "name": "Systolic blood pressure",
                "scale": "Qn",
                "value": bp['systolic'],
                "units": "mm[Hg]",
                "unitsCode": "mm[Hg]",
                "categoryCode": "vital-signs",
                "categoryDisplay": "Vital Signs"
            }
            template = template_env.get_template('observation.xml')
            print >> pfile, template.render(dict(globals(), **locals()))

            id = diastolicid
            o = {
                "date": bp['date'],
                "code": "8462-4",
                "name": "Diastolic blood pressure",
                "scale": "Qn",
                "value": bp['diastolic'],
                "units": "mm[Hg]",
                "unitsCode": "mm[Hg]",
                "categoryCode": "vital-signs",
                "categoryDisplay": "Vital Signs"
            }
            template = template_env.get_template('observation.xml')
            print >> pfile, template.render(dict(globals(), **locals()))

        template = template_env.get_template('observation.xml')
        for o in othervitals:
            id = uid(
                "Observation", '-'.join(
                    (o["id"], o["name"].lower().replace(' ',
                                                        '').replace('_', ''))),
                prefix)
            if "units" in o.keys():
                o["unitsCode"] = o["units"]
                o["categoryCode"] = "vital-signs"
                o["categoryDisplay"] = "Vital Signs"
            print >> pfile, template.render(dict(globals(), **locals()))

        if self.pid in Lab.results:
            for o in Lab.results[self.pid]:
                id = uid("Observation", "%s-lab" % o.id, prefix)
                o.categoryCode = "laboratory"
                o.categoryDisplay = "Laboratory"
                print >> pfile, template.render(dict(globals(), **locals()))

        medtemplate = template_env.get_template('medication.xml')
        dispensetemplate = template_env.get_template('medication_dispense.xml')
        if self.pid in Med.meds:
            for m in Med.meds[self.pid]:
                medid = id = uid("MedicationOrder", m.id, prefix)
                print >> pfile, medtemplate.render(dict(globals(), **locals()))

                for f in Refill.refill_list(m.pid, m.rxn):
                    id = uid("MedicationDispense", f.id, prefix)
                    print >> pfile, dispensetemplate.render(
                        dict(globals(), **locals()))

        template = template_env.get_template('condition.xml')
        if self.pid in Problem.problems:
            for c in Problem.problems[self.pid]:
                id = uid("Condition", c.id, prefix)
                print >> pfile, template.render(dict(globals(), **locals()))

        template = template_env.get_template('procedure.xml')
        if self.pid in Procedure.procedures:
            for w in Procedure.procedures[self.pid]:
                id = uid("Procedure", w.id, prefix)
                print >> pfile, template.render(dict(globals(), **locals()))

        template = template_env.get_template('immunization.xml')
        if self.pid in Immunization.immunizations:
            for i in Immunization.immunizations[self.pid]:
                id = uid("Immunization", i.id, prefix)
                i.cvx_system, i.cvx_id = i.cvx.rsplit("cvx", 1)
                i.cvx_system += "cvx"
                print >> pfile, template.render(dict(globals(), **locals()))

        template = template_env.get_template('family_history.xml')
        if self.pid in FamilyHistory.familyHistories:
            for fh in FamilyHistory.familyHistories[self.pid]:
                id = uid("FamilyMemberHistory", fh.id, prefix)
                print >> pfile, template.render(dict(globals(), **locals()))

        template = template_env.get_template('smoking_status.xml')
        if self.pid in SocialHistory.socialHistories:
            t = SocialHistory.socialHistories[self.pid]
            t.smokingStatusText = SMOKINGCODES[t.smokingStatusCode]
            id = uid("Observation", '-'.join((t.id, "smokingstatus")), prefix)
            print >> pfile, template.render(dict(globals(), **locals()))

        if p.gestage:
            template = template_env.get_template('observation.xml')
            o = {
                "date": p.dob,
                "code": "18185-9",
                "name": "Gestational age at birth",
                "scale": "Qn",
                "value": p.gestage,
                "units": "weeks",
                "unitsCode": "wk",
                "categoryCode": "exam",
                "categoryDisplay": "Exam"
            }
            id = uid("Observation", "%s-gestage" % self.pid, prefix)
            print >> pfile, template.render(dict(globals(), **locals()))

        if self.pid in Allergy.allergies:
            for al in Allergy.allergies[self.pid]:
                if al.statement == 'positive':
                    if al.type == 'drugClass':
                        al.typeDescription = 'medication'
                        al.system = "http://rxnav.nlm.nih.gov/REST/Ndfrt"
                    elif al.type == 'drug':
                        al.typeDescription = 'medication'
                        al.system = "http://www.nlm.nih.gov/research/umls/rxnorm"
                    elif al.type == 'food':
                        al.typeDescription = 'food'
                        al.system = "http://fda.gov/UNII/"
                    elif al.type == 'environmental':
                        al.typeDescription = 'environment'
                        al.system = "http://fda.gov/UNII/"
                    if al.reaction:
                        if al.severity.lower() == 'mild':
                            al.severity = 'mild'
                            al.criticality = 'CRITL'
                        elif al.severity.lower() == 'severe':
                            al.severity = 'severe'
                            al.criticality = 'CRITH'
                        elif al.severity.lower(
                        ) == 'life threatening' or al.severity.lower(
                        ) == 'fatal':
                            al.severity = 'severe'
                            al.criticality = 'CRITH'
                        elif al.severity.lower() == 'moderate':
                            al.severity = 'moderate'
                            al.criticality = 'CRITU'
                        else:
                            al.severity = None
                    id = uid("AllergyIntolerance", al.id, prefix)
                    template = template_env.get_template('allergy.xml')
                    print >> pfile, template.render(dict(
                        globals(), **locals()))
                elif al.statement == 'negative' and al.type == 'general':
                    if al.code == '160244002':
                        template = template_env.get_template(
                            'no_known_allergies.xml')
                        id = uid("List", al.id, prefix)
                        al.loinc_code = '52473-6'
                        al.loinc_display = 'Allergy'
                        al.text = 'No known allergies'
                        print >> pfile, template.render(
                            dict(globals(), **locals()))
                    elif al.code == '409137002':
                        template = template_env.get_template(
                            'no_known_allergies.xml')
                        id = uid("List", al.id, prefix)
                        al.loinc_code = '11382-9'
                        al.loinc_display = 'Medication allergy'
                        al.text = 'No known history of drug allergy'
                        print >> pfile, template.render(
                            dict(globals(), **locals()))
                    else:
                        template = template_env.get_template(
                            'general_observation.xml')
                        o = {
                            "date": al.start,
                            "system": "http://snomed.info/sct",
                            "code": al.code,
                            "name": al.allergen,
                            "categoryCode": "exam",
                            "categoryDisplay": "Exam"
                        }
                        id = uid("Observation", "%s-allergy" % al.id, prefix)
                        print >> pfile, template.render(
                            dict(globals(), **locals()))

        addedPractitioner = False

        if self.pid in ClinicalNote.clinicalNotes:
            id = 'Practitioner/SMART-1234'
            template = template_env.get_template('practitioner.xml')
            print >> pfile, template.render(dict(globals(), **locals()))
            addedPractitioner = True
            for d in ClinicalNote.clinicalNotes[self.pid]:
                if d.mime_type == 'text/plain':
                    data = fetch_document(self.pid, d.file_name)
                    d.content = data['base64_content']
                    b = d
                    id = uid("Binary", "%s-note" % d.id, prefix)
                    d.binary_id = id
                    template = template_env.get_template('binary.xml')
                    print >> pfile, template.render(dict(
                        globals(), **locals()))
                    id = uid("DocumentReference", "%s-note" % d.id, prefix)
                    d.system = "http://loinc.org"
                    d.code = '34109-9'
                    d.display = 'Note'
                    template = template_env.get_template('document.xml')
                    print >> pfile, template.render(dict(
                        globals(), **locals()))

        if self.pid in Document.documents:
            if not addedPractitioner:
                id = 'Practitioner/SMART-1234'
                template = template_env.get_template('practitioner.xml')
                print >> pfile, template.render(dict(globals(), **locals()))
            for d in [
                    doc for doc in Document.documents[self.pid]
                    if doc.type != 'photograph'
            ]:
                data = fetch_document(self.pid, d.file_name)
                d.content = data['base64_content']
                d.size = data['size']
                d.hash = data['hash']
                b = d
                id = uid("Binary", "%s-document" % d.id, prefix)
                d.binary_id = id
                template = template_env.get_template('binary.xml')
                print >> pfile, template.render(dict(globals(), **locals()))
                id = uid("DocumentReference", "%s-document" % d.id, prefix)
                d.system = 'http://smarthealthit.org/terms/codes/DocumentType#'
                d.code = d.type
                d.display = d.type
                template = template_env.get_template('document.xml')
                print >> pfile, template.render(dict(globals(), **locals()))

        if self.pid in ImagingStudy.imagingStudies:
            st = {}
            for img in ImagingStudy.imagingStudies[self.pid]:
                data = fetch_document(self.pid, img.image_file_name)
                img.mime_type = "application/dicom"
                img.content = data['base64_content']
                img.size = data['size']
                img.hash = data['hash']
                b = img
                id = uid("Binary", "%s-dicom" % img.id, prefix)
                img.binary_id = id
                template = template_env.get_template('binary.xml')
                print >> pfile, template.render(dict(globals(), **locals()))
                if img.study_oid not in st.keys():
                    st[img.study_oid] = {
                        'id': img.id,
                        'title': img.study_title,
                        'date': img.study_date,
                        'accession_number': img.study_accession_number,
                        'modality': img.study_modality,
                        'oid': img.study_oid,
                        'series_count': 0,
                        'images_count': 0,
                        'series': {}
                    }
                series = st[img.study_oid]['series']
                if img.series_oid not in series.keys():
                    st[img.study_oid]['series_count'] += 1
                    series[img.series_oid] = {
                        'number': st[img.study_oid]['series_count'],
                        'title': img.series_title,
                        'oid': img.series_oid,
                        'images_count': 0,
                        'images': []
                    }
                st[img.study_oid]['images_count'] += 1
                series[img.series_oid]['images_count'] += 1
                series[img.series_oid]['images'].append({
                    'title':
                    img.image_title,
                    'date':
                    img.image_date,
                    'file_name':
                    img.image_file_name,
                    'oid':
                    img.image_oid,
                    'binary_id':
                    img.binary_id,
                    'sop':
                    img.image_sop,
                    'number':
                    series[img.series_oid]['images_count']
                })

            for i in st:
                s = st[i]
                id = uid("ImagingStudy", s['id'], prefix)
                template = template_env.get_template('imagingstudy.xml')
                print >> pfile, template.render(dict(globals(), **locals()))

        print >> pfile, "\n</Bundle>"
        pfile.close()
Esempio n. 12
0

def displayPatientSummary(pid):
    """writes a patient summary to stdout"""
    if not pid in Patient.mpi: return
    print Patient.mpi[pid].asTabString()
    print "PROBLEMS: ",
    if not pid in Problem.problems: print "None",
    else:
        for prob in Problem.problems[pid]:
            print prob.name + "; ",
    print "\nMEDICATIONS: ",
    if not pid in Med.meds: print "None",
    else:
        for med in Med.meds[pid]:
            print med.name + "{%d}; " % len(Refill.refill_list(pid, med.rxn)),
    print "\nLABS: ",
    if not pid in Lab.results: print "None",
    else:
        print "%d results" % len(Lab.results[pid])
    print "\n"


if __name__ == '__main__':

    parser = argparse.ArgumentParser(
        description='SMART on FHIR Test Data Generator')
    group = parser.add_mutually_exclusive_group()
    group.add_argument('--summary',
                       metavar='pid',
                       nargs='?',