Memoization

I have been meaning to write short posts about interesting programming concepts and alternative programming movements (like alt.net). Topic of this post is an interesting programming concept called Memoization and its implementation in C# as a method attribute.

Memoization is an optimization technique which speeds up a program by remembering the values returned by function calls for specific input values, its also known as tabling.

Many of the new languages (Ruby, Python, C#) provide a very neat way to implement Memoization and many functional languages (Lisp, OCaml) have it as a first class construct for the runtime. Here is a my cheap implementation showing how one can use an integer based Memo attribute in C#

class Test
{   [Memo]
    public int DoSomething(int i)
    {
        for (int k = 0; k < 10000; k++)
        {
            int j = 0;
            j = j + 500;
        }
        Console.WriteLine("DoSomething " + i);
        return i + 5;
    }
}

Here is a simple driver which implements the Memoization :

static void Main(string[] args)
 {
     Debug.WriteLine("Invoking Memoizable Code");

     Type t = typeof(Test);
     Test objT = new Test();

     // Implement Memoization
     Dictionary<int, int> memoize = new Dictionary<int, int>();
     MethodInfo[] mi = t.GetMethods();
     foreach (MethodInfo m in mi)
     {
         foreach (Attribute a in m.GetCustomAttributes(false))
         {
             if (a is MemoAttribute)
             {
                 for (int i = 0; i < 2; i++)
                 {
                     int j;
                     if (memoize.TryGetValue(i, out j))
                     {
                         Debug.WriteLine("Remembered " + i);
                         continue;
                     }
                     else
                     {
                         j = (int) m.Invoke(objT, new object[]{i});
                         memoize[i] = j;
                         Debug.WriteLine("Memorized " + i);
                     }
                 }
             }
         }
     }
     Console.ReadLine();
 }

May be in comments you can suggest ways to implement a more generic Memo attribute (similar to Python’s @memo).

Understanding CCR

Update: Fixed typos, added links to related tools and articles, updated the example.

CCR or Continuity of Care Record is a standard meant to ease the exchange of clinical information with a relatively easy to read and practical data-format and schema. There is ton of great information about CCR on its resource site. CCR document format is supported by majority of personal Health clouds, both – Microsoft HealthVault & Google Health.

The CCR specification comprises an implementation guide, XML schema definition and a guidance spreadsheet for each data element that makes up the standard. These resources can be bought from ASTM.

The document format of CCR is very straight forward, consisting of a header, body and a footer with the following top-level elements:

Header Body Body Footer
  • CCR Document ID
  • Language
  • Version
  • Creation Date
  • Patient
  • From
  • To
  • Purpose
  • Payers
  • Advance Directives
  • Support
  • Functional Status
  • Problems
  • Family History
  • Social History
  • Alerts
  • Medications
  • Medical Equipment
  • Immunizations
  • Vital Signs
  • Results
  • Procedures
  • Encounters
  • Plan Of Care
  • HealthCareProviders
  • Actors
  • Signatures
  • References
  • Comments
  •  

    Google Health supports only a limited set of entities from the above, while HealthVault supports the entire standard and also allows transformation of some of these entities in to native HealthVault types. You can read more about working with CCR in HealthVault and various input mappings, output mappings, and CCR vocabularies.

    Here are some illustrative CCR figures from Dr. Waldren’s presentation (see end of article).

    image image

    Using the SNOMED-CT concepts one can write the Systolic Blood pressure reading in CCR as the following (UPDATE: Well-formatted the CCR to include source, object-id and actors, thanks to Matt Wagner):

    <?xml version="1.0" encoding="utf-8"?>
    <ContinuityOfCareRecord xmlns='urn:astm-org:CCR'>
      <CCRDocumentObjectID>Doc</CCRDocumentObjectID>
      <Language>
        <Text>English</Text>
      </Language>
      <Version>V1.0</Version>
      <DateTime>
        <ExactDateTime>2008</ExactDateTime>
      </DateTime>
      <Patient>
        <ActorID>Patient</ActorID>
      </Patient>
      <Body>
        <VitalSigns>
          <Result>
            <CCRDataObjectID>0001</CCRDataObjectID>
            <Description>
              <Text>Blood Pressure</Text>
            </Description>
            <Source>
              <Description>
                <Text>Unknown</Text>
              </Description>
            </Source>
            <Test>
              <CCRDataObjectID>0002</CCRDataObjectID>
              <Description>
                <Text>Systolic</Text>
                <Code>
                  <Value>163030003</Value>
                  <CodingSystem>SNOMEDCT</CodingSystem>
                </Code>
              </Description>
              <Source>
                <Description>
                  <Text>Unknown</Text>
                </Description>
              </Source>
              <TestResult>
                <Value>120</Value>
                <Units>
                  <Unit>mmHg</Unit>
                </Units>
              </TestResult>
            </Test>
            <Test>
              <CCRDataObjectID>0003</CCRDataObjectID>
              <Description>
                <Text>Diastolic</Text>
                <Code>
                  <Value>163031004</Value>
                  <CodingSystem>SNOMEDCT</CodingSystem>
                </Code>
              </Description>
              <Source>
                <Description>
                  <Text>Unknown</Text>
                </Description>
              </Source>
              <TestResult>
                <Value>75</Value>
                <Units>
                  <Unit>mmHg</Unit>
                </Units>
              </TestResult>
            </Test>
          </Result>
        </VitalSigns>
      </Body>
      <Actors>
        <Actor>
          <ActorObjectID>Patient</ActorObjectID>
          <Person>
            <Name>
              <CurrentName>
                <Given>John</Given>
                <Family>Doe</Family>
              </CurrentName>
            </Name>
          </Person>
          <Source>
            <Description>
              <Text>Unknown</Text>
            </Description>
          </Source>
        </Actor>
      </Actors>
    </ContinuityOfCareRecord>
    

    Note CodingSystem element. It allows CCR to interpret various medical vocabularies.

    Relevant Tools:

    (Thanks to Kathleen Connor)

    • The CCR Validator, is an important resource to test/validate a CCR instance, is a now available  Not only does it validate the CCR against the XSD but also the constraints of the implementation guide.
    • An Open Source StyleSheet to view CCR files.
    • CCR to CCD & HL7 Mappers – tools which Map CCR to CCD and HL7 V2 & V3. You can access them directly here.
    • Application to embed CCR in PDF-HealthCare.

    Related Article(s):

    • To get familiar with CCR I would highly recommended this 13 minute video by Dr. Steve Waldren.
    • Adam Bosworth posted an interesting read on standards, his take (simple, human readable, focus on known structured data, etc.) favors CCR.

    In this series:

    1. Understanding Vocabularies. Wait! What did you say?
    2. Understanding Vocabularies #2 – HealthVault Recommendations
    3. Understanding SNOMED CT
    4. Understanding CCR
    Special thanks to Kathy Osborne for proof reading this post.

    Running HealthVault Apps On Windows Azure

    HealthVault SDK 1.0 introduces an interesting capability by which an HealthVault application can read their application certificate from a file. Eric has some details about this on his blog.

    I’m going to describe how this capability of reading an application’s certificates from the file store could be used to run HealthVault application on Windows Azure. Here are the steps to get a simple HealthVault application (which I call HelloHV) running on Windows Azure:

    1. Install the Azure SDK and HealthVault SDK. Create your HealthVault application as a Web Role.
    2. Configure and create an HealthVault application using the application manager utility in HealthVault SDK. Make sure you set the Action-Url to http://<yourapp>.cloudapp.net/Redirect.aspx  using the Application Configuration Center.
    3. Copy the Redirect.aspx & Redirect.cs from HealthVault samples (HelloWorld in HealthVault SDK) in to your application and add reference to HealthVault assemblies (you can find them in C:\Program Files\Microsoft HealthVault\SDK\DotNet\Assemblies)
    4. Add the HealthVault related config settings to your WebRole’s Web.Config, the easiest way to do this would be copy the relevant key(s) from a sample in HealthVault SDK. Here is an illustration :
      <appSettings>
        <add key="ApplicationId" value="01e21bd1-cb13-40d6-8f01-596286827d6d"/>
        <add key="ShellUrl" value="https://account.healthvault-ppe.com/"/>
        <add key="HealthServiceUrl" value="https://platform.healthvault-ppe.com/platform/"/>
        <!-- when we call the SignOut() method on HealthServicePage,
             it redirects us to the page below -->
        <!--<add key="NonProductionActionUrlRedirectOverride" value="Redirect.aspx" />-->
        <!-- The redirect page (specified above) uses these keys below to redirect to different
             pages based on the response from the shell -->
        <add key="WCPage_ActionHome" value="default.aspx"/>
        <add key="WCPage_ActionAppAuthSuccess" value="HelloHV.aspx"/>
        <add key="ApplicationCertificateFileName"
             value="~\cert\WildcatApp-01e21bd1-cb13-40d6-8f01-596286827d6d.pfx"/>
      </appSettings>

    5. While testing on your local machine uncomment the following line in the Web.Config, this will allow HealthVault to communicate with your local machine. However make sure that this is commented when you publish the application.  Alternatively the following key can also be stored in UserApplicationConfigs.xml, if you maintain one for your development.
      <!--<add key="NonProductionActionUrlRedirectOverride" value="Redirect.aspx" />—->

      Gotacha1: Windows Azure changes the port numbers for your application so its hard to make it work without using the action-url configured for your application in Application Configuration Center.

    6. In your Default HealthVault Page Make sure you read the certificate for your application from a local file (you can also use Azure Storage).

      Gotacha2: HealthVault SDK expects the ApplicationCertificateFileName to be absolute filename, this is impossible to determine for a cloud system like Azure. However we can get the absolute path by changing the value of the key at run-time.

      
      public partial class HelloHV : HealthServicePage
      {
          protected void Page_PreInit(object sender, EventArgs e)
          {
              ConfigurationSettings.AppSettings["ApplicationCertificateFileName"] =
                  MapPath(@"~\cert\WildcatApp-01e21bd1-cb13-40d6-8f01-596286827d6d.pfx");
          }
      
          protected void Page_Load(object sender, EventArgs e)
          {
      
      ..
      
    7. Hit Run and see your Hello HealthVault  application in action!!

    Now the show time:

    Check out a simple (HelloHV application) running on Windows Azure here.

    image

    The associated code for this application is shared here.

    Remember to switch to SSL and secure your application certificate (using password or Azure Storage) before you consider taking an application running on Windows Azure live as a production HealthVault application.

    Understanding SNOMED CT

    I have previously posted about Understanding Health Ontologies and Standards. In this post I’ll focus on SNOMED-CT (Systematized Nomenclature of Medicine Clinical Terms). SNOMED-CT is the most comprehensive vocabulary to express clinical terms – it spans languages, specialties and geographic borders.

    SNOMED-CT includes:

    • Terms or synonyms relating to a clinical concept
    • Links between different concepts

    To give you a taste here is an example of Blood pressure reading represented using SNOMED-CT from the linked paper (“Towards semantic interoperability in healthcare: ontology mapping from SNOMED-CT to HL7 version 3”, Amanda Ryan):

    Ontology_Mapping

    In addition to having a model to represent concepts and linkages the biggest draw of SNOMED CT is a staggering number of coded qualifiers (which belong to one concept or other). According to IHTSO there are about 311,000 actively used SNOMED CT concepts.

    You can register for SNOMED CT here. Its free for companies and individuals in United States, however your registration is processed by NLM and it might take over 3 days to receive a confirmation and access.

    Once you are through with registration and have an account, start by downloading the core subset of SNOMED CT concepts here, this list consists of about 5000 most frequently used terms by institutions across US. Its a good set to get familiar with, it consists of the following concept area:

    • Clinical finding        : 4,550 codes in total
    • Procedure            :   414 codes in total
    • Situation with explicit context    :   132 codes in total
    • Event                :    38 codes in total
    • Body structure            :    46 codes in total
    • Social context            :     2 codes in total

    Snomed_Subset

    We can use BCP to copy the files from SNOMED CT Core in to our local database, and do more interesting queries & data analysis like find distribution on these terms, co-relate problems vs. findings and of course work on the larger SNOMED CT database to find synonyms etc.; but I’ll keep that for another day. Here very quickly I’ll show how one can use a web-based browser, Snowflake, http://snomed.dataline.co.uk/ (requires registration) to lookup a SNOMED code and see what else it relates to. We can see that in line 3 above SNOMED CT concept 10085004 is marked as Metatarsalgia (finding), however using the Snowflake browser we can see in that in addition to being a finding this concept is a problem as well.

    Snomed_Snowflake

    This was just tip of the ice-berg, please leave comments for future posts / areas to consider in the Ontology domain.

    Further reading / relevant links:

    In this series:

    1. Understanding Vocabularies. Wait! What did you say?
    2. Understanding Vocabularies #2 – HealthVault Recommendations
    3. Understanding SNOMED CT

    Health 2.0

    I overviewed the Health 2.0 2009 conference largely through twitter. Here are my key takeaways:

    • HealthCare needs to become more consumer: All innovation will be driven through this domain, PatientsLikeMe & CureTogether are prime examples.
    • Keas launched as a platform for Care plans – I took it for a spin love the way you can create action items! Not as intuitive as Mint but not really a good analogy either.
    • Health 2.0 Accelerator – A lot of media towards this effort of trying a create a platform (yet again) to add for value for the end consumer using the better together model. Here is a Demo Video.
    • Public Health Media: Microsoft’s H1N1 Center, Google Flu Trends
    • Mobile: WebMD iPhone App
    • Physician’s Office: NPDigest.com – open source groupware for a clinic.

    Please add your thought about the conference through the comments.