Wednesday, September 9, 2020

The Bug that Almost Got Away

I discovered a tricky issue in bed counting while finishing up the automated measure for bed counts.

The tricky bit is that you what you are counting is beds (locations), but what you can find out about based on the reporting period (via a FHIR Query) is encounters, and that's what I almost counted.

Here's where it gets ugly.  A patient can have multiple encounters in the same day.  And they can be in different beds (locations) during the same encounter.

It can be worked out so long as as few simplifying assumptions can be made.

  1. Locations referenced by an Encounter are ordered from most to least recent.
  2. Patients can only be in one location at a time.
  3. Each location can handle only one patient.
  4. Encounters are ordered from most to least recent.
  5. If an encounter is active, then the most recent location is occupied by the patient.
Let L be a set of locations and encounters
For each active encounter E during the reporting period:
    if E.location.location is not in L
        Add E to L
        Add E.location.location to L
    end if
End For

At the end of the loop, L will contain:
  1. All occupied locations.
  2. The most recent encounter to cause that location to be occupied.
Here's almost the same thing in FHIRPath.

aggregate(
  iif($total.select(location[0]).location contains $this.location.location.first(),
      {},$total | $this)

Three lines of precious brevity. 

There were so many places I could have gone wrong, and I won't actually know it works until maybe Thursday.  But at least now I'll be counting occupied beds at the end of the period, rather than all beds that were occupations of beds during the period.


1 comment: