PhD Sébastien Henschel
email: sebastien.henschel@univ-lille3.fr

Prof Jean-Louis Nandrino
email: jean-louis.nandrino@univ-lille.fr

PhD Karyn Doba
email: karyn.doba@univ-lille.fr

Emotion regulation and empathic abilities in young adults: The role of attachment styles

Keywords: Attachment, emotion regulation, affective empathy, cognitive empathy Attachment styles, emotion regulation difficulties, affective empathy, cognitive empathy

Much research has shown strong relationships between attachment security and the development of emotion regulation (ER) and empathic abilities in childhood. However, less is known about how attachment styles influence ER and empathy in adulthood. The aim of this study was to examine how differences in attachment styles influence the relationships between ER and affective and cognitive empathy in adults. From a total sample of 870 participants, 168 individuals were selected according to their specific attachment style and completed self-reports of attachment styles, ER difficulties, and affective and cognitive empathy. Concerning empathic dimensions, anxious individuals reported higher personal distress and fantasy than secure and avoidant individuals. The results also revealed that individuals with anxious attachment had higher ER difficulties than secure and avoidant individuals. Furthermore, partial least square modeling highlighted that the mediating role of ER in the relationship between attachment and empathy varied according to the attachment styles and the dimensions of empathy. This study emphasizes the role of attachment profiles and ER competences in developing cognitive and affective empathic abilities in adults.

Introduction

Attachment and empathy

Despite the well-reported relationships between attachment security and the development of emotion regulation (ER) and empathy in childhood, less is known about how attachment styles affect ER competences and empathy in adults. A fundamental concept of attachment theory suggests that individuals' emotional experiences with primary caregivers lead to the development of secure, avoidant or anxious attachment styles in adult relationships [START_REF] Ainsworth | Patterns of Attachment: A Psychological Study of the Strange Situation[END_REF][START_REF] Bowlby | Developmental psychiatry comes of age[END_REF]. Adults with a secure attachment style are willing to rely on others for support, comfortable with intimacy, and confident that they are valued by others [START_REF] Fraley | Adult Romantic Attachment: Theoretical Developments, Emerging Controversies, and Unanswered Questions[END_REF]. The anxious style is defined by insecurity concerning the responses of others together with a strong desire for intimacy and a high fear of rejection [START_REF] Fraley | Adult attachment and the suppression of unwanted thoughts[END_REF][START_REF] Shaver | Attachment-related psychodynamics[END_REF]. The avoidant style is characterized by insecurity concerning the intentions of others, a rejection of assistance, and reduced expressions of affection and intimacy [START_REF] Edelstein | Avoidant attachment: Exploration of an oxymoron[END_REF][START_REF] Fraley | Adult attachment and the suppression of unwanted thoughts[END_REF]. These different attachment styles correspond to underlying differences in the internal working models of self (such as being worthy or unworthy of support and love) and others (such as responsive or unresponsive) originating from interactions with main caregivers [START_REF] Bretherton | Internal working models in attachment relationships: Elaborating a central construct of attachment theory[END_REF][START_REF] Cassidy | Contributions of attachment theory and research: A framework for future research, translation, and policy[END_REF]. Child-caregiver interactions underlie the development and emergence of internal "working models" consisting of beliefs and expectations about whether the caregiver is caring and sensitive, and whether the self is worthy of attention and care [START_REF] Ainsworth | Patterns of Attachment: A Psychological Study of the Strange Situation[END_REF][START_REF] Bowlby | Attachment and loss[END_REF][START_REF] Main | Security in infancy, childhood, and adulthood: A move to the level of representation[END_REF].

Over time, sensitive caregivers shape the empathic responses of their children. In turn, this behavioral pattern is likely to be integrated into the internal working models of secure children as a script of how to react to the distress of others [START_REF] Hojat | Empathy in patient care: antecedents, development, measurement, and outcomes[END_REF][START_REF] Troyer | The impact of attachment orientations on empathy in adults: Considering the mediating role of emotion regulation strategies and negative affectivity[END_REF]. Empathy corresponds to the ability to understand the minds of others, to feel their emotions outside our own, and to respond with kindness, concern and care to their emotions. It is a multidimensional construct [START_REF] Dan-Glauser | Measuring individual differences in empathy: Evidence for a multidimensional approach[END_REF][START_REF] Decety | The neural pathways, development and functions of empathy[END_REF][START_REF] Decety | From emotion resonance to empathic understanding: A social developmental neuroscience account[END_REF] encompassing an affective component (i.e. tendencies to feel compassion and concern for others) and a cognitive component (i.e. an ability to understand the reasons for another person's emotions and to imagine different viewpoints beyond one's own).

Attachment, emotion regulation and empathy

Attachment theory also suggests that the co-regulation of distress between an infant and caregivers enables the development of the self-regulation of distress, such as the ability to identify, accept, and cope effectively with negative emotions oneself [START_REF] Bowlby | Loss[END_REF][START_REF] Stern | Empathy from infancy to adolescence : An attachment perspective on the development of individual differences[END_REF]. ER refers to an individual's ability to monitor, evaluate, and modulate emotional experiences according to the demands of a specific context or set of goals [START_REF] Gratz | Multidimensional assessment of emotion regulation and dysregulation: Development, factor structure, and initial validation of the difficulties in emotion regulation scale[END_REF][START_REF] Gross | Antecedent-and Response-Focused Emotion Regulation : Divergent Consequences for Experience[END_REF]. It also includes a set of adaptive ER strategies (e.g. positive reappraisal, acceptance and planning) to modify the magnitude and/or the type of the emotional experience [START_REF] Aldao | Emotion-regulation strategies across psychopathology: A meta-analytic review[END_REF][START_REF] Garnefski | Cognitive emotion regulation questionnaire -development of a short 18-item version (CERQ-short)[END_REF]. Studies have shown that individuals with ER difficulties have problems in monitoring, evaluating, and modulating emotional experiences or use maladaptive ER strategies (e.g. self-blame, otherblame, rumination, catastrophizing) [START_REF] Gross | Antecedent-and Response-Focused Emotion Regulation : Divergent Consequences for Experience[END_REF][START_REF] Koole | The psychology of emotion regulation: An integrative review[END_REF]. Substantial research suggests that ER abilities such as high levels of emotion recognition and understanding are central to empathic responding, enabling individuals to see, interpret, and feel the emotions of others without becoming overly distressed themselves [START_REF] Eisenberg | Emotion, regulation, and moral development[END_REF][START_REF] Stern | Empathy from infancy to adolescence : An attachment perspective on the development of individual differences[END_REF].

In this way, ER is thought to play a key role in understanding the link between attachment and empathy [START_REF] Shaver | A lifespan perspective on attachment and care for others: Empathy, altruism, and prosocial behavior[END_REF][START_REF] Stern | Empathy from infancy to adolescence : An attachment perspective on the development of individual differences[END_REF]. Recent studies have demonstrated that ER mediates the relationship between attachment security and empathy in childhood [START_REF] Kim | Relational antecedents and social implications of the emotion of empathy: Evidence from three studies[END_REF][START_REF] Murphy | Attachment's Links with Adolescents' Social Emotions: The Roles of Negative Emotionality and Emotion Regulation[END_REF][START_REF] Panfile | Attachment Security and Child's Empathy: The Mediating Role of Emotion Regulation[END_REF]. A higher level of attachment security is associated with fewer ER difficulties, which in turn lead to increased levels of affective and cognitive empathy [START_REF] Ştefan | The multifaceted role of attachment during preschool: moderator of its indirect effect on empathy through emotion regulation[END_REF]. Such an association has been shown in toddlers [START_REF] Murphy | The influence of attachment security on preschool children's empathic concern[END_REF], children [START_REF] Ştefan | The multifaceted role of attachment during preschool: moderator of its indirect effect on empathy through emotion regulation[END_REF], and adolescents [START_REF] Murphy | Attachment's Links with Adolescents' Social Emotions: The Roles of Negative Emotionality and Emotion Regulation[END_REF], but research in adulthood is scarce.

Early attachment security fosters the development of emotion understanding and empathy capacities in children and contributes to promoting these capacities in adulthood. It is likely that the influence exerted by attachment on empathy is indirect, operating through multiple mediating mechanisms, such as ER. Studies have shown that a secure working model in adults may provide a behavioral script for how to recognize others' needs for help and how to respond empathically [START_REF] Groh | Adults' Autonomic and Subjective Emotional Responses to Infant Vocalizations: The Role of Secure Base Script Knowledge[END_REF][START_REF] Laible | The Differential Relations of Parent and Peer Attachment to Adolescent Adjustment[END_REF][START_REF] Troyer | The impact of attachment orientations on empathy in adults: Considering the mediating role of emotion regulation strategies and negative affectivity[END_REF]. In adults, Troyer & Greitemeyer (2017) found that adaptive ER strategies of reappraisal but not suppression mediated the relationship between attachment security and cognitive empathy. Unlike secure individuals, anxious adults are more likely to engage in distress with exacerbating mental rumination [START_REF] Caldwell | Exploring the Cognitive-Emotional Pathways between Adult Attachment and Ego-Resiliency[END_REF][START_REF] Garrison | Emotional avoidance and rumination as mediators of the relation between adult attachment and emotional disclosure[END_REF][START_REF] Reynolds | Adult attachment styles and rumination in the context of intimate relationships[END_REF]. In addition, anxious individuals tend to seek others' proximity and have a hypersensitivity towards others' emotions [START_REF] Fraley | Adult Attachment and the Perception of Emotional Expressions: Probing the Hyperactivating Strategies Underlying Anxious Attachment[END_REF]. In reaction to others' emotions, anxious individuals tend to focus on their own unregulated emotions, and to project their emotions on others rather than focusing on others' independent emotional states [START_REF] Joireman | Relationships between Dimensions of Attachment and Empathy[END_REF]Mikulincer & Shaver, 2003;[START_REF] Westmaas | The role of attachment in responses to victims of life[END_REF]. Anxious individuals develop a high level of personal distress and a low level of perspective-taking when exposed to others' distress [START_REF] Joireman | Relationships between Dimensions of Attachment and Empathy[END_REF]. Avoidant individuals use strategies to increase their distance from others in stressful situations, which make it difficult for them to empathize with others [START_REF] Burnette | Insecure attachment and depressive symptoms: The mediating role of rumination, empathy, and forgiveness[END_REF][START_REF] Holmberg | Adult attachment styles and stressor severity as moderators of the coping sequence[END_REF]. Indeed, avoidance attachment is associated with low levels of perspective-taking and empathic concern towards people in distress [START_REF] Britton | The Relations Among Varieties of Adult Attachment and the Components of Empathy[END_REF][START_REF] Izhaki-Costi | I do not know you and I am keeping it that way: Attachment avoidance and empathic accuracy in the perception of strangers[END_REF]. Although these studies revealed that attachment might influence the development of empathic abilities, they did not consider the different types of attachment insecurity and ER difficulties in adulthood [START_REF] Murphy | Attachment's Links with Adolescents' Social Emotions: The Roles of Negative Emotionality and Emotion Regulation[END_REF][START_REF] Ştefan | The multifaceted role of attachment during preschool: moderator of its indirect effect on empathy through emotion regulation[END_REF][START_REF] Troyer | The impact of attachment orientations on empathy in adults: Considering the mediating role of emotion regulation strategies and negative affectivity[END_REF].

Consequently, the purpose of the present study was to examine how differences in attachment styles influence ER and the cognitive and affective dimensions of empathy in adults.

The first aim of this study was to compare secure, avoidant and anxious individuals regarding different dimensions of ER and empathy. Unlike individuals with a secure attachment style, we hypothesized that avoidant individuals would show ER difficulties and lower levels of affective and cognitive empathy. For anxious individuals, we also hypothesized that they would show higher levels of ER difficulties and affective empathy associated with a lower level of cognitive empathy. The second aim was to investigate whether the relationships between attachment and empathic abilities (i.e. cognitive or affective) are differently impacted by adaptive ER strategies and ER difficulties, including maladaptive ER strategies, in secure, anxious and avoidant individuals.

Method

Participants

This study was approved by an independent ethics committee (edited out for blind review) and adhered to the tenets of the Declaration of Helsinki. A sample of 870 participants was recruited from a population of college students in different universities. Participants individually completed a questionnaire assessing attachment styles in the presence of the experimenter (Relationship Scales Questionnaire; [START_REF] Griffin | Models of the self and other: Fundamental dimensions underlying measures of adult attachment[END_REF][START_REF] Guédeney | La version française du Relationship Scales Questionnaire de Bartholomew (RSQ, Questionnaire des échelles de relation): étude de validation du construit[END_REF]. To obtain the most sensitive and reliable assessment of attachment style, we created continuous indexes of attachment style by averaging z-transformed data [START_REF] Ognibene | Adult attachment styles, perceived social support and coping strategies[END_REF]. To recruit participants who reported one specific attachment style (e.g. exclusively secure), we selected and assigned participants according to their highest attachment category [START_REF] Ognibene | Adult attachment styles, perceived social support and coping strategies[END_REF]. Therefore, 168 of the 870 students from 18 to 26 years old (109 women; M = 19.96; SD = 2.22) were selected according to their highest category score on the attachment questionnaire, and who reported the most use of one attachment strategy [START_REF] Ognibene | Adult attachment styles, perceived social support and coping strategies[END_REF]. For example, secure participants reported the highest scores in the secure dimension (more than one standard deviation above the sample mean in the secure dimension) and the lowest scores in the anxiety and avoidance dimensions (less than one standard deviation below the sample mean in the anxiety and avoidance dimensions). Three groups were created, namely those with secure (n = 54; 29 women; Mage = 20.09 years; SD = 1.98), anxious (n = 51; 38 women; Mage = 20.48 years; SD = 2.43), or avoidant (n = 63; 42 women; Mage = 19.8 years; SD = 1.86) styles. The three attachment groups were significantly different in RSQ scores (p < .05). For example, the anxious group reported significantly higher scores in the anxious dimensions than participants of the secure and avoidant groups (p < .001). Table 1 summarizes the attachment scores and statistics.

- ---------------------------------------Insert Table 1 about here

--------------------------------------

Procedure

All participants were individually invited to take part in research concerning emotions and empathy in interpersonal relationships. They were informed that their responses to the questionnaires would be anonymous and confidential. There was no compensation for participation. After each participant received an information note of the study and provided written and informed consent to participate, four self-reported questionnaires were administered in an individual room.

Measures

Relationship Scales Questionnaire (RSQ; [START_REF] Griffin | Models of the self and other: Fundamental dimensions underlying measures of adult attachment[END_REF][START_REF] Guédeney | La version française du Relationship Scales Questionnaire de Bartholomew (RSQ, Questionnaire des échelles de relation): étude de validation du construit[END_REF]. This scale includes 30 items that describe "feelings about close relationships" on a 5point Likert scale ranging from 1 (not at all like me) to 5 (very much like me). Participants were asked to rate the extent to which each statement best described their characteristic style in close relationships. RSQ examines three dimensions of attachment relationships: secure, anxious and avoidant. Higher scores reflect a higher correspondence of the participant with the attachment style: (1) secure (Cronbach's α = .60), ( 2) anxious (α = .69), and (3) avoidant (α = .66). Each participant reported a score in each attachment category. Scale (DERS;[START_REF] Dan-Glauser | Measuring individual differences in empathy: Evidence for a multidimensional approach[END_REF][START_REF] Gratz | Multidimensional assessment of emotion regulation and dysregulation: Development, factor structure, and initial validation of the difficulties in emotion regulation scale[END_REF]) is a 36-item self-report measure to assess ER difficulties with responses ranging from 1 (almost never) to 5 (almost always). The DERS contains six subscales assessing ER difficulties in: (1) acceptance of emotional response (α =.87), (2) adopting goal-directed behaviors (α = .90), (3) controlling impulsive behaviors (α = .87), (4) emotional awareness (α = .80), (5) access to ER strategies (α = .80), and (6) emotional identification (α = .74). Higher scores reflect higher ER difficulties.

Difficulties in Emotion Regulation

Cognitive Emotion Regulation Questionnaire. The CERQ [START_REF] Jermann | Cognitive Emotion Regulation Questionnaire (CERQ)[END_REF]) is used to measure ER strategies that characterize the individual's style of responding to stressful events as well as strategies that are used in a particular stressful situation. The CERQ is a 36-item questionnaire, distinguishing different coping strategies. It measures nine adaptive and maladaptive strategies of ER. Maladaptive strategies correspond to (1) self-blame (α = .78), (2) rumination (α = .74), (3) catastrophizing (α = .68) and (4) other-blame (α = .80). Adaptive strategies correspond to (5) acceptance (α = .68) (, (6) positive refocusing (α = .83), (7) refocusing on planning (α = .81), (8) positive reappraisal (α = .87), and (9) putting into perspective (α = .83). Items are measured on a 5-point Likert scale ranging from 1 (almost never) to 5 (almost always). The higher the subscale score, the more a specific strategy is used.

Interpersonal Reactivity Index. The IRI [START_REF] Dan-Glauser | Measuring individual differences in empathy: Evidence for a multidimensional approach[END_REF][START_REF] Gilet | Assessing dispositional empathy in Adults: A french validation of the interpersonal reactivity index (IRI)[END_REF] was developed as a measure of the cognitive and affective components of empathy.

Two subscales measure cognitive empathy: (1) perspective-taking (α = .79) (i.e. the ability to adopt another's perspective or point of view) and ( 2) fantasy (α = .82) (i.e. a propensity to get involved in fictional situations and to identify with fictional characters in books, movies, or plays). Two other subscales measure affective empathy: (3) empathic concern (α = .80) (i.e. the tendency to experience feelings of concern or compassion for others) and (4) personal distress (α = .75) (i.e. the tendency to experience distress or discomfort in response to others' emotional distress). Each subscale consists of seven items and is responded to on a Likert scale ranging from (does not describe me well) to 4 (describes me very well). Higher scores reflect greater affective and cognitive empathy.

Statistical analyses

First, Kruskal-Wallis non-parametric tests, which did not assume the data to be normally distributed, were performed to investigate the effect of attachment group on scores for the dimensions of the IRI, DERS and CERQ. Then, pairwise Mann-Whitney comparisons between secure, anxious and avoidant attachment groups were carried out for dimensions on which a significant effect of attachment style group was found. Bonferroni's correction was applied.

Second, associations between attachment, ER and empathy were assessed using Partial Least Squares Path Modeling (PLS-PM; [START_REF] Vinzi | PLS path modeling: from foundations to recent developments and open issues for model assessment and improvement[END_REF]. The PLS-PM method enables complex cause-effect relationship models to be estimated between observed variables (MVs) and latent variables (LVs). A full path model is composed of two sub-models: the inner model, specifying the relationships between the LVs, and the outer model, describing associations between each LV and its respective MV. For analyses, we used SmartPLS version 3.2.1 software [START_REF] Ringle | SmartPLS 3. Boenningstedt[END_REF].

Results

Intergroup comparisons

Emotion Regulation

For DERS scores, there was a main significant effect of attachment style group on acceptance (χ² = 11.254; p < .01; η² = .116), goals (χ² = 7.265; p < .05; η² = .075), impulsivity (χ² = 13.859; p < .01; η² = .143), strategies (χ² = 14.815; p < .01; η² = .153) and identification (χ² = 16.093; p < .01; η² = .166). Pairwise Mann-Whitney comparisons with Bonferroni's correction revealed that anxious participants had significantly higher scores in acceptance (p < .01), goals (p < .05), impulsivity (p < .01), strategies (p < .001) and identification (p < .01) than secure participants while avoidant participants had significantly higher scores in identification (p < .05) than secure participants. The results are summarized in Table 2.

For CERQ scores, there was an effect of attachment style group on the strategies of rumination (χ² = 7.981; p < .05; η² = .082), self-blame (χ² = 10.965; p < .01; η² = .113) and catastrophizing (χ² = 10.927; p < .01; η² = .113). Pairwise Mann-Whitney comparisons with Bonferroni's correction showed that anxious participants had higher scores in rumination (p < .05), selfblame (p < .01) and catastrophizing (p < .05) than secure participants. The results are summarized in Table 2.

Empathy

There was a main effect of attachment group on perspective-taking scores (χ² = 7.548; p < .05; η² = 0,078), fantasy (χ² = 18.804; p < .01; η² = .194), personal distress (χ² = 18.297; p < .01; η² = .189) and empathic concern (χ² = 23.701; p < .01; η² = .244). Pairwise comparisons with Bonferroni's correction revealed that the anxious group reported significantly higher scores in fantasy and personal distress than the avoidant group and the secure group (p < .001). Likewise, the anxious group reported higher scores in empathic concern than the avoidant group (p < .001). The avoidant participants showed lower scores in empathic concern than the secure group (p < .05). The results are summarized in Table 2. Figure 1 describes a cluster summary of average scores on DERS, CERQ and IRI in the three attachment groups.

- -------------------------------Insert Table 2 and Figure 1 about here-----------------------------------

Structural modeling

Measurement models with PLS-PM

The

Outer model

Three MVs were removed because of non-significant loadings: two for the LV emotion regulation difficulties (i.e. other-blame and difficulties in awareness), and one for the LV cognitive empathy (i.e. fantasy). The resulting outer model consisted of 17 MVs loaded on 5 LVs: attachment, adaptive strategies, emotion regulation difficulties, cognitive empathy and affective empathy. The quality of this outer model was acceptable regarding the unidimensionality of all LVs (all DGrho > 0.70) and cross-loadings. MVs were always more correlated with their respective LVs [START_REF] Hair | The use of partial least squares structural equation modeling in strategic management research: a review of past practices and recommendations for future applications[END_REF].

Inner models for security, anxiety and avoidance

The inner model was built to study the relationships between attachment, adaptive strategies, emotion regulation difficulties, cognitive empathy and affective empathy. The inner model was tested for secure participants (i.e. the security model), for anxious participants (i.e. the anxiety model) and avoidant participants (i.e. the avoidance model).

For the security model, the goodness-of-fit (GoF) index was 0.32 and R² determination coefficients were calculated indicating small-to-moderate values: adaptive strategies (R² = 0.03), emotion regulation difficulties (R² = .12), cognitive empathy (R² = .12), affective empathy (R² = .30). For the anxiety model, the GoF was 0.36 and R² determination coefficients were calculated indicating small-to-moderate values: adaptive strategies (R² = .03), emotion regulation difficulties (R² = .28), cognitive empathy (R² = .11), and affective empathy (R² = .32).

For the avoidance model, the GoF was 0.28 and R² determination coefficients were calculated indicating small-to-moderate values: adaptive strategies (R² = .08), emotion regulation difficulties (R² = .03), cognitive empathy (R² = .12), and affective empathy (R² = .28). Direct and indirect bootstrapped path coefficients are given in Table 3. In this study, the estimated values for path relationships in the structural model were evaluated in terms of sign, magnitude and significance (the latter via bootstrapping) and values of at least 0.3 indicated moderate associations [START_REF] Chin | The partial least squares approach for structural equation modeling[END_REF].

----------------------------------Insert Table 3 about here- ---------------------------------------For secure participants, the direct path results showed moderate associations (|β| > 0.3) between attachment security and emotion regulation difficulties, between emotion regulation difficulties and affective empathy, and between adaptive strategies and cognitive empathy. The results indicated an indirect path between attachment security and cognitive empathy through adaptive strategies. The indirect path results also showed that the indirect effect from attachment security through emotion regulation difficulties to affective empathy was significant (Figure 2).

For anxious participants, the direct path results showed moderate associations (|β| > 0.3) between attachment anxiety and emotion regulation difficulties, between attachment anxiety and affective empathy, between emotion regulation difficulties and affective empathy, and between adaptive strategies and cognitive empathy. The results showed an indirect path between attachment anxiety and affective empathy through emotion regulation difficulties (Figure 3).

For avoidant participants, the direct path results showed moderate associations (|β| > 0.3) between adaptive strategies and cognitive empathy, and between emotion regulation difficulties and affective empathy. The results showed an indirect path between attachment avoidance and affective empathy through emotion regulation difficulties (Figure 4).

---------------------------------Insert Figures 2, 3 and4 about here----------------------------------

Discussion

Differences in emotion regulation and empathy according to attachment style

The first aim of this study was to investigate how attachment styles influence ER difficulties, adaptive strategies of ER, and affective and cognitive dimensions of empathy in adults. First, our results indicated that anxious individuals revealed higher levels of personal distress and fantasy than secure and avoidant individuals. These results are consistent with the study of [START_REF] Joireman | Relationships between Dimensions of Attachment and Empathy[END_REF] showing that attachment anxiety is associated with high levels of personal distress, the tendency to experience distress or discomfort in response to others' emotional distress and different altruistic motivations for the ultimate goal of reducing the needs of another person [START_REF] Gilet | Assessing dispositional empathy in adults: A French validation of the Interpersonal Reactivity Index (IRI)[END_REF]. In addition, the current findings expand these results by showing the importance of fantasy in anxious participants, reflecting their propensity to transpose themselves imaginatively into the emotional lives of fictional characters found in books and movies [START_REF] Dan-Glauser | Measuring individual differences in empathy: Evidence for a multidimensional approach[END_REF][START_REF] Dan-Glauser | Measuring individual differences in empathy: Evidence for a multidimensional approach[END_REF]. Several studies have shown that individuals with higher fantasy levels are more likely to imagine what another is experiencing and then feel those emotions themselves [START_REF] Adams | Empathy, neural imaging and the theory versus simulation debate[END_REF]. Previous studies have found that anxious individuals tend to project their emotions onto others rather than focusing on others' independent affective states [START_REF] Joireman | Relationships between Dimensions of Attachment and Empathy[END_REF][START_REF] Mikulincer | Attachment Theory and Affect Regulation: The Dynamics, Development, and Cognitive Consequences of Attachment-Related Strategies[END_REF][START_REF] Westmaas | The role of attachment in responses to victims of life[END_REF]. In line with these results, our findings suggest that anxious attachment, characterized by high levels of personal distress and fantasy, could lead to a greater overlap between the self and other and impairments in interpersonal relationships [START_REF] Calderoni | Selective cognitive empathy deficit in adolescents with restrictive anorexia nervosa[END_REF][START_REF] Gleason | The role of empathic accuracy in adolescents' peer relations and adjustment[END_REF][START_REF] Ruby | How would you feel versus how do you think she would feel? A neuroimaging study of perspective-taking with social emotions[END_REF].

In addition, avoidant individuals reported lower levels of empathic concern than secure and anxious individuals. These results point out that low levels of empathic concern may be indicative of low social skills and social loneliness in avoidant individuals (DiTommaso, [START_REF] Ditommaso | Attachment styles, social skills and loneliness in young adults[END_REF]. Lastly, a low level of affective empathy in these individuals would be more likely to be associated with overall socio-cognitive difficulties, especially in assessing others' and one's own emotional state [START_REF] Schipper | Relating empathy and emotion regulation: Do deficits in empathy trigger emotion dysregulation[END_REF]. Second, we observed that the different attachment styles were characterized by different ER difficulties. Indeed, anxious individuals showed more ER difficulties than secure individuals, especially in identifying and accepting emotions, controlling impulsivity, pursuing goal-oriented behaviors as well as difficulties in accessing ER strategies. The results also showed that anxious individuals reported a higher use of rumination, self-blame and catastrophization than secure individuals. These findings are congruent with previous studies, which have highlighted that anxious individuals experience negative emotions more intensely, have easier access to negative memories, and have difficulties in suppressing negative feelings [START_REF] Feeney | Adult attachment and emotional control[END_REF][START_REF] Marganska | Adult attachment, emotion dysregulation, and symptoms of depression and generalized anxiety disorder[END_REF][START_REF] Mikulincer | Attachment styles and repressive defensiveness: The accessibility and architecture of affective memories[END_REF]. Our findings suggest that rumination associated with difficulties in accessing adaptive strategies in anxious individuals may constitute a risk factor for severe and prolonged periods of distress [START_REF] Nolen-Hoeksema | Sex differences in unipolar depression: evidence and theory[END_REF][START_REF] Nolen-Hoeksema | Ruminative Coping With Depressed Mood Following Loss[END_REF].

In addition, our results revealed that avoidant individuals showed more difficulties in identifying emotions than secure individuals. These findings are consistent with the growing body of research indicating that avoidant individuals are more likely to engage in deactivating strategies and actively repress a conscious awareness of attachment feelings [START_REF] Fraley | Adult attachment patterns: A test of the typological model[END_REF][START_REF] Mallinckrodt | Attachment, social competencies, social support, and psychological distress[END_REF][START_REF] Wei | Adult attachment, affect regulation, negative mood, and interpersonal problems: The mediating roles of emotional reactivity and emotional cutoff[END_REF]. All these results provide empirical evidence that individuals with different attachment styles show distinct ER abilities, as well as different affective and cognitive empathic capacities. Thus, in adulthood, attachment styles still influence the processing of socio-emotional information by the use of certain emotion regulation strategies and by sensitivity to the distress of partners.

Relationships between attachment, emotion regulation and empathy

The second aim of this study was to investigate whether the relationships between attachment strategies and empathy (i.e. cognitive or affective) are differently impacted by adaptive ER strategies and ER difficulties including maladaptive ER strategies in secure, anxious and avoidant individuals. Although previous research has consistently identified the associations between attachment security and empathy [START_REF] Panfile | Attachment Security and Child's Empathy: The Mediating Role of Emotion Regulation[END_REF][START_REF] Troyer | The impact of attachment orientations on empathy in adults: Considering the mediating role of emotion regulation strategies and negative affectivity[END_REF], our results indicated that attachment styles influenced affective and cognitive empathy through ER difficulties and adaptive ER strategies in more complex ways than previously hypothesized. Specifically, the results highlighted that adaptive ER strategies mediated the relationship between security attachment strategies and cognitive empathy in secure individuals. Secure individuals used more adaptive ER strategies, enabling them to take another person's perspective more adequately. These findings complete the previous results of Troyer and Greitemeyer (2017) demonstrating that the ER strategy of reappraisal provides better cognitive empathy in secure individuals. A key contribution of our results is that the relationship between higher levels of attachment security and higher scores in perspectivetaking was mediated by the use of adaptive ER strategies such as acceptance, positive reappraisal, positive refocusing, putting into perspective and refocusing on planning.

Conversely, there was only a direct association between adaptive ER strategies and cognitive empathy in individuals with avoidant or anxious attachment. The use of adaptive ER strategies and cognitive empathy was not predicted by higher levels of anxious or avoidant attachment and could rather be associated with other psychological processes, such as the quality of the emotion regulation processes of the parents or the level of mentalization (e.g. [START_REF] Fonagy | The capacity for understanding mental states: The reflective self in parent and child and its significance for security of attachment[END_REF]. Furthermore, the results showed that ER difficulties had an important mediating role in the association between adult attachment strategies and affective empathy. They revealed that a high level of attachment security was associated with lower affective empathy (i.e. personal distress and empathic concern) indirectly through lower levels of ER difficulties in secure individuals. This result supports the findings of previous studies [START_REF] Murphy | Attachment's Links with Adolescents' Social Emotions: The Roles of Negative Emotionality and Emotion Regulation[END_REF][START_REF] Panfile | Attachment Security and Child's Empathy: The Mediating Role of Emotion Regulation[END_REF][START_REF] Troyer | The impact of attachment orientations on empathy in adults: Considering the mediating role of emotion regulation strategies and negative affectivity[END_REF] showing that ER abilities mediate the relationship between attachment security and empathy. Another contribution of these results is that higher levels of avoidant and anxious attachment led to an increase in ER difficulties, which in turn contributed to the emergence of higher affective empathy. Finally, these results suggested that avoidance and anxious attachment were associated with ER difficulties, thereby increasing affective empathy, such as personal distress and a tendency to experience feelings of concern or compassion for others. The results also evidenced that anxious attachment had both a direct effect on affective empathy and an indirect effect through ER difficulties. One can suggest that the impact of anxious attachment leads to more severe emotional disturbances than those observed in avoidant individuals. Thus, in future research, we intend to explore the role of emotional variables other than emotion regulation that might serve as mediators between anxious attachment and affective empathy.

Limitations and strengths

Although the current study revealed relevant findings, it has some limitations. The present results were based entirely on self-report measures. Nevertheless, the use of selfreported attachment styles provided a large initial sample, enabling the screening of individuals with specific attachment insecurity (avoidance or anxiety). Replication with other methods of data collection (e.g. observer ratings or other-report) would be useful in future research, which should also include both the Adult Attachment Interview (AAI; [START_REF] George | Adult attachment interview[END_REF] and self-report measures of adult attachment. Interview methods and self-report methods assess different facets of adult attachment. Attachment dimensions measured in self-reports may reflect a stress-diathesis perspective on attachment dynamics, whereas the AAI scoring reflects unconscious processes and states of mind [START_REF] Ravitz | Adult attachment measures: A 25-year review[END_REF]. The second limitation concerns the over-representation of female participants in our sample. Several studies have shown that socio-emotional competences may differ according to gender (e.g. [START_REF] Eisenberg | Sex differences in empathy and related capacities[END_REF][START_REF] Van Der Mark | Development of empathy in girls during the second year of life: Associations with parenting, attachment, and temperament[END_REF]. Another limitation concerns Cronbach's alpha coefficients for the subscales of the RSQ indicating a mean internal consistency between 0.60 and 0.69. These values could be explained by the number of items, which is known to influence strongly the alpha coefficient [START_REF] Cortina | What is coefficient alpha? An examination of theory and applications[END_REF]. When considering the factors resulting from the factor analysis, the test-retest reliability is satisfactory (≥ 0.80) for the scores of the three scales of the RSQ [START_REF] Guédeney | La version française du Relationship Scales Questionnaire de Bartholomew (RSQ, Questionnaire des échelles de relation): étude de validation du construit[END_REF]. Finally, the last limitation concerns the absence of an assessment of suppression among ER strategies. Additional investigations are needed to evaluate other cognitive strategies of ER that may contribute to the relationships between attachment styles and empathy. Although the present results were computed using PLS-PM [START_REF] Vinzi | PLS path modeling: from foundations to recent developments and open issues for model assessment and improvement[END_REF], they are still based on correlational data. Longitudinal studies employing measures of attachment at multiple timepoints may help to clarify how attachment shapes the pathways to ER and empathy at different ages.

Conclusion

Taken together, these findings provide attachment research with empirical support by showing that attachment experiences may influence affective and cognitive empathy, especially through ER abilities in adulthood. The present study emphasizes the importance of differentiating affective empathy from cognitive empathy in order to evaluate whether differences in attachment styles are likely to trigger difficulties in the ability to construct mental representations of distress and to adopt another's perspective as well as to experience compassion or distress in response to others' emotional distress. These distinct capacities could display different trajectories reflecting the different developmental pathways from experiences in attachment relationships.

Finally, the findings of the present study have specific implications for clinical interventions targeting the development of socio-emotional competences. The therapeutic goals might be to restore a sense of attachment security in individuals with high levels of insecure attachment through the identification of specific ER difficulties and maladaptive ER strategies and by helping them develop alternative ER strategies in response to others' distress [START_REF] Gross | Emotion regulation: Taking stock and moving forward[END_REF]. This, in turn, could help them to differentiate their own internal states from those of

  first theoretical model involved 20 MVs (outer model) loaded on 5 LVs (inner model): (1) attachment, (2) adaptive strategies, (3) emotion regulation difficulties, (4) cognitive empathy and (5) affective empathy. The LV attachment corresponds to the factors of RSQ, LV emotion regulation difficulties refer to the factors of DERS and the maladaptive strategies of CERQ, LV cognitive empathy corresponds to the factors of the cognitive components of IRI and LV affective empathy refers to the factors of the affective components of IRI. To consider the specific effects of adaptive strategies (CERQ), which measure distinct aspects of emotion regulation difficulties, adaptive strategies were defined as a LV.

Figure 1 .

 1 Figure 1. Cluster summary of scores in empathy (IRI), emotion regulation difficulties (DERS) and ER strategies (CERQ) in secure, anxious and

  Note. ERD: Emotion Regulation Difficulties. DERS: Difficulties in Emotion Regulation Scale. CERQ: Cognitive Emotion Regulation Questionnaire. IRI: Interpersonal Reactivity Index.

Figure 2 .

 2 Figure 2. PLS-PM graphs for secure participants.

Figure 3 .

 3 Figure 3. PLS-PM graphs for anxious participants.

Figure 4 .

 4 Figure 4. PLS-PM graphs for avoidant participants.

Table 1 .

 1 crises. Journal of Personality and Social Psychology. US: American Psychological Association. https://doi.org/10.1037/0022-3514.80.3.425 Descriptive statistics and intergroup comparisons between secure, anxious and avoidant individuals.

		Secure	Anxious		Avoidant
		(n = 54)	(n = 51)		(n = 63)
		M	SD	M	SD	M	SD	Statistics
	Age	20.09	1.98	20.48	2.43	19.80	1.86	χ² = .866 b
	RSQ -Secure	3.85	.35	2.79	.41	2.82	.43	χ² = 91.239*** a
	RSQ -Anxious	2.90	.54	4.29	.41	2.68	.74	χ² = 83.430*** a
	RSQ -Avoidant	2.79	.53	2.99	.48	3.90	.47	χ² = 60.079***

a Note. a Kruskal-Wallis test. b Chi-Square test. RSQ: Relationships Scale Questionnaire. n: sample size. M: Mean. SD: Standard Deviation. *** p < 001. N =168.

Table 2 .

 2 Descriptive statistics and intergroup comparisons between secure, anxious and avoidant individuals. Note. DERS: Difficulties in Emotion Regulation Scale. CERQ: Cognitive Emotion Regulation Questionnaire. IRI: Interpersonal Reactivity Index. Post-hoc Bonferroni's correction was applied to the p-value in dimensions of IRI, DERS and CERQ. *** p < .001. ** p < .01. * p < .05. N = 168.

				Descriptive statistics					Intergroup comparisons
		Secure	Anxious	Avoidant	Secure -Avoidant	Secure -Anxious	Avoidant -Anxious
		(n = 54)	(n = 51)	(n = 63)
		M	SD	M	SD	M	SD	U	η²	U	η²	U	η²
	IRI
	Perspective-taking	26.481	4.055	24.078	5.469	24.048	5.347	1268.5	0.0484	1002.5	0.0557	1596.5	0.0000
	Fantasy	26.463	5.240	30.078	3.161	26.683	5.012	1660	0.0004	775***	0.1442	957***	0.1220
	Empathic concern	26.500	5.298	27.549	4.627	23.762	5.031	1176.5*	0.0712	1219	0.0099	874.5***	0.1548
	Personal distress	19.556	5.421	24.765	4.727	21.810	5.605	1248.5	0.0529	642***	0.2143	1110*	0.0712
	DERS
	Acceptance	12.259	6.119	16.412	7.346	14.460	6.858	1329	0.0359	869**	0.1024	1331	0.0219
	Goals	15.074	5.421	17.902	4.937	15.778	5.754	1570	0.0044	964*	0.0677	1271	0.0325
	Impulsivity	11.722	5.134	15.863	6.060	13.397	5.796	1406	0.0226	807**	0.1290	1202	0.0472
	Awareness	15.037	4.960	14.843	4.941	16.476	5.708	-	-	-	-	-	-

others and to become more confident in their own emotional processes, thereby facilitating the development of socio-emotional competences (Schipper & Petermann, 2013;Stern & Cassidy, 2017).

grant from funding agencies in the public, commercial, or notforprofit sectors.

Conflicts of interest: None.


Benoit Gaudou

Christophe Lang

Marilleau Nicolas

Guilhelm Savin

Sébastien Rey-Coyrehourcq

Jean-Marc Nicod

Netlogo, An Open Simulation Environment

à la diffusion de documents scientifiques de niveau recherche, publiés ou non, émanant des établissements d'enseignement et de recherche français ou étrangers, des laboratoires publics ou privés.

Introduction to extensions in NetLogo

NetLogo is a generic simulation environment in the sense that it was not designed with any specific domain of application in mind. NetLogo offers a wide range of features and generic operators to its users. Additionally, to make up for any missing features, NetLogo is compatible with other platforms and libraries, as we will demonstrate throughout this book.

There is a vast library of extensions available to users, allowing them to integrate additional functionality that is not present in the native version of NetLogo, but which might nonetheless be necessary for the development of a given model. An official library of extensions is available on the official NetLogo Website. We will explore some of these extensions later in this chapter. But many modelers have also developed their own extensions to tackle specific problems that are of interest to them. These extensions are developed with an open Java API. We will discuss this in more detail in section 1.2.

Conversely, NetLogo can also be called and controlled by other programs, such as OpenMole 1 , Python 2 and R 3 . To do this, NetLogo provides a Java API that allows models to be loaded, executed and gives access to their variables and methods. The usage of this API is presented in detail in section 1.3.

Examples of typical NetLogo extensions

There are many different types of extension. The GitHub page of the NetLogo platform 4 gives one possible list of examples. This list distinguishes between internally developed extensions, which are included with the platform (e.g. GIS or network), and extensions developed by the community, which have to be installed manually (section 1.1.2). In Chapter 3 of Volume 1 [BAN 15a], we presented a number of these extensions (GIS and network) to showcase some of additional functionnalities of NetLogo. Some of these extensions include language extensions, which allow the modeler to manipulate more complex object types than those natively present in NetLogo. Indeed, the language of the platform has relatively few complex structures (unlike most programming languages) and primitives for manipulating them. For instance, the array, table and matrix extensions are now included with NetLogo. However, extensions such as string and file are external.

More generally, the functionalities of the NetLogo language can be augmented with a wide range of extensions, for example to achieve better network management (network and nw), to provide more primitives for network analysis (additional metrics and indicators) or to integrate geographical data represented in vector form into NetLogo models (GIS). This is not an easy task, but this is absolutely necessary, as NetLogo models are natively based on a grid-based discrete environment. As another example, the SQL extension allows models to interact with a database by sending SQL-formatted queries and receiving data in response. Finally, the sound and MIDI extensions allow sounds to be integrated into NetLogo models.

There are a number of extensions that enable NetLogo to interact with other tools. This interaction can take various different forms: it might simply involve reading or writing files that are compatible with a third-party application. For example, it is possible to process image files (bitmap), tabular data (csv), Java 4 https://github.com/Netlogo/Netlogo/wiki/Extensions. system properties (Props), POV rays (RayTracing), VRML (VRML), NetCDF (NetCDF), etc. This allows modelers with different backgrounds to increase the realism of their simulations by exploiting real data in useful formats.

Other extensions allow deeper forms of interaction by directly integrating third-party functionality into NetLogo; for this kind of interaction, NetLogo must be able to connect with another application to send requests and retrieve results, such as Matlab (MATLAB), Prolog (NetProLogo), IODA [KUB 11] (IODA) and Graphstream5 (gs).

For example, the NetLogo language can be extended with primitives allowing it to benefit from the scientific calculation tool R [THI 10], and in particular to call R functions from within a NetLogo model. The R extension for NetLogo can be downloaded on the Netlogo-R-Extension Website6 . It fulfills the task of communicating data between the two tools, and in particular performs type conversions from one language to the other. A working installation of R is required. There is also a reverse extension that allows NetLogo to be called from R, known as RNetlogo7 .

Finally, there are several extensions enabling NetLogo to connect with various types of hardware (sensors, actuators, etc.). Examples include the extensions Arduino (microcontroller), GoGo (sensors) and wiimote (game controller with an accelerometer).

Installing and using extensions in models

The extensions used by NetLogo are located in the extensions folder in the NetLogo root directory. Each extension has its own separate folder.

To use an extension that is not included with NetLogo, it has to first be downloaded (usually as an archive file), unzipped and installed. Installation is extremely simple -the folder extracted from the archive has to copied into the extensions folder. The folder name must be the same as the name of the extension.

To use the primitives provided by the extension in a NetLogo model, we have to first declare the extensions used by the model:

1 extensions [extension_name1 extension_name2]
To use a primitive defined in this extension, we simply call it by its name in the model prefixed by the name of the extension: extension_name1:primitive_name parameters For example, to extend NetLogo functionality to include additional time management functions, we can use the time extension, also known as the NetLogo Time Extension 8 . Once unzipped, the archive produces the folder time-1.3.0 (which corresponds to Version 1.3.0) containing the source files of the extension, documentation, example models and .jar files (Java archives). To use it in a NetLogo model, we have to simply rename this folder as time instead of time-1.3.0, and copy it into the extensions folder 9 .

In order to use this extension, we declare it in the model:

extensions [time]
We can now use the primitives defined by this extension using the prefix time:. For example, time allows us to create a date object (with the create primitive) and to manipulate it, in order to retrieve the day, month or year of this date (get primitive), to perform operations on dates (plus primitive) or to compare dates (is-before, is-after and is-equal primitives) 10 : 8 https://github.com/colinsheppard/time/. 9 In fact, for this extension (and most other extensions), only the .jar files (time.jar and joda-time-2.2.jar) are required. These contain the definitions of the new primitives. 10 Other examples are included with the extension.

Designing and developing extensions

A project that allows minimal extensions to be easily compiled in Scala with SBT or Maven can be found within the GitHub repository Netlogoextension-build-example 11 .

Environment for compiling extensions

Maven and Java

Maven is a software build management system developed by the Apache Foundation. It works by defining and using Project Object Model (POM) files, which contain a set of instructions for successfully building the program.

The first step is to install Maven on the workstation.

Maven works by relying on repositories (local or online) containing the dependencies that must be downloaded at compilation. Since March 2016, NetLogo uses the online repository Bintray 12 , and it is no longer necessary to manually add the Netlogo.jar file to your local repository. Development versions (NetLogo 6.0) are already available from the online repository. However, in this book, we will use the stable Version 5.3.1.

As a reminder, since only NetLogo versions 5.3 and later are available online, we will recall how to register a .jar file in the local repository of your device. Follow the instructions given in the documentation 13 . Once you are in the NetLogo /app/ directory that you wish to install (replace X.X by the version number), you can run the following command from the command line to install the .jar file in the local Maven repository: 11 https://github.com/Spatial-ABM-with-Netlogo/Chapitre-A. 12 https://bintray.com/netlogo/NetLogo-JVM/netlogo. 13 https://maven.apache.org/guides/mini/guide-3rd-party-jars-local.html. mvn install:install-file -Dfile=Netlogo.jar -DgroupId=org.nlogo -DartifactId=Netlogo -Dversion=X.X -Dpackaging=jar

→

For the development of most extensions, the Netlogo.jar file and the scala-library dependency will be enough. Other extensions that use specific NetLogo functions may, however, require other dependencies, most of which will be contained in the .jar files in the NetLogo /app/ directory.

Users who wish to develop extensions in Scala or Java will need to pay attention to the version of NetLogo. NetLogo 5.3 is only compatible with Scala versions 2.9.x, and NetLogo 5.3.1 is only compatible with Scala versions 2.10.x. In both cases, the Java version needs to be 7.x. We have to wait for the next version of NetLogo before we can use Scala 2.10.x with Java 8.x.

The simplest solution for compiling an extension is based on the modification of the JavaHOME variable used by Maven. In Linux, simply type the following command in the terminal before calling the mvn command:

export Java_HOME=/path/to/jdk7/ The pom.xml file and the Maven project that can be used to compile a minimal Java extension may be obtained from the Java-plugin-Netlogo-maven project on GitHub. This project can be directly opened in the software workbench (or IDE) Java IntelliJ.

The pom.xml file contains the list of dependencies to be loaded locally or from the Maven repositories, and also the configuration of two plugins: maven-compiler-plugin and maven-jar-plugin. The first plugin allows the Java sources to be compiled by running the Maven command mvn compile in the project root directory. The second one allows the .jar to be created in the /target repository by running the Maven command mvn install.

SBT and Scala

Simple Build Tool (SBT) is a build system similar to Maven, but which is commonly used to compile sources written in Scala. NetLogo is compiled with SBT, since its most recent versions are written in Scala.

Unlike Maven, which manages dependencies by using pom.xml files, SBT uses files written in Scala to determine the structure of the project and its dependencies. One of the most important such files is build.sbt, which may be found in the project root directory. SBT uses the same online repositories as Maven to download the right dependencies for compiling and packaging extensions in development. The primary SBT file, named build.sbt, uses Netlogo-Extension-Plugin14 , which automatically downloads the right Netlogo.jar file and provides a simplified interface for packaging extensions.

Since NetLogo version 5.3.1 can only be compiled with Java 7, we must tell SBT where to find this version on your device: sbt -Java-home /path/to/Java/home.

Even though it may not be immediately useful in our case, note that it is possible to tell SBT which version of Java it should use to run Java programs by adding the following lines to build.sbt: fork in run := true JavaHome in run := Some(file("/path/to/Java/home/" ))

Finally, the extension is compiled by running the sbt compile command, and the .jar is built by calling sbt package.

Notes on type conversion between NetLogo and Java/Scala

All numeric variables used in NetLogo extensions must be converted into the Double type, as this is the only numeric type accepted by NetLogo. There are tools available to developers for converting from Java/Scala to NetLogo. But conversion in the other direction is not so easy.

Type conversion from NetLogo to Java or Scala is more tricky, in particular for LogoList lists. Since NetLogo lists are able to contain different types, it is impossible to know in advance which types of objects are contained in the list variable. The only solution is to carefully typecast15 each element in the list before performing any operations.

Java

From Java to NetLogo: numeric type conversion can be performed with the command Double.valueOf(valueToConvert). This command wraps the double variables in a Double class, which is understood by NetLogo.

From NetLogo to Java: handling lists requires generous use of try/catch blocks to detect and convert the types of objects contained in the list. We will illustrate this conversion when we present the code of the primitive for calculating the average of a list of values passed as parameters.

Scala

Support for automatic type conversion from Scala to NetLogo has been added by the developers of NetLogo via the following import, which can be added to the start of a program: import org.nlogo.api.ScalaConversions.

Calling the function .toLogoObject on any Scala data type (Boolean, Float, Character, Short, Int, Float, Long, Double, Byte, Seq) initiates the conversion process, which automatically returns a type that is compatible with NetLogo.

With SBT, it is possible to initialize an interactive console, which can access the set of dependencies included in the project. This interactive mode allows us to enter commands directly into a terminal without having to compile or package the extension first.

In the root directory, simply type the command sbt console into a terminal, followed by the following commands: import org.nlogo.api.ScalaConversions._ val myIntValue:Int = 5 myIntValue.toLogoObject // return Java.lang.Double val myFloatValue:Float = 2.2 myDoubleValue.toLogoObject // return Java.lang.Double val myScalaList = Seq(2,3,8) myScalaList.toLogoObject // return org.nlogo.api.LogoList

Commentary of an example extension

The .jar file created by Maven or SBT after executing the second command includes a valid manifest file, which is usually named my-extension.jar. This should be copied into the directory /app/extensions/my-extension in NetLogo 5.3, and then called in the program with the following code: extensions [my-extension].

The extension named my-extension, which we compiled in the previous few sections, allows us to do three things:

-return the sequence of characters "hello world" (print-message); -return the average of the numbers passed as parameters (get-mean); -construct a list of random numbers with length equal to the variable passed as an argument to the primitive (build-a-random-list).

Calling the following command in the NetLogo observer returns the character sequence "hello world": print my-extension:print-message.

Calling the following command in the NetLogo observer returns the average of the list of numbers passed as parameters: print my-extension:get-mean list (10, 12, 15).

Calling the following command in the NetLogo observer returns a list of five random elements: print my-extension:build-a-random-list 5.

The extension code is given in Java in the below examples. Equivalent code in Scala is also available from the GitHub repository containing the examples for compilation with Maven and SBT.

Minimum content of an extension

In order for NetLogo to be capable of loading an extension, the .jar file should contain two elements: a manifest containing NetLogo-specific properties, and a class implementing the ClassManager interface of the org.nlogo.api package. The .jar file must contain all classes associated with the extension.

If additional software libraries are used, they can be placed in the extension folder in the NetLogo extensions directory.

Manifest

The manifest must contain the following three properties:

-Extension-Name, the name of the extension;

The ClassManager

To develop the DefaultClassManager of the extension, we can extend the DefaultClassManager class of org.nlogo.api to reduce the list of methods that we must implement for load(PrimitiveManager). Passing the PrimitiveManager object as a parameter allows us to add new primitives (commands or reporters). To define the call to the three primitives, we replace the comment in the load function with the following code:

Consider the following minimal example of the extension

primitiveManager.addPrimitive("print-message", new MyMessage()); primitiveManager.addPrimitive("get-mean", new ComputeMean()); 3 primitiveManager.addPrimitive("build-a-random-list", new BuildRandomList());

Snapshot of a primitive

The three primitives are placed in three separate Java files, each of which contains the description of a primitive: In the next sections, we describe the way that these functions are called, and the results that they return.

Displaying "hello world"

These primitives do not take any input parameter, and simply return a message. The function Syntax.reporterSyntax() therefore only has one single argument, which indicates the expected type to be returned. Since "hello world" has the type of a string, we use the code Syntax.StringType().

public Syntax getSyntax() { 2 return Syntax.reporterSyntax(Syntax.StringType()); } Other types can be returned, such as Syntax.NumberType(), which indicates that a numerical value should be returned, Syntax.ListType(), indicating that a list is expected, or any other NetLogo object that can be manipulated by an extension, as shown by the list of functions defined in the Syntax object: BooleanType(), AgentsetType(), TurtleType(), PatchType(), LinkType()...

Return the average value of an array of variable size

We can define the call to this primitive in two different ways, either by using the syntax Syntax.NumberType() | Syntax.RepeatableType() to define a repeatable number, or by directly using a variable-size list Syntax.ListType(). Finally, it should also be noted that we can specify as many Syntax.typeName values as the number of arguments that we wish to be returned when we call the primitive. Thus, new int[]{Syntax.NumberType() | Syntax.NumberType(), Syntax.StringType()} indicates a primitive that takes three input arguments, i.e. two numbers and one sequence of characters. In the first case, the primitive is called with: print (my-extension:get-mean 0.0 5.0 10.0), and in the second case with: print my-extension:get-mean list 0.0 5.0 10.0 or print my-extension:get-mean [0.0 5.0 10.0]. The second syntax, shown below, has the advantage of being more easily understood by beginners, but requires developers to check the content of the table before performing any operations. As discussed in the previous section on type conversion, the methods for retrieving the content of the LogoList variables return a collection of Object variables that need to be tested 16 .

Arguments should always be recovered using the "safe methods" provided by the developers of NetLogo, which we wrapped into a method below. 16 Both versions of the code are available from the GitHub repository online.

Future versions of the NetLogo API

Although the NetLogo API has been relatively stable for several versions, it is expected to change with version 6.0.

Here are a couple of changes that have already been confirmed for the future version of the API:

-multiple classes will be renamed or reorganized in future. For example, a new package org.nlogo.core already uses classes from org.nlogo.api, org.nlogo.nvm, and org.nlogo.agent; -DefaultReporter and DefaultCommand will be removed, and org.nlogo.api.Reporter and org.nlogo.api.Command will become easier to extend.

Since this version is still in development, more information can be found on the webpage dedicated to the transition 17 .

Help will be available on the various channels of communication used by the developers of Netlogo: gitter 18 , GitHub 19 and the NetLogo wiki, which details the extensions API 20 , the discussion group 21 , and the StackOverflow 22 website under the NetLogo tag.

Extending the graphical interface

The NetLogo API does not currently allow the development of dedicated graphics widgets. However, it is possible to add a new tab to the interface and directly manipulate its AWT/Swing canvas. We will use the GRAPHSTREAM 23 software library, which allows graphs to be dynamically manipulated. The purpose of the extension is to display a graph showing the set of turtles and the links between them.

For the connection from NetLogo to the graph, we will use the functionality provided by the NetLogoListener interface of the API, which mainly consists of information about events that occur at the NetLogo interface. The method that we are interested in, tickCounterChanged(double), informs us when the system undergoes a new iteration. We can therefore create events to describe the corresponding changes in the graph at these moments.

To "listen" to changes in the graph and propagate these changes to the NetLogo model, the GSNetLogoSink class implements the Sink interface of GraphStream, which connects to the graph. This is a minimal version of the function. It only updates the model in one direction, from NetLogo to GraphStream. Readers can refer to the project source code for more details.

Creating a new tab

The final part of the extension adds a new tab to the NetLogo interface on which the graph will be displayed. We will build on the addTab() method mentioned earlier. We could also add a separate primitive to make displaying the graph optional.

Tabs are managed by JTabbedPane objects (provided by Swing), which can be retrieved through the App object: App.app().tabs().

Example: the RungeKutta extension

In this section, we will present a simple but concrete example of an extension in a few lines.

The rungekutta extension has been used for epidemiological simulation models in Chapter 3. It includes a compute-SIR function taking six Double parameters that calculates the evolution of the population stock passed as an argument using a fourth-order Runge-Kutta numerical integration method applied to the SIR equations. These equations and their solutions are described in more detail in Chapter 3.

Using NetLogo from other platforms

The reason for wanting to use a NetLogo model from outside the NetLogo interface, i.e. from another language, becomes apparent as soon as we become interested in automating NetLogo simulations in batch mode (model exploration), coupling different models together (using the output of one model as the input of another), or supporting compatibility with other programs.

The NetLogo interface is useful because it allows rapid and visual development within the context of an "agile"-type approach, which means that the model is developed and then tested in fast-paced cycles, so that any change is tested as soon as it is written. The interface has graphical objects, which can be used to rapidly construct visualizations of models, and a "batch" mode, which can be used to explore models. However, there are also limitations: the graphics layout is fixed and is not necessarily suitable for operational applications. Batch mode is limited to exhaustive model exploration and only allows integrative coupling (see section 2.5). To overcome these constraints, NetLogo provides a Java API (included in the official distribution) that provides an opening to other environments. This API makes it possible to interact with the model without needing a control interface (modify simulation parameters, retrieve results, execute, etc.), as well as to modify the model (by executing NetLogo commands as if they were entered into the interface "command center"). Due to this API, we can interact with NetLogo from programs such as R or languages such as Python. As described below, this interaction unfolds according to a client/server paradigm, in which software clients such as R or Python send requests to a Java server responsible for executing the NetLogo model. This opening to other programs allows us, for example, to:

-take advantage of all of the features of the host language (R -to exploit all of its statistical primitives, Python -to use numerical calculation libraries (NumPy 25 ), Java -to use JavaFX graphics elements and any other useful libraries); -explore NetLogo models with specific search algorithms (simulated annealing, genetic algorithms or screening), or even combinations of algorithms. Given the amount of time required to execute some simulations 25 http://www.numpy.org. and the size of the parameter space, exhaustive model exploration is often impossible. Choosing a suitable exploration algorithm is the crucial first step toward obtaining results within a reasonable time frame; -couple models by channeling the output of one model to other models with essentially zero language-related constraints due to the numerous gateways available in Java for connecting with other languages.

In the next section, we will give a brief description of the approaches that can be used to establish an interface between NetLogo and Java, Python and R. We will omit any specific details relating to the implementation, and simply explore the basic principles of a simple example of coupling.

Using NetLogo from Java

To run NetLogo commands from Java, we first need to import a library. import org.nlogo.app.App;

In order to run NetLogo programs, the Netlogo.jar file needs to be located in one of the directories known to Java (classpath). The same is true of the lib directory. The latter and the .jar file are included within the NetLogo distribution.

We will illustrate how to use Java to run a simulation with the example of a forest fire, Fire.nlogo, which is included within the NetLogo distribution. From here, it is very simple to run NetLogo commands with App.app.command(), as in the below example. In this case, we assign a value to a variable and run setup.

App.app.command("set number-of-turtles 100"); 2 App.app.command("setup");

In this simulation, we need to be able to retrieve the values of the variables stored in Java. This will allow us to explore the model, either by means of sophisticated processing or suitable visual representations. To retrieve the value of a NetLogo variable, we must use the report function. In the example below, we display the value of the variable number-of-turtles.

System.out.println(App.app().report("number-of-turtles"));

This example is based on the execution of a NetLogo model in "singleton" mode. In this mode, running multiple simulations in parallel with the same model or different models is not possible. The origin of this limitation lies in the fact that these instructions manipulate static objects. The alternative is to use the notion of "workspace". Each simulation is assigned to a workspace, and so one workspace must be created for each simulation. Each workspace acts as a wrapper for the context of the simulation with which it is associated, saving its attributes, model and execution thread.

To implement this approach, we must create an instance of the HeadlessWorkspace class with its default constructor. We can then open a model and execute NetLogo commands. The example below reuses the previous code together with the "Fire" model to execute two simulations in parallel, each with different parameters: More details on these features are available on the NetLogo GitHub page26 . There are technical subtleties relating to memory consumption, controlling threads and the choice of whether to execute via a graphical user interface (GUI) or the command line (Headless).

As well as allowing multiple executions, each with its own context, the Java API provides the key to interoperability with other platforms and development languages. Java has many possibilities and gateways to other languages (C, Python, R, etc.). The NetLogo APIs developed by the community for other programming languages build on these gateways and the native Java API distributed with NetLogo. In the next part of this section, we will consider two examples showing how to use NetLogo from other languages and applications: Python and RNetlogo.

Using NetLogo from Python

Python is a programming language widely used in science, and its popularity continues to grow. It has many different libraries, in particular NumPy, which is extremely useful for scientific computations and numerical simulations of mathematical models based on differential equations.

With NumPy, Python can be viewed as a way of combining mathematical models and multiagent models. Python also proves very useful for dynamically generating experimental protocols and automatically executing them.

There is no direct interface between Python and NetLogo. This means that a Java bridge (JavaGateway) is required, running as a background task. This bridge receives the NetLogo commands from Python and executes them in the model to obtain the desired results.

One example of such a Java bridge was developed by David Masad, and is available on the webpage Bad Networking 27 . We will distribute a modified version that allows multiple simulations to be executed. The sources and executable of the modified version can be downloaded from the GitHub page of this book, at https://github.com/Spatial-ABM-with-Netlogo.

The idea is to run a Java program that will act as a server. The Python program uses a library (package) that allows it to connect to this server. Each time that Python wishes to access NetLogo, it sends a request to the Java program. This program then executes the instructions in the NetLogo model to obtain the desired results.

Thus, executing a NetLogo model form Python unfolds in the following stages:

1) check that the Java bridge is running in the background, otherwise start it up;

2) connect Python to the Java-NetLogo bridge;

3) create as many workspaces as required to run simulations; 4) initialize the simulations with the right parameters; 5) execute the simulations; 6) analyze the results.

The Java server program works according to the above steps. An example of Java and Python code allowing multiple simulations to be simultaneously executed from Python and Java commands is available on the GitHub page of this book.

27 http://davidmasad.com/blog/Netlogo-from-python/http://davidmasad.com/blog/Netlogofrom-python/.

Once you have checked that the Java-Netlogo bridge is running properly, you need to create a JavaGateway object to establish a connection with the Java server.

# import from py4j.Java_gateway import JavaGateway # connect Python to the Java-Netlogo bridge 5 gw = JavaGateway() bridge = gw.entry_point

It is now relatively simple to open an example model by creating a workspace in Java, which is identified by a number in Python:

# create one workspace for each simulation we wish to run sample_models = "/Applications/Netlogo 5.0.2/models/Sample Models/" forest_fire = "Earth Science/Fire.nlogo" 4 wks1 = bridge.createWorkspace() wks2 = bridge.createWorkspace() bridge.openModel(wks1,sample_models + forest_fire) bridge.openModel(wks2,sample_models + forest_fire)

We can now execute the NetLogo commands by specifying the desired workspace with its number (this procedure is specific to our interface):

# Initialize the simulations with the desired parameters # Parameters of the 1st simulation 3 bridge.command(wks1,"set density 62") bridge.command(wks1,"random-seed 0") bridge.command(wks1,"setup") # Parameters of the 2nd simulation 8 bridge.command(wks2,"set density 50") bridge.command(wks2,"random-seed 2") bridge.command(wks2,"setup")

# Run the simulations 13 bridge.command(wks2,"repeat 50 [go]") bridge.command(wks1,"repeat 50 [go]") # Process the results of the simulation ... 8 NLCommand("setup") NLCommand("go") NLDoCommand(10, "go") NLDoCommandWhile("ticks < 200", "go")

We also need to be able to retrieve the values of variables. This can be done very simply with the NLreport() command. As you can see, running NetLogo from R is relatively simple. This allows you to exploit the powerful calculation functions available in R to explore your models.

Discussion

The three examples given above show that accessing and externally controlling a NetLogo model passes through the Java interface distributed with each version of NetLogo.

Java is an expressive language, which makes it possible to develop links to most platforms and languages. The communities of the most commonly used languages in science, such as R and Python, have already created implementations of these links (RNetlogo and Python-Netlogo respectively). Most of these links seem to follow a common pattern, using primitives to load the NetLogo model and then execute commands written in NetLogo.

If the need should ever arise, the Java interface could definitely be used to develop an ad-hoc links with specific functionality. This is the principle behind the Open-Mole platform, a distributed environment for model exploration, which we will discuss in section 5.6.

Deploying NetLogo models online

As well as the classical NetLogo application installed on personal computers, which comes with a well-stocked library of models, NetLogo also exists on the Internet. The NetLogo Web30 application is similar to the desktop version (with somewhat reduced functionality) and can be accessed from a web browser (section 1.4.1). The NetLogo community is extremely active on the Internet and on a number of Websites for publishing models. In the next section, we will present the two best-known of these websites: Modeling Commons31 dedicated to distributing NetLogo models (section 1.4.2) and the more general-purpose web portal OpenABM32 for publishing and sharing models (section 1.4.3).

Netlogo Web

NetLogo Web (http://www.Netlogoweb.org) is one of the official Internet websites of the NetLogo platform. It gives not only a download link for the desktop application, but also provides access to an online implementation of NetLogo via the web browser (see the section presenting NetLogo 1.1). The web version of the NetLogo application allows you to run the models available on the platform, but you can also upload your own models. The usual features are available: the command center, the code editor and information relating to the model description. You can run the application as if it were installed on your personal computer. There are, however, some restrictions, as some features are not yet available. For example, extensions, some languagespecific primitives, file reading and writing, 3D models and BehaviorSpace are not yet available. Therefore, if your model uses one of the features unavailable in the online version, you will need to use the desktop version of NetLogo. If not, this platform is a great way of running models without having to install the application (Figure 1.2).

Modeling Commons

Modeling Commons33 (Figure 1.3) is an Internet-based platform for facilitating collaboration between NetLogo modelers. Users can share their models, as well as edit, create and execute them.

The platform also allows users to save their own personal models, and specify the level of visibility. Models can be set to private, or restricted to a certain specific group of users. The first step is to create a user account (using the platform is completely free). This is only required if you wish to save models online, edit them, or comment on existing models. Browsing and downloading public models do not require logging in.

You can now upload a model (Figure 1.4). The platform will ask you to specify the name of the model, provide the filepath on your computer and optionally upload an image as an illustration. The reading and writing permissions of the model must then be selected. The model can be set to either public or private -collaborators can always be added at a later point. The History tab gives an overview of all versions, and allows you to download each of them. You can also revert to a previous version.

Finally, the update function allows you to create a child version of the current parent model. Child models are created by performing the classical operation of forking, as is common practice within the programming community. The development of the parent and child models then follows independent paths. However, the relationship between the two remains visible in the History tab.

In summary, the Modeling Commons platform is oriented toward sharing NetLogo models. It provides simple and easy-to-access functionality. The ability to manage groups and organized models into projects helps to develop an effective workflow.

OpenABM

OpenABM is a consortium that unites teachers, researchers and professionals with the objective of promoting agent-based modeling. The Website 34 (Figure 1.6) offers a large collection of resources on related topics. 34 http://www.openabm.org.

They already have a very extensive library of community-submitted models. Each model is documented, and the source code is provided. But this platform is much more than just a repository of agent models. The Education section of the website contains an extensive range of tutorials and documentation for helping to develop models. There are also links to online courses, textbooks and a YouTube channel 35 .

A comprehensive selection of resources is available, such as links to development platforms, the websites of modeling-related journals and a wellstocked reading list. There is also a calender of topical events, a forum and job opportunities.

More than anything else, OpenABM is a platform for sharing models and resources on agent-based modeling. As a tool, it is truly comprehensive.

Conclusion

In this chapter, we showed how the openness of the NetLogo platform holds the key to a great amount of potential. This is reflected first and foremost in its extensions, which are numerous. We non-exhaustively listed a couple of examples that we consider to be particularly significant, such as array, R, gis, sound, raytracing, etc. We also took the opportunity to explain how to install and use NetLogo extensions, and showed how to personally design a new extension. We gave a list of compilation environments and explained the mandatory content of a minimal extension.

In section 1.3, we examined the possibility of using NetLogo from other platforms. We considered the cases of Java, Python and R. There are other platforms that can make calls to NetLogo, such as OpenMole, an environment dedicated to exploring models using high-performance computations. We will discuss this further in section 5.6.

Finally, we discussed the different ways of deploying models on the Internet. NetLogo Web allows models to be executed online, and Modeling Commons provides additional features to support collaboration. We ended the chapter by presenting OpenABM, a privileged hub for resources on relevant topics.

-

  Class-Manager, the extension class implementing ClassManager; -Netlogo-Extension-API-version, the version of the NetLogo API used by the extension. If an extension named test has ClassManager implemented by the class MyExtension in the package org.test and uses the NetLogo API 5.1, it needs to have the following Manifest: Manifest-Version: 1.0 Extension-Name: test Class-Manager: org.test.MyExtension Netlogo-Extension-API-Version: 5.3

2/

  /BuildRandomList.Java public class BuildRandomList extends DefaultReporter { ... } //CountCharacter.Java 7 public class CountCharacter extends DefaultReporter { ... } //MyMessage.Java public class MyMessage extends DefaultReporter { ... } These three classes extend the DefaultReporter interface, and so have to implement the following functions: public Syntax getSyntax() {...} public Object report(Argument args[], Context context) throws ExtensionException, LogoException {...}

  The operation that converts LogoList logoListNumbers into ArrayList<Double> numbers is defined as follows in our code: 3 public Object report(Argument args[], Context context) throws ExtensionException, LogoException { final LogoList logoListNumbers = getListOrNull(args); // LogoList return an array of Object, so we need to cast to ArrayListobjectArray = logoListNumbers.toArray(); logoDouble = Arrays.copyOf(objectArray, objectArray.length, Double[].class); }catch (ClassCastException e){ 13 System.out.println("Cast Error, only numbers are supported here");

  the following arguments. We will consider the case of an initial population of 100 individuals: -the population stock S (99 susceptible individuals); -the population stock I (1 infected individual); -the population stock R (0 recovered individual); -the Alpha parameter (rate of recovery I to R = 0.2);

  burned <-NLReport("number-of-turtles")

Figure 1 . 1 .

 11 Figure 1.1. NetLogo Web homepage (March 2016)

Figure 1 . 2 .

 12 Figure 1.2. Interface of one of the models available online (March 2016)

Figure 1 . 3 .

 13 Figure 1.3. Modeling Commons homepage (March 2016)

Figure 1 . 4 .

 14 Figure 1.4. Interface for uploading a model (March 2016)

Figure 1 . 5 .

 15 Figure 1.5. Model management window (March 2016)

Figure 1 . 6 .

 16 Figure 1.6. OpenAbm.org homepage (March 2016)

  MyExtension:

	1 package org.test;
	import org.nlogo.api.DefaultClassManager;
	import org.nlogo.api.ExtensionException;
	import org.nlogo.api.PrimitiveManager;
	6
	public class MyExtension extends DefaultClassManager {
		@Override
		public void load(PrimitiveManager primitiveManager) throws
		ExtensionException {
		//Declare primitives
	11	}
	}

  GSNetLogoSink is structured as follows:

		Link l = (Link) a;
		String edgeId = getLinkId(l);
		Edge edge = ext.getGraph().getEdge(edgeId);
		if (edge == null)
		edge = ext.getGraph().addEdge(edgeId, getTurtleId(l.end1())
		→	getTurtleId(l.end2()), l.isDirectedLink());
		edges.add(edge);
	}
	// Remove non-existent edges
	Iterator<Edge> itEdges = ext.getGraph().getEdgeIterator();
	while (it.hasNext()) {
	import org.nlogo.api.NetLogoAdapter; Edge e = it.next();
	import org.graphstream.stream.Sink; if (!edges.contains(e))
	it.remove(); public class GSNetLogoSink extends NetLogoAdapter implements Sink { } protected World world; protected GSExtension ext; }
	public GSNetLogoSink(GSExtension ext) {
	this.ext = ext;
	}
	// NetLogoListener
	public void tickCounterChanged(double arg0) { ... }
	// Sink
	public void nodeAdded(String sourceId, long timeId, String nodeId) {
	→	... }
	public void nodeRemoved(String sourceId, long timeId, String nodeId) {
	→	... }
	public void edgeAdded(String sourceId, long timeId, String edgeId,
		String fromId, String toId, boolean directed) { ... }

→ public void edgeRemoved(String sourceId, long timeId, String edgeId) { ... } → // ... other methods of Sink not used here }

http://graphstream-project.org.

http://r-ext.sourceforge.net/.

http://cran.r-project.org/web/packages/RNetlogo/index.html. 4 Agent-based Spatial Simulation with NetLogo 2

https://github.com/Netlogo/Netlogo-Extension-Plugin.

Also known as type coercion, this means converting a variable from one type to another.

https://github.com/Netlogo/Netlogo/wiki/Controlling-API.

http://www.Netlogoweb.org/.

http://modelingcommons.org/account/login.

https://www.openabm.org/.

http://modelingcommons.org.

http://www.youtube.com/user/CoMSESNet/.

}

ArrayList<Double> numbers = new ArrayList<Double>(Arrays.asList(logoDouble));

18 return average(numbers);

}

Other conversion methods probably exist, but this topic is currently little documented on the official website. Note that in this last example wrapping the variable returned by the function average(numbers) in a Double is not strictly necessary, as Java can perform "autoboxing" in certain conditions: http://docs.oracle.com/Javase/tutorial/Java/data/autoboxing.html.

Construct and return a table of variable size

The first argument new int[]{Syntax.NumberType()} of the function Syntax.reporterSyntax() states that the primitive expects an integer input. The second argument Syntax.ListType() tells NetLogo that a list will be returned. Lists can be constructed using a "builder" provided by the developers:

Adding a Double (not double) can be achieved with a simple loop as a function of the value n, assigned by calling the getIntValue() method of the class Argument on the table args[0]: for (int i = 0; i < n; i++) { list.add(Double.valueOf(r.nextDouble())); }

The following code provides the basic structure of the extension. We will later show how to develop one part of the missing content. The code is available in full on GitHub 24 .

NetLogo/GraphStream connection

In a simulation, the NetLogo model and the graph coexist separately, and consistency needs to be maintained between them. Modifications affecting the NetLogo model must therefore update the graph, and vice versa. The GSNetLogoSink class of the extension is dedicated to managing this connection.

To establish the connection between NetLogo and GraphStream, we must create a shared procedure for identifying agents (nodes) and their connections (edges). We assume that these objects are characterized by a sequence of characters of the form breedName.agentNumber. We can therefore add a method that retrieves the identifier of a Turtle object: The tickCounterChanged(double) method needs to contain code allowing the NetLogo model to be compared with the contents of the graph. To do this, we need to iterate over the agents and their existing connections. This iteration is provided by the World object and its methods turtles() and links(). A minimal version of the function might look like this: -the Beta parameter (rate of infection S to I = 0.5/100); -the integration step h.

The following report block passes these arguments to the function that calculates the evolution step: Once the arguments have been safely retrieved using getDoubleValue, the values are passed to the rungeKuta4(...) function, which performs integration then returns an updated table of the SIR stock Array(ds,di,dr). We still need to convert this table into LogoList using the automatic conversion function .toLogoList.

Here is an example of how this method can be called in NetLogo:

show rungeKuta:compute-SIR 99.0 1.0 0.0 0.2 (0.5 / 100) 0.01 This call returns the following values, which describe the propagation of infection:

[98.99504281588354 1.0029542312962296 0.00200295282023009] The source code of this extension is available in the repository for Chapter 1.

We can now retrieve the values of the variables and display them:

... 2 # Process the results of the simulation burned_trees = [0]*2 burned_trees[0] = bridge.report(wks1,"burned-trees") burned_trees[1] = bridge.report(wks2,"burned-trees")

7 print "the average number of burned tree is: ", sum(burned_trees)/float(len(burned_trees))

As you can see, this works the same way as Java, except that we can now use the advanced features offered by Python to automatically execute a parametrized series of models and construct all sorts of visual results, for example using libraries such as matplotlib.

Exploring and analyzing models with R

NetLogo can be called from R using RNetlogo 28 . As presented in the article (https://www.jstatsoft.org/article/view/v058i02), this package is also based on the NetLogo Controller API (in Java), with an additional layer that provides a connection between Java and R. The package can be installed as usual with the following command in R:

install.packages("RNetlogo")

Once the package is installed, it simply needs to be loaded. This must be performed once for each NetLogo session, and is done with the following function:

library("RNetlogo")

We can now run NetLogo from R. As was the case for Java, there are two available modes: GUI and headless, i.e. with a graphical interface or from the command line. To launch the GUI mode 29 : install.packages(c("JGR","Deducer","DeducerExtras"))

To actually run it, we need to execute the following commands:

Sys.setenv(NOAWT=1) library(JGR) Sys.unsetenv("NOAWT") 4 JGR() Next, run NetLogo: 1 nl.path <-"/Applications/Netlogo 5.3.1/Java/" NLStart(nl.path)

We can now control NetLogo with R. For example, we can load a model (or in our example a library of models using the function NLLoadModel in R), execute commands on models (with the function NLCommand) and modify the values of model parameters or execute individual model methods (for example, setup then go).

;; Load a model model.path <-file.path("models", "Sample Models", "Earth Science", "Fire.nlogo") 3 model.library.path <-"/Applications/Netlogo 5.3.1/" NLLoadModel(file.path(model.library.path, model.path)) ;; Execute commands on this model NLCommand("set density 77") 29 The path is the path to the folder with the Netlogo.jar archive. However, users running Mac OS X or Linux who wish to run NetLogo in GUI mode will need to use JGC. The installation steps are given on this page: http://www.deducer.org/pmwiki/pmwiki.php?n= Main.MacOSXInstallation.