Saturday, February 4, 2023

Medical knowledge as a probabilistic decision tree

Medical reasoning can sound like a large decision tree ("if this then that"). This post documents the nuances that render a decision tree data structure inadequate. 

  • Nuances about input data
    • Extracting facts relevant to diagnosis is challenging. 
      • A parent of an infant may report their baby is not eating much, but does that mean the baby is refusing food, sleepy, crying, vomiting...
    • Looking merely at the current symptoms is inadequate. Patient history matters. Family history can matter.
    • distinguishing irrelevant information is important. Temporal correlation does not mean causation.
    • There are varying degrees of uncertainty about data quality. For example, I would discount the data from a person who does not tell their story well, and put a greater weight on a lab test. But for someone who tells their story well, the history features may sway more than their lab. 
    • How questions get asked matter
      • "Does your family have a history of arrhythmia?" will get a "no," but
        • "Have people in your family drowned or died in a car accident?" would get a yes because arrhythmia can lead to drowning and accidents.
        • "did any babies in the family have hearing problems?"
    • Patients don't know the precise medical jargon
      • "Does your family have a history heart attacks?" is likely actually a different medical cause when the patient doesn't know the jargon or the specifics about cholesterol.
    • Humans are not uniform, and the differences can matter. 
      • "male versus female" isn't an easy binary in all cases
      • "age" isn't a scalar positive number
        • age since birth ("post-gestational age")
        • age since conception ("gestational age")
        • cognitive ability versus temporal age versus physical dexterity

    • Decisions
      • A lot of the reasoning is probabilistic rather than definitive. The exact probabilities are also unknown -- one is dealing with relative probabilities. 
      • Discarding data should be weighted by the consequence of removing the data
    • Causal explanations based on physiology can be used to discard information, or give insight about additional symptoms to ask about. [Writing down all of physiology is a separate task.]
    • The differential list should include not only a ranking of most likely diagnoses but also diagnoses that one should not miss. This is one area where some doctors say that doctors are better than nurse practitioners. The nurse practitioner tells the patient the most likely diagnosis, but the doctor knows other diagnoses that are less likely, but should not be missed and counsel accordingly. In other words, just guessing based on a "most likely" diagnosis is insufficient. Are there "do not miss" outcomes that could be explanatory for the diagnosis?
    • Suggestions for action by the patient includes, "what to do if this other symptom arises" or "what to do if this symptom persists"



    The clinical decision analysis using decision tree
    doi 10.4178/epih/e2014025

    Sunday, December 18, 2022

    MONTEREY PHOENIX grammar, keywords, and common patterns

    MONTEREY PHOENIX grammar

    In this table A is an event and B and C are events in A
    description of pattern grammar rule
    Ordered sequence of events (B followed by C) A: B C;
    Alternative events (B or C) A: ( B | C );
    Optional event (B or no event at all) A: [ B ];
    Ordered sequence of zero or more events B A: (* B *);
    Ordered sequence of one or more events B A: (+ B +);
    Unordered set of events B and C (B and C may happen concurrently) A: { B, C };
    Unordered set of zero or more events B A: {* B *};
    Unordered set of one or more events B A: {+ B +};

     

    description of pattern grammar rule
    name of model SCHEMA
    Identifies an actor ROOT
    event precedence across swimlanes COORDINATE
    if and only if <->
    <!>
    a condition that each valid trace should satisfy ENSURE
    FOREACH
    BUILD
    DISJ
    MARK
    ONFAIL
    CHECK
    AFTER
    EXISTS
    MAP
    CLEAR
    SHOW
    message box that prints text SAY("hello world")

    Common pattern: branching logic in swimlane

    ROOT Driver: enters_car (starts_car | exits_car);
    starts_car:  move_forward
                 stops_car
                 exits_car;
    

    Common pattern: dependency across swimlanes

    COORDINATE
    $a: turn_steering_wheel_right FROM driver,
    $b: right FROM front_tires
    DO 
    ADD $a PRECEDES $b; 
    OD;
    

    Common pattern: shared events

    Driver, Car SHARE ALL move_forward, 
                          turn_left, 
                          turn_right;
    

    MONTEREY PHOENIX model checker

    In this blog post I discuss a model involving two actors: a car and a driver. Each actor has an associated set of actions they can take.

    For a video walkthrough of this code, see https://youtu.be/r6aPKem6WLs

    Using the web interface https://firebird.nps.edu/, run this model

    SCHEMA using_a_car /* model title */
    
    /* Actor Behaviors */
    
    /* purple text is an MP keyword,
       actors are green text,
       atomic events are blue */
    
    /* with space as the separator, 
       the events (blue) are an ordered sequence */
    
    ROOT Driver: enters_car 
                 starts_car
                 move_forward turn_left turn_right 
                 stops_car
                 exits_car;
    
    ROOT Car: off
              starting 
              running_idle
              move_forward
              turn_left
              turn_right
              shutting_down;
    

    Introduce branching logic

    SCHEMA using_a_car /* model title */
    
    /* Actor Behaviors */
    
    /* purple text is an MP keyword,
       actors are green text,
       atomic events are blue,
       composit events are orange */
    
    /* 
          ( A | B ) are alternative events 
    */
    
    ROOT Driver: enters_car (starts_car | exits_car);
    starts_car:  move_forward turn_left turn_right 
                 stops_car
                 exits_car;
    
    ROOT Car: off
              starting 
              running_idle
              move_forward
              turn_left
              turn_right
              shutting_down;
    

    Events among actors are coordinated

    SCHEMA using_a_car /* model title */
    
    /* Actor Behaviors */
    
    /* purple text is an MP keyword,
       actors are green text,
       atomic events are blue,
       composit events are orange */
    
    ROOT Driver: enters_car (starts_car | exits_car);
    starts_car:  move_forward turn_left turn_right 
                 stops_car
                 exits_car;
    
    ROOT Car: off
              starting 
              running_idle
              move_forward
              turn_left
              turn_right
              shutting_down;
    
    /* the two processes are related by specific events */
    
    COORDINATE
    $a: starts_car FROM Driver,
    $b: starting FROM Car
    DO
    ADD $a PROCEEDS $b;
    OD;
    
    COORDINATE
    $a: stops_car FROM Driver,
    $b: shutting_down FROM Car
    DO
    ADD $a PROCEEDS $b;
    OD;
    

    Actors may take zero or more actions

    SCHEMA using_a_car /* model title */
    
    /* Actor Behaviors */
    
    /* purple text is an MP keyword,
       actors are green text,
       atomic events are blue,
       composit events are orange */
    
    /* 
        {* *} is an unordered set of zero or more events 
    */
    
    ROOT Driver: enters_car (starts_car | exits_car);
    starts_car:  {* ( move_forward | 
                      turn_left | 
                      turn_right ) *}
                 stops_car
                 exits_car;
    
    ROOT Car: off
              starting 
              running_idle
              {* ( move_forward | 
                   turn_left | 
                   turn_right ) *}
              shutting_down;
    
    COORDINATE
    $a: starts_car FROM Driver,
    $b: starting FROM Car
    DO
    ADD $a PROCEEDS $b;
    OD;
    
    COORDINATE
    $a: stops_car FROM Driver,
    $b: shutting_down FROM Car
    DO
    ADD $a PROCEEDS $b;
    OD;
    

    Events are shared among actors

    SCHEMA using_a_car /* model title */
    
    /* Actor Behaviors */
    
    /* purple text is an MP keyword,
       actors are green text,
       atomic events are blue,
       composit events are orange */
    
    ROOT Driver: enters_car (starts_car | exits_car);
    starts_car:  {* ( move_forward | 
                      turn_left | 
                      turn_right ) *}
                 stops_car
                 exits_car;
    
    ROOT Car: off
              starting 
              running_idle
              {* ( move_forward | 
                   turn_left | 
                   turn_right ) *}
              shutting_down;
    
    Driver, Car SHARE ALL move_forward, 
                          turn_left, 
                          turn_right;
    
    COORDINATE
    $a: starts_car FROM Driver,
    $b: starting FROM Car
    DO
    ADD $a PROCEEDS $b;
    OD;
    
    COORDINATE
    $a: stops_car FROM Driver,
    $b: shutting_down FROM Car
    DO
    ADD $a PROCEEDS $b;
    OD;
    

    Sunday, November 20, 2022

    steps I took to add a picture to the website frontpage

    The current iteration of https://derivationmap.net/ uses data from a JSON file to dynamically generate page content. 

    On the front page of https://derivationmap.net/ there's currently an SVG. I wanted to place a PNG next to the SVG. Before placing the PNG, I wanted to make the SVG narrower. Looking at the source code for the page index.html, I see

    <svg id='viz'></svg>
    

    Inspecting the source code of the rendered page, I see

    var width = 600;

    which comes from https://github.com/allofphysicsgraph/proofofconcept/blob/gh-pages/v7_pickle_web_interface/flask/templates/_d3_js.html#L29

    To test out a change to a narrower width, I start "Docker desktop" on my Mac and, in the directory allofphysicsgraph/proofofconcept/v7_pickle_web_interface, run the command

    docker-compose up --build --remove-orphans
    

    In a web browser I was then able to access http://localhost:80 and got a warning from Chrome that the certs were invalid. Incognito mode seemed to be working better.

    Wednesday, October 26, 2022

    Levels of reproducibility and repeatability and replication

    Knowledge progresses when one person can leverage the insights of another person. There are levels of reproducibility that require different levels investment on the part of the person looking to build on the initial knowledge. 

    The levels described below are ranked from "requires lots of work to build upon" to "very easy to leverage."

    Level 0: discoverable claim

    Undocumented claims that no one else is aware of are irrelevant to the advancement of science. 

    Level 1: claim without evidence

    example: "My design for this car tire supports operational speeds of 50 miles per hour and will be usable for 50,000 miles."
    No software or analytical calculations are provided. No explanation of how claim was arrived at.


    Level 2: verbal hints of process used

    software-based example: My design for the car tire is based on calculations from code written in Python.
    analytical example: In my calculation of operational speed I used the Fourier transform.

    What distinguishes 2 from 1: Advertising that code was written, or math was done. 
    Most peer-reviewed scientific papers are written at this level or, if you're lucky, level 2. 
    Most presentations of experiments (e.g., at conferences and lectures) also are made at this level or level 2.


    Level 3: software without documentation or dependencies; or, for analytical, a few of the key equations

    software-based example: Python script provided by the author to back up claim. No configuration file or random seed value. Library dependencies and versions need to be determined through trial and error (aka digital archeology).
    analytical example: a few key equations (from a much more complex derivation) are mentioned, as are a few (not all) of the assumptions.

    consequence: If you're smart and diligent, you may be able to recover statistically similar (though not exact) behavior for stochastic models, assuming neither you nor the original author had any bugs in the implementation.


    Level 4:

    software-based example: Python script with random seed value specified and configuration parameters documented. Documentation not included, nor are dependencies made explicit. 
    analytical example: complete derivation provided, with explanation of assumptions

    Level 5: repeatable

    software-based example: Python script containerized, software versions pinned. Build process is executable. No digital archeology needed.
    analytical example: portions of the complete derivation are checked by a computer algebra system (CAS) for correctness.


    Level 6:

    software-based example: Python script containerized with documentation of assumptions and examples of how to use. Configuration file with parameters and random seed values provided.
    analytical example: complete derivation checked by a computer algebra system (CAS) for correctness. Proofs provided.  Citations where appropriate.


    Caveat: the levels described above are not actually linear. There are a few meandering paths that get from 0 to 6. 


    References

    "Reproducibility vs. Replicability: A Brief History of a Confused Terminology"
    https://www.ncbi.nlm.nih.gov/pmc/articles/PMC5778115/

    Sunday, October 9, 2022

    TLA+ comparison with other formal verification software

    The scope of this post is limited to formal verification of algorithms and protocols. 

    To save docker images to my repo,

    docker pull official/imagename
    docker image tag official/imagename:latest myusername/imagename:latest
    docker push myusername/imagename:latest


    TLA+

    Check the correctness of a specification. 
    Not tied to a specific implementation or tests of an implementation.

    Jepsen



    "Jepsen is a Clojure library. A test is a Clojure program which uses the Jepsen library to set up a distributed system, run a bunch of operations against that system, and verify that the history of those operations makes sense."

    For distributed systems, introduce {partitions, added resources, removed resources, delays, clock skew} and other noises, run operations, and then compare against expected results. 

    Stateright



    "Stateright is a Rust actor library that aims to solve this problem by providing an embedded model checker, a UI for exploring system behavior (demo), and a lightweight actor runtime. It also features a linearizability tester that can be run within the model checker for more exhaustive test coverage than similar solutions such as Jepsen."

    F*


    Can generate C, as well as parser/generators. 

    Not explicitly temporal (whereas TLA+ is explicitly about temporal actions), but F* could be used for temporal models.

    Why3


    https://why3.lri.fr/

    Z3

    written by the same developer as SMV after the developer moved to Microsoft

    https://github.com/z3prover/z3/pkgs/container/z3

    Coq

    constructive dependent type theory

    Lean

    "Simple formally verified compiler in Lean" by Ericson (2021)

    SMV

    CMU's SMV --> Cadence SMV --> nuSMV

    https://swmath.org/software/7795
    http://mcmil.net/smv.html
    https://www.cs.cmu.edu/~modelcheck/smv.html
    https://sws.cs.ru.nl/publications/papers/biniam/smv/
    https://web.cs.wpi.edu/~kfisler/Courses/525V/S02/Readings/smv-cadence.pdf

    https://nusmv.fbk.eu/
    https://en.wikipedia.org/wiki/NuSMV

    Isabelle/HOL

    simple type theory


    Alloy


    Cryptol



    Spin and Promela

    P

    Event B

    "a modelling method for formalising and developing systems whose components can be modelled as discrete transition systems. An evolution of the (classical) B-method, Event-B is now centred around the general notion of events, which are also found in other formal methods such as Action Systems, TLA and UNITY."

    An Introduction to the Event-B Modelling Method

    Translating B to TLA+ for Validation with TLC

    https://www3.hhu.de/stups/downloads/pdf/HansenLeuschel_TLC4B_techreport.pdf

    https://www.sciencedirect.com/science/article/pii/S0167642316300235

    classical B for software development

    https://discuss.tlapl.us/msg03080.html

    Relevance of TLA+ to the Physics Derivation Graph

    The Physics Derivation Graph is just a CRUD application, so I didn't expect TLA+ would be relevant. My initial view was that there isn't an algorithm or a protocol in the PDG. The PDG is just a webpage, some middleware (e.g., bash or Python) and a back-end database (CSV, SQL, JSON, Neo4j, etc). Standard MVC applies. 


    After spending 1 day reviewing TLA+ materials, I realized the PDG has a workflow specification that I hadn't previously considered in detail. 

    1. User has a derivation in mind and they want to integrate it with existing PDG content. User knows their derivation's expressions, steps, symbols (variables and constants), and operators.
    2. User writes their derivation into the PDG referencing existing symbols, existing expressions, and existing inference rules. 
      • If the relevant symbol isn't available, add it.
      • If an existing symbol needs to be corrected/revised/merged, modify it.
      • If the relevant inference rule isn't available, add it.
      • If an existing inference rule needs to be corrected/revised/merged, modify it.
    3. Integrated derivation steps are checked for correctness using a Computer Algebra System (e.g., SymPy, Mathematica, etc)
    That user story sounds reasonable until you consider two concurrent users editing the same steps or expressions or symbols or inference rules or operators. If each of the above steps are considered atomic, there are potential conflicts. 
    • One user could be attempting to create a new derivation step while another modifies existing symbols or inference rules. 
    • Two users could concurrently attempt to modify/merge/edit existing symbols or inference rules. When they commit their change, the thing they are changing may have disappeared or been altered.
    One way to avoid the above potential for conflict would be to lock the database while edits are made (no concurrent users).
    Another avoidance mechanism would be to queue changes and check consistency of every change sequentially (serialize concurrency).