{'fraction_non_alphanumeric': 0.022063132149499377, 'fraction_numerical': 0.004101806323405773, 'mean_word_length': 4.91144578313253, 'pattern_counts': {'":': 0, '<': 0, '<?xml version=': 0, '>': 0, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 1, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
A hierarchical narrative framework for OCD

This paper gives an explanatory framework for obsessive-compulsive disorder (OCD) based on a generative model of cognition. The framework is constructed using the new concept of a 'formal narrative' which is a sequence of cognitive states inferred from sense data. First we propose that human cognition uses a hierarchy of narratives to predict changes in the natural and social environment. Each layer in the hierarchy represents a distinct 'view of the world', but it also contributes to a global unitary perspective. Second, the generative models used for cognitive inference can create new narratives from those states already experienced by an individual. We hypothesise that when a threat is recognised, narratives are generated as a cognitive model of possible threat scenarios. Using this framework, we suggest that OCD arises from a dysfunction in sub-surface levels of inference while the global unitary perspective remains intact. The failure of inference is felt as the external world being 'not just right', and its automatic correction by the perceptual system is experienced as compulsion. Ordering and symmetry obsessions are the effects of the perceptual system trying to achieve precise inference. Checking behaviour arises because the security system attempts to finesse inference as part of its protection behaviour. Similarly, fear of harm and distressing thoughts occur because the failure of inference results in an indistinct view of the past or the future. A wide variety of symptoms in OCD is thus explained by a single dysfunction.


Introduction
The symptoms of OCD suggest no obvious common cause and the disorder is heterogeneous, possibly with different subtypes [42]. Psychological models for OCD do not go far beyond a description of the symptoms or traits of the patient [29] and so they have weak explanatory power. Biological models explain observed abnormalities in, for example imaging data, but they do not provide the level of description needed to explain symptoms. In explaining psychopathology, the different levels of explanation -formal electrophysical models at the neural level, and qualitative psychological explanations of symptoms -have tended to be disjoint. There is some work that attempts to close this 'explanatory gap', in particular the Bayesian brain hypothesis [43] [44] which has been applied to both neuroscientific observations [45] and symptoms of mental illness [46] [47]. Under this approach the brain is hypothesised to maintain probabilistic models of the environment and update the models using Bayesian inference [43]. More specifically, the brain minimises the discrepancy between sensory input and the predictions made by an internal model, and in this way it implements Bayesian inference. The explanatory power of prediction error minimisation for perception is explored in depth in the text by Hohwy [48]. The Bayesian brain concept is usually traced to Helmholtz's theory of perception [49] [50] in which stimuli are seen as insufficient to generate percepts without prior information enabling unconscious inference. O'Callaghan describes the development of perceptual theory from Helmholtz to a contemporary understanding [51, p78], and Friston provides a short history of the Bayesian Brain idea [44] from a neuroscientific point of view.
Two relevant applications of predictive coding to psychopathology are as follows. Fletcher and Frith [46] use a hierarchical model of brain function to explain the positive symptoms of schizophrenia -hallucinations and delusions. In a hierarchical model, prediction errors at a low level are passed up the hierarchy until they are resolved or 'explained away' by a higher level. In schizophrenia there is a failure in inference which leads to improper integration of new evidence and a resulting prediction error. Corlett et al. [52] focus on delusions and again propose a predictive coding model to help explain them. Following Helmholtz, they define the brain as an inference machine, and they understand delusions as false inferences. Predictive learning and prediction error are general mechanisms of brain function and they relate them to neurotransmitter signalling, and to experimental evidence of the effect of, for example, NMDA receptor antagonists. Their hypothesis is that aberrant prediction error leads to aberrant learning and this in turn leads to delusions and perceptual aberrations. The approach taken in this paper also uses a hierarchical model of cognition and its dysfunction, in this case to explain the symptoms of OCD.

Hierarchical inference
We first explain hierarchical Bayesian inference as a model for human cognition. An important function for any animal is to know its environment by using observations from its senses. We define an external state X as a cause or condition in the environment that fully determines the observations U . We define an internal state W as the cognitive representation of an external state based on the observations. The task for the cognitive apparatus is to find the distribution of internal states conditioned on observations, p(W |U ) in order to model the external state. Figure 1 illustrates the process. The probability of each state W 1 . . . W k individually generating the observations U is determined. The process of inference is one of selecting the stateŴ that is most likely to have generated the observations U . The result is shown on the right hand side of the figure as a graph of p(W |U ) against the internal states W . For a known pattern generated by a familiar state, the graph will show resonance for the corresponding model.  Figure 1: Perception as cognitive resonance. The rectangular boxes represent internal state models W1 . . . W k each of which can generate simulated observations UW 1 . . . U W k . Perception is the process of inferring the model that best explains current observations U by using Bayes' rule to find p(W |U ) from p(U |W ). In the figure, W2 is shown as resonating strongly with the observations. The process results in the graph p(W |U ) which has a peak at W2 (right hand side). A familiar pattern will exhibit resonance, while closely related patterns also resonate to some extent. For example, an infant will recognise any human face, but will show particular affinity for the mother's face.
Higher level inference is accomplished by using a hierarchy in which states inferred by one level are used as observations for the next. Figure 2 shows the hierarchy of inference levels. Observations arrive from sensory neurons as spike trains which are processed into features, such as edges in a visual scene. The features themselves become observations for a second level of inference which in turn uses them to infer states that are meaningful to the next level up. So higher levels attempt to predict or 'explain away' lower levels, so that ultimately the sense data is explained by the internal cognitive model.

Formal narratives
The generative models used for inference can also generate artificial observations which have the same distribution as those already experienced. We illustrate the process by using a generative model of language to  A pictorial representation of cognition as multi-level inference of inferred states. The graphs represent the conditional distribution p(W |U ) which has a peak at the most likely stateŴ . Inferences from the lowest level may consist of features, such as edges in the visual scene, which become observations for the next level in the hierarchy. High level percepts needed for beliefs, thoughts and imagination are represented at the top of the hierarchy. The perception-belief spectrum was suggested by Corlett [52] to be relevant to delusions and hallucinations in schizophrenia.
create English sentences. The probability of a sequence of words W k can be expanded as, We can approximate the terms in the expansion by limiting the history length to give a bigram word model, which assumes that the probability of each word is influenced only by its predecessor, The model then comprises the frequencies of starting words and pairs of words found in the training data.
To create a new sentence, we take a starting word w 1 and choose the next word randomly according to its distribution in the model, and continue until the desired length is reached. Shannon [53, p7] gives an example of an artificial sentence derived from such a model of word sequences, The sentence as a whole approximates the distribution of the natural word order. If a bigram model is used, the generated text is word salad. Longer n-grams can be used, in which case the model comprises longer sequences of words. In this case the generated text becomes much more recognisably like English in its construction, but it usually has no coherent meaning.
We consider the same process of generation, but instead of words, we use the cognitive states W as generated elements. We call a sequence of generated states a narrative. To illustrate the point we use an example of a threatening scenario faced by an individual. When someone encounters a large dog in the street, they quickly make an assessment of whether it is likely to pose a danger, and then act accordingly. We denote the internal state representing a fierce dog as W dog−f ierce , and an internal state representing the individual running away as W you−run , and so on. Some prospective narratives representing this fight-or-flight scenario are, where j is the number of states in N k . In this simple model the narratives cover all possibilities, so k p(N k ) = 1. The scenario is illustrated in Figure 3. The states are those that best 'explain away' or predict the observations, which are themselves inferred states from lower in the cognitive hierarchy. A network of prospective narratives is generated, whose probabilities depend on past experience.

Hierarchies of narratives
The states chosen for the example represent a cognitive state in linguistic form. For example W dog−f ierce represents the cognitive state inferred by an individual when they see a fierce dog. Since the example uses recognisable states, it can be presented as a narrative in the more colloquial sense. So the formal narrative N 3 can be expressed retrospectively as, "I saw a fierce dog, I fought it and it ran away".
The substates from which the state W dog−f ierce is inferred can not so easily be expressed in a natural language, but there is evidence that more primitive perceptions are also the outcome of a generative process. For example, the visual hallucinations that occur in Charles Bonnet Syndrome have been proposed as evidence for a generative model of vision [54]. This observation suggests that formal narratives could occur at levels of inference below those that can be expressed in a natural language. In Figure 4 we generalise the model in Figure 2 to allow inference from narratives, where a narrative is either a single inferred state or a sequence of inferred states.   Figure 2 because a narrative is either a single inferred state or a sequence of inferred states. At the lowest levels the states are comprised of features derived from the different sensory modes. The conditional distribution of states at lower levels is shown as more peaked than that at higher levels, reflecting the expansion of possible inferences as we move up the cognitive hierarchy.
The model has some intuitive appeal because applying inference to narratives is common. For example if someone hears N 3 as a retrospective narrative they will question if the speaker really did fight off a dog. But the model also implies that inference of narratives occurs at lower levels of cognition suggesting that the human perspective is composed of a hierarchy of layers, each of which contributes to the individual's perspective or 'view of the world'. Support for a layered model of cognition is provided by instances when individuals do not believe what they see, for example with optical illusions. In these cases inference at a high level overrides inferences made by a subordinate level, so the individual has the experience of perception without its consequent belief. The potential lack of coherence between levels is also relevant to OCD, where the individual recognizes that the obsessional thoughts, impulses, or images are a product of his or her own mind [1][55].

Unitary perception and multiple inference
However in normal cognition, the usual experience of perception is unitary, and we perceive just one reality. For example the Necker Cube, shown in Figure 5 can be interpreted as a solid in two different orientations. By fixing the perception, for example by viewing the fourth highest vertex on the page as being at the back, a solid of a given orientation is visualised. Conversely, by imagining the cube as in the alternative orientation, the perceptual view is fixed. In either case, the imagined solid is coherent with the perception, and it is seen in only one orientation at a given time. The unitary nature of perception and consciousness has a long philosophical lineage: Bayne gives an introduction in [56], and a text of his recent work is [57]. But although the experience of perception is unitary, the inference on which it relies must entertain multiple scenarios. The Necker Cube is an ambiguous visual scene which admits two interpretations each of which is consistent with the lines on the page, and this ambiguity is processed by the cognitive apparatus. Further, a partially obscured scene admits many interpretations because it is an under-determined problem: we have to formulate multiple hypotheses for what might be buried under the ground or hidden behind a bush. The hierarchy of states model in Figure 2 fulfils this purpose by computing the most likely internal states given the sensory input 1 . For spatiotemporal modelling the hierarchy of narratives shown in Figure 4 is needed.

Mental time travel
An animal derives a selective advantage from successfully interpreting and predicting changes in its natural environment: it is more likely to reproduce if it can anticipate the threat from a hidden predator, or the reward from a buried cache of food. The natural environment presents different levels of cognitive challenge. The physical world and flora are passive, and their behaviour is relatively easy to learn. Animals, especially predators, are harder to predict, but their threats can often be learned. Other humans pose the most complex challenge because they are agents with the same cognitive apparatus as the individual. The attribution of mental states to others is called 'theory of mind' or 'mentalising', and it usually develops in early childhood. Theoretical accounts of theory of mind fall into two classes: 1) the individual learns through hypothesis and experiment, in the same way that they learn about the behaviour of inanimate objects, 2) the individual employs their own cognitive apparatus to simulate another person's behaviour. An explanation of these accounts and some of the cognitive challenges posed by simulation are given by Mitchell [58]. A related theory is that social cognition is based on the recognition that others are 'like me' [59], and there is some evidential support for this idea provided by Gardner et al. [60].
The faculty of 'mental time travel', a term coined by Suddendorf and Corballis, [61], is also related to simulation. It allows humans to mentally project themselves backwards in time to re-live, or forwards to prelive, events. The emergence of mental time travel in evolution is hypothesised to be a crucial step towards human current success [62]. It is suggested that mental time travel is enabled by a special conscious state called 'chronesthesia', a hypothesis that has some experimental support [63].
Helmholtz realised that the senses cannot even resolve ambiguous scenes without combining evidence with prior information [64] [49], which is a computationally difficult problem. Modelling behaviour is harder still: it involves not just the inference of scenes, but a prediction of how they might evolve. A solution is the constant formulation of counterfactuals and the simulation of possible scenarios. So here we apply the simulation model not just to mentalising, but more generally for mental time travel. Under the predictive coding model, an individual predicts their sensory data and minimises the error between that prediction and the real input. Error minimisation serves for perception of current events, but what about prospection, which has no input against which to minimise error? We propose that the generative models used for perception create a distribution of narratives which are constantly updated as sensory data is received.
So a hypothesis is as follows, Narratives, or sequences of cognitive states, are created from a generative model for the purposes of mental time travel. Since narratives are generated from percepts and unconscious inferences as shown in Figure 3, chronesthesia can be understood as unitary perception extended into a manifold past and future. Just as a movie passes through time using a series of 2-dimensional scenes, a single prospective narrative can run percepts forward in time, generating for each step a prospective scene. Chronesthesia is the conscious awareness of examining such scenes, which might be aversive, for example being bitten by a dog or rewarding, like winning the national lottery. However, whereas conscious perception is usually veridical 2 , prospective narratives are mostly counterfactual.
Mental time travel is based on the manifold inferences from sense data rather than on the most likely inference from that data, which is experienced as perception. This facet of the model is relevant to 'fear of harm' in OCD, in which highly unlikely scenarios are generated from seemingly false inferences.

The security motivational system
The risk of an adverse event is the subject of some symptoms of OCD, such as checking and fear of harm. Szechtman and Woody [39] hypothesise that a dysfunction in the security motivational system (SMS) underlies such symptoms, specifically an inability to generate the normal 'feeling of knowing' that normally signals task completion. The security motivational system refers to a 'set of biologically based (hardwired), species-typical behaviours directed toward protection from danger of self and others' [39, p113]. In this paper we use the term to refer to the cognitive function that invokes those behaviours. We suggest that the SMS simulates potential behaviour by creating a collection of narratives which is used to guide the response.
So a secondary hypothesis is as follows, In response to a threat stimulus, a collection of narratives relating to that threat is generated. The threat stimulus is anything that has previously been associated with peril, and the narratives are constructed scenarios that involve a threat to the individual. For example, on hearing a rustling of leaves, the individual might construct scenarios of a predator waiting to attack. Such narratives would involve the highest levels of cognition, particularly if the threat is social. But the response has to be fast, suggesting that the 'view' of lower levels of cognition, using simpler inferred states, is important.
That humans should create threat scenarios is not surprising, when we consider threats at a corporate level. Organisational security is routinely tested using penetration tests which use unlikely scenarios to determine how attackers can gain access to sites or data. Significantly, these scenarios include threats which arise from within the organisation either through action or inaction. The point here is not that the individual security mechanisms are necessarily similar to corporate security mechanisms but that in both cases the threats are open and underdetermined. So at the individual level, the construction of threats is not pathological, but a normal cognitive function. However, within the human population there is likely to be some variation in the 'creativity' of the narratives. Highly creative narratives, although unrealistic, confer some protection in unpredictable circumstances, while uncreative narratives make for quick identification. At the extremes, we might expect there to be some dysfunction.

A hierarchical narrative account of OCD
The notion of generated threat scenarios, including threats from within, speaks to 'fear of harm' obsessions in OCD. However it explains part of normal functioning rather than the dysfunction that leads to pathological obsessions. The challenge for any account of OCD is to propose a dysfunction that explains symptoms and which is supported by other evidence. For example, why are obsessions in OCD recurrent in nature, and why do they lead to marked distress [1]?
OCD covers a broad range of symptoms and there is no single set of features in common and peculiar to all instances of the disorder [29, p26]. Rather than confronting the problem of definition, the approach taken here is to explain specific behaviours and symptoms that are found in some individuals with OCD. We begin by examining the results from Gillan et al.'s laboratory study of avoidance behaviour in OCD and control participants [65]. Gillan et al.'s study is important both for its results and for its method, which provides an experimental model for some kinds of compulsion. So we apply the hierarchical narrative account first to Gillan et al.'s study then to specific symptoms of OCD.

Gillan et al. -Excessive avoidance habits
Gillan et al. [65] tested one possibility inspired by the cognitive-behavioural account of OCD. That is, that excessive behavioral repetition in OCD is driven by a failure to learn about safety. They compared a group of 25 individuals having OCD with a matched control group. Participants were asked to avoid an electric shock by responding to a warning stimulus presented on the screen. Two electrodes were used, one connected to each wrist and each delivering a shock at random intervals. The shocks were preceded by a warning stimulus whose color denoted either the right or left wrist as the target. To avoid the shock, participants had to respond within 750ms using a corresponding left or right pedal switch. The experimenters examined the effect of stimulus devaluation on goal-directed learning by disconnecting one of the electrodes in full view of the participant. The task design consisted of four stages: a training session, a first devaluation test, an extended training session and a final devaluation test.
In the first devaluation test, both the OCD group and the control group behaved in a similar way: they responded more to the valued stimulus, which represented a real shock than to the devalued stimulus, which did not. So both OCD patients and control participants were capable of learning about safety. After extended training, the OCD group showed greater avoidance of the devalued stimulus compared with the control group, but there were no measurable differences in contingency knowledge, explicit threat appraisal, or physiological arousal between the groups. Those who responded to the devalued stimulus were asked to account for their action -why did they continue to respond to the stimulus corresponding to the disconnected electrode? The main categories of response were threat beliefs, 'I thought it could still shock me', and accidental responses, 'I lost concentration'. The authors concluded that these findings supported an account of OCD involving habit formation. How might Gillan et al.'s results be explained using the hierarchical model? We consider three questions:

1) Why do some participants continue to respond to a devalued stimulus?
During the experiment the security motivational system in all participants generates prospective narratives which represent the scenario in which a shock occurs. This results in an understanding, or view, that a shock will occur if the participant does not press the correct pedal when the electrode is connected and a stimulus appears. When the electrode is disconnected the SMS continues to generate narratives, and the participant examines these narratives in order to direct their action. Those who responded to the devalued stimulus were unable to form a clear view of the prospective situation, at the lower levels of cognitive inference 3 . If Bayesian learning fails, heuristics may act as a fall back strategy [66], and there is evidence that in a rapidly changing environment, people act according to the last choice that they made [67]. So the participants' action is simply based on a heuristic of selecting the last action that they performed in similar circumstances.
2) Why is some participants' understanding not consistent with their behaviour ?
In the experiment, the participants are aware of the usual conduct of modern psychological experiments, the function of electrical circuits and so on. These external conditions are coded by narratives at the highest level of cognition in both the OCD and control groups. There are also narratives at a lower level of cognition which make use of simpler internal states representing the stimulus and the shock. Both levels of narrative contribute to the individual's conscious view of the situation and to their evaluation of any threat. There is a failure of inference at lower levels of cognition so the individual resorts to a heuristic. However the individual's conscious view of the situation is unitary and it is derived from the most likely inference from all cognitive layers. This highest level of inference remains intact and results in a veridical perspective: the participants who responded to the devalued stimulus were not deluded. Instead they found their behaviour to be inconsistent with what they felt to be their subjective view and understanding of the situation.
3) How do we account for the participants' post-hoc explanations for their behaviour?
Gillan et al. [65] note that 'In situations of cognitive dissonance, where behavior contradicts belief, humans are known to alter beliefs to match behavior [68]. Within this framework, irrational obsessive thoughts in OCD might function to resolve the internal conflict arising from experiencing an otherwise nonsensical urge to avoid.' Resolving the internal conflict between action and understanding necessitates creating a unitary inference to explain one's own behaviour. Clearly this is a difficult task for the participants since they are in effect being asked to explain OCD. According to the hierarchical narrative model, the participants' perception is internally inconsistent, so they can not present a simple answer to explain their behaviour. Situations promoting cognitive dissonance are not uncommon: for example playing the national lottery, or the avoidance behaviour associated with rare diseases are both cases in point. Most participants reported either subjective threat beliefs or accidental slips and these explanations are similar to given by others in situations promoting cognitive dissonance in that they focus on the threat (or reward) or on accidental events rather than on exploring the inconsistency.

The nature of the dysfunction
We suggest that the dysfunction in OCD is a failure of inference at sub-surface levels of the cognitive hierarchy. When an individual has inadequate information to perform inference about a threat, they act both to improve that inference and to respond to the threat. For example a driver slows down on approaching a traffic junction both to avoid a collision and to see the junction more clearly 4 . The system for monitoring threats, the SMS, usually operates silently but in OCD attention returns repeatedly to a non-existent threat. The reason is that lower levels of inference are failing so that the individual is constantly taking action to correct their perspective and to manage a potential threat. The urge to respond is compelling: consider the reaction of a driver whose vision suddenly becomes obscured. This account explains why the compulsion to act is strong and why attention keeps returning to the perceived threat. It also explains why individuals with OCD do not usually believe that a real threat exists: global inference is robust to failures of inference occurring at lower levels, just as it is robust to deficiencies in the sensory data resulting from an occluded scene. So the individual's overall judgement is broadly unimpaired.
Among the human population there is likely to be some variation in the 'creativity', in effect the number, of narratives generated for threat simulation. If there is a propensity towards a broad distribution of p(N |U ) at low levels of cognition, then the posterior distribution becomes less peaked and inference becomes more uncertain. So we locate the dysfunction in the generative process, which in turn causes a failure in inference.

Explaining symptoms of OCD
This section applies the hierarchical narrative models to symptoms of OCD: checking, intrusive thoughts and fear of harm, and ordering and symmetry obsessions.

Checking
An example of checking in OCD cited by de Silva [2, p196] is of someone who repeatedly checks that a gas tap is turned off. The explanation is broadly the same as that for the results of Gillan et al.'s experiment given in the last section. The individual with OCD has a correct understanding that the gas tap is off even though there is a failure of sub-surface levels of inference. The individual's SMS relies on this lower level inference, which does not provide a clear 'view' of the state of the gas tap. As a result the individual has to act both to improve the inference and for self-protection. Since inference about the external world is failing, the individual resorts to their last action under those conditions, and checks the state of the gas tap. However, the act of checking does not rectify the failure in inference so the SMS does not terminate its response to the perceived threat.

Fear of causing harm
An example of the fear of causing harm is a case reported by de Silva [2, p196] of an individual thinking, without justification, that he had knocked someone down with his car. In this case and in the case of checking there is a feeling of uncertainty about the true state of affairs -whether the gas tap is off, and whether an accident has really occurred -accompanied by a recognition that the obsessional thoughts are a product of his or her own mind [1] [55]. The central difference between the examples is that in the case of checking, the threat stimulus is present to the individual whereas with fear of harm, the threat stimulus is no longer present. In both cases, the individual is generating retrospective narratives to examine the scene in memory, and prospective narratives to assess the threat.
The recognition that an accident has not happened shows that the individual's overall perception is functioning correctly and that he is not deluded. In both healthy individuals and those with OCD, the SMS generates narratives and these correctly explain the likely cause: the individual perhaps experiences a bump in the road and correctly explains the cause as, for example, a pothole. In individuals with OCD, a failure of inference at sub-surface levels of the cognitive hierarchy results in an unclear 'view' of the scene. The SMS acts both to protect the individual from a potential threat and to correct the failure of inference. So the individual is forced to finesse their perspective, but since the dysfunction is internal their action does not terminate the SMS.

Intrusive thoughts
Hudak et al. [71] report a case of intrusive thoughts associated with postpartum OCD. A woman was afraid to be alone with her 9 week old son because of her terrifying thoughts of stuffing the baby into a microwave oven. She also reported thoughts about stuffing her husband into a microwave oven which she found even more frightening because she realised that this was physically impossible. The explanation for these thoughts has the same basis as for the examples of checking and fear of harm given above, but with some additions. The SMS constantly creates prospective narratives simulating threat scenarios, in this case involving a microwave, but the dysfunction of sub-surface inference results in an unclear 'view' of the generated scenarios. Without a clear view of a threatening situation, the SMS signals a strong urge to act to correct the perception to ensure that the child is protected. The SMS usually operates silently, and without the individual being aware of the simulated scenarios, but the action brings the process to the individual's attention.
This account identifies the dysfunction with the evaluation of thoughts rather than with their content, so it does not explain the bizarre nature of the obsession where woman thinks of stuffing her husband in the microwave. To explain the aberrant content, we use the more precise description of the dysfunction as an unduly 'creative' generative process 5 In this case the inference at higher levels will struggle to interpret their meaning, so leading to bizarre or absurd inferences. However the global inference which informs unitary perception is intact with the result that the individual is not deluded.

Ordering and symmetry obsessions
Summerfeldt [3] cites an example of a 38-year-old man who had obsessions with themes of: '(1) the need to know or remember details, (2) the need for exactness in behavior and precision of expression, and (3) the need for symmetry and sameness in his physical environment (e.g., his appearance, the alignment of books, the condition of belongings). . . . Distress centered on not the content of obsessions, but . . . on a tormenting sense of hyperawareness and dissatisfaction.' The explanations given earlier for checking, fear of harm and intrusive thoughts have implicated a dysfunction of the SMS. The dysfunction was identified as a failure of inference associated with a failure to obtain 'resonance' in the distribution of p(N |U ) at sub-surface levels of the cognitive hierarchy. With ordering and symmetry obsessions, the involvement of the SMS is less obvious 6 , but the underlying dysfunction affects other functions that rely on modelling external events. The point is illustrated using Figure 6 which shows examples of resonant and dissonant images. The image on the right is dissonant because it is close to a common form but it has one part missing, so it evokes an error at a sub-surface level of inference. The situation is one where we can potentially finesse the inference by some action, such as moving our perspective to reveal the hidden eye. Such 5 Increased 'creativity' in the generative process may arise from the need to protect the infant, in addition to any dysfunction. 6 Although some ordering obsessions are associated with a fear of harm if the associated ritual is suppressed. Figure 6: Examples of resonant and dissonant images. The image on the left resonates with the internal model that generates a face. The dissonant image lacks one eye and it is hard to recognise. In other words, it is hard to use the image to make an inference. The perceptual system acts to finesse inference, or gain resonance, which in this case would involve revealing the missing eye.
an action is normal ordering behaviour which is aimed at bringing about recognition, or resonance. In OCD, this process occurs with ordinary scenes, leading to them appearing 'not just right' [32], and resulting in a compulsion to act. It is the response to prediction error that explains not just ordering behaviour but the dysfunction of the SMS implicated in other manifestations of OCD.

Discussion
We have presented a hierarchical narrative framework of cognition and used it to propose an explanation of OCD. The central concept, the formal narrative, follows from the use of generative models in cognitive inference. The framework consists of the following claims, 1) A hierarchical model of narratives leads to the idea that the human perspective is composed of a hierarchy of layers, each of which contributes to the individual's perspective or 'view of the world'. This idea is reconciled with a unitary perception by considering situations when we do not believe what we see, such as visual illusions.
2) Prospective and retrospective narratives provide a model for mental time travel. Narratives are generated autonomously and constantly by the brain to model the past, present and future.
3) The security motivational system (SMS) generates a collection of narratives in response to a threat. Rather than passively identifying threats, the SMS actively tries to find evidence for the created scenarios. This process is similar to a corporation performing penetration testing in which unlikely risk scenarios are created and evaluated.
The idea that perception is generated is well-established, and it is just a small step to suggest that the generative process can operate autonomously. In [72] Friston et al. proposed that 'the same generative models used to make predictions can be deployed to predict the actions of self or others by simply changing the bias or precision (i.e. attention) afforded to proprioceptive signals.'. A similar idea for employing generative models for prospection, retrospection and mental imagery was put forward in [73].
We suggest that OCD arises from a dysfunction in sub-surface levels of inference while global inference is broadly unimpaired. The dysfunction of inference is caused by an over-creative generative process, which leads to a unusually broad range of potential narratives. The consequent lack of resonance is sensed as the external world being 'not just right', and its automatic correction by the perceptual system is experienced as compulsion. Ordering and symmetry obsessions are thus the effects of the perceptual system trying to achieve precise inference. The failure of inference affects the view not only of current scenes, but also of prospective and retrospective views which the SMS relies on. The dysfunction leads to an individual not having a 'clear view' of prospective scenes, leading to fear of harm or intrusive thoughts. Action by the SMS to protect the individual and finesse the inference is felt as a compulsion to re-check.
Ian Jakes considered the qualities of a good explanation of OCD, citing Imre Lakatos [29, p154], who identified research as theoretically progressive if it leads to new predictions and empirically progressive if the predictions are successful. In this context prediction can be of a fact that is already known as well as predicting a new finding. One of the limitations of psychological explanations of OCD is that they are not formal, and do not make quantitative predictions. The same limitation applies to the explanation in this paper in that the exact form of the hierarchical narrative model is yet to be defined. However there is potential for a formal model which could then be applied to electrophysical data, so closing the explanatory gap between the neural and psychological explanations.