{'fraction_non_alphanumeric': 0.02756699644606666, 'fraction_numerical': 0.006387474786283738, 'mean_word_length': 4.980183802412407, 'pattern_counts': {'":': 0, '<': 0, '<?xml version=': 0, '>': 1, 'https://': 1, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
Behavior Trees as a Representation for Medical Procedures

Objective: Effective collaboration between machines and clinicians requires flexible data structures to represent medical processes and clinical practice guidelines. Such a data structure could enable effective turn-taking between human and automated components of a complex treatment, accurate on-line monitoring of clinical treatments (for example to detect medical errors), or automated treatment systems (such as future medical robots) whose overall treatment plan is understandable and auditable by human experts. Materials and Methods: Behavior trees (BTs) emerged from video game development as a graphical language for modeling intelligent agent behavior. BTs have several properties which are attractive for modeling medical procedures including human-readability, authoring tools, and composability. Results: This paper will illustrate construction of BTs for exemplary medical procedures and clinical protocols. Discussion and Conclusion: Behavior Trees thus form a useful, and human authorable/readable bridge between clinical practice guidelines and AI systems.

periodicity [8], less attention has been paid to application of these descriptions to automated reasoning, sensor information processing, or robotics.
In a panel discussion paper on the state of AI in Medicine [9], Peter Szolovitz writes "I think it is a great challenge to build better modeling tools that permit the integration of human expertise (recognizing its fallibility) with machine learning methods that exploit a huge variety of available data." and "Human expertise, developed over centuries of experience and experimentation, cannot be discarded in the hope that it will all be re-discovered (more accurately) by analyzing data." Objective In this paper we apply Behavior Trees (BTs) to the representation of existing medical procedures, developed by the profession, but at multiple levels of abstraction. The goal is to integrate advanced medical procedural knowledge with AI systems, via stimulating exploration of BTs in medical informatics systems.
The purpose of this paper is to illustrate the process of converting previously published and validated clinical procedures and protocols to BTs. There are differing opinions among experts about clinical protocols. Thus, the focus of this paper is on the process of converting to a BT and not on which specific clinical protocol to use. Diverse examples were chosen for this paper to illustrate the applicability of BTs to both medical procedures and medical management protocols.
Background Prior to about 2010, the term Behavior Tree was used idiosyncratically by several authors, but around that time a body of literature began to emerge around a tree model of behaviors used by the video game industry for AI-based non-player characters [10,11]. These BTs assume that units of intelligent behavior (such as decisions or units of action) can be described such that they perform a piece of an overall task/behavior, and that they can determine and return a 1-bit result indicating success or failure. These units are the leaves of BTs. The level of abstraction of BT leaves is not specified by the BT formalism and varies from one application to another or within a single BT. In the context of medicine, BT leaves could be diagnostic or theraputic steps such as the administration of a blood test or a small step of a surgical procedure such as tying a knot. In describing patient management, that might occur over several days, a BT leaf might describe a sub-procedure such as to perform a biopsy, but that biopsy could in-turn be broken down into its own BT.
In medical robotics, researchers are turning attention to augmentation of the purely teleoperated surgery of existing systems such as the daVinci T M surgical robotic system (Intuitive Surgical, Sunnyvale, CA) with intelligent functions [12,13]. In this context, BT leaves could represent such functions as a guarded move, a precision cutting action, acquisition of an ultrasound image, creation of a plan, etc. Earlier medical robotics systems containing automation, such as Robodoc [14] addressed represented task sequences with scripting languages.
Recent literature has applied BTs to UAV control [15], humanoid robotic control [16], and human-robot cooperation in manufacturing [17]. Theoretical classification of BTs has been conducted by several authors [18] which formally relates BTs to Finite State Machines (FSMs). BTs have advantages of modularity and scalability with respect to finite state machines. Other theoretical studies have related BTs to Hybrid Dynamical Systems [19], humanoid robotic behavior [16], and have developed means to guarantee correctness of BTs [20]. Software packages and Robotic Operating System (ROS, [21]) implementations 2 are now available [22]. Several of the above references have ample introductory material and examples of BT concepts.

Materials and Methods
When representing a process with BTs, the analyst breaks the task down into modules which are the leaves of the BT. Each BT node must return either Success or Failure when called by its parent node. All higher level nodes in the BT define composition rules to combine the leaves including: Sequence , Selector , and Parallel node types. A Sequence node defines the order of execution of leaves and returns Success if all leaves succeed in order, returning Failure at the first child failure. A Selector node (also called "Priority" node by some authors) tries leaf behaviors in a fixed order, returns success when a node succeeds, and returns failure if all leaves fail. A Parallel node starts all its child nodes concurrently and returns success if a specified fraction of its children return success. Further refining the behavior tree, Decorator nodes have a single child and can modify behavior of subsequent branches with rules such as "repeat until X > 0".  Figure 1: Behavior Tree constructed (using BT symbols at left) for the basic blood draw procedure documented by the World Health Organization [27].
Applied to robotics, BTs have been explored in the context of humanoid robot control [22,23,24] and recently as a modeling language for intelligent robotic surgical procedures [25].
Many clinical practice guidelines or algorithms are today represented as flowcharts, using a familiar notation similar to the ISO 5807:1985 standard for computer program flowcharts. One use of such a diagram of a medical procedure is as a real-time reference to guide practice (for example an emergency airway algorithm posted on the wall of an ER). We do not propose the use of BTs for this purpose. At this time it appears that a clincian would need some additional training to read a BT properly. In this paper we instead introduce BTs as a means to represent medical procedures (or clinical practice guidelines) in a form that is both machine readable, useful with theoretical constructs such as hybrid system theory, as well as human authorable and readable. A data structure with these properties could enable effective turn-taking between human and automated components of a complex treatment, accurate on-line monitoring of clinical treatments (for example to detect medical errors), or automated treatment systems (such as future medical robots) whose overall treatment plan is understandable and auditable by human experts. In contrast, automated medical procedures achieved by machine learning (e.g. [26]) cannot be understood by even expert humans.

Example 1. Blood Draw
The World Health Organization issues a best practices document 3 on drawing blood for medical tests (phlebotomy) [27]. This over-100-page document gives many details for each step of what is mostly a serial process with few branches. A BT representing the first several steps of this process was developed and is represented in Figure 1. It is worth re-emphasizing that we make no statement about the effectiveness or appropriateness of the medical procedures described in the examples selected here, but rather we use them to illustrate the BT notation. Nor do we intend to criticize the appropriateness of the cited flowcharts for their intended purposes.
The root (top) node of a BT, Φ, encapsulates task start, task end, and the overall task Success or Failure status. For this procedure, its only child is a Sequence node ( ) indicating that execution will be passed to each child in sequence from left to right as shown, with Failure returned by the node if any child returns Failure (the BT root always has one child). The first child of the main Sequence node is also a sequence node which secures equipment and paperwork, and assesses the overall readiness of the patient. In this and subsequent diagrams, leaves of the tree are actions (blue), or queries (yellow) to indicate a logical test or sensing operation. Query nodes return Success or Failure if a condition is satisfied (in this case if the patient is ready). Blue leaves of the tree indicate tasks that are physically performed. The second child of the main Sequence node is a Selector node ( ) in which the phlebotomist determines whether or not a suitable vein is present in the left or right arm. If neither arm shows a suitable vein then the Selector node will fail and that failure will propagate up to the Sequence and in turn to the tree itself. This tree could be simplified with equivalent meaning if the lower left Sequence node is deleted and its three children connected to the top-level Sequence node.

Process of BT Creation
So far it is a manual process to convert an existing published algorithm into a BT. When an algorithm is published as a flow-chart, this process is straightforward when aided by a few conventions. Sequences in traditional flowcharts are traditionally represented by a vertical chain of blocks. Each procedural block may be mapped to a BT leaf (although flowcharts do not require a Success or Failure decision from each block). These leaves are then connected by a Sequence node ( ).
For branching, many flowcharts contain a diamond shape to indicate "if-then-else". To straightforwardly convert if-then-else blocks into a BT, replace the block with a Selector node ( ). The first child of the Selector is a Sequence in which the first child of that Sequence is a test for the condition. The test returns Success if the condition is true and Failure if the condition is false. The second child node represents the flow chart action(s) for the cases where the condition succeeds. If the condition fails, control passes to the Selector node which then executes a child representing the condition-fail branch. This mapping is illustrated in Figure 2.
Graphical user interfaces have been developed for BT authoring, or the BT can be exported from existing tools like GLARE [8].

Example 2. Emergency Airway Ventilation
Human life will expire in minutes if the upper airway is blocked. A medical team thus must quickly follow a best practice sequence of interventions until airflow is reestablished. Restoration of airway consists of a rapid succession of increasingly invasive steps, starting with insertion of a laryngoscope, and, as a last resort, surgical opening of the airway through crychothyroidotomoy. The literature on airway restoration algorithms contains many diagrammatic languages for representation of the airway algorithm. In one example [28] the flow chart includes an exception in the form of a separate box to the side of the flowchart containing: "If SpO2 drops to 93% at any point: Facemask + OPA or SGA. If no ETCO2 with best attempts, progress to surgical airway." [28] This box can is explicitly outside the flowchart but indicates a concurrent monitoring and interrupt task which is hard to represent in the original selected notation.
We constructed a BT for the airway procedure based on [28] and interpreted by https://emcrit.org/ racc/shock-trauma-center-failed-airway-algorithm/ (Figure 3). The first logic node (directly below Φ) is a Parallel node, which indicates that its children should execute concurrently. The first child of the Parallel node represents the concurrent monitoring procedure represented as a side box in [28]. The right branch, defining the main algorithm, contains a sequence node (→). Its left-most child in turn is a Selector node which allows for alternative methods, returning when the first of its children succeeds. It can be verified that in the normal procedure, the surgical airway procedure is a last-resort which only is attempted when laryngoscopy (up to 3 attempts) and intubating Laryngeal Mask Airway (LMA) placement (two attempts) both fail. LMA and Supraglottic Airway (SGA) are similar equipment.
Compared to the flowchart of [28], the BT is a uniform representation which clearly labels alternative strategies and fallbacks (via the Selector nodes), and is amenable to direct software execution (assuming code modules (such as for example ROS nodes) are available for each leaf.
A second airway establishment procedure was published by Davis et al. [29] using a flow-chart like diagram. A BT for their procedure is given in Figure 4 Recovery Margin Image Segmentation  Figure 5: BT implemented in software controller for robotic detection and ablation/treatment of positive tumor margins (redrawn from [25], with permission). A blackboard data store is commonly used with BTs to allow leaves to share information.

Example 3. Simulated Tumor Margin Ablation
In recent bench-top surgical robotics experiments [25,30] a system was developed which illustrated a future surgical scenario for treatment of glioma. In this scenario, a surgeon will expose the tumor and manually remove it, but the problem remains of detecting and treating any remaining tumor material at the edge of the resulting cavity. In many cancer surgeries, a margin of up to one centimeter is taken around the tumor to increase the odds that no residual cells are left behind. In this work Hu et al. assumed the existence of a currently-under-development biomarker for brain tumors [31] which would allow residual tumor material to be detected through fluorescence. They developed a robotic system which could scan the cavity for stimulated fluorescence, detect a response, and plan and execute one or more treatment plans.
The BT we developed ( Figure 5) performs this task, and checks up to four planning algorithms (lower left leaves) for appropriateness depending on the area and shape of the detected fluorescent region. Notably Hu et al., developed a new type of node, the "Recovery" node, which is able to fall back to a recovery tree in the event of a task failure.
Another notable feature of this Medical BT is the action leaf labeled "Select". In this implementation, selecting of the plan from among several computed plans, was performed by manual input from a surgeon. Thus the BT framework can easily incorporate manual steps into a complex and composable procedure. Furthermore, should an automated function be developed with sufficient confidence, it can easily be dropped in to the select leaf node of the BT.

Example 4: BT for post operative patient management
One attractive feature of BTs is that they are equally useful at different levels of abstraction and time scales. In this section we describe a BT for post operative management of Calcium in thyroidectomy patients. After thyroidectomy, it is critical that clinicians properly verify that Calcium regulation by the parathyroid glands is not disrupted by the thyroidectomy. Patel et al. [32] describe (using a traditional flow-chart) a newly validated clinical pathway for postoperative calcium management after thyroidectomy in pediatric patients. We have converted this algorithm into a BT containing 47 leaves.
Besides expanding the applicability of our proposed theoretical approach to patient management and higher level actions, this application will challenge our process with a significantly larger BT. Following the flowchart of Patel et al., [32] (Figure 6), we created a BT for this procedure by breaking it down for convenience into four smaller BTs:

High Risk / Asymptomatic
Each of which has its own BT (Figure 7). Then, completing the patient management algorithm, the four BTs of Figure 7 are combined into the overall algorithm ( Figure 8). Note that the partitioning of this BT as shown in Figures 7 and 8 could be done in many different ways and is done here solely for graphical convenience.
One challenging aspect of this conversion is that throughout the procedure of Figure 6, there are instructions such as "check total Ca ++ Q6 hours," or "recheck total Ca ++ after 2 h". Through these distributed references, Ca ++ checks are performed regularly but are distributed throughout the flowchart and create additional process steps due to the testing time delays. In creating these BTs, the Ca ++ monitoring parts of the procedure were representationally simplified by defining 1. a Parallel node and BT branch to allow a repetitive Ca ++ monitoring process (different for High Risk and Low Risk Patients) and 2. a variable, Tca, indicating the time between Ca ++ tests.
With the above definitions, the BT turns out simpler because Tca can be modified throughout the procedure without otherwise storing "state" or future instructions for Ca ++ monitoring.

Discussion and Conclusion
This paper has introduced Behavior Trees as a notation and data structure for representing medical procedures or clinical practice guidelines. We have used some published guidelines as examples to illustrate this representation. The use of BTs for medical algorithms is still conceptual. Anticipated uses to be developed and validated in the future include: • Documentation of the standard of care, through clinical practice guidelines by and for human medical providers, for example in decision support systems.
• Integration of clinical practice guidelines with several advanced AI methods.
• Execution frameworks for automated medical robotic tasks.
Compared to Finite State Machines, Hidden Markov Models, and similar approaches, BTs afford a humanreadable and writable representation through its small number of relatively easy to understand combinatorial operators: Sequence , Selector , and Parallel , and the ease by which BTs can be combined (using those same operators). These properties seem to be well matched to conventional human thinking about procedures.
There are also limitations of BTs which need further exploration and elucidation to make sure they are used appropriately. For example  • BTs do not have an explicit "interrupt" mechanism by which an ongoing procedure can be stopped.
For example, although the emergency airway BT of Figure 3 illustrates checking in parallel for the condition of low SpO2 and converting to surgical airway, if this parallel node succeeds (i.e. the low SpO2 condition is met, and subsequent steps succeed), it does not explicitly halt its other child tree (the remainder of the procedure on the right branch). A similar issue exists in Figure 8 if the patient meets discharge or ICU referral criteria.
• Human clinicians might need training if BTs are used in clincian-facing applications. Although understanding the BT is not difficult, and some flowcharts can be confusing, flowcharts at least have familiarity and an appearance of being self-explanatory.
• New safety checking mechanisms (such as the "Recovery" node described in Hu et al. [25,30]) need further development and unification. Several authors have introduced special nodes to apply BTs in particular domains and this may require more standardization and study.
There are exciting future possibilities for the integration of BTs with AI. For example, automated learning of BTs is still very much an open problem. Initial study [11] and more recent works [34,35] suggest some possibilities for on-line autonomous performance improvement by BT driven systems.
To aid inference based on BTs, an exciting future direction is the augmentation of BTs with additional information such as probability distributions of expected duration in each leaf, or sensor emissions expected while each leaf is executes. Such augmentation is the subject of future work. Current CIG formalisms have been developed by academic groups to encode medical guidelines in a computer interpretable and executable manner, often to interface with medical information systems. As such, they have depended upon research funding without clear business models [36]. In contrast, development of BTs has been driven by the multi-billion dollar computer gaming industry. The demand for more realistic modeling of non-player character behavior in videogames, or recent adoption of BTs in robotics, may spur development of additional capabilities for medical BT models.