Use of reactive documents to illustrate basic epidemiological calculations and Bayes theorem

These are some interactive, reactive documents I wrote to help students understand some basic epidemiological/statistical calculations.

(Source on github)

These documents make use of the excellent tangle and D3 libraries.

Posted in medicine | Comments Off

Query for medications containing acetaminophen

Hepatotoxicity due to excessive acetaminophen exposure and idiosyncratic drug reactions are now the most common causes of acute liver failure in the United States, surpassing liver failure from viral hepatitis [1-2]. A lack of awareness for how frequently acetaminophen is found in medications may contribute to overexposure.

(Code on Github)


# Use National Library of Medicine's RXNorm API to
# find medications containing a given ingredient

import requests, json, urllib

def name_resolve_json (name):
    # Give a possibly ambiguous name, returns a list of possible matches ranked
    # by a likelihood score
    s = 'http://rxnav.nlm.nih.gov/REST/approximateTerm?term=xx&maxEntries=3'.replace('xx', urllib.quote(name))
    r = requests.get(s, headers={'Accept': 'application/json', 'charset': 'UTF-8'})
    return r.json()

def first_ranked_cui (approximates):
    # Just return the identifier for the best match by score
    return extract_from_json(approximates, "candidate", l=[])[0][0]['rxcui']

def contains (cui_l):
    # Give a list of ingredient identifiers, return drugs which contain
    # those ingredients
    sl = '+'.join(cui_l)
    s = 'http://rxnav.nlm.nih.gov/REST/brands?ingredientids=xx'.replace('xx', sl)
    r = requests.get(s, headers={'Accept': 'application/json', 'application/json' 'charset': 'UTF-8'})
    return r.json()

def extract_from_json (data, key, l=[]):
    # Extract a list of value(s) from a key in
    # a (potentially deeply) nested json object
    if isinstance(data, list):
        for item in data:
            extract_from_json(item, key, l)
    elif isinstance(data, dict):
        for k, v in data.iteritems():
            if (k == key):
                l.append(v)
            extract_from_json(v, key, l)
    return l

cv = contains([first_ranked_cui(name_resolve_json('acetaminophen'))])
cl = extract_from_json(cv, "name", l=[])
print "{0} medications contain acetaminophen:".format(len(cl))
print "\n".join(cl)

    406 medications contain acetaminophen:

          666 Cold Preparation
          Acephen
          Acetadrink
          Acetadryl
          Actamin
          Actifed Cold & Sinus
          Actifed Plus
          Acuflex
          Adprin B
          Alagesic
          Ali Flex
          Alka-Seltzer Cold and Sinus
          Alka-Seltzer Plus Cold
          Alka-Seltzer Plus Cold Liquigel
          Alka-Seltzer Plus Cold and Sinus
          Alka-Seltzer Plus Cough and Cold Liquigel
          Alka-Seltzer Plus Cough and Cold Liquigel Reformulated Aug 2011
          Alka-Seltzer Plus Day Severe Cold, Cough And Flu
          Alka-Seltzer Plus Flu Liquigels
          Alka-Seltzer Plus Flu Reformulated Jan 2011
          Alka-Seltzer Plus Night Cold and Flu
          Alka-Seltzer Plus Night Severe Cold, Cough and Flu
          Alka-Seltzer Plus Night Time Cold Liquigel
          Alka-Seltzer Plus Night Time Reformulated Dec 2006
          Alka-Seltzer Plus Severe Allergy
          Alka-Seltzer Plus Severe Sinus Congestion and Cough
          Allerest Headache Strength
          Allerest No Drowsiness
          Allerest Sinus
          Alpain
          Anabar
          Anacin AF
          Anacin Advanced Headache Formula
          Anacin PM Aspirin Free
          Anexsia
          Anolor
          Apra
          Arthriten Inflammatory Pain
          BF-Paradac
          BP Poly-650
          Backaid
          Backaid IPF
          Backprin
          Bactimicina
          Baczol Cold Medicine
          Balacet
          Bayer Migraine
          Bayer Select Decongestant
          Benadryl Allergy Cold
          Benadryl Allergy Cold Reformulated Jun 2007
          Benadryl Severe Allergy Sinus Headache Reformulated Jun 2007
          Bromo Seltzer
          Bupap
          By Ache
          Cafgesic
          Capacet
          Capital and Codeine
          Cephadyn
          Cetafen
          Children's Mucinex Multi-Symptom Cold and Fever
          Childrens Tylenol Cold Plus Cough
          Childrens Tylenol Plus Cold & Allergy
          Co-Gesic
          Cocet
          Codrix
          Comtrex Allergy Sinus
          Comtrex Cold and Cough Nighttime
          Comtrex Cold and Cough Non Drowsy
          Comtrex Cold and Flu Maximum Strength Liquid
          Comtrex Cold and Flu Maximum Strength Reformulated Aug 2006
          Comtrex Deep Chest Cold Non Drowsy
          Comtrex Nighttime Acute Head Cold
          Comtrex Non-Drowsy
          Comtrex Sore Throat Relief
          Contac Cold and Flu Cooling Night
          Contac Cold and Flu Maximum Strength
          Contac Cold and Flu Non Drowsy Maximum Strength
          Contac Severe Cold and Flu Non Drowsy
          Contragesic
          Coricidin
          Coricidin D Cold
          Coricidin HBP Flu Maximum Strength
          Coricidin HBP Nighttime Multi-Symptom Cold Reformulated Feb 2013
          Coricidin Night Time Cold Relief
          Cotabflu
          CounterAct Pain
          Counteract Day
          Counteract Night
          Counteract PM
          Darvocet
          DayQuil Sinex
          Dayquil
          Dayquil Cold & Flu
          Dayquil Liquicaps Reformulated Apr 2009
          Dayquil Sinus
          Delsym Adult Night Time Multi-Symptom
          Delsym Children's Nighttime Cough and Cold Reformulated Apr 2013
          Delsym Cough Plus Cold Daytime
          Delsym Cough Plus Cold Night Time
          Delsym Night Time Cough and Cold
          Diabetic Tussin Night Time Formula
          Dilotab
          Dimetapp Nighttime Flu
          Dimetapp Nighttime Flu Reformulated Sep 2007
          Dolacet
          Dolgic LQ
          Dolgic Plus
          Dologen
          Dologesic
          Dolorex Forte
          Dristan Cold
          Dristan Cold Multi Symptom
          Drixoral Sinus
          Durabac
          Durabac Forte
          Duraflu
          Duraxin
          EZ III
          Ed Flex
          Elixsure Fever/Pain
          Emagrin Forte
          Endocet
          Ephed Plus Cold Flu and Sinus
          Epidrin
          Esgic
          Exaprin
          Excedrin
          Excedrin Aspirin Free
          Excedrin Back & Body
          Excedrin PM
          Excedrin Quick Tab
          Excedrin Sinus
          Excedrin Sinus Headache
          Excedrin Tension Headache
          Feverall
          Fioricet
          Fioricet with Codeine
          Flextra
          Flextra Plus
          Frenadol
          Genapap
          Geone
          Goody's Body Pain
          Goody's Extra Strength
          Goody's Headache Relief Shot
          Goody's Migraine Relief
          Goody's PM
          Histenol
          Hy-Phen
          Hycet
          Infantaire
          Kolephrin
          Kolephrin DM
          Lagesic
          Legatrin PM
          Levacet
          Liquicet
          Little Colds
          Little Fevers
          Lorcet
          Lortab
          Lusonex Plus
          Lynox
          Magnacet
          Mapap
          Mapap Cold Formula
          Mapap PM
          Mapap Sinus Congestion and Pain
          Margesic
          Margesic-H
          Marten-Tab
          Maxidone
          Maxiflu CD
          Maxiflu DM
          Medigesic
          Mejoralito
          Midol Maximum Strength Menstrual
          Midol PM
          Midol PM Reformulated Apr 2011
          Midol PMS Maximum Strength
          Midol Teen
          Midrin
          Mucinex Children's Night Time Multi-Symptom Cold
          Mucinex Fast-Max Cold and Sinus
          Mucinex Fast-Max Cold, Flu and Sore Throat
          Mucinex Fast-Max Night Time Cold and Flu
          Mucinex Fast-Max Severe Cold
          Mucinex Sinus-Max Day
          Mucinex Sinus-Max Night
          Mygrex
          Nature Fusion Cold & Flu
          Nonbac
          Norco
          Norel AD
          Norel SR
          Nortemp
          Novagesic
          NyQuil D
          NyQuil Sinex
          Nyquil Alcohol Free
          Nyquil Cold & Flu
          Nyquil Multi-Symptom
          Ofirmev
          Onetab Cold and Flu
          Onset Forte
          Orbivan
          Orbivan CF
          Ornex
          Painaid
          Painaid BRF
          Painaid ESF
          Pamprin Cramp Formula
          Pamprin Max Formula
          Pamprin Multi-Symptom
          Panadol
          Panadol Cold & Flu Non Drowsy
          Panadol PM
          Pancold S
          Panlor DC Reformulated Jan 2008
          Panlor SS
          PediaCare Children's Plus Cough and Sore Throat
          Pediacare Children's Fever Reducer Pain Reliever
          Pediacare Children's Plus Cough and Runny Nose
          Pediacare Infant Fever Reducer
          Percocet
          Percogesic Reformulated Jan 2011
          Pharbetol
          Phenflu CD
          Phenflu DM
          Phrenilin
          Phrenilin with Caffeine and Codeine
          Poly-Vent Plus
          Premsyn PMS
          Primalev
          Prodrin
          Promacet
          Protid
          Pyrroxate Cold & Congestion
          Redutemp
          Relagesic
          Repan
          Respa C&C
          Rhinoflex
          Rhinogesic
          Rid-A-Pain
          Ringl
          Robitussin Cold Cough and Flu
          Robitussin Honey Flu Nighttime
          Robitussin Honey Flu Non-Drowsy
          Robitussin Night Cold
          Robitussin Night Relief
          Robitussin Peak Cold Daytime Cold Plus Flu
          Robitussin Peak Cold Nasal
          Robitussin Peak Cold Nighttime Cold Plus Flu
          Robitussin Peak Cold Nighttime Multi-Symptom Cold
          Robitussin Peak Cold Nighttime Nasal Relief
          Roxicet
          Rx-Act Cold Head Congestion
          Rx-Act Flu & Severe Cold & Cough
          Rx-Act Flu & Sore Throat
          Rx-Act Headache Formula
          Rx-Act Nighttime
          Rx-Act Pain Relief
          Rx-Act Pain Relief PM
          Rx-Act Sinus Congestion & Pain
          Saleto
          SanaTos Night
          Sanatos Day
          Scot-Tussin Multisymptom Cold and Allergy
          Sedalmex
          Sedapap
          Silapap
          Sinarest
          Sinarest Sinus
          Sine-Off Cold and Cough
          Sine-Off Maximum Strength
          Sine-Off Maximum Strength Reformulated Sep 2008
          Sine-Off Sinus and Cold
          Singlet
          Sinutab Ex-Strength
          Sinutab Sinus
          St. Joseph Aspirin-Free
          Stagesic
          Stona
          Sudafed PE Cold & Cough
          Sudafed PE Nighttime Cold
          Sudafed PE Pressure Plus Pain Plus Cough
          Sudafed PE Pressure Plus Pain Plus Mucus
          Sudafed PE Severe Cold
          Sudafed PE Sinus Headache
          Sudafed PE Triple Action
          Sudafed Triple Action
          Supac
          Syncol
          T-Painol
          T-Painol Extra Strength
          Tactinal
          Talacen
          Tavist Allergy/Sinus/Headache
          Tavist Sinus
          Tempra
          Tempra 2
          Tempra Quicklets
          Tencon
          Theraflu Cold & Sore Throat
          Theraflu Cold & Sore Throat Reformulated Sep 2008
          Theraflu Daytime Severe Cold
          Theraflu Daytime Severe Cold & Cough
          Theraflu Flu & Chest Congestion
          Theraflu Flu & Sore Throat
          Theraflu Flu & Sore Throat Reformulated Sep 2008
          Theraflu Flu and Cold Medicine Powder
          Theraflu Max-D
          Theraflu Nighttime Maximum Strength
          Theraflu Nighttime Severe Cold
          Theraflu Nighttime Severe Cold & Cough
          Theraflu Nighttime Severe Cold Capsule
          Theraflu Severe Cold & Congestion Non-Drowsy
          Theraflu Severe Cold Nighttime
          Theraflu Sore Throat Maximum Strength
          Theraflu Warming Cold & Chest Congestion
          Theraflu Warming Relief
          Theraflu, Flu, Cold, and Cough
          Trezix
          Trezix Reformulated Oct 2011
          Triaminic Cold and Fever
          Triaminic Cough & Sore Throat
          Triaminic Cough & Sore Throat Reformulated Jul 2007
          Triaminic Fever & Pain
          Triaminic Infant Drops Reformulated Nov 2010
          Triaminic Multi-Symptom Fever
          Triaminic Softchews Allergy Sinus
          Triaminic Softchews Cough & Sore Throat
          Triaminic Softchews Cough & Sore Throat Reformulated Jul 2007
          Triaminic Sore Throat Formula
          Triaminicin
          Tycolene
          Tylenol
          Tylenol Allergy Multi-Symptom
          Tylenol Allergy Multi-Symptom Nighttime
          Tylenol Allergy Sinus
          Tylenol Chest Congestion
          Tylenol Children's Multi-Symptom Cold Plus
          Tylenol Children's Plus Cold
          Tylenol Children's Plus Cold & Cough
          Tylenol Children's Plus Cold Reformulated Mar 2013
          Tylenol Childrens Plus Cough & Runny Nose
          Tylenol Childrens Plus Cough & Sore Throat
          Tylenol Cold
          Tylenol Cold & Flu Severe Day Time
          Tylenol Cold Complete Formula
          Tylenol Cold Head Congestion Severe
          Tylenol Cold Multi-Symptom Daytime
          Tylenol Cold Multi-Symptom Nighttime
          Tylenol Cold Multi-Symptom Nighttime Liquid
          Tylenol Cold Multi-Symptom Severe Daytime
          Tylenol Cold Relief Nighttime
          Tylenol Cold Severe Congestion Non-Drowsy
          Tylenol Cough & Sore Throat Night Time
          Tylenol Cough and Sore Throat Daytime
          Tylenol Flu Maximum Strength Nighttime
          Tylenol PM
          Tylenol Severe Allergy
          Tylenol Sinus
          Tylenol Sinus Congestion and Pain Daytime
          Tylenol Sinus Congestion and Pain Severe
          Tylenol Sinus NightTime
          Tylenol Sinus Severe Congestion
          Tylenol with Codeine
          Tylox
          Ultracet
          Un-Aspirin
          Uniserts
          Unisom with Pain Relief
          Valorin Extra
          Vanquish
          Vicks 44 Cold, Flu and Cough
          Vicks Formula 44 Custom Care Cough & Cold PM
          Vicks Formula 44M
          Vicks Nature Fusion Cold and Flu Night
          Vicodin
          Vistra
          Vitapap
          Vopac
          Wal-Dryl Severe Allergy & Sinus
          Wal-Flu Cold and Sore Throat
          Wal-Flu Daytime Severe Cold and Cough
          Wal-Flu Flu and Sore Throat
          Wal-Flu Severe Cold
          Wal-Flu Severe Cold and Cough
          Wal-Phed Cold & Cough
          Wal-Phed PE Severe Cold
          Womens Tylenol Menstrual Relief
          XL-DOL
          Xodol
          Xolox
          Yinchiao Fast Relief Flu
          Zamicet
          Zebutal
          Zflex
          Zgesic
          Zicam Flu Nighttime
          Zicam Multi-Symptom Cold and Flu Daytime
          Zicam Multi-Symptom Cold and Flu Nighttime
          Zolvit
          Zydone

[1] Sood GK et al. Acute Liver Failure Medscape eMedicine Reference, August 20, 2012.
[2] George Ostapowicz, Robert J. Fontana, Frank V. Schiødt, Anne Larson, Timothy J. Davern, Steven H.B. Han, Timothy M. McCashland, A. Obaid Shakil, J. Eileen Hay, Linda Hynan, Jeffrey S. Crippin, Andres T. Blei, Grace Samuel, Joan Reisch, William M. Lee, the U.S. Acute Liver Failure Study Group; Results of a Prospective Study of Acute Liver Failure at 17 Tertiary Care Centers in the United States. Annals of Internal Medicine. 2002 Dec;137(12):947-954.

Posted in medicine | Comments Off

Allen’s temporal calculus

I ported Allen’s temporal calculus to Racket (Scheme) – details here.

Posted in Uncategorized | Comments Off

Real time tracking of symptoms for research and clinical support


A need that comes up in both research and clinical practice is a way to track in as close to real-time as possible various self-reported measures. In the literature, this capability is usually referred to as ecological momentary assessment. For example, in drug/alcohol dependence treatment research, it’s useful to track measures such as craving levels. Correlations with other measures (e.g. stress level) or presence of specific triggers (e.g., proximity to a geographic location) can be made. Clinicians might be interested in tracking real-time measures of mood or side effects after starting or changing a medication.

Here’s a prototype for tracking ecological momentary assessment with smartphones using the Android platform. It allows you to rate yourself on a particular measure (0 – 100) scale and include comments. This information is stored in a remote database, allowing retrieval of that data either from the phone or from a web based interface. You can also trigger assessments remotely via the web – the patient’s phone will receive a notification indicating it’s time for another assessment.

If you have at least a device (or emulator) running Android 2.2 or later, browse back to this webpage using your device browser and click here to install the Track application (md5 hash: 4846fa76222671469bf4b01aa4e7a87f) on your device.

The assessment notification system is based on Google’s Cloud to Device Messaging (C2DM) service. If you want to trigger assessment notifications on your phone, you need a Google account associated with your phone (most likely you’ve already done this, but if not, set from the Settings->Accounts & Sync menu) and Google Market installed on your phone.

Try it:

  1. Start Track on your phone, then press ‘Menu’, press ‘Preferences, and enter some simple username and password (DO NOT use your Google Account/Gmail username and password – that info is not needed at all by the app….you just need a linked working Google account on your phone so that C2DM will work).
  2. Use the slider to assess your current need for speed, enter a comment if you want, and press ‘Store’. That measure ultimately ends up on a non-device (remote) database.
  3. Press ‘Menu’->’History’ to see a history of your particular assessments in a crude format.
  4. Next take a look at the web interface to the assessment database (and remote assessment trigger). It’s probably easiest to next use a regular computer web browser. Surf to the web interface and login there using the same username and password you used in Track on your phone. You should get the same assessment history view on the web, along with a history of external assessment triggers.

 
You can also generate assessment triggers to your own phone…either the default “need for speed” assessment, or you can generate something else you want to measure.

I’m currently implementing selectable input methods, graphical reports, and a little crontab function to allow scheduled assessments.

Additional references:

Stone, AA. Shiffman, S. Ecological momentary assessment (EMA) in behavorial medicine. Annals of Behavioral Medicine, Vol 16(3), 1994, 199-202.
Moskowitz, DS. Young SN. Ecological momentary assessment: what it is and why it is a method of the future in clinical psychopharmacology. J Psychiatry Neurosci. 2006 January; 31(1): 13–20.
Collins RL, Kashdan TB, Gollnisch G. The feasibility of using cellular phones to collect ecological momentary assessment data: application to alcohol consumption. Exp Clin Psychopharmacol. 2003;11(1):73–78.
Freedman MJ, Lester KM, McNamara C, Milby JB, Schumacher JE. Cell phones for ecological momentary assessment with cocaine-addicted homeless patients in treatment. J Subst Abuse Treat. 2006;30(2):105–111.

Posted in android, medicine | Comments Off

Real-time tweets containing the word ‘overdose’

Here is a reasonably real-time feed of Twitter comments (“tweets) containing the word ‘overdose’, with a query performed about every 5 seconds.

Usernames have been stripped off (some usernames contain the word ‘overdose’ so it’s possible you won’t see the word ‘overdose’ in a given tweet). To experiment you can filter for a couple of other terms: cocaine, meth, kratom, purple drank.

The vast majority of these tweets are of course innocuous. However, a couple of interesting questions arise from data like this.

Could tweets reflect or warn of an epidemic of overdoses in a community or region? The widespread prescription, use, and diversion of opioids has contributed to an enormous problem, as noted in the popular press:

Drug deaths now outnumber U.S. traffic fatalities (September, 2011).
Drugs exceeded motor vehicle accidents as a cause of death in 2009, killing at least 37,485 people nationwide, according to preliminary data from the U.S. Centers for Disease Control and Prevention.

While most major causes of preventable death are declining, drugs are an exception. The death toll has doubled in the last decade, now claiming a life every 14 minutes. By contrast, traffic accidents have been dropping for decades because of huge investments in auto safety.

Public health experts have used the comparison to draw attention to the nation’s growing prescription drug problem, which they characterize as an epidemic. This is the first time that drugs have accounted for more fatalities than traffic accidents since the government started tracking drug-induced deaths in 1979.

Many of these deaths may be localized to certain areas. The U.S. Drug Enforcement Administration, for example, considers Los Angeles to be one of three “pill mills” where there may have been even easier availability of potentially dangerous prescription medications. Would data mined from the social web reflect that geographic availability?

Some Twitter feeds are geo-tagged (I have not displayed any geo-tagging in the demonstration feed).

It’s not unheard of for a badly synthesized chemical to find it’s way into a particular region, sometimes with disastrous effects. In other instances, increased exposure to non-prescription substances are problematic.

Related questions:

  • What might other widely available data sources reveal (e.g. Google Trends (search data) and Ngrams (historical use of phrases in writing)?
  • Could sentiment analysis of social data discover trends in experiences with various substances?
Posted in medicine | Comments Off

Visualizing methamphetamine use in San Francisco Bay Area

I wrote some tools in Javascript and Python to track and visualize a few aspects of close-to-real-time methamphetamine use in the San Francisco Bay Area. You can see all the tools here.

Disclaimer: the intent here is just to demonstrate the technology and showcase some of the data available. It isn’t a commentary on any perceived “methamphetamine problem” in SF. Alcohol and cigarettes, for example, cause much more damage (and represent more costs to municipalities) than meth or the other currently illegal drugs.

Posted in medicine | Comments Off

Simple clinical reasoning using Kanren

Here’s an example of construction of a tiny ontology and use of a particularly robust logic programming system — Dan Friedman and Oleg Kiselyov’s Kanren and a functional language like Scheme:


;; Assert a few simple facts
(define causes
  (extend-relation (a1 a2)
                   (fact () 'schizophrenia 'paranoia)
                   (fact () 'depression 'paranoia)
                   (fact () 'depression 'anhedonia)
                   (fact () 'depression 'insomnia)))

;; We can also add facts to our little ontology
(define causes
  (extend-relation (a1 a2) causes
    (fact () '(bipolar disorder) 'paranoia)))
(define causes
  (extend-relation (a1 a2) causes
    (fact () '(bipolar disorder) 'mania)))
(define causes
  (extend-relation (a1 a2) causes
    (fact () '(bipolar disorder) 'insomnia)))

;; Establish relationship of anatomical structures
(define caudal-to
  (extend-relation (a1 a2)
    (fact () 'capsule 'midbrain)
    (fact () 'midbrain 'pons)
    (fact () 'pons 'medulla)
    (fact () 'medulla 'cord)))

(define crosses-at
  (extend-relation (a1)
    (fact () 'pons)))

(define caudal-all
  (lambda (cephalic caudal)
    (any
     (adjacent cephalic caudal)
     (exists (intermediate)
       (all (adjacent cephalic intermediate)
         (caudal-all intermediate caudal))))))

(define ipsilateral-symptoms?
  (lambda (lesion-at)
    (names (solve 5 (x)
      (caudal-all lesion-at
        (car (names
          (solve 5 (s) (crosses-at s))))))))

;; Prettify solutions a bit
(define names
  (lambda (ls)
     (map car
          (map cdr
               (map car ls)))))

;; Try a simple relationship query:
;;   What symptoms can depression cause?
;;   (solve 5 ...) means 'give me at most 5 solutions
;;   for the logic variable x that would make
;;   (causes 'depression x) true.
> (names (solve 5 (x) (causes 'depression x)))
(paranoia anhedonia insomnia)

;; What symptoms can bipolar disorder cause?
> (names (solve 5 (x) (causes '(bipolar disorder) x)))
(paranoia mania insomnia)

;; What conditions cause paranoia?
> (names (solve 5 (x) (causes x 'paranoia)))
(schizophrenia depression (bipolar disorder))

;; What structure is immediately caudal to the midbrain?
> (names (solve 5 (x) (caudal-to 'midbrain x)))
(pons)

;; What are *all* structures caudal to midbrain?
> (names (solve 5 (x) (caudal-all 'midbrain x)))
(pons medulla cord)

;; What structure is cephalic to the pons?
;;    (Note reordering of terms in the predicate.
;;    You can read this logic statement as 'give me
;;    all answers such that x makes predicate caudal-all true'
> (names (solve 5 (x) (caudal-to x 'pons)))
(midbrain)

;; Give all terms cephalic to pons:
> (names (solve 5 (x) (caudal-all x 'pons)))
(midbrain capsule)

;; Are symptoms ipsilateral to a given lesion location?
> (ipsilateral-symptoms? 'cord)
()  ;; i.e., false (empty list)

> (ipsilateral-symptoms? 'medulla)
(_.0) ;; i.e., true for all

These are trivial examples. However, very sophisticated systems can be constructed using logical rather than declarative programming models.

The old standby for logic programming is Prolog. However, systems like the Kanren family can be embedded in languages like Scheme, Lisp, and Haskell to take advantage of a functional paradigm. Compilation is possible to lower level languages like C for easy porting to various platforms, including increasingly ubiquitous portable computers.

For a good introduction to the use of logic programming embedded in a functional language like Scheme, see sections 4.3 – 4.4 of SICP [1].

Much if not all of the current talk around clinical software unfortunately stops at electronic health records (EHR) – the paper chart (with all its limitations) mirrored in various incarnations of ‘the cloud’ (with the additional disadvantage of confidentiality rot). For all the endless effort put into EHR, it was a problem solved long ago with nothing more than punched-card-fed mainframes. All we are seeing now is the iterative pursuit of competing data interchange platforms.

Physicians and researchers need software that advances the goal of making routine things routine beyond just the level of data storage and retrieval…to decision support, data discovery and visualization, unsupervised ontology construction, and scripting of reasoning agents.

Historical attempts at decision support include Mycin for diagnosing infectious blood diseases, which contained assertions and rules in the form if IF-THEN clauses:

IF
   the site of the culture is blood, AND the organism gram +, AND
   the original infectious site was the GI tract, AND
   the abdomen is the locus of infection, OR
   the pelvis is the locus of infection
THEN
   therapy should cover Enterobacteriaceae

Rules structured in this manner are brittle, and don’t use unification. Such a system, for example, would not robustly provide answers to queries for all flora that would be likely found in a pelvic infection. The narrow domains and lack of some of what we might call “common sense” knowledge can be problematic: H.R. Ekbia [1] humorously notes that querying a medical inference engine for suggestions on what could be causing the reddish-brown spots on the chassis and body of your Jeep, you’d get “measles”. Another medical support program, asked to suggest treatment for bacterial infection in the kidney, suggested boiling the kidney in hot water.

Another decision support system of historical interest was Internist-I – a system with a much broader domain of medical rules and knowledge. Here’s a transcript of a consultation with that system.

References:

[1] Abelson H, Sussman GJ, Sussman J. Structure and Interpretation of Computer Programs, 2nd Edition. 1996, MIT Press, Cambridge MA.
[2] Ekbia, HR. Artificial Dreams – The Quest for Non-Biological Intelligence. 2008, Cambridge University Press, ppg 96-97.

Posted in medicine | Comments Off

Gambit for Android v 0.2 Released

Gambit for Android version 0.2 is now available.

Features added:

  • Allows user to email developer a description and stack backtrace if a native code crash occurs
  • Adding a new script adds to the beginning of the list, rather than the end
  • User can start REPL server from Android menu

Bug fixes:

  • Some Java-Native Interface functions were serialized to prevent contention.
  • Fixed REPL window backspace problem, which caused a StringIndexException
  • Fixed aviation weather script example – NOAA seems to have changed its interface
  • Added standard Gambit tests to the Android version test suite. Gambit for Android runs the following tests successfully:

r4rstest.scm
mix.scm
debug.scm
error.scm

Posted in android | Comments Off

From the chaotic

Hidden away in Frank Oppenheimer’s glorious Exploratorium is an unnamed, little-noticed exhibit.

Thousands of tiny white spheres are enclosed between glass plates that form a plane, upon which the spheres are free to move. You give the whole thing a random shake or two. You wait for the little quanta to settle. You ponder pattern from chaos:

Here’s a simulation. Move your mouse pointer over the window below to release the spheres. Moving the mouse outside the window will freeze the spheres. Click within the window to add new spheres.

(Uses verlet integration for the physics of collisions, with code I adapted from Florian Boesch. You may need a fast browser like Chrome to view the simulation)

So. Alternately enchanted and dismayed by this universe of order arising from and dissolving into chaos, I’m always heartened to find the occasional calm in the eddies:

Posted in mathematics | Comments Off

Gambit for Android

Release your inner nerd: Gambit for Android.

Run the Gambit Scheme interpreter on your Android device.

Posted in android | Comments Off