diff --git "a/data_all_eng_slimpj/shuffled/split2/finalzzqgwo" "b/data_all_eng_slimpj/shuffled/split2/finalzzqgwo" new file mode 100644--- /dev/null +++ "b/data_all_eng_slimpj/shuffled/split2/finalzzqgwo" @@ -0,0 +1,5 @@ +{"text":"\\section{Introduction}\nThe effect of shilling attacks on recommender systems, where malicious users create fake profiles so that they can then manipulate algorithms by providing fake reviews or ratings, have been long studied. Previous work has characterized and modeled shilling attacks on recommenders, defined new metrics to quantify the impacts of these attacks on known recommender algorithms, and applied a \\emph{detect+filtering} approach to mitigate the effects of spammers on recommendations (see recent survey~\\cite{burke2015robust}). We observe from the literature that empirical analysis thus far has focused on assessing the robustness of recommender systems via \\textit{simulated attacks}~\\cite{burke2015robust,seminario2013accuracy}. Unfortunately, there is lack of evidence on what is the impact of fake reviews or fake ratings in a \\textit{real-world }setting.\n\nWe present a preliminary analysis conducted to understand the influence of fraudulent reviews on the recommendation process. We do this through an initial study on known datasets with gold standards in different domains and a commonly-used recommendation algorithm. Our goal is to shed light on the effect of this attack and identify gaps to be addressed in the future by seamlessly connecting\nrecommender and data mining research, as the latter has a rich body of work when it comes to spam detection and prevention. \n\n\n\\section{Analysis Framework}\n\n\n{\\bf Datasets.} We use two real-world datasets (Table~\\ref{fig:datasets}) that offer information about fraudulent reviews,\nwhich we treat as ground truth.\n\n{\\em Yelp!}~\\cite{MukherjeeV0G13}: This dataset consists of Yelp reviews from two domains: hotels (\\textbf{YH}) and restaurants (\\textbf{YR}). Yelp filters fake\/suspicious reviews and puts them in a spam list. A study found the Yelp filter to be highly accurate~\\cite{Bloomberg} and researchers have used filtered spam reviews as ground truth for spammer detection (e.g., ~\\cite{RayanaA15}). Spammers, in our case, are users who wrote at least one filtered review. \n\n{\\em Amazon}~\\cite{McAuleyL13}: Here we consider reviews from two domains: beauty (\\textbf{AB}) and health (\\textbf{AH}). In this case, we define ground truth following the framework in ~\\cite{FayaziLCS15}, which is based on helpfulness votes.\nThus, we treat as a spammer every user who wrote at least one review in which he rated a product as 4 or 5 and has helpfulness ratio $\\leq 0.4$. \n\n\\begin{table}[t]\n\\begin{tabular}{@{}lcccc@{}}\n\\toprule\n\\textbf{Dataset} & \\multicolumn{1}{l}{\\textbf{Users}} & \\multicolumn{1}{l}{\\textbf{Items}} & \\multicolumn{1}{l}{\\textbf{Ratings}} & \\multicolumn{1}{l}{\\textbf{Spammers}} \\\\ \\midrule\n\\textit{Amazon-Beauty} & 167,725 & 29,004 & 252,056 & 3.26\\% \\\\\n\\textit{Amazon-Health} & 311,636 & 39,539 & 428,781 & 4.12\\% \\\\\n\\textit{Yelp!-Hotel} & 5,027 & 72 & 5,857 & 14.92\\% \\\\\n\\textit{Yelp!-Restaurant} & 34,523 & 129 & 66,060 & 20.25\\% \\\\ \\bottomrule\n\\end{tabular}\n\\caption{Summary of datasets}\\vspace{-8mm}\n\\label{fig:datasets}\n\\end{table}\n\n\n{\\bf Experimental setting.} In this paper, we analyze the robustness to shilling attacks of matrix factorization (MF), a commonly-used recommender algorithm. \nWe used probabilistic MF~\\cite{mnih2008probabilistic} with 40 latent factors and 150 iterations. We performed 5-fold cross-validation and measured the performance in terms of \\textit{RMSE}\\footnote{Using \\textit{hitRatio}, we obtained similar outcomes. Thus, due to space limitations, we excluded that metric from our discussion.} only for non-spam users. We also used \\textit{prediction shift} (PS), a measure explicitly defined to quantify the impact of spammer attacks on recommenders, which captures the average changes in predicted ratings~\\cite{burke2015robust}~\\footnote{In addition to PS, we considered \\textit{stability of prediction}, another common measure to quantify spammer attacks. As it is inversely proportional to PS, we only report PS.}.\n\n\\section{Results \\& Discussions}\nWe discuss the effect of fake reviews on recommendations offered to users in \\textit{real-world }scenarios, as opposed to \\textit{simulated} attacks.\n\n{\\bf Do spam ratings affect recommendations?}\nBy following the classical evaluation framework for shilling attacks on recommender systems~\\cite{burke2015robust}, we measured the performances on the original dataset (with spam) and when we remove all the reviews written by spammers (shilling attack).\nWe report the results of our assessment in Table~\\ref{fig:results}.\n\nWe anticipated a lower RMSE when removing spam. However, we did not observe this trend among most datasets in our study. This result aligns with previous work reporting (simulated) shilling attacks are not detectable using traditional measures of algorithm performance~\\cite{LamR04}. \nPrevious works also show PS values ranging from 0.5 to 1.5 when shilling attacks are simulated. However, we observe very low values in real-world scenarios: in our case, considered, PS ranges from 0.047 to 0.15, which we argue is not enough to promote or demote products attacked by the spammers. \nWe believe this to be one of the reasons why algorithm robustness is not reflected by average metrics like RMSE. \nFurther, looking at users as a whole does not help us quantify how much spammers are able to deceit recommenders or who are the users that are affected the most.\n\n\\begin{table}[h]\n\\begin{tabular}{@{}lcc@{}}\n\\toprule\n\\textbf{Dataset} & \\multicolumn{1}{l}{\\textbf{\\begin{tabular}[c]{@{}c@{}}W\/ Spammers\\\\(RMSE, PS)\\end{tabular}}} & \\multicolumn{1}{l}{\\textbf{\\begin{tabular}[c]{@{}c@{}} W\/o Spammers \\\\RMSE\\end{tabular}}} \\\\ \\midrule\n\\textit{Amazon-Beauty} & (0.871, 0.122) & 0.901 \\\\\n\\textit{Amazon-Health} & (1.056, 0.047) & 1.053\\\\\n\\textit{Yelp!-Hotel} & (1.124, 0.150) & 1.125\\\\\n\\textit{Yelp!-Restaurant} & (1.039, 0.133) & 1.034 \\\\ \\bottomrule\n\\end{tabular}\n\\caption{RSME and PS on datasets with and without spam.}\\vspace{-6mm}\n\\label{fig:results}\n\\vspace{-1.5mm}\n\\end{table}\n\n\\begin{figure}[t]\n\\includegraphics[width=0.45\\textwidth]{restaurant_plot2.png}\n\\vspace{-3mm}\n\\caption{Yelp-Restaurants (YR); RMSE differences for ranges [0.4,0.5] and [0.7,1] are significant, $p<0.001$.}\\label{fig:plotYelp}\n\\vspace{-4.25mm}\n\\end{figure} \n{\\bf Who is really affected by spammers?}\nTo better understand\nwhich users are really affected by spammers, we analyzed users based on their \\textit{reliability}: the ability of a user to rate a product according to what it deserves; as in \n~\\cite{icdm16}. The rating a product deserves often aligns with what the majority of benign users think about that product given that they outnumber spam users.\nThen, a \\textit{reliable} user is one that always rates according to what a product deserves, whereas an \\textit{unreliable} user deviates from that value. It seems, however, that by this definition spammers are unreliable as they may try to promote or demote a product by rating it differently than benign users. However, benign users may also be mistakenly treated as unreliable users, if they happen to be the type of users that disagree with average ratings assigned by the majority. \n\nFigures~\\ref{fig:plotYelp} and~\\ref{fig:plotAmazon} illustrate how the RMSE varies according to the reliability of the users and the distribution of user reliability in YR\nand A\n\\footnote{Results are similar for the other two datasets, excluded for space limitations.}. We observe that spammers and benign users have similar reliability distributions.\nUnfortunately, this is why spammers are able to camouflage as benign users very well, in terms of reliability. Regarding RMSE, we see that benign users that benefit from removing spam when generating recommendations are either \\textit{unreliable} users or \\textit{very reliable} ones. This result depends on spammers' reliability. Intuitively, the users more affected by spammers are the ones exhibiting a rating behavior very different from the spammers. Thus, \\textit{traditional} spammers, i.e., unreliable ones, impact reliable benign users (right tail of the plots), while \\emph{smart} spammers, i.e., the ones that are able to camouflage themselves as reliable benign users, affect unreliable benign users, i.e., those who disagree with the average (left tail). This latter result aligns with what observed for trust-based recommenders~\\cite{golbeck2006generating}, which is not unexpected if we think \nof spammers as untrusted users in the network, in our case\n\nOverall,\n26.6\\% (4\\%, 5.6\\%, 0.7\\%) of benign users receive worse recommendations in presence of spam on YR (YH, AH, AB, resp.\n. We infer that the high (low, resp.) percentage observed for YR (AB, resp.)\nis due to the proportion of spam in the dataset (see Table \\ref{fig:datasets}). In a real-world scenario, the aforementioned percentages would translate into hundreds of thousands of users who would not be equally satisfied by recommenders that are not robust to shilling attacks.\nWe believe this to be why this area warrants further study to make recommender algorithms not only \\textit{more robust}, but also able to better serve \\textit{all type of users} through stricter spam detection.\n\n\n\n\\section{Conclusions \\& Future Work}\nWe have presented the results of an initial empirical analysis that has allowed us to demonstrate that trends observed as a result of simulated shilling attacks on recommender algorithms remain the same in a real-world scenario. We validated that average metrics are not able to properly capture attack effect and that in the presence of spam, recommender algorithms are not uniformly robust for all type of benign users.\nThese initial discoveries lead us to argue in favor of\nnew algorithms that are not only robust to attacks, but that also ensure that all users are protected against spam while supporting spam detection that accurately spots the subset of spammers who in fact affect recommendations without mistreating non-traditional users (i.e., users whose taste differs from the popular)\nas spammers.\n\n\\begin{figure}[t]\n\\includegraphics[width=0.45\\textwidth]{health_plot2.png}\n\\vspace{-3mm}\n\\caption{Amazon-Health (AH); RMSE differences for ranges [0.2,0.4] and [0.7-1] are significant $p<0.01$.}\\label{fig:plotAmazon}\n\\vspace{-5.25mm}\n\\end{figure}\n","meta":{"redpajama_set_name":"RedPajamaArXiv"}} +{"text":"\\section{Introduction}\nCancer is an evolutionary process taking place within a genetically and functionally heterogeneous population of cells that traffic from one anatomical site to another via hematogenous and lymphatic routes \\cite{bib1,bib7,bib12,bib53,bib60}. The population of cells associated with the primary and metastatic tumors evolve, adapt, proliferate, and disseminate in an environment in which a fitness landscape controls survival and replication \\cite{bib31}. Tumorigenesis occurs as the result of inherited and acquired genetic, epigenetic and other abnormalities accumulated over a long period of time in otherwise normal cells \\cite{bib28,bib49}. Before we can typically detect the presence of a tumor, the cells are already competing for resources in a Darwinian struggle for existence in tissues that progressively age and evolve. It is well established that the regenerative capacity of individual cells within a tumor, and their ability to traffic multi-directionally from the primary tumor to metastatic tumors all represent significant challenges associated with the efficacy of different cancer treatments and our resulting ability to control systemic spread of many soft-tissue cancers \\cite{bib36,bib59}. Details of the metastatic and evolutionary process are poorly understood, particularly in the subclinical stages when tumors are actively developing but not yet clinically visible \\cite{bib52}. It could be argued that in order to truly understand cancer progression at the level in which quantitative predictions become feasible, it is necessary to understand how genetically and epigenetically heterogeneous populations of cells compete and evolve within the tumor environment well before the tumor is clinically detectable. Additionally, a better understanding of how these populations develop resistance to specific therapies \\cite{bib16,bib22} might help in developing optimal strategies to attack the tumor and slow disease progression.\n\nEvolutionary game theory is perhaps the best quantitative framework for modeling evolution and natural selection. It is a dynamic version of classical game theory in which a game between two (or more) competitors is played repeatedly, giving each participant the ability to adjust their strategy based on the outcome of the previous string of games. While this may seem like a minor variant of classical (static) game theory, as developed by the mathematicians von Neumann and Morgenstern in the 1940's \\cite{bib57}, it is not. Developed mostly by the mathematical biologists John Maynard Smith and George Price in the 1970s \\cite{bib29,bib30} and Martin Nowak and Karl Sigmund \\cite{bib44,bib47} more recently, this dynamic generalization of classical game theory has proven to be one of the main quantitative tools available to evolutionary biologists (with a mathematical bent) whose goal is to understand natural selection in evolving populations. In this biological context, a strategy is not necessarily a deliberate course of action, but an inheritable trait \\cite{bib50}. Instead of identifying Nash equilibria, as in the static setting \\cite{bib34,bib35}, one looks for evolutionary stable strategies (ESS) and fixation probabilities \\cite{bib19,bib44} of a subpopulation. This subpopulation might be traced to a specific cell with enhanced replicative capacity, for example, that has undergone a sequence of mutations and is in the process of clonally expanding \\cite{bib48}. A relevant question in that case is what is the probability of fixation of that subpopulation? More explicitly, how does one subpopulation invade another in a developing colony of cells? \n\nOne game in particular, the Prisoner's Dilemma game, has played a central role in cancer modeling (as well as other contexts such as political science and economics) \\cite{bib2,bib3,bib4,bib10,bib11,bib14,bib15,bib17,bib18,bib19,bib20,bib21,bib23,bib45,bib46,bib47,bib54,bib55,bib56,bib58}. It was originally developed by Flood, Dresher and Tucker in the 1950s as an example of a game which shows how rational players might not cooperate, even if it seems to be in their best interest to do so. The evolutionary version of the Prisoner's Dilemma game has thus become a paradigm for the evolution of cooperation among a group of selfish individuals and thus plays a key role in understanding and modeling the evolution of altruistic behavior \\cite{bib2,bib3}. Perhaps the best introductory discussion of these ideas is found in Dawkins' celebrated book, The Selfish Gene \\cite{bib8}. The framework of evolutionary game theory allows the modeler to track the relative frequencies of competing subpopulations with different traits within a bigger population by defining mutual payoffs among pairs within the group. One can then define a fitness landscape over which the subpopulations evolve. The fitness of different phenotypes is frequency dependent and is associated with reproductive prowess, while the `players' in the evolutionary game compete selfishly for the largest share of descendants \\cite{bib19,bib58}. Our goal in this article is provide a brief introduction to how the Prisoner's Dilemma game can be used to model the interaction of competing subpopulations of cells, say healthy, and cancerous, in a developing tumor and beyond.\n\n\\section{The prisoner's dilemma evolutionary game}\nAn evolutionary game between two players is defined by a 2 x 2 payoff matrix which assigns a reward to each player (monetary reward, vacation time, reduced time in jail, etc.) on a given interaction. Let us call the two players A and B. In the case of a prisoner's dilemma game between cell types in an evolving population of cells, let there be two subpopulations of cell types which we will call `healthy', and `cancerous'. We can think of the healthy cells as the subpopulation that is cooperating, and the cancer cells as formerly cooperating cells that have defected via a sequence of somatic driver mutations. Imagine a sequence of `games' played between two cells (A and B) selected at random from the population, but chosen in proportion to their prevalence in the population pool. Think of a cancer-free organ or tissue as one in which a population of healthy cells are all cooperating, and the normal organ functions are able to proceed, with birth and death rates that statistically balance, so an equilibrium healthy population is maintained (on average). Now imagine a mutated cell introduced into the population with enhanced proliferative capability as encoded by its genome as represented as a binary sequence of 0's and 1's carrying forward its genetic information (which is passed on to daughter cells). A schematic diagram associated with this process is shown in Figure 1. We can think of this cancer cell as a formerly cooperating cell that has defected and begins to compete against the surrounding population of healthy cells for resources and reproductive prowess. From that point forward, one can imagine tumor development to be a competition between two distinct competing subpopulations of cells, healthy (cooperators) and cancerous (defectors). We are interested in the growth rates of a `tumor' made up of a collection of cancer cells within the entire population, or equivalently, we are interested in tracking the proportion of cancer cells, $i(t)$, vs. the proportion of healthy cells, $N-i(t)$, in a population of $N$ cells comprising the simulated tissue region. \n\nTo quantify how the interactions proceed, and how birth\/death rates are ultimately assigned, we introduce the 2 x 2 prisoner's dilemma payoff matrix:\n\n\\begin{equation} \\label{eqn1}\nA = \\left( \\begin{array}{cc}\na & b \\\\\nc & d \\end{array} \\right) = \\left( \\begin{array}{cc}\n3 & 0 \\\\\n5 & 1 \\end{array} \\right) \n\\end{equation}\n\nThe essence of the prisoner's dilemma game is the two players compete against each other, and each has to decide what best strategy to adopt in order to maximize their payoff. This 2 x 2 matrix assigns the payoff (e.g. reward) to each player on each interaction. My options, as a strategy or, equivalently, as a cell type, are listed along the rows, with row 1 associated with my possible choice to cooperate, or equivalently my cell type being healthy, and row 2 associated with my possible choice to defect, or equivalently my cell type being cancerous. Your options are listed down the columns, with column 1 associated with your choice to cooperate (or you being a healthy cell), and column 2 associated with your choice to defect (or you being a cancer cell). The analysis of a rational player in a prisoner's dilemma game runs as follows. I do not know what strategy you will choose, but suppose you choose to cooperate (column 1). In that case, I am better off defecting (row 2) since I receive a payoff of 5 instead of 3 (if I also cooperate). Suppose instead you choose to defect (column 2). In that case, I am also better off defecting (row 2) since I receive a payoff of 1 instead of 0 (if I were to have cooperated). Therefore, {\\em no matter what you choose, I am better off (from a pure payoff point of view) if I defect}. What makes this game such a useful paradigm for strategic interactions ranging from economics, political science, biology, and even psychology \\cite{bib2,bib29,bib58} is the following additional observation. {\\em You will analyze the game in exactly the same way I did (just switch the roles of me and you in the previous rational analysis), so you will also decide to defect no matter what I do}. The upshot if we both defect is that we will each receive a payoff of 1, instead of each receiving a payoff of 3 if we had both chosen to cooperate. The defect-defect combination is a Nash equilibrium \\cite{bib34,bib35}, and yet it is sub-optimal for both players and for the system as a whole. Rational thought rules out the cooperate-cooperate combination which would be better for each player (3 points each) and for both players combined (6 points). In fact, the Nash equilibrium strategy of defect-defect is the worst possible system wide choice, yielding a total payoff of 2 points, compared to the cooperate-defect or defect-cooperate combination, which yields a total payoff of 5 points, or the best system-wide strategy of cooperate-cooperate yielding a total payoff of 6 points.\n\nThe game becomes even more interesting if it is played repeatedly \\cite{bib58}, stochastically \\cite{bib55}, and with spatial structure \\cite{bib27} with each player allowed to decide what strategy to use on each interaction so as to accumulate a higher payoff than the competition over a sequence of $N$ games. In order to analyze this kind of an evolving set-up, a fitness function must be introduced based on the payoff matrix A. Let us now switch our terminology so that the relevance to tumor cell kinetics becomes clear. When modeling cell competition, one has to be careful about the meaning of the term `choosing a strategy'. Cells do not choose a strategy, but they do behave in different ways depending on whether they are normal healthy cells cooperating as a cohesive group, with birth and death rates that statistically balance, or whether they are cancer cells with an overactive cell division mechanism (as triggered by the presence of oncogenes) and an underactive `break' mechanism (as triggered by the absence of tumor suppressor genes) \\cite{bib60}. In our context, it is not the strategies that evolve, as cells cannot change type based on strategy (only based on mutations), but the prevalence of each cell type in the population is evolving, with the winner identified as the sub-type that first saturates in the population. \n\n\n\\section{A tumor growth model}\n\nConsider a population of $N$ cells driven by a stochastic birth-death process as depicted in Figure \\ref{fig1:fig1}, with red cells depicting cancer cells (higher fitness) and blue cells depicting healthy cells (lower fitness, but cooperative). We model the cell population as a stochastic Moran process \\cite{bib61} of $N$ cells, `$i$' of which are cancerous, `$N-i$' of which are healthy. If each cell had equal fitness, the birth-death rates would all be equal and a statistical balance would ensue. At each step, a cell is chosen (randomly but based on the prevalence in the population pool) and eliminated (death), while another is chosen to divide (birth). If all cells had equal fitness, the birth\/death rates of the cancer cells would be $i\/N$, while those of the healthy cells would be $(N-i)\/N$. With no mechanism for introducing a cancer cells in the population, the birth\/death rates of the healthy cells would be 1, and no tumor would form. \n\n\\begin{figure}[ht!]\n\\begin{subfigure}{.9\\textwidth}\n\\begin{center}\n \\noindent \\includegraphics[width=0.4\\linewidth]{1a}\n \\caption{}{}\n \\label{fig1:a}\n\\end{center}\n\\end{subfigure}\n\\newline\n\\begin{subfigure}{0.9\\textwidth}\n\\begin{center}\n \\noindent \\includegraphics[width=0.7\\linewidth]{1b}\n \\caption{}{}\n \\label{fig1:b}\n\\end{center}\n\\end{subfigure}\n\\caption{Schematic of the Moran Process --- (a) During each time step, a single cell is chosen for reproduction, where an exact replica is produced. With probability $m$ ($0 \\leq m \\leq 1$), a mutation may occur. (b) The number of cancer cells, $i$, is defined on the state space $i = 0, 1, \\ldots, N$ where $N$ is the total number of cells. The cancer population can change at most by one each time step, so a transition exists only between state $i$ and $i \u2013 1$, $i$, and $i + 1$.}\n\\label{fig1:fig1}\n\\end{figure}\n\n\nNow, introduce one cancer cell into the population of healthy cells, as shown in Figure \\ref{fig1:fig1}. At each step, there would be a certain probability of this cell dividing ($P_{i,i+1}$), being eliminated ($P_{i,i-1}$), or simply not being chosen for either division or death ($P_{i,i}$). Based on this random process, it might be possible for the cancer cells to saturate the population, as shown by one simulation in Figure \\ref{fig2} depicting $N=1000$ cells, with initially $i=1$ cancer cell, and $N-i = 999$ healthy cells. However, the growth curve would not show any distinct shape (Figure \\ref{fig2} (black)), and might well become extinct after any number of cell divisions, as opposed to reaching saturation. But we emphasize that without mutational dynamics, heritability, and natural selection operating on the cell population, the shape of the growth curve would look random, and we know this is not how tumors tend to grow \\cite{bib25,bib26}. By contrast, Figure \\ref{fig2} (red) shows a Gompertzian growth curve starting with exponential growth of the cancer cell subpopulation, followed by linear growth, ending with saturation. The growth rate is not constant throughout the full history of tumor development, but after an initial period of exponential growth, the rate decelerates until the region saturates with cancer cells. The basic ingredients necessary to sustain Gompertzian growth seem to be: an underlying stochastic engine of developing cells, mutational dynamics, heritability, and a fitness landscape that governs birth and death rates giving rise to some sort of natural selection.\n\n\\begin{figure}[!ht]\n\\begin{center}\n\\includegraphics[width=0.7\\textwidth]{2}\n\\end{center}\n\\caption{Emergence of Gompertzian growth via selection --- Random drift (black) plotted for a single simulation of $10^3$ cells for $4\\cdot 10^4$ generations shows no particular shape. A single simulation of the Moran process (red) with selection ($w = 0.5$) and mutations ($m = 0.1$) gives rise to the characteristic S-shaped curve associated with Gompertzian growth.}\n\\label{fig2}\n\\end{figure}\n\n\n\\subsection{Mutations and heritability}\n\nEach of the $N$ cells in our simulated population carries with it a discrete packet of information that represents some form of molecular differences among the cells. In our model, we code this information in the form of a 4-digit binary string from 0000 up to 1111, giving rise to a population made up of 16 distinct cell types. At each discrete step in the birth-death process, one of the digits in the binary string is able to undergo a point mutation \\cite{bib13,bib28}, where a digit spontaneously flips from 0 to 1, or 1 to 0, with probability $p_m$. The mutation process is shown in Figure \\ref{fig1:fig1}, while a mutation diagram is shown in Figure \\ref{fig3} in the form of a directed graph. This figure shows the possible mutational transitions that can occur in each cell, from step to step in a simulation. A typical simulation begins with a population of $N$ healthy cells, all with identical binary strings 0000. The edges on the directed graph represent possible mutations that could occur on a given step. The first 11 binary string values (0-10) represent healthy cells in our model that are at different stages in their evolutionary progression towards becoming a cancer cell (the exact details of this genotype to phenotype map do not matter much). Mutations strictly within this subpopulation are called passenger mutations as the cells all have the same fitness characteristics. The first driver mutation occurs when a binary string reaches value 11-15. The first cell that transitions from the healthy state to the cancerous state is the renegade cell in the population that then has the potential to clonally expand and take over the population. How does this process occur?\n\n\\begin{figure}[!ht]\n\\begin{center}\n\\includegraphics[width=0.5\\textwidth]{3}\n\\end{center}\n\\caption{Markov Point Mutation Diagram --- Diagram shows 16 genetic cell types based on 4-digit binary string and the effect of a point mutation on each cell type. Blue indicates healthy cell type (0000 --- 1010), red indicates cancerous cell type (1011 --- 1111). Black arrows indicate passenger mutations (healthy to healthy or cancer to cancer), red arrows indicate driver mutations (healthy to cancer).}\n\\label{fig3}\n\\end{figure}\n\n\\subsection{The fitness landscape}\n\nAt the heart of how the Prisoner's Dilemma evolutionary game dictates birth and death rates which in turn control tumor growth, is the definition of cell fitness. Let us start by laying out the various probabilities of pairs of cells interacting and clearly defining payoffs when there are i cancer cells, and $N-i$ healthy cells in the population. The probability that a healthy cell interacts with another healthy cell is given by $(N-i-1)\/(N-1)$, whereas the probability that a healthy cell interacts with a cancer cell is $i\/(N-1)$. The probability that a cancer cell interacts with a healthy cell is $(N-i)\/(N-1)$, whereas the probability that a cancer cell interacts with another cancer cell is $(i-1)\/(N-1)$. \n\nIn a fixed population of $N$ cells, with i cancer cells, the number of healthy cells is given by $N-i$. The average payoff of a single cell ($\\pi^H, \\pi^C$), is dependent on the payoff matrix value weighted by the relative frequency of types in the current population:\n\n\\begin{equation}\\label{eqn2}\n\\pi_{i}^H = \\frac{a(N-i-1) + bi}{N-1}\n\\end{equation}\n\n\\begin{equation}\\label{eqn3}\n\\pi_{i}^C = \\frac{c(N-i) + d(i-1)}{N-1}\n\\end{equation}\n\n\\noindent Here, $a=3$, $b=0$, $c=5$, $d=1$ are the entries in the Prisoner's Dilemma payoff matrix (\\ref{eqn1}). For the Prisoner's dilemma game, the average payoff of a single cancer cell is always greater than the average payoff for a healthy cell (Figure \\ref{fig4:c}). With the invasion of the first cancer cell, the higher payoff gives a higher probability of survival when in competition with a single healthy cell. \n\nSelection acts on the entire population of cells as it depends not on the payoff, but on the effective fitness of the subtype population. The effective fitness of each cell type ($f^H$, $f^C$) is given by the relative contribution of the payoff of that cell type, weighted by the selection pressure: \n\n\\begin{equation}\\label{eqn4}\nf_{i}^H = 1-w +w \\pi_{i}^H\n\\end{equation}\n\n\\noindent and the fitness of the cancer cells as:\n\n\\begin{equation}\\label{eqn5}\nf_{i}^C = 1-w +w \\pi_{i}^C\n\\end{equation}\n \n\\noindent The probability of birthing a new cancer cell depends on the relative frequency (random drift) weighted by the effective fitness, and the death rate is proportional to the relative frequency. The transition probabilities can be written:\n\n\\begin{equation}\\label{eqn6}\nP_{i,i+1} = \\frac{if_i^C}{if_i^C + (N-i)f_i^H}\\frac{N-i}{N}\n\\end{equation}\n\n\\begin{equation}\\label{eqn7}\nP_{i,i-1} = \\frac{(N-i)f_i^H}{if_i^C + (N-i)f_i^H}\\frac{i}{N}\n\\end{equation}\n\n\\begin{equation}\\label{eqn8}\nP_{i,i} = 1 - P_{i,i+1} - P_{i,i-1}; \\quad P_{0,0} = 1; \\quad P_{N,N} = 1.\n\\end{equation}\n\nIn the event of the first driver mutation, the first cancer cell is birthed. At the beginning of the simulation, the effective fitness of the healthy population is much greater than the fitness of the cancer population (Figure \\ref{fig4:b}). This is because although the single cancer has a higher {\\em payoff} than any of the healthy cells, the number of healthy cells far outnumber the single cancer cells. That single cancer cell initiates a regime of explosive high growth and the fitness of the cancer population steadily increases. Cancer cells are continually competing with healthy cells and receiving a higher payoff in this regime (compare the payoff entries of a cancer cell receiving $c = 5$ vs a healthy cell receiving $b = 0$). At later times, growth slows because cancer cells are competing in a population consisting mostly of other cancer cells. The payoff for a cancer cell is dramatically lower when interacting with a cancer cell (observe the payoff entry of both cancer cells receiving $d = 1$ when interacting). As the cancer population grows, the payoff attainable decreases and growth slows. In addition, the average fitness of the total population steadily declines because each interaction derives less total payoff, from $c + b = 5$ to $d + d = 1$.\n\n\\begin{figure}[ht!]\n\\begin{subfigure}{.9\\textwidth}\n \\begin{center}\n \\noindent \\includegraphics[width=0.8\\linewidth]{4a}\n \\end{center}\n \\caption{}{}\n \\label{fig4:a}\n\\end{subfigure}\n\\newline\n\\begin{subfigure}{.9\\textwidth}\n \\begin{center}\n \\noindent \\includegraphics[width=0.8\\linewidth]{4b}\n \\end{center}\n \\caption{}{}\n \\label{fig4:b}\n\\end{subfigure}\n\\newline\n\\begin{subfigure}{.9\\textwidth}\n \\begin{center}\n \\noindent \\includegraphics[width=0.8\\linewidth]{4c}\n \\end{center}\n \\caption{}{}\n \\label{fig4:c}\n\\end{subfigure}\n\\caption{Tumor fitness drives tumor growth --- (a) The average of 25 stochastic simulations ($N = 1000$ cells, $w= 0.5$, $m = 0.1$) is plotted for 20,000 cell divisions to show the cancer cell population (defectors) saturating. The pink lines delineate the regions of tumor growth (defined by the maximum and minimum points of the second-derivative of $i(t)$). (b) Fitness of the healthy population, cancer population, and total population plotted for the range cancer cell proportion. (c) Average payoff of a single healthy cell, cancer cell, and all cells plotted for the range cancer cell proportion.}\n\\label{fig4:fig4}\n\\end{figure}\n\n\nThis complex process of competition among cell types and survival of subpopulations, where defection is selected over cooperation, produces a Gompertzian growth curve shown in Figure \\ref{fig5}, and compared with a compilation based on a wide range of data first shown in \\cite{bib25,bib26}. It is now well established that tumor cell populations (and other competing populations, such as bacteria and viral populations) generally follow this growth pattern, although the literature is complicated by the fact that different parts of the growth curve have vastly different growth rates \\cite{bib25,bib26}, and it is nearly impossible to follow the growth of a population of cancer cells {\\em in vivo} from the first cancer cell through to an entire tumor made up of $O(10^9 - 10^{12})$ cells. Growth rates are typically measured for a short clinical time period \\cite{bib25,bib26}, and then extrapolated back to the first renegade cell, and forward to the fully developed tumor population.\n\n\\begin{figure}[!ht]\n\\begin{center}\n\\includegraphics[width=0.7\\textwidth]{5}\n\\end{center}\n\\caption{Moran Process fit to Gompertzian Growth Data --- The mean and deviation of 25 stochastic simulations ($N = 10^3$ cells, $w= 0.7$, $m = 0.3$) is overlaid on data from a ``normalized\" Gompertzian \\cite{bib25,bib26}. Values for m and w were chosen by implementing a least-squares fit to the data over a range of $m$ ($0 \\leq m \\leq 1$), and $w$ ($0 \\leq w \\leq 1$). Pink lines delineate regions of growth (defined by the maximum and minimum points of the second-derivative of $i(t)$).}\n\\label{fig5}\n\\end{figure}\n\n\n\\subsection{Heterogeneity drives growth}\n\nInsights into the process by which growth rates vary and conspire to produce a Gompertzian shape can be achieved by positing that growth is related to molecular and cellular heterogeneity of the developing population \\cite{bib5,bib24,bib53}. Indeed, an outcome of the model is that molecular heterogeneity (i.e. the dynamical distribution of the 4-digit binary string 0000---1111 making up the population of cells) drives growth. Consider entropy \\cite{bib6,bib39} of the cell population as a measure of heterogeneity:\n\n\\begin{equation}\nE(t) = - \\sum_{i=1}^{N} p_i \\log_{2} p_i \\label{eqn9}\n\\end{equation}\n\n\\noindent (here, log is defined as base 2). The probability $p_i$ measures the proportion of cells of type $i$, with $i = 1,\\ldots,16$ representing the distribution of binary strings ranging from 0000 to 1111. We typically course-grain this distribution further so that cells having strings ranging from 0000 up to 1010 are called `healthy', while those ranging from 1011 to 1111 are `cancerous'. Then growth is determined by:\n\n\\begin{equation}\n\\frac{dn_{E}}{dt}= \\alpha E(t) \\label{eqn10}\n\\end{equation}\n\nIt follows from (\\ref{eqn10}) that the cancer cell proportion $n_E(t)$ can be written in terms of entropy as:\n\n\\begin{equation}\nn_{E}(t) = \\alpha \\int_{0}^t E(t) dt \\label{eqn11}\n\\end{equation}\n\nThis relationship between growth of the cancer cell population and entropy is pinned down and detailed in \\cite{bib61}. We consider it to be one of the key emergent features of our simple model. \n\nA typical example of the emergence of genetic heterogeneity in our model system is shown in the form of a phylogenetic tree in Figure \\ref{fig6}. This particular tree is obtained via a simulation of only 30 healthy phenotypic cells (0000), which during the course of a simulation expand out (radially in time) to form a much more heterogeneous population of cells at the end of the simulation. In our model, the genetic time-history of each cell is tracked and the population can be statistically analyzed after the simulation finishes.\n\n\\begin{figure}[!ht]\n\\begin{center}\n\\includegraphics[width=0.7\\textwidth]{6}\n\\end{center}\n\\caption{Phylogenetic Tree --- Sample dendritic phylogenetic tree tracking point mutations as time extends radially, depicting the emergence of molecular heterogeneity. The tree shows a simulation of 30 cells (all with genetic string 0000 at the beginning of the simulation) with strong selection ($w = 1$, $m = 0.2$). Pathways are color coded to indicate genetic cell type.}\n\\label{fig6}\n\\end{figure}\n\n\\section{Simulated drug dosing strategies and therapeutic response}\n\nFigure \\ref{fig7} shows the clear advantage of early stage therapy in our model system. We compare the effect of therapy given at an early stage, mid-stage, and late stages of the Gompertzian growth of the tumor. The black Gompertzian curve is the freely growing cancer cell population. The blue curve shows the cancer cell population diminishing to zero in time $\\Delta t_1$ of continual therapy. The red curves shows the same therapy administered at a later stage in the growth phase (three stochastic simulations), diminishing to zero in time $\\Delta t_2 > \\Delta t_1$. The yellow curves show the therapy (five stochastic simulations) administered even later, diminishing in time $\\Delta t_3 > \\Delta t_2 > \\Delta t_1$. In one of the simulations, the growing cancer cell population overcomes the killing effect of the therapy. The purple curves shown in the figure all are late stage therapies which do not kill the full population of cancer cells. In these cases, the growth of the cancer cell population outstrips the ability of the simulated therapy to kill them off. Clearly, the earlier in the growth phase the therapy is administered, the less time is required to kill off the full population of cancer cells. But since the cancer cell population grows at very different rates throughout the full Gompertzian history of the developing tumor, this balance of kill cycles based on dose density and accelerated growth due to fitness advantage needs to be quantitatively determined. \n\n\\begin{figure}[!ht]\n\\begin{center}\n\\includegraphics[width=0.9\\textwidth]{7}\n\\end{center}\n\\caption{Effects of early stage, mid-stage, and late-stage therapies --- An average of 5 stochastic simulations ($N = 10^3$ cells, $w = 0.5$, $m = 0.1$) with no therapy is plotted (black). The stochastic response to therapy is shown for 4 different time points in tumor progression. Therapy is designed to ``kill off\" cancer cells with potency equal to their proportion. The first therapy (blue, beginning at $7\\cdot10^3$ cell divisions) has the shortest time to total elimination of cancer cells. The second (red at $8.5\\cdot 10^3$ cell) has a longer time to total elimination. The kill effect is diminished further for the third and fourth therapy (yellow, $10^4$ and purple, $1.15\\cdot 10^4$ cell divisions) and some stochastic simulations are not able to eliminate all cancer cells but only delay saturation.}\n\\label{fig7}\n\\end{figure}\n\nAn established empirical law which relates drug dose density to its effectiveness in killing off cancer cells is known as the `log-kill' law \\cite{bib51}. The log kill law states that a given dose of chemotherapy kills the same fraction of tumor cells (as opposed to the same number of tumor cells), regardless of the size of the tumor at the time the therapy is administered \\cite{bib51}, a consequence of exponential growth with a constant growth rate. This effect is best illustrated on a dose-response curve, plotting the dose density, $D$, with respect to the probability of tumor cell survival, $P_S$. The dose density is simply the product of the drug concentration, $c$, and the time over which the therapy is administered, $t$:\n\n\\begin{equation}\nD = c \\cdot t \\label{eqn12}\n\\end{equation}\n\n\\noindent Thus, the log-kill law states the following:\n\n\\begin{equation}\n\\log (P_S) = - \\beta D \\label{eqn13}\n\\end{equation} \n\nAs an example, if there are 1000 cancer cells in a population, and the first therapy dose kills off 90\\% of them, then after the first round of therapy there will be 100 cancer cells remaining. If a second round of therapy is administered, exactly as the first round, starting soon enough so that no new cancer cells have formed, then this next round will also kill off 90\\% of the cells, leaving 10 cells, and so on for each future round of therapy. In a sense, since the first round killed 900 cells, while the second identical round killed only 90 cells, the population gets increasingly more difficult to kill off using the same treatment on each cycle. The log-kill law, a fundamentally static law (doesn't say anything about the relationship of the fraction of cells killed vs. the growth rate of the tumor), is verified in our model system, as shown in Figure \\ref{fig8:a}. On the x-axis, we increase the dose density D, and we plot the number of surviving cancer cells. The slope of this straight line (verifying the log-kill law) can be thought of as the rate of regression of the tumor, $\\beta$.\n\n\n\\begin{figure}[ht!]\n\\begin{center}\n\\begin{subfigure}{.45\\textwidth}\n \\centering\n \\noindent \\includegraphics[width=1.0\\linewidth]{8a}\n \\caption{}{}\n \\label{fig8:a}\n\\end{subfigure}\n\\begin{subfigure}{.45\\textwidth}\n \\centering\n \\noindent \\includegraphics[width=1.0\\linewidth]{8b}\n \\caption{}{}\n \\label{fig8:b}\n\\end{subfigure}\n\\end{center}\n\\caption{Growth-dependent tumor regression --- (a) Average of 25 stochastic simulations ($N = 10^3$ cells, $w = 0.5$, $m = 0.1$) where therapy is administered with varied dose densities ($0 \\leq D \\leq 1500$, $t = 100$). The rate of tumor regression, $\\beta$, the slope of the red curve fit, is constant for a short period of simulated time where the tumor growth rate is approximately constant. This is the log-kill law. (b) The process to find the rate of tumor regression, $\\beta$, is repeated for a range of instantaneous tumor growth rates ($1\\cdot 10^{-4} \\leq \\gamma \\leq 6\\cdot 10^{-4}$). The Norton-Simon hypothesis predicts that $\\beta$ is proportional to $\\gamma$, indicated by a linear fit (red).}\n\\label{fig8:fig8}\n\\end{figure}\n\n\nSo how is the rate of regression, $\\beta$, related to the growth rate of the tumor, $\\gamma$? This is relevant, since we know from the shape of the Gompertzian curve, the growth rate is highest (exponential) at the beginning stage of tumor development and lowest at the late saturation stage. The Norton-Simon hypothesis \\cite{bib41,bib42,bib43} states that the rate of regression is proportional to the instantaneous growth rate for an untreated tumor of that size at the time therapy is first administered. Faster growing tumors (early stage) should show higher rates of regression than more slowly growing tumors (late stage). This hypothesis is also verified in our model system, and shown clearly in Figure \\ref{fig8:b}. The reality of this growth-dependent tumor regression rate effect (where early stage faster growing tumors are more vulnerable to therapy than later stage more slowly growing tumors) combined with the fact that the first round of therapy is more effective than future rounds of identical therapies, dramatically reinforces the need to administer drug treatment early in tumor progression when growth rates are high and there are fewer cancer cells to kill off. As drug concentration, $c$, is kept constant, the effect of treatment is reduced at later times in tumor development (Figure \\ref{fig7}) until the same drug concentration is simply unable to overcome the tumor growth rate.\n\n\\section{Markov dissemination and progression patterns}\n\nSo how do these molecular and cellular growth details manifest themselves on the larger scales associated with metastatic progression patterns in patients? Despite the fact that disease progression patterns can vary from patient to patient, if a sufficiently large cohort of patients with similar characteristics is tracked over the course of the disease, statistical patterns emerge and can be exploited to build dynamical models of large scale progression. This lies at the heart of the models described in \\cite{bib37,bib38,bib39} for lung cancer progression, and \\cite{bib39,bib40} for breast cancer progression. \n\nAs an example of the kinds of whole-body scale models that can be built, consider first the tree-ring diagram shown in Figure \\ref{fig9}a. The diagram encapsulates the entire progression history of a cohort of 289 primary breast cancer patients tracked at the Memorial Sloan Kettering Cancer Center for a 20 year period. All of the patients entered the cohort with a primary breast tumor, but no metastatic tumors. The inner ring, shown in pink, represents this cohort when they entered the study. As time progresses, the rings grow out, surrounding the inner breast ring. The first ring out shows the metastatic tumor distribution associated with first recurrence. The sector sizes represent the percentage of patients in this group. Likewise, the second ring out represents the distribution of tumors on second recurrence, and so forth for the further rings out. Hence, subsequent rings outward represent the tumor distributions as time progresses, with each patient history depicted on a ray going out from the center of the ring diagram. We caution that despite our usage of the term `tree-ring' diagrams for these representations, the thickness of the rings are all equal, hence do not reflect the time between subsequent recurrences (timescales of progression are documented and modeled in \\cite{bib40}). The power of the diagrams is that in one quick glance, one gains an appreciation for the statistical complexity of the disease \\cite{bib39,bib40}. From them, one can also calculate the probability of the disease `transitioning' from one site to another as the disease progresses (called transition probabilities). These can then be used to create a single Markov transition matrix for each cancer type \\cite{bib39}, which quantitatively encodes much of the information associated with the disease. Figure 9b shows the Markov transition graph from the last metastatic site to the deceased state for the cohort from Figure \\ref{fig9}a. The sites are ordered clockwise from the most probably last metastatic site, to the least probable.\n\n\\begin{figure}[!ht]\n\\begin{center}\n\\includegraphics[width=0.9\\textwidth]{9}\n\\end{center}\n\\caption{Spatiotemporal patterns of breast cancer metastasis --- (a) Tree-ring diagram depicting all the paths in the clinical cohort over a 20-year period. (b) Markov chain network depicting transition probabilities from patients last metastatic tumor to deceased. (c) Reduced Markov chain diagram for sub-population of Her2+ patients. Red sites are spreader sites, blue sites are sponge sites. Note that bone is the main spreader. (d) Reduced Markov chain diagram for sub-population of ER-\/Her2- patients. Red sites are spreader sites, blue sites are sponge sites. Note that bone is the main spreader, but Lung\/pleura switches from being a spreader for Her2+ patients, to being a sponge for ER-\/Her2- patient.}\n\\label{fig9}\n\\end{figure}\n\nFigures \\ref{fig9}c and \\ref{fig9}d show reduced Markov diagrams \\cite{bib39, bib40} for two specific important sub-groups of breast cancer patients, Her2+ patients, and ER-\/Her2- patients. Generally speaking, Her2+ patients have the poorest prognosis. The red sites in these reduced diagrams (bone, lung\/pleura, chest wall, LN (mam)) in Figure \\ref{fig9}c, and bone, LN (mam), chest wall in Figure 9d are the spreaders associated with these groups. The blue sites (liver, LN (dist), brain for Fig. \\ref{fig9}c; LN (dist), lung\/pleura, liver, brain for Fig. \\ref{fig9}d) are the sponges \\cite{bib37,bib38,bib39}. It is interesting to note that lung\/pleura switches from a spreader in the Her2+ sub-group to a sponge in the ER-\/Her2- sub-group, suggesting a possible biological difference of the site in the different groups that correlates with different survival probabilities. \n\n\\section{Mathematical modeling and tumor analytics}\n\nIt is important to keep in mind that no mathematical model captures all aspects of reality, so choices must be made which involve prioritizing the features that are most essential in capturing the essence of a complex process and which are not. Most experts now agree that the evolutionary processes in a tumor played out among subpopulations of competing cells are key to understanding aspects of growth and resistance to chemotherapy, which will ultimately lead the way toward a quantitative understanding of tumor growth and cancer progression \\cite{bib31,bib59,bib60}. The paradigm of the cancer cell subpopulation and the healthy cell subpopulation competing as the defectors and cooperators in a Prisoner's Dilemma evolutionary game has been useful in obtaining a quantitative handle on many of these processes and frames the problem in an intuitive yet predictive way. \n\nNonetheless, the mathematical `taste' of the modeler plays a role in what techniques are selected and ultimately where the spotlight shines. This fact makes clinicians uncomfortable and can lead to deep suspicion of the mathematical modeling enterprise as a whole. Aren't the outcomes and predictions of mathematical models a straightforward consequence of the model assumptions? Once those choices are made, isn't the cake already baked? So why should we be surprised if you tell us it tastes good? Why not simply use tried and true statistical tools like regression methods to curve-fit the data directly, with no built in assumptions, and be satisfied with uncovering correlations and trends? Clinicians (and experimentalists, in general) feel that they are dealing directly with reality, so why mess around with `toy' systems based on possibly `ad hoc' or incorrect assumptions that create artificial realities that may or may not be relevant? To a theoretician, calling their assumptions ad hoc, as opposed to natural, is as insulting as calling a clinician sloppy and uncaring (try this for yourself at the next conference you go to! But please use the term `somewhat ad hoc' to lessen the blow.) And if you want to deliver an even harsher insult, you could comment that the model seems like an exercise in curve fitting. \n\nBut the usefulness of mathematical models built on simplified assumptions is well established in the history of the physical sciences, as detailed beautifully in Peter Dear's book, {\\em The Intelligibility of Nature: How Science Makes Sense of the World} \\cite{bib9}. Bohr's simple model of the structure of the atom was crucial in moving the community forward towards a deeper understanding of cause and effect, and ultimately pushing others to develop more realistic atomic models. The same could be said for many other important, but ultimately discarded models of reality (e.g. the notion of aether used as a vehicle to understand the mysterious notion of action-at-a-distance \\cite{bib9}) now relegated to footnotes in the history of the physical sciences. \n\nLessons from this history highlight the importance of using the principle of Occam's razor (law of parsimony) as a heuristic guide in developing models: (1) keep things simple, but not too simple; (2) see what can be explained by using a given set of assumptions, and try to identify what is either wrong or cannot be explained; (3) add complexity to the model, but do this carefully. Since ultimately, the model will always be wrong (with respect to some well chosen and specific new question being posed about a system), it is important that it be {\\em useful as a vehicle of intelligibility} \\cite{bib9} associated with the set of questions surrounding the phenomena it was built to explain. Answers to some new questions will be found using the model as a temporary crutch, and new questions will emerge in the process that had not yet been asked, as their relevance had never previously been realized. A new quantitative language will emerge in which aspects of the model will be associated with the underlying reality it is attempting to describe, predictions will be easier to frame and test, and shortcomings will be exposed. In his famous article \\cite{bib62}, Eugene Wigner writes compellingly that `the miracle of the appropriateness of the language of mathematics for the formulation of the laws of physics is a wonderful gift which we neither understand nor deserve. We should be grateful for it and hope that it will remain valid in future research and that it will extend, for better or for worse, to our pleasure, even though perhaps also to our bafflement, to wide branches of learning.'\n\nIn general, the more complex the model (as measured, for example, by the number of independent parameters associated with it), the less useful it will be, and the less likely it is to be adopted by the community at large. After all, if the model is as complex as the phenomena it was built to understand, why not stick with reality? Effective models can be thought of as {\\em low-dimensional approximations of reality}, surrogates that help us bootstrap our way forward. They arise as the outcome of a complex balancing act between simplicity of the ingredients, and complexity of the reality the model is meant to describe. They generally do not arise in a vacuum, but are built in the context of informed and sustained discussions among people with different expertise. In the context of medical oncology, this means physical scientists developing ongoing interactions with clinical oncologists, radiologists, pathologists, molecular and cell biologists and other relevant medical specialists.\n\nAppropriate data is a necessary ingredient in developing and testing any successful model, and treasure troves of medical data sit unexamined in patient files and government databases across the country waiting to be put to good use. There is no doubt that they are telling an interesting and important story that we have yet to fully understand. It is not currently possible for the computer to simulate all of the complex, relevant, and systemic ingredients at play to faithfully recreate all aspects of cancer progression and treatment response in patients. It is hard to imagine that a deep and actionable understanding can ever be obtained without the combined use of data, models, and computer simulations to help guide us and highlight some of the underlying causal mechanisms of this complex and deadly disease. \n\n\\section*{References}\n","meta":{"redpajama_set_name":"RedPajamaArXiv"}} +{"text":"\\section{Introduction}\n\\label{sec:intro}\nTime-evolving data analysis is of interest in many disciplines to capture the underlying patterns as well as the evolution of those patterns. For instance, in neuroscience, underlying patterns may correspond to spatial networks capturing functional connectivity \\cite{YuLiZh18}, and in social networks, patterns may reveal communities. Capturing those patterns (networks) as well as their temporal evolution, holds the promise to improve our understanding of complex dynamic systems such as the brain, social networks, and molecular mechanisms in the body \\cite{WoPaKo18}.\n\nAn effective way of representing time-evolving data is to use higher-order tensors (also referred to as multi-way arrays), i.e., tensors with more than two axes of variation. For instance, functional magnetic resonance imaging (fMRI) data from multiple subjects can be rearranged as a third-order tensor with modes: \\emph{subjects}, \\emph{voxels}, and \\emph{time windows}. Tensor factorizations \\cite{AcYe09,tensordec:KoTaBa09} have proved useful in terms of revealing the underlying patterns in such higher-order data sets. Previously, for the analysis of time-evolving data, a popular tensor factorization model called the CANDECOMP\/PARAFAC (CP) \\cite{PARAFAC:Ha70, PARAFAC:Ca70} model has been used to extract temporal patterns to address the temporal link prediction problem \\cite{tensor:linkpred:AcDuKo09}, to capture the evolving popularity of different meaningful topics from email threads \\cite{tensor:CP:enron:BaBeBr08} and to detect suspicious activity in network traffic \\cite{tensor:poisson:ensign:BrBaEzHeLe16}. However, the CP model assumes that underlying patterns stay the same across time, which may not be satisfied by dynamic data \\cite{temporal:ShiftCP:MoHaArLiMa08,temporal:ConvCP:MoHa11,tensor:smoothness:parafac2:COPA:AfPePaSeHoSe18,parafac2:BrAnKi99}.\n\nIn data mining, there is an increasing interest in capturing time-evolving factors. One approach is to use sliding window-based methods \\cite{tensor:slidingwindow:SuPaYu08, tensor:tenClustS:FeFaGa18}; however, patterns are still assumed to be static within each window, and determining the window size is a challenge. \nAlternatively, dynamic data has been modeled using temporal matrix factorizations with temporally evolving patterns \\cite{Matrix:community:temporalnetworks:TMF:YuAgWa17, matrix:collaborative:temporalsvd:Ko09}, but with a focus on reconstruction of data matrices, e.g., for link prediction, without discussing the uniqueness of the captured patterns.\n\nIn this paper, we use the PARAFAC2 tensor factorization model, with rather well-studied uniqueness properties \\cite{KiTeBr99}, to model time-evolving data in such a way that coupled matrices correspond to matrices at different time points and underlying patterns in the matrices may change over time. PARAFAC2 has been used to analyze time-evolving data previously \\cite{evolvingfactors:SCAP:TiKi03, parafac2:fMRI:MaChNaMo17}, but the coupled matrices corresponded to matrices for different subjects and patterns were allowed to change across subjects, rather than across time. Here, we assess the performance of the PARAFAC2 model in terms of capturing temporal evolution of the underlying patterns and demonstrate that it is a promising tool to trace the evolution of networks such as growing, shrinking and shifting networks. We also use the PARAFAC2 model in a novel neuroimaging application to understand task-related connectivity and capture time-evolving connectivity patterns that significantly differ between patients with schizophrenia and healthy controls. \n\n\\section{Methods}\n\\emph{Higher-order tensors} are extensions of matrices to more than two modes, i.e., a vector is a first-order tensor and a matrix is a second-order tensor. This section briefly describes two tensor factorization models, CP and PARAFAC2, which we compare in terms of capturing evolving patterns.\\\\\n\n{\\noindent \\bf{CANDECOMP\/PARAFAC:}}\nThe CP model \\cite{PARAFAC:Ha70,PARAFAC:Ca70} represents a tensor as the sum of minimum number of rank-one components, i.e., an $R$-component CP model of tensor $\\T{X} \\in {\\mathbb R}^{I \\times J \\times K}$ is defined as \n$\\T{X} \\approx \\sum_{r=1}^R \\MC{A}{r} \\Oprod \\MC{B}{r} \\Oprod \\MC{C}{r}$, where $\\Oprod$ denotes the vector outer product, $\\MC{A}{r}, \\MC{B}{r}$, and $\\MC{C}{r}$ are the $r$th column of factor matrices $\\M{A} \\in {\\mathbb R}^{I \\times R}, \\M{B} \\in {\\mathbb R}^{J \\times R}$, and $\\M{C} \\in {\\mathbb R}^{K \\times R}$, respectively. Using CP, each frontal slice ($\\M{X}_k \\in {\\mathbb R}^{I \\times J}$) is formulated as:\n\\begin{equation}\n\\small\n \\M{X}_k \\approx \\M{A} \\text{diag}(\\MR{c}{k}) \\M{B}\\Tra,\n\\end{equation}\nwhere $\\text{diag}(\\MR{c}{k})$ is an $R \\times R$ diagonal matrix with the $kth$ row of $\\M{C}$ on the diagonal. If $\\T{X}$ represents a \\emph{subjects} by \\emph{voxels} by \\emph{time windows} tensor, each column of $\\M{B}$ may reveal a spatial network, $\\M{A}$ indicates which networks are present in each subject, and $\\M{C}$ contains the temporal profile of each network.\\\\\n\n{\\noindent \\bf{PARAFAC2:}}\nPARAFAC2 \\cite{tensor:parafac2:Ha72} is a more flexible model than the CP model. While CP assumes that each slice, \\(\\TFS{X}{k} \\in {\\mathbb R}^{I \\times J}\\), has the same $\\M{A}$ and $\\M{B}$ matrices, PARAFAC2 allows each slice to have a different $\\M{B}$ matrix (\\cref{fig:multilinearity_parafac2}) as follows: \n\\begin{equation}\n\\small\n \\TFS{X}{k} \\approx \\M{A} \\text{diag}(\\MR{c}{k}) \\MnTra{B}{k}, \\label{eq:pf2}\n\\end{equation}\nwhere $\\Mn{B}{k}$s follow the \\emph{PARAFAC2 constraint}, i.e., $\\smash{\\MnTra{B}{k_1}\\Mn{B}{k_1}} = {\\MnTra{B}{k_2}\\Mn{B}{k_2}}$ for all $k_1, k_2 \\leq K$. If $\\TFS{X}{k}$ slices correspond to time windows, then networks captured by columns of $\\Mn{B}{k}$ may change over time as long as they satisfy this constraint. We use the notation $[\\MC{b}{k}]_r$ to denote the $r$th column of matrix $\\Mn{B}{k}$.\n\n\\begin{figure}[t]\n\\begin{minipage}[b]{1.0\\linewidth}\n \\centering\n \\centerline{\\includegraphics[width=1.0\\linewidth, trim=5 5 10 5,clip]{Parafac2_3.pdf}}\n\\end{minipage}\n\\caption{\\ninept{Illustration of a two-component PARAFAC2 model.}}\n\\label{fig:multilinearity_parafac2}\n\\end{figure}\n\n\\section{Experiments}\nIn this section, we assess the performance of PARAFAC2 in terms of extracting time-evolving networks using both simulated and real data. First, we generate data with time-evolving patterns, and demonstrate that the model can recover the underlying evolving patterns, performing much better than a CP model. Then we use the PARAFAC2 model to analyze fMRI signals from a group of subjects consisting of healthy controls and patients with schizophrenia and show the promise of the model in terms of revealing the difference in the evolution of task-related spatial networks across the two groups.\n\n\\subsection{Simulated data}\n\n\\subsubsection{Generation of simulated data}\\label{sec:simulation}\nWe generated two types of simulated data: (i) data sets following \\eqref{eq:pf2} and the PARAFAC2 constraint, and (ii) data sets following \\eqref{eq:pf2}, having time-evolving patterns $\\Mn{B}{k}$s that do not necessarily follow the PARAFAC2 constraints.\n\nFactor matrices in each mode are generated as follows (with $R=4$): The factor matrix for the first mode (i.e. subjects) (\\(\\M{A}\\)) has a clustering structure as shown in \\cref{fig:AandC}. For the second mode (i.e. voxels), (\\(\\Mn{B}{k}\\))s are generated in two different ways: (i) \\emph{Random:} random matrices following the PARAFAC2 constraint, (ii) \\emph{Network:} matrices with each column corresponding to either a shifting, a growing, a shrinking or a both shifting and growing network (\\cref{fig:B}). Finally, the factor matrix in the third mode (i.e., time) (\\(\\M{C}\\)) is generated in two different ways: (i) \\emph{Random:} with all columns drawn from a uniform random distribution, (ii) \\emph{Trends:} with one random column, and other three columns following either a sinusoidal, an exponential or a sigmoidal curve (\\cref{fig:AandC}).\\footnote{Simulations are described in detail in the supplementary material: \\url{https:\/\/github.com\/marieroald\/ICASSP20}, with links to the simulation code and Python implementations of CP and PARAFAC2.} \n\nOnce $\\T{X}$ is constructed based on \\eqref{eq:pf2} using the generated factor matrices, we add random noise: $\\T{X}_{\\text{noisy}} = \\T{X} + \\eta\\T{E}\\frac{\\fnorm{\\T{X}}}{\\fnorm{\\T{E}}}$, where $\\eta$ is the noise level, $\\fnorm{\\cdot}$ is the Frobenius norm, entries of $\\T{E}$ follow a standard normal distribution. \n\n\\subsubsection{Performance evaluation}\nWe generated twenty random data sets for all possible combinations of factor matrix generation schemes and used different noise levels; $\\eta=0$ and $\\eta=0.33$ ($\\approx 10\\%$ of the data being noise). We fit both CP and PARAFAC2 using alternating least squares \\cite{tensordec:KoTaBa09,KiTeBr99} with multiple random starts, and the start with the best fit score was chosen for further analysis (after validating the uniqueness of the model). Non-negativity constraints were imposed in the \\emph{time} mode when fitting PARAFAC2 to resolve the sign ambiguity \\cite{tensor:sign:parafac2:BrLeJo13}, which is more critical for PARAFAC2 than CP. Model performance is assessed in terms of the following measures:\n\n{\\noindent \\bf{Model fit:}} One metric used to assess the quality of the data reconstruction, denoted by $\\That{X}$, is the \\emph{model fit} defined as $ \\text{Fit} (\\T{X},\\That{X}) = 100 \\times \\left(1 - \\frac{ \\norm{\\T{X} - \\That{X}}^2}{ \\norm{\\T{X}}^2}\\right)$. The fit tells us how well the model explains the data. \n\n{\\noindent \\bf{Factor Match Score (FMS):}}\nWe measure the accuracy of the methods, i.e., how well the methods recover underlying factor vectors, using FMS defined, for each mode separately, as:\n\\begin{equation*}\n\\small\n \\text{FMS}_{\\M{U}} = \\frac{1}{R}\\sum_{r=1} \\frac{\\left|\\MC{u}{r}\\Tra \\MhatC{u}{r}\\right|}{\\norm{\\MC{u}{r}} \\norm{\\MhatC{u}{r}}},\n\\end{equation*}\nwhere $\\V{u}_r$ and $\\Vhat{u}_r$ are true and estimated $r$th column of factor matrix $\\M{U}$, respectively (after fixing the permutation ambiguity). For the evolving mode ($\\M{B}$), we concatenate all time steps to form a $(JK\\times R)$ matrix, $\\tilde{\\M{B}}$, and compute $\\text{FMS}_{\\M{B}}$ using $\\tilde{\\M{B}}$. For CP, the same $\\V{b}_r$ vector is repeated $K$ times.\\\\\n{\\noindent \\bf{Clustering accuracy:}}\nThe clustering performance is assessed using $k$-means clustering on the factor matrix extracted from the first mode, using all possible combinations of factor vectors, and the best performance is reported. \n\n\\subsubsection{Results of simulated data analysis}\n\\cref{tab:results} shows the average performance (for twenty random data sets) of CP and PARAFAC2 ($R=4$) using different data generation schemes. Results demonstrate that PARAFAC2 performs well in terms of recovering the true patterns and their evolution with average FMS values above 0.90 for the evolving network mode, and with much higher FMS in other modes, consistently performing better than the CP model. \n\nWe observe that CP partially discovers $\\M{A}$ and $\\M{C}$ matrices for the network data, even in the noisy case, while completely failing for data with random $\\M{B}$s. Despite failing to capture the true $\\M{A}$, CP often has high clustering accuracy due to the clustering structure in the simulations designed to separate groups with several components, i.e., if a model recovers any informative components, the clustering accuracy will be high. \n\nThe results also demonstrate that there is room for improvement for PARAFAC2, especially when the PARAFAC2 constraint is not satisfied, i.e. the evolving network case. Note that PARAFAC2 does not reveal the true components perfectly when $\\Mn{B}{k}$s have an evolving network structure, even in the noise-free case. This challenge stems from the PARAFAC2 constraint, which requires that the 2-norm of the network factor vectors are constant in time. If a network grows or shrinks in density, the resulting change in norm cannot be represented in $\\M{B}$, but rather in $\\M{C}$. In the noisy case, we observe similar performance for both random and time-evolving network data. \\cref{fig:AandC} and \\cref{fig:B} illustrate how well PARAFAC2 performs in terms of capturing the true patterns in the noisy data.\n\\begin{table*}[t]\n\\footnotesize\n\\centering\n\\caption{\\ninept{The mean performance of PARAFAC2 (PF2) and CP for different setups.}}\\label{tab:results}\n\\begin{tabular}{@{}lccccccccccccc@{}}\n\\toprule\n & & & \\multicolumn{2}{c}{\\textbf{Fit [\\%]}} & \\multicolumn{2}{c}{\\textbf{Clustering Acc [\\%]}} &\n\\multicolumn{2}{c}{\\textbf{FMS}\\(_{\\M{A}}\\)} & \\multicolumn{2}{c}{\\textbf{FMS}\\(_{\\M{B}}\\)} &\n\\multicolumn{2}{c}{\\textbf{FMS}\\(_{\\M{C}}\\)}\\\\\n\n\\cmidrule(lr){4-5}\\cmidrule(lr){6-7}\\cmidrule(lr){8-9}\\cmidrule(lr){10-11}\\cmidrule(lr){12-13}\n\\textbf{Noise} & \\textbf{C setup} & \\textbf{B Setup} & \\multicolumn{1}{c}{CP} & \\multicolumn{1}{c}{PF2} & \\multicolumn{1}{c}{CP} & \\multicolumn{1}{c}{PF2} & \\multicolumn{1}{c}{CP} & \\multicolumn{1}{c}{PF2} & \\multicolumn{1}{c}{CP} & \\multicolumn{1}{c}{PF2} & \\multicolumn{1}{c}{CP} & \\multicolumn{1}{c}{PF2}\\\\\n\n\\cmidrule(r){1-1}\\cmidrule(r){2-2}\\cmidrule(lr){3-3}\\cmidrule(lr){4-4}\\cmidrule(lr){5-5}\\cmidrule(lr){6-6}\\cmidrule(lr){7-7}\\cmidrule(lr){8-8}\\cmidrule(lr){9-9}\\cmidrule(lr){10-10}\\cmidrule(lr){11-11}\\cmidrule(lr){12-12}\\cmidrule(lr){13-13}\n0 & Random & Network & 75.1 & 100.0 & 89.3 & 94.6 & 0.75 & 0.98 & 0.58 & 0.97 & 0.87 & 0.98 \\\\\n & & Random & 13.2 & 100.0 & 82.5 & 90.9 & 0.27 & 1.00 & 0.01 & 1.00 & 0.59 & 1.00 \\\\\n & Trends & Network & 80.7 & 100.0 & 82.0 & 92.0 & 0.52 & 0.97 & 0.54 & 0.98 & 0.86 & 0.98 \\\\\n & & Random & 15.5 & 100.0 & 77.8 & 91.8 & 0.17 & 1.00 & 0.01 & 1.00 & 0.47 & 1.00 \\vspace{0.5em}\\\\\n \n0.33 & Random & Network & 67.8 & 91.1 & 88.1 & 95.0 & 0.74 & 0.98 & 0.58 & 0.95 & 0.87 & 0.98 \\\\\n & & Random & 11.9 & 91.1 & 82.4 & 93.0 & 0.27 & 0.97 & 0.01 & 0.92 & 0.58 & 1.00 \\\\\n & Trends & Network & 72.8 & 91.1 & 85.9 & 95.0 & 0.52 & 0.95 & 0.52 & 0.92 & 0.86 & 0.98 \\\\\n & & Random & 14.0 & 91.1 & 77.4 & 90.3 & 0.17 & 0.95 & 0.01 & 0.90 & 0.47 & 0.99 \\\\\n\\bottomrule\n\n\\end{tabular}\n\\end{table*}\n\n\\begin{figure}[t!]\n\n\\begin{minipage}[t]{1.0\\linewidth}\n \\centering\n \\centerline{\\includegraphics[width=1.0\\linewidth,trim={0 0 0 0.8cm},clip]{A_components.pdf}}\n \\centering\n \\centerline{\\includegraphics[width=1.0\\linewidth,trim={0 1.2cm 0 0.8cm},clip]{C_components.pdf}}\n\\end{minipage}\n\\caption{\\ninept{Top: Scatter plot of true columns of \\(\\M{A}\\) and the ones captured by PARAFAC2. Bottom: Line plot of true columns of \\(\\M{C}\\) and the ones estimated by PARAFAC2 (noisy case).}}\n\\label{fig:AandC}\n\\end{figure}\n\n\\begin{figure}[t!]\n\n\\begin{minipage}[b]{1.0\\linewidth}\n \\centering\n \\centerline{\\includegraphics[width=0.95\\linewidth]{B_components.pdf}}\n\\end{minipage}\n\\caption{\\ninept{True \\(\\Mn{B}{k}\\) factor vectors (left) and the ones captured by PARAFAC2 (right) (noisy case). Factor vectors are shown as heat maps, where brighter colors represent active nodes.}}\n\\label{fig:B}\n\\end{figure}\n\n\n\\subsection{Real data: fMRI}\nOur motivation for exploring PARAFAC2 is to understand task-related dynamic connectivity in the brain and how that differs between controls and patients suffering from a psychiatric disorder. Here, we use PARAFAC2 to analyze fMRI data from the MCIC collection \\cite{fMRI:MCIC}, which contains fMRI scans from patients with schizophrenia and healthy controls for different tasks. For this work, we used the sensory motor task (SM) data from the 3T fMRI scanners at the University of Iowa and Minnesota\\footnote{We have excluded the data from other sites either due to scanner difference or observed site differences in our preliminary analysis.}. During the SM task, subjects were equipped with headphones that played sounds with increasing pitch, with a resting period between each sound. Subjects were instructed to push a button each time they heard a sound. \n\nTo construct the data tensor, we first extracted the fractional amplitude of low-level fluctuations (fALFF) \\cite{fmri:falff:ZoEtAl08} signal from sliding time windows of the blood-oxygen-level-dependent signal. The fALFF is calculated in three steps: (1) Discard high and low frequency components to remove noise and the signal from the vascular system. (2) Sum the square root of the frequency components to get the amplitude of low-frequency fluctuation. (3) Divide by the total sum of frequencies in the window. This approach provides a time-evolving measure of brain activity within each voxel. The window size and stride length were chosen so that each time window, corresponding to 16 seconds, contains precisely one block of task or rest with no overlap between the windows. The data tensor was constructed using the fALFF values for the voxels corresponding to gray matter as a feature vector for each time window and each subject. The constructed tensor is in the form of $145$ \\emph{subjects} (of which, 90 of them are healthy controls) by $63652$ \\emph{voxels} by $14$ \\emph{time windows}.\n\n\\subsubsection{Results for fMRI data analysis}\n\n\\begin{figure}[t]\n \\centering\n \\includegraphics[width=1.\\linewidth,trim=10 21 10 10,clip]{fmri_parafac2_threshold_1_2.pdf}\n \\caption{\\ninept{Factor vectors in \\emph{voxels} and \\emph{time windows} modes of 2-component PARAFAC2 model. In \\emph{voxels} mode, only the first time window, i.e., \\(\\Mn{B}{1}\\), is visualized. The $p$-values are \\(2.8 \\times 10^{-4}\\) and \\(4.1 \\times 10^{-2}\\) for component 1 and 2, respectively.}}\n \\label{fig:fmri.results.pf2}\n\\end{figure}\n\n\n\\begin{figure}[t]\n \\centering\n \\includegraphics[width=1.\\linewidth,trim=10 21 10 10,clip]{fmri_cp_threshold_1_2.pdf}\n \\caption{\\ninept{Factor vectors in \\emph{voxels} and \\emph{time windows} mode of a 2-component CP model. The $p$-values are \\(6.2 \\times 10^{-4}\\) and \\(3.7 \\times 10^{-1}\\) for component 1 and 2, respectively.}}\n \\label{fig:fmri.results.cp}\n\\end{figure}\nBefore the analysis, the fMRI tensor was preprocessed by subtracting the mean fALFF signal across the \\emph{voxels} mode, and dividing each \\emph{voxels} mode fiber by its norm. The preprocessed tensor was then modelled using PARAFAC2 and CP such that \\(\\M{A}\\), \\(\\Mn{B}{k}\\)(or \\(\\M{B}\\) matrix for CP) and \\(\\M{C}\\) correspond to \\emph{subjects}, \\emph{voxels} and \\emph{time windows}, respectively. To resolve the sign indeterminacy, we imposed non-negativity constraints on \\(\\M{C}\\) for the PARAFAC2 model. Previously, PARAFAC2 was used for fMRI data analysis \\cite{parafac2:fMRI:MaChNaMo17}, where each slice $\\TFS{X}{k}$ corresponded to raw signals from a single subject and patterns in time and\/or voxels were allowed to change across subjects. Instead, we construct a tensor based on features capturing the dynamic activity within each window and model the tensor using PARAFAC2, letting the voxel patterns ($\\Mn{B}{k}$) change in time, rather than across subjects.\n\nOnce the models were fit, we performed a two-sample $t$-test on each column of the \\emph{subjects} mode factor matrix. We achieved the lowest $p$-values using 2-component CP and 2-component PARAFAC2 models illustrated in \\cref{fig:fmri.results.pf2,fig:fmri.results.cp}. Spatial maps are plotted using the patterns from the \\emph{voxels} modes as z-maps and thresholding at $|z| \\geq 1.2$ such that red voxels indicate an increase in controls over patients and blue voxels indicate an increase in patients over controls.\n\nBoth CP and PARAFAC2 reveal activity in the sensorimotor cortex (component 1) and auditory cortex (component 2), two brain regions known to be engaged by the SM task \\cite{fMRI:MCIC}. The sensorimotor component has significantly lower activation for schizophrenic patients than healthy controls, i.e., entries of the corresponding \\emph{subjects} mode vector are positive for both groups but statistically significantly higher in controls than patients. That makes sense since it is difficult for patients to follow the task; hence the activation is lower. Temporal profiles, especially for the first component, reflect the on-off task pattern. While both models reveal similar spatial networks, PARAFAC2 captures the temporal evolution of these spatial networks (see supplementary material\\footnote{\\url{https:\/\/github.com\/marieroald\/ICASSP20}} for videos showing the temporal evolution). We also observe that due to the flexibility of PARAFAC2, the PARAFAC2 spatial maps are noisier compared to the ones captured by the CP model.\n\n\\section{Conclusion}\nIn this work, we have demonstrated that the tensor factorization model PARAFAC2 can recover the underlying patterns and their evolution from dynamic data, even for data not strictly following the PARAFAC2 constraints. Moreover, PARAFAC2 shows promising performance for detecting task-related brain connectivity and its evolution from fMRI data. As future work, we plan to relax the PARAFAC2 constraints and incorporate prior information about the evolving network structure (e.g., temporal and spatial smoothness) by regularizing the model to improve the recovery of underlying patterns. \n\n\\section{Acknowledgments}\nWe thank Rasmus Bro for helpful discussions on PARAFAC2. We also would like to acknowledge Khondoker Hossain for his help during fMRI preprocessing.\n\n\n\n\\bibliographystyle{IEEEbib}\n\n\n\n","meta":{"redpajama_set_name":"RedPajamaArXiv"}} +{"text":"\\section{Introduction}\n\n\\par Classical Cepheids are the first step on the ladder of the extragalactic distance scale. Cepheid distances were first computed from period-luminosity (PL) relations in the optical bands, but the metallicity dependence of the optical PL-relations \\citep[e.g.,][]{Roma2008} and the interstellar absorption led researchers to prefer period-luminosity or period-Wesenheit (PW) relations in the near-infrared \\citep[e.g.,][]{Bono2010,Feast2012,Ripepi2012,Gie2013,Inno2013,Bhar2016} where the Wesenheit index is a reddening-free quantity \\citep{Mado1982}. In the recent years, these relations have been extended to the mid-infrared \\citep[e.g.,][]{Mon2012,Ngeow2012,Scow2013,Rich2014,Ngeow2015}. Most of them are tied to very accurate parallax measurements for the closest Cepheids \\citep{Bene2007,vLeeuw2007}.\\\\\n\n\\par Independent distances to Cepheids can also be obtained with the Baade-Wesselink (BW) method, which combines the absolute variation of the radius of the star with the variation of its angular diameter. The former is obtained by integrating the pulsational velocity curve of the Cepheid that is derived from its radial velocity curve via the projection factor (p). The latter uses surface-brightness (SB) relations to transform variations of the color of the Cepheid to variations of its angular diameter. SB relations were first derived in the optical bands \\citep[e.g.,][]{Wess1969,BE1976} and extended to the near-infrared by \\cite{Welch1994}, and \\citet{Fou1997}. Extremely accurate angular diameter variations can be obtained from interferometry \\citep[e.g.,][]{Mou1997,Ker2004} but this technique is currently limited to the closest Cepheids.\\\\\n\n\\par Published values of the $p$-factor consistently cluster around $\\sim$1.3. However, the exact value of the $p$-factor and its dependence on the pulsation period remain uncertain at the level of 5-10\\% \\citep{Ker2017}. In a series of papers, \\cite{Storm2004a,Storm2004b,Gie2005,Fou2007}; and \\citet{Storm2011a,Storm2011b} found that the $p$-factor strongly depends on the period. Similar conclusions were obtained independently by \\cite{Groe2008,Groe2013}. Using hydrostatic, spherically-symmetric models of stellar atmospheres, \\citet{Neil2012} indicate that the $p$-factor varies with the period, but the dependence derived is not compatible with the\nobservational results of, e.g., \\citet{Nar2014a} and \\citet{Storm2011a,Storm2011b}. To overcome these issues, \\citet{Mer2015} implemented a new flavor of the Baade-Wesselink method: they fit simultaneously all the photometric, interferometric and radial velocity measurements in order to obtain a global model of the stellar pulsation. Applying this method to the Cepheids for which trigonometric parallaxes are available, \\citet{Breit2016} found a constant value of the $p$-factor, with no dependence on the pulsation period.\\\\\n\n\\par Among the aforementioned studies that include LMC\/SMC Cepheids, only those of \\citet{Groe2008,Groe2013} rely on abundance determinations for individual Cepheids while the others use either the (oxygen) abundances derived in nearby HII regions or a mean, global abundance for a given galaxy. Because the determination of nebular abundances is still affected by uncertainties as pointed out by \\citet{Kew2008} \\citep[but see, e.g.,][]{Pil2016}; and because the correlation between oxygen and iron varies from galaxy to galaxy, it is of crucial importance to have direct metallicity measurements in Cepheids. This task is now well achieved for Milky Way Cepheids \\citep[see][and references therein]{Lem2007,Lem2008,Lem2013,Luck2011a,Luck2011b,Gen2013,Gen2014,Gen2015}. Despite the large number of Cepheids discovered in the Magellanic Clouds (3375\/4630 in the LMC\/SMC, respectively) by microlensing surveys such as OGLE \\citep[the Optical Gravitational Lensing Experiment][]{Udal2015}, only a few dozens have been followed up via high-resolution spectroscopy in order to determine their metallicities \\citep{Roma2005,Roma2008} or chemical composition \\citep{Luck1992,Luck1998}. In this context, it is worth mentioning that by transforming a hydrodynamical model of $\\delta$ Cephei into a consistent model of the same star in the LMC, \\citet{Nar2011} found a weak dependence of the $p$-factor on metallicity (1.5\\% difference between LMC and Solar metallicities).\\\\\n\n\\par NGC~1866 is of specific interest in that respect, as it is a young (age range of 100-200~Myr), massive cluster in the outskirts of the LMC that is known to harbor a large number (23) of Cepheids \\citep[e.g.,][]{Welch1993}. Many studies investigated the pulsational and evolutionary properties of the intermediate-mass stars in NGC~1866 \\citep[e.g.,][]{Bono1997,Fio2007,Mar2013,Mus2016} or the multiple stellar populations in LMC clusters \\citep{Mil2017}. The focus on pulsating stars in NGC~1866 is obviously driven by the need to improve the extragalactic distance scale using either period-luminosity relations or the Baade-Wesselink methods \\citep[e.g.,][]{Storm2011a,Storm2011b,Moli2012}.\\\\ \n\n\\par It is therefore quite surprising that the chemical composition of NGC~1866 stars has been investigated only in a few high-resolution spectroscopic studies: \\cite{Hill2000} analyzed a few elements in three red giant branch (RGB) stars in NGC~1866 and report [Fe\/H]=$-0.50\\pm0.1$~dex. \\cite{Mucc2011} derived the detailed chemical composition of 14 members of NGC~1866 and of 11 additional LMC field stars. They found an average [Fe\/H]=$-0.43$~dex for NGC~1866. \\cite{Colu2011,Colu2012a} determined the age and metallicity of NGC~1866 via high-resolution integrated light spectroscopy and extended their work to other elements in \\cite{Colu2012b}. The study of \\cite{Colu2012a} also includes three stellar targets in NGC~1866 for comparison purposes, with metallicities ranging from $-0.31$ to $-0.39$~dex.\\\\\n\n\\par In this paper, we focus on the chemical properties of six Cepheids in NGC~1866 and four field Cepheids in the SMC, and investigate what their chemical composition tells us about the stellar populations they belong to. Our sample increases the number of Cepheids with known metallicities in the LMC\/SMC by 20\\%\/25\\% and the number of Cepheids with known detailed chemical composition in the LMC\/SMC by 46\\%\/50\\%. The Baade-Wesselink analysis will be presented in a companion paper.\n\n\n\\section{Observations}\n\n\\par We selected stars for which both optical \\& near-infrared light curves and radial velocity measurements of good quality are already available, but for which no direct determination of the metallicity exists. We selected six Cepheids in the LMC NGC~1866 cluster and four field Cepheids in the SMC. The LMC cluster stars were observed with the FLAMES\/UVES high-resolution spectrograph \\citep{Pas2002} while the SMC field stars were observed with the UVES high-resolution spectrograph \\citep{Dek2000}. We used the red arm (CD \\#3) standard template centered on 580~nm which offers a resolution of 47~000 and covers the 476--684 nm wavelength range with a 5~nm gap around the central wavelength. We used the ESO reflex pipeline \\citep{Freu2013}\\footnote[1]{ftp:\/\/ftp.eso.org\/pub\/dfs\/pipelines\/uves\/uves-fibre-pipeline-manual-18.8.1.pdf\\\\ftp:\/\/ftp.eso.org\/pub\/dfs\/pipelines\/uves\/uves-pipeline-manual-22.14.1.pdf} to perform the basic data reduction of the spectra. The heliocentric corrections of the radial velocities were computed with the IRAF task {\\it rvcorrect}. The observing log is listed in Table~\\ref{obslog}. For the FLAMES\/UVES sample, the weather conditions deteriorated during the night. We therefore analyzed only the first three spectra of a series of six for each star, as they reached a higher S\/N. The S\/N values are listed in Table~\\ref{atmparam}.\\\\\n\n\\par The phases were computed by adopting the period and the epoch of maximum light from OGLE IV \\citep{Udal2015} as a zero point reference, except for HV~12202 for which no OGLE IV data are available. For this star, we used the values provided by \\cite{Moli2012}. The computations were made using heliocentric Julian dates (HJD), i. e., 0.5 days were added to the modified Julian dates (MJD) and the light travel time between the Earth and the Sun was taken into account. The HJDs were double-checked using the IRAF task {\\it rvcorrect}.\n\n\\begin{table*}[!htbp]\n\\caption{Observing log. The first six lines are spectra taken with the FLAMES\/UVES multi-object spectrograph. The other spectra were taken with the UVES spectrograph.}\n\\label{obslog}\n\\centering\\begin{tabular}{ccccc}\n\\hline\\hline\n Target & Date & MJD & Airmass & Exp time \\\\\n & & & (start) & (s) \\\\ \n\n\\hline\nNGC~1866 & 2008-12-06T00:35:23.385 & 54806.02457622 & 1.848 & 4800 \\\\\nNGC~1866 & 2008-12-06T01:56:13.752 & 54806.08071473 & 1.541 & 4800 \\\\\nNGC~1866 & 2008-12-06T03:17:03.638 & 54806.13684767 & 1.381 & 4800 \\\\\nNGC~1866 & 2008-12-06T04:50:18.350 & 54806.20160128 & 1.320 & 4800 \\\\\nNGC~1866 & 2008-12-06T06:11:08.646 & 54806.25773897 & 1.358 & 4800 \\\\\nNGC~1866 & 2008-12-06T07:31:58.631 & 54806.31387305 & 1.490 & 3600 \\\\\nHV~822 & 2008-11-15T00:57:58.745 & 54785.04026326 & 1.531 & 1000 \\\\\n & 2008-11-15T01:15:28.075 & 54785.05240828 & 1.523 & 1000 \\\\\n & 2008-11-15T01:32:57.446 & 54785.06455378 & 1.519 & 1000 \\\\\nHV~1328 & 2008-11-15T00:11:13.084 & 54785.00779033 & 1.569 & 800 \\\\\n & 2008-11-15T00:25:22.587 & 54785.01762254 & 1.556 & 800 \\\\\n & 2008-11-15T00:39:31.570 & 54785.02744873 & 1.545 & 800 \\\\\nHV~1333 & 2008-11-15T01:53:56.155 & 54785.07912217 & 1.531 & 1200 \\\\\n & 2008-11-15T02:14:45.620 & 54785.09358357 & 1.537 & 1200 \\\\ \n & 2008-11-15T02:35:34.996 & 54785.10804394 & 1.547 & 1200 \\\\\nHV~1335 & 2008-11-15T03:03:49.091 & 54785.12765152 & 1.569 & 1300 \\\\\n & 2008-11-15T03:26:18.517 & 54785.14326987 & 1.594 & 1300 \\\\\n & 2008-11-15T03:48:48.862 & 54785.15889887 & 1.625 & 1300 \\\\\n\\hline\n\\end{tabular}\n\\end{table*}\n\n\n\\section{Chemical abundances}\n\n\\subsection{Data analysis}\n\\label{dao}\n\\par In our spectra, we measured the equivalent widths of the absorption lines with DAOSPEC \\citep{Stet2008}: DAOSPEC fits lines with saturated Gaussians and all the lines detected are cross-correlated with a list of lines provided by the user. For each individual measurement of an equivalent width (EW), DAOSPEC provides the standard error $\\sigma_{EW}$ on the measurement and a quality parameter Q that becomes higher in the regions where the quality of the spectrum decreases or for strong lines that deviate from a Gaussian profile. We selected only lines with $\\sigma_{EW}$ $\\leq$ 10~\\% and Q~$\\leq$ 1.25. For both the determination of the atmospheric parameters and the computation of the abundances, we considered only the lines with 20~$\\leq$~EW~$\\leq$~130~m\\AA. \n\nThe equivalent width method was favoured as it enables a more homogeneous continuum placement, especially for spectra with a relatively low S\/N like ours (see examples in Fig.\\ref{spec}). The hyperfine structure can therefore not be taken into account. Current studies indicate that the effects of hyperfine structure splitting (hfs) are negligible or small for Y, Zr, Nd, and Eu in Cepheids \\citep{daSilva2016}, but not for Mn (Lemasle et al., in prep) or to a lesser extent La \\citep{daSilva2016}. A more detailed discussion about the hfs is provided in Sect~\\ref{hfs}.\n\n\\begin{figure}[!htbp] \n\\centering \n \\includegraphics[angle=-90,width=\\columnwidth]{spec_5317_5347.ps}\n \\caption{Excerpts of spectra covering the 5317--5347 \\AA{} range. {\\it Top:} HV1328 (SMC) at MJD=54785.01762254 (S\/N$\\approx$20).\n{\\it Bottom:} HV12198 (NGC~1866) at 54806.13684767 (S\/N$\\approx$30).}\n\\label{spec}\n\\end{figure}\n\n\\subsection{Radial velocities}\n\n\\par For the NGC 1866 sample, the accuracy of the radial velocity determined by DAOSPEC is in general better than $\\pm$2~km~s$^{-1}$, with a mean error in the individual velocities measurement of 1.157~km~s$^{-1}$. Thanks to a higher S\/N, the radial velocities for the SMC sample are even more accurate, with a mean error of 0.804~km~s$^{-1}$. Our measurements are listed in Table~\\ref{Vr}. Comments in footnotes come from the OGLE-III database \\citep{Sos2010a}. Note that in both cases the radial velocities obtained from the lower (L) and the upper (U) chip of the UVES red arm are in excellent agreement. The averaged radial velocities and the heliocentric corrections (computed with the IRAF task {\\it rvcorrect}, with a negligible uncertainty of $\\approx$0.005~km~s$^{-1}$) are also listed in Table~\\ref{Vr}.\n\n\\begin{table*}[htbp!]\n\\centering\n\\caption{Radial velocities for our targets in the LMC cluster NGC~1866 and in the field of the SMC. The radial velocities derived for the lower (L) and upper (U) chips of the UVES red arm are listed in cols. 4 and 5. The averaged values are listed in col. 6, the barycentric corrections in col.7 and the final values for the radial velocity (after correction) in col. 8.}\n\\label{Vr}\n\\begin{tabular}{cccccccc}\n\\hline\\hline\n\\multicolumn{8}{c}{{\\bf Targets in the LMC cluster NGC~1866}}\\\\\n\\hline\nTarget & Period (P) & Phase $\\phi$ & Vr$_{L}$\\tablefootmark{a} & Vr$_{U}$\\tablefootmark{b} & Vr (averaged) & Heliocentric correction & Vr corrected \\\\\n & (d) & & (km~s$^{-1}$) & (km~s$^{-1}$) & (km~s$^{-1}$) & (km~s$^{-1}$) & (km~s$^{-1}$)\\\\ \n\\hline \nHV~12197 & 3.1437642 & 0.081 & 283.399$\\pm$1.919 & 282.260$\\pm$3.202 & 283.098$\\pm$1.646 & -2.205 & 280.893$\\pm$1.646 \\\\\n & & 0.099 & 284.238$\\pm$1.390 & 284.180$\\pm$1.641 & 284.214$\\pm$1.061 & -2.242 & 281.972$\\pm$1.061 \\\\ \n & & 0.117 & 285.289$\\pm$1.567 & 284.997$\\pm$1.378 & 285.124$\\pm$1.035 & -2.294 & 282.830$\\pm$1.035 \\\\ \nHV~12198 & 3.5227781 & 0.643 & 315.940$\\pm$1.384 & 315.921$\\pm$1.552 & 315.932$\\pm$1.033 & -2.190 & 313.742$\\pm$1.033 \\\\ \n & & 0.659 & 316.662$\\pm$1.031 & 316.566$\\pm$1.332 & 316.626$\\pm$0.815 & -2.227 & 314.399$\\pm$0.815 \\\\ \n & & 0.675 & 316.960$\\pm$1.305 & 316.943$\\pm$1.097 & 316.950$\\pm$0.840 & -2.279 & 314.671$\\pm$0.840 \\\\ \nHV~12199 & 2.6391571 & 0.928 & 289.626$\\pm$2.129 & 289.346$\\pm$4.279 & 289.570$\\pm$1.906 & -2.199 & 287.371$\\pm$1.906 \\\\ \n & & 0.949 & 284.720$\\pm$1.187 & 284.655$\\pm$2.177 & 284.705$\\pm$1.042 & -2.236 & 282.469$\\pm$1.042 \\\\ \n & & 0.970 & 281.507$\\pm$1.528 & 281.312$\\pm$1.867 & 281.429$\\pm$1.182 & -2.288 & 279.141$\\pm$1.182 \\\\ \nHV~12202 & 3.101207 & 0.807 & 319.318$\\pm$2.632 & 318.444$\\pm$4.291 & 319.079$\\pm$2.244 & -2.180 & 316.899$\\pm$2.244 \\\\ \n & & 0.825 & 316.907$\\pm$2.040 & 316.018$\\pm$2.053 & 316.465$\\pm$1.447 & -2.217 & 314.248$\\pm$1.447 \\\\ \n & & 0.843 & 313.635$\\pm$1.472 & 312.713$\\pm$3.442 & 313.492$\\pm$1.353 & -2.269 & 311.223$\\pm$1.353 \\\\ \nHV~12203 & 2.9541342 & 0.765 & 323.664$\\pm$1.902 & 323.307$\\pm$2.098 & 323.503$\\pm$1.409 & -2.180 & 321.323$\\pm$1.409 \\\\ \n & & 0.784 & 322.905$\\pm$1.775 & 322.400$\\pm$1.448 & 322.602$\\pm$1.122 & -2.217 & 320.385$\\pm$1.122 \\\\ \n & & 0.803 & 320.983$\\pm$1.407 & 321.260$\\pm$1.702 & 321.095$\\pm$1.084 & -2.269 & 318.826$\\pm$1.084 \\\\ \nHV~12204 & 3.4387315 & 0.519 & 292.454$\\pm$0.524 & 292.107$\\pm$0.955 & 292.374$\\pm$0.459 & -2.163 & 290.211$\\pm$0.459 \\\\ \n & & 0.535 & 293.664$\\pm$0.919 & 293.164$\\pm$0.751 & 293.364$\\pm$0.582 & -2.200 & 291.164$\\pm$0.582 \\\\ \n & & 0.551 & 294.177$\\pm$0.713 & 294.166$\\pm$0.895 & 294.173$\\pm$0.558 & -2.252 & 291.921$\\pm$0.558 \\\\ \n\\hline \n\\multicolumn{8}{c}{{\\bf Targets in the SMC}}\\\\\n\\hline\nHV~822\\tablefootmark{c} & 16.7419693 & 0.998 & 101.288$\\pm$1.736 & 101.438$\\pm$2.309 & 101.342$\\pm$1.388 & -12.692 & 88.650$\\pm$1.388 \\\\\n & & 0.999 & 101.143$\\pm$1.931 & 101.027$\\pm$1.672 & 101.077$\\pm$1.264 & -12.701 & 88.376$\\pm$1.264 \\\\\n & & 0.999 & 101.450$\\pm$0.939 & 100.845$\\pm$1.543 & 101.286$\\pm$0.802 & -12.709 & 88.577$\\pm$0.802 \\\\\nHV~1328\\tablefootmark{d} & 15.8377104 & 0.883 & 121.800$\\pm$1.013 & 121.771$\\pm$1.605 & 121.792$\\pm$0.857 & -12.808 & 108.984$\\pm$0.857 \\\\\n & & 0.884 & 121.592$\\pm$0.626 & 121.509$\\pm$0.615 & 121.550$\\pm$0.439 & -12.814 & 108.736$\\pm$0.439 \\\\\n & & 0.884 & 121.402$\\pm$1.069 & 121.716$\\pm$0.876 & 121.590$\\pm$0.678 & -12.821 & 108.769$\\pm$0.678 \\\\\nHV~1333 & 16.2961015 & 0.659 & 179.553$\\pm$1.333 & 179.786$\\pm$0.735 & 179.732$\\pm$0.644 & -12.742 & 166.990$\\pm$0.644 \\\\\n & & 0.660 & 179.816$\\pm$1.267 & 179.909$\\pm$0.930 & 179.876$\\pm$0.750 & -12.752 & 167.124$\\pm$0.750 \\\\\n & & 0.661 & 179.486$\\pm$1.555 & 179.972$\\pm$0.827 & 179.865$\\pm$0.730 & -12.761 & 167.104$\\pm$0.730 \\\\\nHV~1335 & 14.3813503 & 0.318 & 163.310$\\pm$0.763 & 163.376$\\pm$1.360 & 163.326$\\pm$0.665 & -12.750 & 150.576$\\pm$0.665 \\\\\n & & 0.319 & 162.985$\\pm$1.154 & 163.194$\\pm$1.102 & 163.094$\\pm$0.797 & -12.760 & 150.334$\\pm$0.797 \\\\\n & & 0.320 & 163.352$\\pm$1.466 & 163.198$\\pm$0.877 & 163.239$\\pm$0.753 & -12.769 & 150.470$\\pm$0.753 \\\\\n\\hline \n\\end{tabular} \n\\tablefoot{\n\\tablefoottext{a}{Red arm lower chip.}\n\\tablefoottext{b}{Red arm upper chip.}\n\\tablefoottext{c}{secondary period of 1.28783d (OGLE-III database).}\n\\tablefoottext{d}{secondary period of 14.186d (OGLE-III database).}\n}\n\\end{table*}\n\n\\par Because this was one of our target selection criteria, there is an extensive amount of radial velocity data available for the Cepheids in our sample. From these data it was possible to ascertain that our NGC~1866 Cepheids are indeed cluster members. Excluding variable stars, \\citet{Mucc2011} report an average heliocentric velocity of v=298.5$\\pm$0.4~km~s$^{-1}$ with a dispersion of $\\sigma$=1.6~km~s$^{-1}$. For both the LMC and SMC targets our radial velocity measurements are in excellent agreement with the expected values at the given pulsation phase obtained from the radial velocity curves published in the literature \\citep{Welch1991,Storm2004a,Storm2005,Moli2012,Mar2013,Mar2017}. \n\\par Systematic shifts between different samples are generally attributed to the orbital motion in a binary system. Two stars in our sample (HV~12202 and HV~12204) were identified as spectroscopic binaries \\citep{Welch1991,Storm2005}. As far as HV~12202 is concerned, our measurements are in good agreement with all the data compiled by \\citet{Storm2005} except for their CTIO data and the latest part of the \\citet{Welch1991} data, and therefore support the shifts of +18~km~s$^{-1}$ (respectively +21~km~s$^{-1}$) applied to these datasets in order to provide an homogeneous radial velocity curve. For the same purpose, the latest data from \\citet{Welch1991} had to be shifted by +7~km~s$^{-1}$ and our measurements should be shifted by $\\approx$ +15~km~s$^{-1}$ in the case of HV~12204. Binarity is a common feature for Milky Way Cepheids \\citep[more than 50\\% of them are binaries, see][]{Sza2003}, but there is a strong observational bias with distance and indeed the number of known binaries is much lower for the farther, fainter Cepheids in the Magellanic Clouds \\citep{Sza2012}. It should be noted that \\cite{Ander2014} found modulations in the radial velocity curves of four Galactic Cepheids. However, the order of magnitude of the effect ranges from several hundred m~s$^{-1}$ to a few km~s$^{-1}$ and cannot account for the differences reported here in the case of HV~12202 and HV~12204.\\\\\n\n\\subsection{Atmospheric parameters}\n \n\\par As Cepheids are variable stars, simultaneous photometric and spectroscopic observations are in general not available and the atmospheric parameters \nare usually derived from the spectra only. \\cite{KovGor2000} have developed an accurate method to derive the effective temperature $T_{\\rm eff}${} from the depth ratio of carefully chosen pairs of lines that have been used extensively in Cepheids studies \\citep{And2002a,Luck2011b}.\n \nAs the red CCD detector of UVES is made of two chips side by side (lower: L; upper: U), there is a gap of $\\approx$ 50~\\AA{} around the central wavelength (580 nm in our case) and we could not use the lines falling in this spectral domain. Moreover, the line depth ratios have been calibrated for Milky Way Cepheids that are more metal-rich than the Magellanic Cepheids (especially in the case of the SMC)\\footnote{The metallicity of Milky Way Cepheids continuously decreases from +0.4--+0.5 dex in the inner disk \\citep[e.g., ][]{And2002b,Pedi2010,Martin2015,And2016} to $\\approx$ $-0.4$~dex in the outer disk \\citep[e.g., ][]{Luck2003, Lem2008}. Current high-resolution spectroscopic studies indicate that Cepheids have metallicities ranging from $-0.62$ to $-0.10$~dex \\citep{Luck1992,Luck1998,Roma2008} in the LMC and from $-0.87$ to $-0.63$~dex in the SMC.}. It also turns out that several stars in our sample were observed at a phase where they reach higher $T_{\\rm eff}${} ($>$6000 K) during the pulsation cycle. The combination of a high $T_{\\rm eff}${} and a rather low metallicity made it very challenging to measure the depth of some lines, and in particular the weak line of the pairs. As a result, we could only use a limited number of line depth ratios (typically 5--10 out of 32) to determine $T_{\\rm eff}$. Moreover, for two stars (HV~12199 and HV~822), we were unable to determine $T_{\\rm eff}${} from the line depth ratio as their temperature ($>$6400~K) at the time of the observations fell above the range of temperatures where most ratios are calibrated \\footnote{Depending on the ratio, the upper limit varies between 6200 and 6700~K.}.\\\\\n \n\\par To ensure the determination of $T_{\\rm eff}$, we double-checked that lines with both high and low $\\chi_{\\rm ex}$ values properly fit the curve of growth (See Appendix~\\ref{CoG_newmarcs}) and that the Fe~I abundances are independent from the excitation potential of the lines. In a canonical spectroscopic analysis, we determined the surface gravity $log~g${} and the microturbulent velocity V$_{t}${} by imposing that the ionization balance between Fe~I and Fe~II is satisfied and that the Fe~I abundance is independent from the EW of the lines. On average we have at our disposal 42~Fe~I\/7~Fe~II lines in the NGC~1866 Cepheids and 42~Fe~I\/11~Fe~II lines in the SMC Cepheids. We note that the adopted $T_{\\rm eff}${} values are in general in very good agreement with those derived from the line depth ratios. The atmospheric parameters are listed in Table~\\ref{atmparam}. \n \n\\par As mentioned above, the Cepheids in our sample have rather high temperatures, two of them hot enough at the phase of the observations to prevent the use of line depth ratios to determine their temperature. It has been noted before \\citep{Bro2004} that these stars are located in the color-magnitude diagram at the hot tip of the so-called \"blue nose\" experienced by core He-burning supergiants. During this evolutionary stage they cross the instability strip and start pulsating.\n\n\\par As we impose the ionization balance between Fe I and Fe II to derive $log~g$, NLTE effects affecting primarily Fe I could hamper an accurate determination of $log~g${} \\citep{LL1985}. There is currently no extensive study of NLTE effects in Cepheids, although NLTE abundances have been derived for some individual elements like O \\citep[][and references therein]{Koro2014} or Ba \\citep[][and references therein]{And2014}. It is beyond the scope of this paper to provide a full discussion of NLTE effects in Cepheids, and we refer the reader to the discussion in e.g., \\citet{Kov1999} or \\citet{Yong2006}. Several arguments have been brought forward to support the fact that NLTE effects may be limited in Cepheids. For instance, \\citet{And2005} followed several Cepheids with 3d$<$P$<$6d throughout the entire period and found identical [Fe\/H] and abundances ratios (within the uncertainties), although $T_{\\rm eff}${} varies by $\\approx$ 1000~K (the same holds for Cepheids with different period ranges studied in this series of papers). Also \\citet[][]{Yong2006} found a mean difference [TiI\/Fe]--[TiII\/Fe]=0.07$\\pm$0.02 ($\\sigma$=0.11). As this difference falls within the measurement uncertainties, they concluded that the values of $log~g${} obtained via the ionization equilibrium of FeI\/FeII are satisfactory. All these arguments point toward the fact that a canonical spectroscopic analysis provides consistent, reliable results. However, the aforementioned studies deal with Milky Way Cepheids. As Magellanic Cepheids are slightly more metal-poor, NLTE effects should be a bit more pronounced than in the Galactic ones. In a study of 9 LMC F supergiants, \\citet{Hill1995} introduced an overionization law and obtained higher (+0.6 dex) spectroscopic gravities that are in good agreement with those derived from photometry. They note that [Fe\/H] becomes only +0.1 dex higher than in the LTE case and that the global abundance pattern remains unchanged, as already reported by, e.g., \\cite{Spite1989}.\n\n\\subsection{Comparison with models}\n\n\\par \\cite{Mar2013} have used non-linear convective pulsation models in order to reproduce simultaneously the lightcurves in several photometric bands and the radial velocity curves of a few Cepheids in NGC~1866. For HV~12197 they reached a good agreement between theory and observations and report a mean $T_{\\rm eff}${} of 5850~K. They also plotted the temperature predicted by the model and for the phases 0.08--0.12 they found $T_{\\rm eff}${} of the order of 6300~K and slightly below (their Fig.~8, bottom panel), in quite good agreement with our measurements that fall around 6150~K. For HV~12199, they report a mean $T_{\\rm eff}${} of 6125~K but had to modify notably the projection factor to reach the best match with the radial velocity curve. They also mention that using the lightcurves only would lead to a hotter star (<~$T_{\\rm eff}${}~> = 6200~K), but in this case an even lower (and unrealistic) value would be required for the projection factor in order to fit the radial velocity curve. The $T_{\\rm eff}${} curve for HV~12199 (their Fig.~8, top panel) in the phases 0.93--0.97 shows a rapid rise of the temperature and the corresponding $T_{\\rm eff}${} value of $\\approx$ 6250--6300~K, somewhat below the values around 6600~K we determined for $T_{\\rm eff}$. \n\n\\subsection{Abundance determinations}\n\n\\par Our abundance analysis is based on equivalent widths measured with DAOSPEC (see Sect.~\\ref{dao}). We derived the abundances of 16 elements (several of them in two ionization states) for which absorption lines could be measured in the spectral domain covered by the UVES red arm (CD~ \\#3, 580~nm) standard template. In a few cases we updated the linelists of \\cite{Gen2013} and \\cite{Lem2013} with oscillator strengths and excitation potentials from recent releases of the Vienna Atomic Lines Database \\citep[VALD,][and references therein]{Kup1999} and from the Gaia-ESO survey linelist \\citep{Heit2015}. We took the values tabulated by \\citet{Anders1989} as Solar references, except for Fe and Ti for which we used $log~\\epsilon_{Fe}$=7.48 and $log~\\epsilon_{Ti}$=5.02. We used MARCS (1D LTE spherical) atmosphere models \\citep{Gus2008} covering the parameter space of Magellanic Clouds Cepheids. Abundances were computed with {\\it calrai}, a LTE spectrum synthesis code originally developed by \\cite{Spite1967} and continuously updated since then. For a given element, the abundance derived from a single spectrum is estimated as the mean value of the abundances determined for each individual line of this element. The final abundance of a star is then obtained by computing the weighted mean (and standard deviation) for the three spectra analyzed, where the weight is the number of lines of a given element measured in each spectrum. \n\n\\begin{table*}[!htbp]\n\\caption{Coordinates, properties and atmospheric parameters for the Cepheids in our sample. V magnitudes and periods are from OGLE IV, except for HV12202, for which they have been found in \\citet{Moli2012} and \\citet{Mus2016}. Col.~7 refers to the $T_{\\rm eff}${} derived from the line depth ratio method \\citep[LDR,][]{KovGor2000} while col.~8 is the $T_{\\rm eff}${} derived from the excitation equilibrium. The last column lists the S\/N around 5228 and 5928 \\AA{} respectively.}\n\\label{atmparam}\n\\centering\\small\n\\begin{tabular}{lccccccccccc}\n\\hline\\hline\n\\multicolumn{12}{c}{{\\bf Targets in the LMC cluster NGC~1866}}\\\\\n\\hline\n Cepheid & RA (J2000) & Dec (J2000) & V & P & $\\phi$ & $T_{\\rm eff}$~(LDR) & $T_{\\rm eff}$ & $log~g$ & V$_{t}$ & [Fe\/H] & S\/N \\\\\n & (dms) & (dms) & (mag) & (d) & & (K) & (K) & (dex) &(km~s$^{-1}$)& (dex) & {\\tiny(5228\/5928\\AA)} \\\\\n\\hline \nHV~12197 & 05 13 13.0 & -65 30 48 & 16.116 & 3.1437642 & 0.081 & 6060$\\pm$ 97 (3) & 6150 & 1.5 & 3.1 & -0.35 & 16\/15 \\\\ \n & & & & 3.1437642 & 0.099 & & 6150 & 1.5 & 3.2 & -0.35 & 28\/27 \\\\ \n & & & & 3.1437642 & 0.117 & & 6100 & 1.5 & 3.1 & -0.35 & 27\/25 \\\\ \nHV~12198 & 05 13 26.7 & -65 27 05 & 15.970 & 3.5227781 & 0.643 & 5634$\\pm$ 85 (6) & 5625 & 1.4 & 3.4 & -0.35 & 13\/19 \\\\ \n & & & & 3.5227781 & 0.659 & & 5625 & 1.5 & 3.6 & -0.35 & 20\/26 \\\\ \n & & & & 3.5227781 & 0.675 & & 5625 & 1.4 & 3.6 & -0.35 & 21\/23 \\\\ \nHV~12199 & 05 13 19.0 & -65 29 30 & 16.283 & 2.6391571 & 0.928 & --~~ & 6550 & 2.2 & 3.2 & -0.30 & 15\/14 \\\\ \n & & & & 2.6391571 & 0.949 & & 6600 & 2.1 & 3.0 & -0.30 & 29\/31 \\\\ \n & & & & 2.6391571 & 0.970 & & 6650 & 2.0 & 3.1 & -0.35 & 26\/32 \\\\ \nHV~12202 & 05 13 39.0 & -65 29 00 & 16.08 & 3.101207 & 0.807 & 5712$\\pm$100 (6) & 5775 & 1.6 & 3.1 & -0.40 & 17\/14 \\\\ \n & & & & 3.101207 & 0.825 & & 5900 & 1.6 & 3.1 & -0.40 & 20\/25 \\\\ \n & & & & 3.101207 & 0.843 & & 5900 & 1.5 & 2.9 & -0.40 & 20\/24 \\\\ \nHV~12203 & 05 13 40.0 & -65 29 36 & 16.146 & 2.9541342 & 0.765 & 5856$\\pm$117 (9) & 5850 & 1.7 & 3.5 & -0.35 & 16\/19 \\\\ \n & & & & 2.9541342 & 0.784 & & 5800 & 1.2 & 3.3 & -0.35 & 17\/26 \\\\ \n & & & & 2.9541342 & 0.803 & & 5800 & 1.6 & 3.4 & -0.35 & 19\/24 \\\\ \nHV~12204 & 05 13 58.0 & -65 28 48 & 15.715 & 3.4387315 & 0.519 & 5727$\\pm$ 98 (11) & 5700 & 1.2 & 2.8 & -0.35 & 19\/23 \\\\ \n & & & & 3.4387315 & 0.535 & & 5725 & 1.3 & 2.9 & -0.35 & 22\/31 \\\\ \n & & & & 3.4387315 & 0.551 & & 5700 & 1.2 & 2.9 & -0.35 & 21\/28 \\\\ \n\\hline \n\\multicolumn{12}{c}{{\\bf Targets in the SMC}}\\\\\n\\hline\nHV~822 & 00 41 55.5 & -73 32 23 & 14.524 & 16.7419693 & 0.998 & --~~ & 6400 & 1.8 & 2.7 & -0.75 & 33\/48 \\\\\n & & & & 16.7419693 & 0.999 & & 6400 & 1.8 & 2.7 & -0.75 & 41\/46 \\\\\n & & & & 16.7419693 & 0.999 & & 6400 & 1.8 & 2.7 & -0.75 & 35\/42 \\\\\nHV~1328 & 00 32 54.9 & -73 49 19 & 14.115 & 15.8377104 & 0.883 & 6325$\\pm$ 98 (5) & 6100 & 1.9 & 2.6 & -0.60 & 26\/37 \\\\\n & & & & 15.8377104 & 0.884 & & 6100 & 1.9 & 2.6 & -0.60 & 31\/37 \\\\\n & & & & 15.8377104 & 0.884 & & 6100 & 1.9 & 2.6 & -0.60 & 29\/40 \\\\\nHV~1333 & 00 36 03.5 & -73 55 58 & 14.729 & 16.2961015 & 0.659 & 5192$\\pm$102 (8) & 5175 & 0.4 & 3.2 & -0.90 & 18\/26 \\\\\n & & & & 16.2961015 & 0.660 & & 5200 & 0.4 & 2.8 & -0.80 & 19\/25 \\\\\n & & & & 16.2961015 & 0.661 & & 5175 & 0.4 & 3.2 & -0.90 & 16\/30 \\\\\nHV~1335 & 00 36 55.7 & -73 56 28 & 14.762 & 14.3813503 & 0.318 & 5566$\\pm$156 (6) & 5600 & 0.6 & 2.6 & -0.80 & 25\/29 \\\\\n & & & & 14.3813503 & 0.319 & & 5675 & 0.8 & 2.6 & -0.75 & 28\/29 \\\\\n & & & & 14.3813503 & 0.320 & & 5600 & 0.6 & 2.7 & -0.80 & 25\/29 \\\\\n\\hline \n\\end{tabular}\n\\end{table*}\n\n\\subsection{Abundances} \n\\label{Ab} \n \n\\par We provide the abundances of one light element (Na), several $\\alpha$-elements (Mg, Si, S, Ca, Ti), iron-peak elements (Sc, Cr, Mn, Fe, Ni), and neutron capture elements (Y, Zr, La, Nd, Eu). As already mentioned, we analyzed three individual (back to back) spectra for each star and the abundances derived are in most cases in excellent agreement. As expected, the size of the error bars is correlated to the number of lines analyzed. In contrast to our Cepheid studies in the Milky Way, where Si comes second after iron for the number of lines measured, the UVES red arm (CD \\#3, 580~nm) spectral domain contains only a few Si lines with sufficient quality but a larger number of Ca lines and indeed 9--11 calcium lines were usually measured in our spectra. The individual abundances (per spectrum) are listed in Tables \\ref{abund_12197}--\\ref{abund_12204} for the NGC~1866 Cepheids and in Tables \\ref{abund_822}--\\ref{abund_1335} for the SMC Cepheids. The last two columns of these tables list the weighted means and standard deviations, adopted as the chemical composition of the star in the rest of the paper.\n\n\\par \\cite{Moli2012} provide the metallicities for three Cepheids in NGC~1866, analyzed in the same way as the stars in \\cite{Mucc2011}. Two of \\cite{Moli2012} Cepheids are also included in our sample, namely HV~12197 and HV~12199: taking into account a tiny difference (0.02 dex) in the solar reference value for [Fe\/H], the results agree very well: they report [Fe\/H]=$-0.39\\pm0.05$ for HV~12197 while we found $-0.33\\pm0.07$~dex, and [Fe\/H]=$-0.38\\pm0.06$ for HV~12199 while we found $-0.31\\pm0.05$. \n\n\\par For a good number of our spectra, several elements (Si, Ti, Cr) could be measured in two ionization states, in addition to the usual Fe~I~\/~Fe~II. When the ionization equilibrium is reached for iron, it is usually also reached for the other elements as the abundances derived from the neutral and ionized species agree within the error bars, thus reinforcing our confidence in our atmospheric parameters, in particular $log~g$. In order to quantify how the results are affected by uncertainties in the atmospheric parameters, we computed the abundances with over- or underestimated values of $T_{\\rm eff}$ ($\\pm$150 K), $log~g$ ($\\pm$0.3 dex), V$_{t}$ ($\\pm$0.5 km~s$^{-1}$) for two spectra at different $T_{\\rm eff}$. Uncertainties in [Fe\/H] leave the abundances unchanged and are therefore not considered in this exercise. The sum in quadrature of the differences in the computed abundances is adopted as the uncertainty in the abundances due to the uncertainties in the atmosphere parameters. The resulting values are listed in Table~\\ref{err_budget_atmparam}. \n\n\\begin{table}[htbp!]\n\\centering\n\\caption{Uncertainties in the final abundances due to uncertainties in the atmospheric parameters. Cols. 2, 3, 4 indicate respectively how the abundances are modified (mean values) when they are computed with over- or underestimated values of $T_{\\rm eff}$ ($\\pm$150 K), $log~g$ ($\\pm$0.3 dex), or V$_{t}$ ($\\pm$0.5 dex). The sum in quadrature of the differences is adopted as the uncertainty in the abundances due to the uncertainties in the atmosphere parameters}\n\\label{err_budget_atmparam}\n\\begin{tabular}{ccccc}\n\\hline\\hline\n\\multicolumn{5}{c}{{Error budget for HV~12198, $\\phi$=0.675 (MJD=54806.13684767)}}\\\\\n\\hline\nElement & $\\Delta$$T_{\\rm eff}$ & $\\Delta$$log~g$ & $\\Delta$V$_{t}$ & Quadratic \\\\\n & {\\small ($\\pm$ 150 K)} & {\\small ($\\pm$ 0.3 dex)} & {\\small ($\\pm$ 0.5 km~s$^{-1}$)} & sum \\\\\n & (dex) & (dex) & (dex) & (dex) \\\\ \n\\hline \n [NaI\/H] & 0.08 & 0.00 & 0.03 & 0.09\\\\{}\n [MgI\/H] & 0.14 & 0.00 & 0.08 & 0.16\\\\{}\n [SiI\/H] & 0.07 & 0.01 & 0.03 & 0.07\\\\{}\n[SiII\/H] & 0.12 & 0.12 & 0.11 & 0.19\\\\{}\n [SI\/H] & 0.07 & 0.08 & 0.04 & 0.11\\\\{}\n [CaI\/H] & 0.10 & 0.00 & 0.06 & 0.12\\\\{}\n[ScII\/H] & 0.03 & 0.12 & 0.08 & 0.15\\\\{}\n [TiI\/H] & 0.15 & 0.00 & 0.03 & 0.15\\\\{}\n[TiII\/H] & 0.02 & 0.12 & 0.02 & 0.12\\\\{}\n[CrII\/H] & 0.02 & 0.11 & 0.07 & 0.13\\\\{}\n [MnI\/H] & 0.12 & 0.00 & 0.03 & 0.12\\\\{}\n [FeI\/H] & 0.13 & 0.00 & 0.05 & 0.13\\\\{}\n[FeII\/H] & 0.01 & 0.12 & 0.05 & 0.13\\\\{}\n [NiI\/H] & 0.13 & 0.00 & 0.04 & 0.13\\\\{}\n [YII\/H] & 0.04 & 0.12 & 0.05 & 0.13\\\\{}\n[ZrII\/H] & 0.03 & 0.11 & 0.03 & 0.12\\\\{}\n[LaII\/H] & 0.07 & 0.12 & 0.04 & 0.14\\\\{}\n[NdII\/H] & 0.07 & 0.22 & 0.05 & 0.23\\\\{}\n[EuII\/H] & 0.04 & 0.12 & 0.02 & 0.12\\\\ \n\\hline\n\\multicolumn{5}{c}{{Error budget for HV~1328, $\\phi$=0.884 (MJD=54785.02744873)}}\\\\\n\\hline\nElement & $\\Delta$$T_{\\rm eff}$ & $\\Delta$$log~g$ & $\\Delta$V$_{t}$ & Quadratic \\\\\n & {\\small ($\\pm$ 150 K)} & {\\small ($\\pm$ 0.3 dex)} & {\\small($\\pm$ 0.5 km~s$^{-1}$)} & sum \\\\\n & (dex) & (dex) & (dex) & (dex) \\\\ \n\\hline \n [NaI\/H] & 0.10 & 0.04 & 0.02 & 0.11 \\\\{}\n [MgI\/H] & 0.11 & 0.05 & 0.02 & 0.12 \\\\{}\n [SiI\/H] & 0.18 & 0.07 & 0.02 & 0.19 \\\\{}\n [CaI\/H] & 0.13 & 0.06 & 0.04 & 0.15 \\\\{}\n[ScII\/H] & 0.28 & 0.10 & 0.06 & 0.30 \\\\{}\n [TiI\/H] & 0.09 & 0.11 & 0.03 & 0.15 \\\\{}\n[TiII\/H] & 0.12 & 0.03 & 0.07 & 0.14 \\\\{}\n [CrI\/H] & 0.13 & 0.05 & 0.07 & 0.15 \\\\{}\n[CrII\/H] & 0.10 & 0.07 & 0.06 & 0.13 \\\\{}\n [FeI\/H] & 0.11 & 0.06 & 0.08 & 0.15 \\\\{}\n[FeII\/H] & 0.22 & 0.13 & 0.09 & 0.26 \\\\{}\n [NiI\/H] & 0.09 & 0.13 & 0.05 & 0.16 \\\\{}\n [YII\/H] & 0.07 & 0.08 & 0.03 & 0.11 \\\\{}\n[ZrII\/H] & 0.31 & 0.12 & 0.02 & 0.33 \\\\{}\n[LaII\/H] & 0.13 & 0.05 & 0.03 & 0.14 \\\\{}\n[NdII\/H] & 0.10 & 0.15 & 0.03 & 0.18 \\\\{}\n[EuII\/H] & 0.28 & 0.08 & 0.03 & 0.29 \\\\\n\\hline \n\\end{tabular} \n\\end{table}\n\n\\label{hfs}\n\\par For the stars in our sample, NLTE effects are negligible for Na ($\\leq$ 0.1 dex) as computed by \\cite{Lind2011} for a range of atmospheric parameters including yellow supergiants and by \\cite{Take2013} for Cepheids. Using DAOSPEC to automatically determine the EW of the lines (and the relatively low S\/N of our spectra) made it impossible for us to take into account the contribution of the hyperfine structure splitting for iron-peak elements, and for neutron-capture elements as in \\cite{daSilva2016}. Depending on the line considered, the latter authors estimated the hfs correction to range from negligible to $\\approx$0.20 dex. In the case of the 6262.29 La~II line, it reaches $-0.211\\pm0.178$~dex, where the quoted error represents the dispersion around the mean hfs correction for this line. In a forthcoming paper (Lemasle et al., in prep) we study the impact of the hfs on the Mn abundance in Milky Way Cepheids. The three Mn lines measured in our Magellanic Cepheids belong to the (6013,6016,6021\\AA) triplet and as expected we find lower Mn abundances when the hfs is taken into account. For the 6013 \\AA{} lines, we find a mean effect of $-0.18\\pm0.21$~dex (max: $-0.65$~dex), while it is slightly lower for the 6016 \\AA{} and 6021 \\AA{} lines, with a mean effect of $-0.12\\pm0.22$~dex (max: $-0.45$~dex) and $-0.12\\pm0.16$~dex (max: $-0.40$~dex) respectively. It should be noted that the Milky Way Cepheids that are on average more metal-rich and somewhat cooler than the Magellanic Cepheids in our sample. \n \n\\section{Discussion} \n \n\\subsection{The chemical composition of Cepheids in NGC~1866} \n \n\\par The most striking feature of the abundance pattern of the NGC~1866 Cepheids is the very low star-to-star scatter (see Fig.~\\ref{AbXH}): all the elements for which a good number of lines could be measured (e.g., Si, Ca, Fe) have abundances [X\/H] that fall within $\\approx$ 0.1 dex from each other. The same also applies for other elements (e.g., S, Sc, Ti, Ni, Y, Zr) where only a small number of lines could be measured, and even in the case of, e.g., Na or Mg, where only one line could be measured, the scatter remains smaller than 0.2 dex. In a few cases (mostly for neutron-capture elements), a star has a discrepant abundance for a given element, either because this element could be measured (probably poorly) in only one of the spectra (e.g., Mn in HV~12199, La in HV~12203) or because one of the spectra gives a discrepant value (e.g., Nd for HV~12202 or Eu for HV~12197). Ignoring the outliers, the star to star scatter is similar to the one observed for the other elements.\n\\par This small star-to-star scatter is a strong indication that the six Cepheids in our NGC~1866 sample are bone fide cluster members, sharing a very similar chemical composition as expected if they were born in the same place and at the same time. Indeed, they all have 2.64d~<~P~<~3.52d and it is well-known that classical Cepheids obey a period-age relation \\citep[e.g.,][see also Sect.~\\ref{age}]{Efre1978,Greb1998,Bono2005}.\\\\\n\n\\begin{figure*}[!htbp] \n\\centering \n \\includegraphics[angle=-90,width=\\textwidth]{NGC1866_XH_morelines.eps}\n \\caption{Abundance ratios ([X\/H]) for our NGC~1866 Cepheids for different elements identified by their atomic number Z.}\n\\label{AbXH}\n\\end{figure*}\n\n\\par With [Fe\/H]~$\\approx$~$-0.4$~dex, our NGC~1866 Cepheids can be compared to Cepheids located in the outer disc of the Milky Way, at Galactocentric distances R$_{G}$~>~10~kpc. A quick glance at the Cepheid abundances in, e.g., \\cite{Lem2013}, and \\citet{Gen2015} indicates that the [Na\/Fe] and [$\\alpha$\/Fe] abundances in the NGC~1866 Cepheids fall slightly below those observed in the Milky Way Cepheids for the corresponding range of metallicities. The same comparison for neutron-capture elements \\citep[in][]{daSilva2016} is less meaningful as the low S\/N of our spectra prevented us from taking the hyperfine structure into account in the current study. The [Y\/Fe] ratios appear to be similar, which is not surprising as the hfs corrections reported by \\cite{daSilva2016} are small for the Y~II lines. The [La\/Fe], [Nd\/Fe], and [Eu\/Fe] ratios appear to be higher than in the Milky Way Cepheids with similar metallicities. This is certainly partially due to the hfs corrections. Indeed \\cite{daSilva2016} report that the abundances derived from some of the La~II lines can be smaller by up to $\\approx$0.2~dex. On the other hand, their hfs corrections for the Eu lines are very small, and they did not apply any correction for Nd, which indicates that at least a fraction of the difference is intrinsic.\\\\ \n \n\\par Cepheids embedded in open clusters are extremely important: as the clusters' distances can be determined independently via main~sequence or isochrone fitting, their Cepheids can be used to calibrate the period-luminosity relations \\citep[e.g.,][]{Tur2010}. Furthermore, they can be used to establish period-age relations since the ages of star clusters can be determined from their resolved color-magnitude diagrams. The search for Cepheids as members of open clusters or OB associations was conducted in a long term effort\\footnote{\\url{http:\/\/www.ap.smu.ca\/~turner\/cdlist.html}} by, e.g., \\cite{Tur2012,Maj2013}, and references therein as well as by \\cite{Ander2013} and \\cite{Chen2015} in recent extensive studies. They combined spatial (position, distance) and kinematic data with additional information (age, [Fe\/H]) about the stellar populations of the open clusters and found roughly 30 Cepheids associated with open clusters in the Milky Way. However the maximum number of Cepheids that belong to a given cluster is two, much lower than the 23 Cepheids found in NGC~1866 \\citep[e.g.,][]{Welch1993}.\\\\\n\\indent Comparing the detailed chemical composition of the Cepheids with the one of the other cluster members, as done for the first time in this paper (see Sect.~\\ref{compRGB}), speaks in favor of the Cepheid membership of the cluster and should be considered in the future as an important criterion when seeking to match Cepheids to open clusters. This argument holds only if the photospheric abundances in this evolutionary phase were not altered by stellar evolution. In the case of Cepheids, this is expected only for C, N (the first dredge-up alters the surface composition of C and N, and leaves O unaltered) and probably Na (the Ne--Na cycle brings Na-enriched material to the surface). As far as the Milky Way is concerned, the chemical composition of (RGB) stars in open clusters containing Cepheids is often missing, while the direct measurement of stellar abundances in more distant galaxies is out of reach for the current facilities, with the exception of bright, red supergiants \\citep[RSGs, e.g., ][]{Davies2015,Pat2015,Gaz2015}. Obtaining detailed abundances from RSGs or cluster integrated light spectroscopy \\citep{Colu2012a} for those extragalactic clusters harboring Cepheids would allow us to investigate the longstanding issue of a possible metallicity dependence of the period-luminosity relations that might affect the extragalactic distance scale \\citep[e.g.,][]{Roma2008}. \n \n\\subsection{Comparison with giant stars in NGC~1866 and integrated light spectroscopy}\n\\label{compRGB} \n \n\\par Fig.~\\ref{Abratios} shows a comparison of the abundance ratios [X\/Fe] between the six NGC~1866 Cepheids in our sample and other NGC~1866 stars: the 14 RGB stars of \\cite{Mucc2011} for which we show the mean abundance ratios and dispersions and the three stars of \\cite{Colu2012a} displayed individually. We also overplot the cluster mean abundance derived from integrated light spectroscopy by \\cite{Colu2012a}. All the abundances have been rescaled to our solar reference values.\\\\\n \n\\begin{figure*}[!htbp] \n\\centering \n \\includegraphics[angle=-90,width=\\textwidth]{NGC1866_morelines_corr.eps}\n \\caption{Abundance ratios ([X\/Fe]) in NGC~1866 for different elements identified by their atomic number Z. Our Cepheids are the colored open circles, The mean value and dispersion for RGB stars in NGC~1866 from \\citet{Mucc2011} are given by the black triangle and solid line. Individual stellar abundances in NGC~1866 by \\citet{Colu2012b} are depicted by gray stars. The mean value and dispersion obtained by \\citet{Colu2012b} via integrated light spectroscopy are indicated by the gray triangle and dotted line. All the abundance ratios have been rescaled to our Solar reference values.}\n\\label{Abratios}\n\\end{figure*}\n\n\\par Our Cepheids are slightly enriched in sodium with respect to the RGB stars of \\cite{Mucc2011}. Similar Na overabundances have already been reported in the Milky Way \\citep[e.g.,][]{Gen2015} when comparing Cepheids and field dwarfs in the thin and thick disc \\citep{Sou2005}. Although this overabundance is probably partially due to NLTE effects (see Sect.~\\ref{Ab}), it has been proposed that it may be caused by mixing events that dredge up material enriched in Na via the NeNa cycle into the surface of the Cepheids \\citep{Sass1986,Deni1994,Take2013}. Similar Na overabundances have also been observed in RGB stars \\citep[e.g.,][]{daSilva2015}, reinforcing this hypothesis. It is interesting to note that Na overabundances are quite homogeneous in Cepheids and do not depend on mass or period \\citep{And2003,Kov2005b,Take2013,Gen2015}. In contrast, \\citet{daSilva2015} report a positive trend with mass for [Na\/Fe] for RGB stars (which cover a shorter mass range).\n\\par The agreement is excellent for the $\\alpha$-elements Mg and Si, and to a lesser extent for Ca for which the Cepheid abundances are slightly larger than in the RGB stars. The agreement is good for Fe and excellent for Ni, the only two iron peak elements for which data are available for both RGB stars and Cepheids. For our 6 Cepheids we find a mean [Fe\/H] = $-0.36$~dex with a dispersion of 0.03 dex. The 14 RGB stars in \\cite{Mucc2011} have an average [Fe\/H] of $-0.43$~dex (to which one should add 0.02 dex to take into account differences in the adopted Solar iron abundance) and a dispersion of 0.04 dex.\n\\par In contrast, the abundances of some neutron-capture elements are quite discrepant between the two studies: Y and Zr are found significantly more abundant (by 0.25\/0.40 dex respectively) than in \\citet{Mucc2011}. Our abundances of La agree only within the error bars whereas Nd and Eu abundances are in excellent agreement with those reported by these authors. The hfs corrections reported by \\citet{daSilva2016} are negligible for Y and therefore cannot account for the difference. In contrast hfs corrections can reach $-0.2$~dex for several La lines, and a good agreement between both studies could be achieved if they were taken into account. A possible explanation for these discrepancies could be that the transitions used to derive the abundances of these elements are associated with different ionization stages. For instance, \\citet[][their Fig.~13]{Allen2006} derived lower Zr abundances from Zr I lines than from Zr II lines in the Barium stars they analyzed, possibly because ionized lines are the dominant species and therefore less affected by departures from the LTE. In the end, their Zr II abundances span a range of 0.40 $\\leq$ [Zr II\/Fe] $\\leq$ 1.60 while their Zr I abundances are found in the $-0.20$ $\\leq$ [Zr I\/Fe] $\\leq$ 1.45 range. \\citet{Mucc2011} do not provide their linelist but given the wavelength range of their spectra, it is likely that they used neutral lines. Unfortunately, neutral lines for these elements are too weak and\/or blended in the spectra of Cepheids and therefore cannot be measured to test this hypothesis. Only the Zr I lines at 6134.58 and 6143.25 \\AA, and the Y I line at 6435.05 \\AA{} could possibly be measured in the most metal-rich Milky Way Cepheids, but they become too weak already at Solar metallicity.\n\\par The abundance ratios derived by \\citet{Mucc2011} for NGC~1866 members are in very good agreement with the field RGB stars in the surroundings they analyzed. It is interesting to note that the [La\/Fe] and [Eu\/Fe] ratios derived in NGC~1866 by \\citet{Mucc2011} are in good agreement with other LMC field RGB stars \\citep[e.g.,][and references therein]{vdS2013}, while their [Y\/Fe] and [Zr\/Fe] ratios fall at the lower end of the LMC field stars distribution. \n\\par Y and Zr belong to the first peak of the s-process, while La and Ce belong to the second peak of the s-process that is favored when metal-poor AGB stars dominate the chemical enrichment \\citep[e.g.,][]{Crist2011}. The large values of [La\/Fe] and [Ce\/Fe] demonstrate that the enrichment in heavy elements is dominated by metal-poor AGB stars for both the Cepheids and RGB stars in NGC~1866. Cepheids show higher Y and Zr abundances than RGB stars. If this difference turns out to be real, it might hint that they experienced extra-enrichment in light s-process elements from more metal-rich AGB stars. \n\n\\par Similar conclusions can be drawn when comparing the Cepheid abundances with the stellar abundances derived by \\cite{Colu2012b}: the $\\alpha$-elements (except Ti) and the iron-peak elements abundance ratios (with respect to iron) they obtained are very similar to those of the Cepheids, while their abundance ratios for the n-capture elements are higher than in the Cepheids, and even higher than those derived by \\cite{Mucc2011}. \\cite{Colu2012b} did not measure Mn in their NGC~1866 stellar sample. However, they found values ([Mn\/Fe]$\\approx-0.35$~dex) slightly lower than ours ([Mn\/Fe]$\\approx-0.25$~dex) in the stars belonging to other young LMC clusters. The Mn abundances reported by \\citet{Mucc2011} are also (much) lower than ours. This is almost certainly due to the fact that both studies included hfs corrections for Mn, which are known to be very significant \\citep[e.g.,][]{Pro2000}. Because these ratios are lower than in Milky Way stars of the same metallicity, they proposed that the type~Ia supernovae yields of Mn are metallicity-dependent, as reported\/modeled in other environments by, e.g., \\citet{McWil2003}, \\citet{Ces2008}, and \\citet{North2012}.\\\\ \n\n\\par In contrast, the abundance ratios they derived from integrated light spectroscopy are almost always significantly larger than those obtained for RGB stars by \\cite{Mucc2011} or for Cepheids (this study), or at least at the higher end. This might be due to the fact that Colucci et al.'s work based on integrated light includes contributions of many different stellar types (and possibly contaminating field populations). This is nevertheless surprising because the integrated flux originating from a young cluster such as NGC~1866 should be dominated by young supergiants, and one would therefore expect a better match between the Cepheids and the integrated light spectroscopy abundance ratios. \n\n\\subsection{Multiple stellar populations in NGC 1866} \n\\label{age}\n\n\\par In a recent paper, \\citet{Mil2017} reported the discovery of a split main sequence (MS) and of an extended main sequence turn-off in NGC~1866. These intriguing features have already been reported in many of the intermediate-age clusters in the Magellanic Clouds as well as for some of their young clusters \\citep[e.g.,][]{Bert2003,Glatt2008,Mil2013}, although there is no agreement whether this is indeed due to multiple stellar populations. The blue MS hosts roughly $\\sfrac{1}{3}$ of the MS stars, the remaining \\sfrac{2}{3} belonging to a spatially more concentrated red MS. \\citet{Mil2017} rule out the possibility that age variations solely can be responsible for the split of the MS in NGC~1866. Instead, the red MS is consistent with a $\\approx$200~Myr old population of extremely fast-rotating stars ($\\omega$=0.9$\\omega_{c}$) while the blue MS is consistent with non-rotating stars of similar age, including a small fraction of even older stars. However, according to \\citet{Mil2017} the upper blue MS can only be reproduced by a somewhat younger population ($\\approx$140~Myr old) accounting for roughly 15\\% of the total MS stars.\n\n\\par As the age range of Cepheids is similar to the one of the NGC~1866 MS stars, it is natural to examine how they fit in the global picture of NGC~1866 drawn by \\citet{Mil2017}. These authors clearly state in their conclusion that the above interpretation should only be considered as a working hypothesis and our only intent here is to examine if Cepheids can shed some light on this scenario. \n\\par It is possible to compute individual ages for Cepheids with a period-age relation derived from pulsation models \\citep[e.g.,][]{Bono2005}. Because rotation brings fresh material to the core during the MS hydrogen burning phase, fast-rotating stars of intermediate masses stay longer on the MS and therefore cross the instability strip later than a non-rotating star. Including rotation in models then increases the ages of Cepheids by 50 to 100\\%, depending on the period, as computed by \\citet{Ander2016}. Following the prescriptions of \\citet{Ander2016} we derive ages for all the Cepheids known in NGC~1866: we use a period-age relation computed with models with average rotation ($\\omega$=0.5$\\omega_{c}$) and averaged over the second and third crossing of the instability strip. Periods are taken from \\citet{Mus2016}. In the absence of further information, we assume that they are fundamental pulsators, except for V5, V6, and V8, as \\citet{Mus2016} report that their periods and light curves are typical of first overtone pulsators. Even more importantly they lie on the PL relations of first overtones. For comparison, we also derive ages using the period-age relation from \\citet{Bono2005}, which was computed using non-rotating pulsation models. Ages are listed in Table~\\ref{ages}. \n\n\\par We first notice that in both cases the age spread is very limited, thus reinforcing previous findings stating that there is no age variation within NGC1866, or at least that Cepheids all belong to the same sub-population. As expected, the ages calculated with the period-age relation from \\citet{Bono2005} lead to younger Cepheids and therefore appear to be compatible only with the 140 Myr old stars populating the upper part of the blue main sequence. None of the period-age relations by \\citet{Bono2005} and \\citet{Ander2016} enables us to compute individual error bars. Uncertainties on the ages of the NGC~1866 Cepheids of the order of 25--30~Myr can be derived by using the standard deviation of the period-age relation by \\citet{Bono2005} as the error. However, given quoted error bars of 50\\% or more \\citep{Ander2016}, an age of 200 Myr cannot be completely excluded. On the other hand, the ages computed with the period-age relation including rotation from \\citet{Ander2016} correspond very well to the fast-rotating red MS population. However the reader should keep in mind that ages should be directly compared only when they are on the same scale, which requires that they were all calculated based on the same models. \n\n\\par Using evolutionary tracks computed with either canonical (no overshooting) or non-canonical (moderate overshooting) assumptions (but no rotation), \\citet{Mus2016} favor an age of 140 Myr. The location of the Cepheids, in between the theoretical blue loops computed in each case, does not allow us to discriminate the two overshooting hypotheses. Adopting a canonical overshooting and an older age of 180 Myr enables us to better fit the observed luminosities of the Cepheids, but the theoretical blue loops are then too short to reach the Cepheids' locus in the CMD. Finally, using high-resolution integrated light spectroscopy and CMD-fitting techniques, \\citet{Colu2011} report a similar age of 130~Myr.\n\n\\par Ages of Cepheids, derived using period-age relations computed with either no rotation or an average rotation ($\\omega$=0.5$\\omega_{c}$), do not allow us to confirm or rule out the hypothesis of \\citet{Mil2017}. Unfortunately, \\citet{Ander2016} do not provide period-age relations for fast-rotators ($\\omega$=0.9$\\omega_{c}$). As far as Cepheid ages are concerned, it is interesting to note that the Cepheids in NGC~1866 match very well the peak of the age distribution for LMC field Cepheids, computed by \\citet{Inno2015b} using new period-age relations (without rotation) at LMC metallicities. \n\n\\begin{table}[!htbp]\n\\caption{Individual ages for Cepheids in NGC~1866 computed with the period-age relations of \\citet{Bono2005} or \\citet{Ander2016} for fundamental pulsators, and the periods listed in \\citet{Mus2016}}\n\\label{ages}\n\\centering\n\\begin{tabular}{rccc}\n\\hline\n\\hline\n Cepheid & Period & Age\\tablefootmark{a} & Age\\tablefootmark{b} \\\\\n & & (no rotation) & (rotation: $\\omega$=0.5$\\omega_{c}$) \\\\ \n & (d) &(Myr)& (Myr) \\\\ \n\\hline\nV6\\tablefootmark{c} & 1.9442620 & 114.5 & 258.7 \\\\\nV8\\tablefootmark{c} & 2.0070000 & 111.7 & 252.0 \\\\\nV5\\tablefootmark{c} & 2.0390710 & 110.3 & 248.7 \\\\\n HV~12199 & 2.6391600 & 120.6 & 222.7 \\\\\n HV~12200 & 2.7249800 & 117.6 & 218.0 \\\\\n We~4 & 2.8603600 & 113.2 & 211.1 \\\\\n WS~5 & 2.8978000 & 112.1 & 209.3 \\\\\n New & 2.9429300 & 110.8 & 207.1 \\\\\n HV~12203 & 2.9541100 & 110.4 & 206.6 \\\\\n We~8 & 3.0398490 & 108.0 & 202.7 \\\\\n We~3 & 3.0490400 & 107.7 & 202.3 \\\\\n WS~11 & 3.0533000 & 107.6 & 202.1 \\\\\n We~2 & 3.0548500 & 107.6 & 202.1 \\\\\n WS~9 & 3.0694500 & 107.2 & 201.4 \\\\\n V1 & 3.0845500 & 106.8 & 200.8 \\\\\n HV~12202 & 3.1012000 & 106.3 & 200.0 \\\\\n HV~12197 & 3.1437100 & 105.2 & 198.2 \\\\\n We~5 & 3.1745000 & 104.4 & 197.0 \\\\\n We~7 & 3.2322700 & 102.9 & 194.6 \\\\\n We~6 & 3.2899400 & 101.5 & 192.3 \\\\\n V4 & 3.3180000 & 100.9 & 191.3 \\\\\n HV~12204 & 3.4388200 & 98.1 & 186.8 \\\\\n V7 & 3.4520700 & 97.8 & 186.3 \\\\\n HV~12198 & 3.5228000 & 96.3 & 183.8 \\\\\n\\hline\n\\end{tabular}\n\\tablefoot{\n\\tablefoottext{a}{Period-age relation from \\citet{Bono2005}.}\n\\tablefoottext{b}{Period-age relation from \\citet{Ander2016}.}\n\\tablefoottext{c}{Ages computed using period-age relations for first overtone pulsators.}}\n\\end{table}\n\n\\subsection{The metallicity gradients from Cepheids in the SMC} \n\n\\par The existence of a metallicity gradient across the SMC is a long-debated issue. Using large numbers of RGB stars, \\citet{Carr2008b,Dobb2014b}, and \\citet{Pari2016} report a radial metallicity gradient ($-0.075\\pm0.011$~dex.deg$^{-1}$ vs. $-0.08\\pm0.02$~dex.deg$^{-1}$ in the two latter studies) in the inner few degrees of the SMC. In both cases, this effect is attributed to the increasing fraction of younger, more metal-rich stars towards the SMC center. However, the presence of such a gradient was not confirmed by C- and M- type AGB stars \\citep{Cioni2009}, populous clusters \\citep[e.g.,][and references therein]{Pari2015,Pari2016}, or RR Lyrae studies \\citep[e.g.,][and references therein]{Has2012a,Deb2015,Sko2016}.\n\\par The SMC is very elongated and tilted by more than 20$^\\circ$ \\citep[e.g.,][]{Has2012b,Subra2012,Nide2013}. Moreover, old and young stellar populations have significantly different spatial distributions and orientations \\citep[e.g.,][]{Has2012b,Jac2017}. Recent studies using mid-infrared Spitzer data \\citep{Scow2016} or optical data from the OGLE IV experiment \\citep{Jac2016} clearly confirmed this complex shape. Our Cepheid abundances combined with those found in the literature \\citep{Roma2008}, and the possibility to derive accurate distances thanks to the period-luminosity relations allow us to shed new light on the SMC metallicity distribution. For the first time, we are able to probe the metallicity gradient in the SMC' young population in the \"depth\" direction. As Cepheids are young stars, it should be noted that our study only concerns the present-day abundance gradient, and as such, the metal-rich end of the metallicity distribution function ([Fe\/H]$>-0.90$~dex). Moreover, our sample is small (17 stars) and does not contain stars in the inner few degrees of the SMC in an on-sky projection (see Fig. \\ref{SMC_sample}). For old populations traced by RR Lyrae stars, no significant metallicity gradient was found in the \"depth\" direction \\citep{Has2012a}.\n\n\\begin{figure}[!htbp] \n\\centering \n \\includegraphics[width=\\columnwidth]{SMC_cep.ps} \n \\caption{SMC Cepheids with known metallicities (red: this study; blue: \\citet{Roma2008}. SMC Cepheids in the OGLE-IV database are shown as gray dots).}\n\\label{SMC_sample}\n\\end{figure}\n\n\\par Individual distance moduli for SMC Cepheids were computed using the [3.6] $\\mu$m mean-light magnitudes tabulated by \\cite{Scow2016} and the corresponding PL-relation in the mid-infrared (MIR) established by the same authors. Combining the extinction law of \\citet{Inde2005} with that of \\citet{Card1989}, \\citet{Mon2012} reported a total-to-selective extinction ratio of A$_{[3.6]}$\/E(B-V)=0.203. We adopted the average color excess found by \\citet{Scow2016} for the SMC: E(B-V)=0.071$\\pm$0.004 mag, which leads to A$_{[3.6]}$=0.014$\\pm$0.001 mag. There is no MIR photometry available for HV822 and HV823. For HV822, we use the distance of 67441.4 pc derived by \\cite{Groe2013} via the Baade-Wesselink method. The typical uncertainty on the individual MIR distances is of the order of $\\pm$3~kpc \\citep{Scow2016}. \n\n\\par For comparison purposes, we also computed distances based on NIR photometry. For the Cepheids in the OGLE-IV database, we used near-infrared J, H and K$_{\\rm{S}}$ magnitudes from the IRSF\/SIRIUS catalog \\citep{Kato2007} that were derived by using the near-infrared light-curve templates of \\citet{Inno2015a}. Distances were computed using period-Wesenheit (PW) relations calibrated on the entire SMC sample of fundamental mode Cepheids \\citep[$>$2200 stars][in prep]{Inno2017}. Wesenheit indices are reddening-free quantities by construction \\citep{Mado1982}. We used the W$_{HJK}$ index as defined by \\citet{Inno2016}: W$_{HJK}$~=~$H$--1.046~$\\times$~($J-K_{\\rm{S}}$) which is minimally affected by the uncertainty in the reddening law \\citep{Inno2016}. For stars that are not in the OGLE-IV database, the same procedure was adopted, except that the distances are derived from 2MASS \\citep{Skru2006} single epoch data (with no template applied). Individual uncertainties on distances are listed in Table~\\ref{SMC_grad}. The typical uncertainty, computed as the average of the individual uncertainties is 993$\\pm$41~pc and can be rounded to 1~kpc. It is beyond the scope of this paper to compare both sets of distances. We simply mention here that they are in very good agreement despite some star-to-star scatter (see Fig.~\\ref{comp_dist}).\n\n\\begin{figure}[!htbp] \n\\centering \n \\includegraphics[width=\\columnwidth]{comp_dist.ps} \n \\caption{Comparison of distances derived either from near-infrared or from mid-infrared photometry (red: this study; blue: \\citet{Roma2008}. Typical uncertainties are shown in the top left corner.}\n\\label{comp_dist}\n\\end{figure}\n\n\\par To investigate the metallicity gradient in the SMC, we combine our [Fe\/H] abundances with those of \\cite{Roma2008}, to which we added 0.03 dex to take into account differences in the Solar reference values. The Cepheids were placed in a Cartesian coordinate system using the transformations of \\citet{vdM2001} and \\citet{Wein2001}. We adopted the value tabulated in SIMBAD for the center of the SMC: $\\alpha_{0}$=00h52m38.0s, $\\delta_{0}$=-72d48m01.00s (J2000). For the SMC distance modulus, we adopted the value reported by \\cite{Gra2014} using eclipsing binaries: 18.965$\\pm$0.025 (stat.) $\\pm$ 0.048 (syst.) mag which translates into a distance of 62.1$\\pm$1.9 kpc. Individual distances and abundances can be found in Table~\\ref{SMC_grad}, as well as ages derived with the period-age relation of \\citet{Bono2005}.\\\\\n\n\\par A first glance at Fig.~\\ref{met_dist_SMC} shows that the (x,y) plane is not very relevant because it does not reflect the depth of the SMC. This fact is reinforced in the case of Cepheids as they are bright stars that can be easily identified and analyzed, even at very large distances. More interesting are the (x,z) and especially the (y,z) plane, as they allow us to study for the first time the metallicity distribution of Cepheids along the SMC main component. Our 17 Cepheids adequately sample the z direction, but the reader should keep in mind that most of our targets are located above the main body of the SMC \\citep[see Fig.~\\ref{SMC_sample} or][their Fig.~16]{Jac2016}. Fig~\\ref{met_dist_SMC} and Fig~\\ref{grad_SMC}, where [Fe\/H] is plotted as a function of z, show no evidence of a metallicity gradient along the main axis of the SMC. The metallicity spread barely reaches 0.3 dex, but both ends of the z-axis seem to be slightly more metal poor that the inner regions as they miss the more metal-rich Cepheids. The age range spans only 100~Myr and we see no correlation between age and metallicity or distance. These interesting findings should nevertheless be considered only as preliminary results, given the small size of our sample and the location of our Cepheids outside the main body of the SMC. \n\n\\begin{figure*}[!htbp] \n\\centering \n \\includegraphics[width=\\textwidth]{met_dist_SMC.ps} \n \\caption{Metallicity distribution of SMC Cepheids in Cartesian coordinates. Distances are based on mid-infrared photometry.}\n\\label{met_dist_SMC}\n\\end{figure*}\n\n\\begin{figure}[!htbp] \n\\centering\n \\includegraphics[width=\\columnwidth]{grad_mir.ps} \n \\includegraphics[width=\\columnwidth]{grad_nir.ps}\n \\caption{SMC metallicity distribution from Cepheids in the z (depth) direction. {\\it Top panel:} distances derived from mid-infrared photometry; {\\it Bottom panel:} distances derived from near-infrared photometry. Typical error bars are shown in the top left corner.} \n\\label{grad_SMC}\n\\end{figure}\n\n\\begin{table*}[!htbp]\n\\caption{Individual distances, ages, and metallicities for SMC Cepheids.\nMetallicities from \\citet{Roma2008} have been put on the same metallicity scale (by adding 0.03 dex to them) as our data.}\n\\label{SMC_grad}\n\\centering\n\\begin{tabular}{rcccccc}\n\\hline\n\\hline\n Cepheid & log P & Age\\tablefootmark{a} & Distance & Distance & Uncertainty on & [Fe\/H] \\\\\n & (d) & (Myr) & (MIR) (pc) & (NIR) (pc) & NIR distances (pc) & (dex) \\\\ \n\\hline\n HV817 & 1.277 & 212.4 & 57502 & 55636\\tablefootmark{c} & 1136 & -0.79 \\\\\n HV823 & 1.504 & 186.9 & - & 60770\\tablefootmark{b} & 964 & -0.77 \\\\\n HV824 & 1.819 & 161.2 & 56700 & 51195\\tablefootmark{c} & 957 & -0.70 \\\\\n HV829 & 1.926 & 154.2 & 55506 & 53625\\tablefootmark{c} & 964 & -0.73 \\\\\n HV834 & 1.867 & 157.9 & 57420 & 60463\\tablefootmark{c} & 1168 & -0.60 \\\\\n HV837 & 1.631 & 175.5 & 60752 & 57692\\tablefootmark{c} & 1033 & -0.80 \\\\\n HV847 & 1.433 & 194.2 & 63160 & 60129\\tablefootmark{b} & 1175 & -0.72 \\\\\n HV865 & 1.523 & 185.2 & 54586 & 58401\\tablefootmark{c} & 1018 & -0.84 \\\\\n HV1365 & 1.094 & 239.7 & 71595 & 68986\\tablefootmark{b} & 1094 & -0.79 \\\\\n HV1954 & 1.222 & 219.8 & 54265 & 57702\\tablefootmark{b} & 1027 & -0.73 \\\\\n HV2064 & 1.527 & 184.7 & 65503 & 58973\\tablefootmark{c} & 1182 & -0.61 \\\\\n HV2195 & 1.621 & 176.3 & 58568 & 58703\\tablefootmark{c} & 1163 & -0.64 \\\\\n HV2209 & 1.355 & 202.8 & 56286 & 56543\\tablefootmark{b} & 1006 & -0.62 \\\\\n HV11211 & 1.330 & 205.8 & 54140 & 53884\\tablefootmark{c} & 966 & -0.80 \\\\\n\\hline \n HV822 & 1.224 & 219.6 & 67447 & 64428\\tablefootmark{b} & 1022 & -0.70 \\\\\n HV1328 & 1.200 & 223.0 & 61750 & 61526\\tablefootmark{b} & 976 & -0.63 \\\\\n HV1333 & 1.212 & 221.2 & 69244 & 69002\\tablefootmark{b} & 1094 & -0.86 \\\\\n HV1335 & 1.158 & 229.3 & 69493 & 68231\\tablefootmark{b} & 1214 & -0.78 \\\\\n\\hline\n\\end{tabular}\n\\tablefoot{\n\\tablefoottext{a}{Period-age relation from \\citet{Bono2005}.}\n\\tablefoottext{b}{Distance based on IRSF\/SIRIUS near-infrared photometry \\citep{Kato2007}.}\n\\tablefoottext{c}{Distance based on 2MASS near-infrared photometry \\citep{Skru2006}.}}\n\\end{table*}\n\n\\section{Conclusions}\n\n\\par In this paper we conducted a spectroscopic analysis of Cepheids in the LMC and in the SMC. We provide abundances for a good number of $\\alpha$, iron-peak, and neutron-capture elements. Our sample increases by 20\\% (respectively 25\\%) the number of Cepheids with known metallicities and by 46\\% (respectively 50\\%) the number of Cepheids with detailed chemical composition in these galaxies.\n\n\\par For the first time, we study the chemical composition of several Cepheids located in the same populous cluster NGC~1866, in the Large Magellanic Cloud. We find that the six Cepheids we studied have a very homogeneous chemical composition, which is also consistent with RGB stars already analyzed in this cluster. Our results are also in good agreement with theoretical models accounting for luminosity and radial velocity variations for the two stars (HV~12197, HV~12199) for which such measurements are available. Using various versions of period--age relations with no ($\\omega$=0) or average rotation ($\\omega$=0.5$\\omega_{c}$) we find a similar age for all the Cepheids in NGC~1866, indicating that they all belong to the same stellar population.\n\n\\par Using near- or mid-infrared photometry and period-luminosity relations \\citep{Inno2016,Scow2016}, we computed the distances for Cepheids in the SMC. Combining our abundances for Cepheids in the SMC with those of \\citet{Roma2008}, we study for the first time the metallicity distribution of the young population in the SMC in the depth direction. We find no metallicity gradient in the SMC, but our data include only a small number of stars and do not contain Cepheids in the inner few degrees of the SMC.\n\n\\begin{acknowledgements}\n\\par The authors would like to thank the referee, M. Van der Swaelmen, for his careful reading of the manuscript and for his valuable comments that helped to improve the quality of this paper.\\\\\n\\par This work was supported by Sonderforschungsbereich SFB 881 \"The Milky Way System\" (subproject A5) of the German Research Foundation (DFG). GF has been supported by the Futuro in Ricerca 2013 (grant RBFR13J716). This work has made use of the VALD database, operated at Uppsala University, the Institute of Astronomy RAS in Moscow, and the University of Vienna. \n\\end{acknowledgements}\n\n\n\n","meta":{"redpajama_set_name":"RedPajamaArXiv"}} +{"text":"\\section{Introduction}\nThe Internet of Things (IoT) is the next evolution of the Internet \\cite{khan2012future} where devices, of any kind and size, will exchange and share data autonomously among themselves. \nBy exchanging data, each device can improve their decision-making processes. IoT devices are ubiquitous in our daily lives and critical infrastructure. For example, air conditioners, irrigation systems, refrigerators, and railway sensors \\cite{rail} have been connected to the Internet in order to provide services and share information with the relevant controllers. Due to the benefits of connecting devices to the Internet, massive quantities of IoT devices have been developed and deployed. This has led leading experts to believe that by 2020 there will be more than 20 billion devices connected to the Internet \\cite{eddy2015gartner}.\n\nWhile the potential for IoT devices is vast, their success depends on how well we can secure these devices. \nHowever, IoTs are diverse and have limited resources. Therefore, securing them is a difficult challenge which has taken a central stage in both industry and academia.\nOne significant security concern with IoTs is that many manufactures do not invest in the security of these devices during their development. Furthermore, discovered vulnerabilities are seldom patched by the manufacture \\cite{notPatchingIOTs}. These vulnerabilities enable attackers to exploit the IoT devices for nefarious purposes \\cite{schneier2014internet} which endanger the users' security and privacy.\n\nThere are various security tools for detecting attacks on embedded devices. One such tool is an intrusion detection system (IDS). An anomaly-based IDSs learn the normal behavior of a network or host, and detect when the behavior deviates from the norm. In this way, these systems have the potential to detect new threats without being explicit programmed to do so (e.g., via remote updates). Aside from being able to detect novel `zero-day' attacks, this approach is desirable because there is vertically no maintenance required.\n\nIn order to prepare an anomaly-based IDS (or any anomaly detection model), the system must collect and learn from \\textit{normal} observations acquired during a time-limited ``training phase''. A fundamental assumption is that the observations obtained during the training phase are both benign and capture all of the device's possible behaviors.\nThis assumption might hold true in some systems. However, when considering the IoT environment, this assumption is challenging for the following reasons:\n\n\\begin{enumerate}\n\t\n\t\n\t\\item \\textbf{Model Generality} It is possible to train the anomaly detection model safely in a lab environment. However, it is difficult to simulate all the possible deployments and interactions with the device. This is because some logic may be dependent on one or more environmental sensors, human interaction, and event based triggers. This approach is also costly and required additional resources. Alternatively, the model can be trained on-site during the deployment itself. However, the model will not be available for execution (detection of threats) until the training phase is complete. Furthermore, it is questionable whether the trained model will capture benign yet rare behaviors. For example, the behavior of the motion detection logic of a smart camera or the response generated by a smoke detector while sensing a fire. These rare but legitimate behaviors will generate false alarms during regular execution.\n\t\n\t\\item \\textbf{Adversarial Attacks} \n\tAlthough training on-site is a more natural approach to learning the normal behavior of an IoT device, the model must assume that all observation during the training-phase are benign. This approach exposes the model to malicious observations, thus enabling an attacker to exploit the device to evade detection or cause some other adverse effect.\n\\end{enumerate}\n\nTo overcome these challenges, the IoT devices can collaborate and train an anomaly detection model together. Consider the following scenario:\n\nAssume that all IoT devices of the same type simultaneously begin training an anomaly detection model, based on their own locally observed behaviors. \nThe devices then share their models with other devices of the same type. Finally, each device merges the received models, into a single model by filtering out potentially malicious behaviors. Finally, each device uses the combined model as it's own local anomaly detection model. As a result, the devices (1) collectively obtain an anomaly detection model which captures a much wider scope of all possible benign behaviors, and (2) are able to significantly limit adversarial attacks during the training phase. The latter point is because the \\textit{initial} training phase is much shorter (scaled according to the number of devices), and rare behaviors unseen by the majority are filtered out.\n\nUsing concept, we present a lightweight, scalable framework which utilizes the blockchain concept to perform distributed and collaborative anomaly detection on devices with limited resources.\n\nA blockchain is an innovative protocol for a distributed database, which is implemented as a chain of blocks and managed by the majority of participants in the network \\cite{swan2015blockchain}.\nEach block contains a list of records and a hash value of the previous block and is accepted into the chain if it satisfies a specific criteria (e.g., bitcoin's proof-of-work criterion \\cite{nakamoto2008bitcoin}).\nThe framework uses the blockchain's concept to define a collaboration protocol which enables devices to autonomously train a trusted anomaly detection model incrementally. The protocol uses self-attestation and consensus among the IoT devices to protect the integrity of the trained model. In our blockchain, a record in a block is a model trained on a specific device, and a block in the chain represents a potential anomaly detection model which has been verified by a significant mass\/majority of devices in the system. By using the blockchain as a secured distributed ledger, we ensure that the devices (1) are using the latest validated anomaly detection model, and (2) can continuously contribute to each other's model with newly observed benign behaviors. \n\nFurthermore, in this paper we also propose a novel approach for performing anomaly detection on a local device using an Extensible Markov Model (EMM) \\cite{bhat2008extended}. The EMM tracks a program's jump sequences between regions on the application's memory space. The EMM can be incrementally updated and merged with other models, and therefore can be trained with real-world observations across multiple devices in parallel. Although there are many other methods for modeling sequences, we chose the EMM model because:\n\\begin{enumerate}\n\t\\item The update and prediction procedures have a complexity of $O(1)$. This is critical considering that many IoT devices have weak processors. \n\t\\item Our collaborative framework requires a model which can be merged with other models efficiently. Moreover, to filter out malicious transitions during the combine step, we needed an efficient and clear algorithm for comparing learned behaviors between different models. The process of comparing and combining other discreet transitional anomaly detection models can be complex or simply has not been defined. \n\t\\item In our evaluations, we found that the EMM performs better than other algorithms in our anomaly detection task.\n\\end{enumerate}\n\n\nWe evaluate both the framework and the anomaly detection model on our own IoT emulation platform, involving 48 Raspberry Pis.\nWe simulate several different IoT devices to assert that the evaluation results do not depend on the IoT device's functionality. \nMoreover, we exploit real vulnerabilities in order to evaluate our method's capability in detecting actual attacks.\nFrom our evaluations, we found that our method is capable in creating strong anomaly detection models in a short period of time, which are resistant to adversarial attacks.\nTo encourage further research and development, the reader may download our data sets and source code from GitHub.\\footnote{\\texttt{https:\/\/git.io\/vAIvd}.} We have also \\href{https:\/\/drive.google.com\/drive\/folders\/15gLytEJyQyYCmhB-EZSkES77KsuCW0hw?usp=sharing}{published a blockchain simulator for our protocol} to help the reader understand and implement the work in this paper.\\footnote{\\texttt{https:\/\/github.com\/ymirsky\/CIoTA-Sim}} \n\nIn summary, this paper's contributions are:\n\\begin{itemize}\n\t\\item \\textbf{A method for detecting code execution attacks by modeling memory jumps sequences} - We define and evaluate a novel approach to efficiently detect abnormal control-flows at a set granularity. The approach is efficient in because we track the program counter's flow between regions of memory, and not actual memory addresses or system calls. As a result, the model is compact (has relatively few states) and is suitable for devices with limited resources (IoT devices).\n\t\n\t\\item \\textbf{A method for enabling safe distributed and collaborative model training on IoTs} - We outline a novel framework and protocol which uses the concept of blockchain to collaboratively train an anomaly detection model. The method is decentralized, reduces train time, false positives, and is robust against potential adversarial attacks during the initial training phase.\n\\end{itemize}\n\n\nThe rest of the paper is organized as follows. \nIn Section \\ref{sec:relworks}, we review related work, and discuss how the proposed method overcomes their limitations.\nIn Sections \\ref{sec:anom} and \\ref{sec:ciota}, we present introduce our novel host-based anomaly detection algorithm and the framework for applying the algorithm in the collaborative distributed setting using the blockchain.\nIn Section \\ref{sec:eval}, we evaluate the proposed method on several different applications and use-cases, and discuss our insights. In section \\ref{sec:security} we analyze the framework's security.\nIn Section \\ref{sec:discussion}, we provide a discussion on the security and challenges of implementing the proposed framework. Finally, in Section \\ref{sec:conclusion} we present a summary and conclusion.\n\n\\section{Related Works}\\label{sec:relworks}\nThe primary aspects of this work relate to both Intrusion Detection and IoT Security. Therefore, in this section we will discuss recent works from both fields, and the limitations of these approaches.\n\n\\subsection{Discreet Sequence Anomaly Detection for Intrusion Detection}\nSoftware inevitable contains flaws which pose security vulnerabilities if exploited by an attacker. Many of these vulnerabilities remain unknown until they are discovered and exploited in the wild (referred to as zero days). An effective way to detect these exploits is to analyze a program's behavior in real-time. \n\nA program's behavior can be observed during runtime by monitoring its system calls, or by tracking the program in the memory \\cite{maske2016advanced,yoon2017learning,kim2016lstm,khreich2017anomaly}. In both cases, the behavior is observed as an ordered sequence of events on which anomaly detection can be performed \\cite{ahmed2016survey,chandola2010anomaly}. To detect attacks in these sequences, many works utilize discreet sequence anomaly detection algorithms. We will now summarize these works in chronological order.\n\nIn \\cite{forrest1996sense} the authors create a database of normal sequences by windowing over system calls, and flag sequences as anomalous sequences if they do not appear in the database. In \\cite{kosoresow1997intrusion} the authors extended the windowing approach to longer sequences via partitioning. In \\cite{lee1997learning} the authors use RIPPER to extract concise rule sets from systems calls to classify malicious sequences. The authors then expanded their work in \\cite{lee1998data} by using the frequent episodes algorithm, computing inter\/intra-audit record patterns, and by proposing a general agent architecture. In \\cite{hofmeyr1998intrusion} the authors proposed a system based on the defenses of natural immune systems. First a database of short normal sequences is created. Then new sequences are scored according to the number of matches (substrings) the sequence has in common. \n\nIn \\cite{warrender1999detecting} the authors performed a comparative evaluation involving Hidden Markov Models (HMM), RIPPER, and threshold-based sequence time delay embedding (t-STIDE). An HMM is similar to a MC except that it model transmissions based on output symbols at each state. We did not use an HMM since the framework needs a light weight model that can be trained efficiently and can be merged with other models. t-STIDE works by looking up the frequency of new sequences (window) in normal dictionary (hash table). Infrequent sequences below a given threshold are considered anomalous. The authors found that the HMM provided the best performance, but t-STIDE had similar performance and was significantly faster to train.\n\nIn \\cite{michael2000two} the authors propose modeling a finite-state machine over system calls such that novel sequences are labeled anomalous. In \\cite{gao2002hmms} the authors apply an HMM over a sliding window of system calls. In \\cite{tandon2003learning} the authors revisit the use of association rule mining by considering the system call's arguments. Based on a mining algorithm called LERAD, the authors propose three variants which out performed t-STIDE for certain attacks. In \\cite{hoang2003multi} the authors propose a multi-layer approach which first uses a normal database and then passes suspicious sequences to a HMM for further analysis. In \\cite{yeung2003host} the authors use a Markov Chain to model normal shell-command sequences, and then detect abnormal (malicious) sequences as an indication of misuse in the system.\n\nIn \\cite{eskin2001modeling,mazeroff2003probabilistic,mazeroff2008probabilistic} the authors use probability suffix trees (PST) to model normal system call sequences. A PST is a variable length Markovian model which forms a tree-liek data structure.\n\nIn \\cite{hu2009simple} the authors propose a method for speeding up HMM training on system calls by 50\\%. They accomplish this by prepossessing the training sequences and by performing incremental training. In \\cite{xie2013evaluating} the authors prose a kernel trick to transfer sequences to Euclidean space in order to perform kNN lookups. In \\cite{kim2016lstm} the authors propose the use of a long-term short-term (LSTM) neural networks to detect abnormal system call sequences. In \\cite{chawla2018host} the authors extent the work of \\cite{chawla2018host} by stacking convolutional networks (CNN) followed by a recurrent neural network (RNN) with Gated Recurrent Units (GRU). Although the use of GRU reduced the training time, the authors needed to use powerful GPUs to train their network. \n\nOur proposed framework uses an EMM, a type of Markov Chain, as the anomaly detection model for detecting abnormal control flows in the memory of applications. In contrast to the above works, the limitation to these approaches are:\n\n\\begin{description}\n\t\\item[Attack Vector Coverage] Many exploits do not use the shell or require the evocation of abnormal system-calls, so the Markov model would not observe any malicious activity during their exploitation processes. For example, exploitation of a buffer overflow vulnerability can be accomplished without making explicit calls. \n\t\\item[Modeling the True Behavior] An application's system and shell calls only capture an application's high-level behavior. As a result, some exploits can be designed so that the executed code will generate seemingly benign sequences (obfuscation) and evade detection. Furthermore, some malware may only require to make benign call sequences to accomplish its objective. For example, a randsomware will read and write files via system-calls (benign) but encrypt the files internally (malicious).\n\t\\item[System Overhead] In order to intercept the system calls of a specific application, one must intercept the system-calls of all applications. As a result, these approaches are suitable for devices with strong computational power such as personal computers, but not IoTs. Moreover, models such as HMMs and neural networks cannot be trained (and sometimes not even executed) on IoTs.\n\\end{description}\n\nBy modeling a Markov Chain on a target application's general jumps through its memory space, our approach is not restricted by the above limitations. Namely, our approach can (1) capture the internal behavior of the application, regardless of the system-calls or shell-code, (2) detect exploitation of vulnerabilities occurring within an application's memory space, and (3) be applied to specific applications, as opposed to the whole system, thus minimizing overhead --making our approach appropriate for IoTs. \n\nSimilar to our approach, in \\cite{7167219} the authors detect anomalous activities by maintaining a heatmap of the \\textit{kernel's} memory space. An anomaly is detected when the probability of a region of the kernel's memory being accessed is below a threshold. By doing so, the authors were able o detect abnormal application activities reflected by interactions with the kernel. This work differs from ours in the following ways:\n\\begin{enumerate}\n\t\\item The kernel-heatmap method cannot detect all of those which our method can. For example, code reuse attacks are ignored because the kernel interactions seem normal. Moreover, abnormal interactions with the kernel can be considered benign because \\textit{other} applications may be performing similar interactions. For example, when privilege escalation is obtained and abused, restricted system calls will not seem abnormal because the context of the requesting app is not considered.\n\t\\item When an anomaly is detected, there is indication of which application has been compromised. This makes it harder to mitigate the threat.\n\t\\item The method in \\cite{7167219} suffers from significantly higher false alarm rates than an EMM. This is because the probability of accessing a memory region is normalized over all accesses. Therefore, rare benign memory interactions are considered anomalous. In contrast, by using an EMM over memory regions, we consider the transition across the memory space which provides an implicit context for each interaction. Later in section \\ref{sec:eval} we provide a comparative evaluation.\n\t\\item Like all other anomaly detection algorithms (including EMMs), the method in \\cite{7167219} is subject to adversarial attacks (poisoning) during training and false positives due to rare benign behaviors (due to human interactions and other stimuli). In our paper we propose a framework which provides accelerated on-site model training in a hostile environment via collaboration, filtration, and self-attestation. \n\\end{enumerate}\n\nAnother approach to deploying an IDS is to distribute the detection across multiple devices \\cite{abraham2007d, zhang2011distributed, snapp1991dids}. In these approaches, the devices share information with one another regarding malicious traffic and the network's state. Similar to our method, a distributed IDS utilizes on collaboration between devices. However, the proposed methods are limited to analyzing network traffic. In many cases, network traffic from a device cannot indicate the exploitation of an application running on the device (e.g., encrypted payloads). When considering the IoT topology and the vision of allowing them to autonomously exchange data, a network based IDS might be problematic, since network traffic near each IoT device may differ significantly. In contrast, our anomaly detection approach on an application's the memory jumps is not affect by the diversity of network traffic near each device. Furthermore, distributed IDS solutions are designed to work collectively as a single intrusion detection system. However, should one node be compromised by an attacker, the security of the entire system may fail. In contrast, our method allows for safe collaboration via self attestation and model anomaly filtration --which makes compromising the whole system much more difficult.\n\n\\subsection{IoT Specific Solutions}\nThe IoT device security solutions have been researched extensively over the last few years.\nHowever, the proposed solutions typically do not address all of an IoT's characteristics: their (1) mass quantity, (2) limited resources, (3) global deployment, (4) dependence on external sensors\/triggers.\n\nIn \\cite{huuck2015iot,oh2014malicious} the authors propose deploying static analysis tools on the IoT devices. However, these approaches require that (1) the device maintain a database of virus signatures and (2) that experts continuously update this database. Furthermore, these approaches are not sufficient when facing viruses which can only be detected during runtime (e.g., execution of a malicious encrypted payload). Our method is anomaly-based and therefore can detect threats automatically without human intervention, and performs continuous dynamic analysis of an application's behavior.\n\nSeveral studies try to secure IoT devices by deploying an anomaly detection model on the device itself \\cite{raza2013svelte,arrington2016behavioral,o2014anomaly, taneja2013analytics}. Some of them suggest to simply apply traditional solutions (meant for stronger devices), while others suggest a novel approaches which are more light-weight. A common denominator for all these approaches is: they neglect of the fact that (1) an anomaly detection model is sensitive to adversarial attacks during the training phase, and (2) rare benign activities (which did not appear in the initial training data) can generate false positives (e.g., an IoT smoke detector being triggered).\nOur method, on the other hand, has a very short initial training-phase and learns from the experiences (events) of millions of IoTs.\n\nOther studies propose that a centralized server should be deployed \\cite{abera2016c,jager2017rolling,ott2015trust}. However, the centralized approach does not scale well with the number of IoT devices. Our method is distributed and autonomous.\n\nAnother direction in the literature is to deploy a network-based IDS at the gateway of IoT distributions \\cite{taneja2013analytics,chen2011novel}. Although this is a suitable solution for smart homes and offices, it does not scale to industrial deployments (e.g., smart railways), or where the IoT devices are connected directly to the Internet (e.g., some survallaince cameras). Our method does not depend on the IoT devices' deployment or topology.\n\nOther studies have tried to avoid the issue of training altogether, by using a trust anchor, such as an IoT device's functional relationship to detect anomalies. In \\cite{moon2015functional}, the authors propose executing every distributed computation twice across different IoT devices and then compare the results to detect deviations (infected devices). However, this method was only designed to protect specific types of IoT devices, from specific types of attacks. Our method is generic to the type of device, and the type of attack.\n\nOther trust anchors solutions include the Trusted Platform Module (TPM) \\cite{morris2011trusted} and Trusted Execution Environment (TEE) \\cite{yiu2015armv8}. ARM's TrustZone \\cite{su2011multi} is a TEE implemented in the hardware, providing a one-way separation between two worlds: ``unsecured'' and ``secured''. In \\cite{abera2016c} the authors proposed C-FLAT which utilizes the Trust Zone for attesting the IoT device's control-flow behavior against a simulation run in parallel on a central server. Although an application's control-flow can be used to detect a vast range of code execution attacks, C-FLAT is limited to specific IoT devices which (1) do not execute code continuously or (2) devices whose behavior is not affected by external sensory events (e.g., smart cameras). Our method analyzes control-flow behavior to detect abnormalities dynamically on-site, and therefore does not have these limitations. \n\n\n\n\\section{The Anomaly Detection Model}\\label{sec:anom}\nIn this section, we present a novel method for efficiently modeling an application's control-flow, and then detecting abnormal patterns with the trained model. The method is applied locally and continuously on a single IoT device. Later, in Section \\ref{sec:ciota}, we will present the proposed framework for enabling the decentralized collaborative training of the anomaly detection model.\n\n\\subsection{Motivation}\nWhen an application is executed, the kernel designates a region of memory for the program to operate in. The region contains the program's code (machine instructions) and room for data (e.g., variables) to be manipulated by the program. As a program runs, a program counter (PC) tracks the current location (in memory) of the current instruction being executed. The PC will jump to different locations when functions, if statements, and loops are performed. By following the location of the PC over the application's region in memory, a pattern emerges. This pattern captures the behavior (control-flow) of the application. The objective is to model the normal behavior of an application's control flow, and then later detect when the behavior changes. \n\nWhen an attacker does not have the victim's credentials, the attacker may attempt to exploit a software vulnerability in order to obtain access to restricted assets, or to perform some other undesirable task (e.g., install a bitcoin mining bot). When an exploit is executed on an application, the control-flow of the app will deviate from the behavior intended by the app's developers. By detecting this abnormality, we can identify the threat and then take the proper steps to alter the user and mitigate it. \n\nBuffer overflow and code-reuse are examples of attacks which abnormally affect the PC's location in memory. Another example is the ``Zimperlich'' \\cite{Zimperlich} vulnerability in Android which gives the attacker privileged escalation. When exploited, the ``Zimperlich'' causes the \\textit{setuid} operation to fail. \nHowever, by monitoring the control-flow of the application, we can detect that the app was attempting access to the region of memory where \\textit{setuid} is located, at an unusual time. As a result, we can raise an alert which will reveal the attack to the user.\n\nWith this approach, it is challenging for the attacker to evade detection. This is because most systems cannot change the code loaded into memory. Therefore, in order for the attacker to execute code which will hide the malicious activities, the attacker must either (1) add code of his own (which will make the PC jump), or (2) override existing code with his own (which will change the behavioral flow of the PC). This places the attacker in a \\textit{catch-22}, where his exploit will ultimately detected as an anomaly (Fig. \\ref{ExecutionFlow}).\n\n\\begin{figure}[!t]\n\t\\centering\n\t\\includegraphics[width=.7\\columnwidth]{Figure\/ExecutionFlow.pdf}\n\t\\caption{A visualization of a smart-light's program control-flow over the memory space, and the affect caused when a vulnerability is exploited to run malicious code.}\n\t\\vspace{-0.3cm}\n\t\\label{ExecutionFlow}\n\\end{figure}\n\n\n\\subsection{Markov Chains}\nIn order to efficiently model sequences, we use a probabilistic model called a Markov chain (MC). An MC is a {\\em memory-less process}, i.e., a process where the probability of transition at time $t$ only depends on the state at time $t$ and not on any of the states leading up that state.\nTypically, an MC is represented as an adjacent matrix $M$, such that $M_{ij}$ stores the probability of transitioning from state $i$ to state $j$ at any given time $t$. Formally, if $X_t$ is the random variable representing the state at time $t$, then \n\\begin{equation} \\label{eq:3}\nM_{ij}=Pr(X_{t+1}=j|X_{t}=i)\n\\end{equation}\nAn EMM \\cite{bhat2008extended} is the incremental version of the MC. Let $N=[n_{ij}]$ be the frequency matrix, such that $n_{ij}$ is the number of transitions which have occurred from state $i$ to state $j$. From here, the MC can be obtained by\n\\begin{equation}\\label{eq:emm}\nM=[M_{ij}]=\\left[\\frac{n_{ij}}{n_i}\\right]\n\\end{equation}\nwhere $n_i=\\sum_j n_{i,j}$ is the total number of outgoing transitions observed by state $i$. By maintaining $N$, we can update $M$ incrementally by simply adding the value '1' to $N_{ij}$ whenever a transition from $i$ to $j$ is observed. In most cases, $N$ is a sparse matrix (most of the entries are zero). When implementing an EMM model, one can use efficient data structures (e.g., compressed row storage or hash maps) to track large numbers of states with a minimal amount of storage space.\n\nIf $N$ was generated using normal data only, then the resulting MC can be used for the purpose of anomaly detection \\cite{Patcha20073448}. Let $Q_{k}$ be the last $k$ observed states in the MC, where $k\\in\\{1,2,3,\\ldots\\}$ is a user defined parameter. \nThe simplest anomaly score metric is the probability of the observed trajectory $Q_{k}=(s_0,\\ldots,s_t)$ w.r.t the given MC. This is given by\n\\begin{equation}\nPr(Q_{k})=Pr(\\bigwedge_{i=0}^k (X_i=s_i))=\\prod_{i=0}^{k-1} M_{s_i,s_{i+1}}\n\\label{eq:trajectory-prob}\n\\end{equation}\nWhen a new transition from state $i$ to state $j$ is observed, we assert that the transition was anomalous if $Pr(Q_k) 0$}\n\t\t\\State $C++$\n\t\t\\EndIf\n\t\t\\EndFor\n\t\t\\If{$\\frac{C}{|\\mathbf{N}|} \\leq p_a$} \\Comment{not enough devices have observed $ij$}\n\t\t\\State $n_{ij} \\gets 0$\n\t\t\\EndIf\n\t\t\\EndFor\n\t\t\\State{\\Return $N$}\n\t\t\\EndFunction\n\t\\end{algorithmic}\t\n\\end{algorithm}\n\n\n\n\\section{The Framework}\\label{sec:ciota}\nIn this section, we present the proposed framework and protocol. The framework enables distributed devices to safely and autonomously train anomaly detection models (Section \\ref{sec:anom}), by utilizing concepts from the block chain protocol. \n\nFirst we will provide an overview and intuition of the framework (\\ref{subsec:overview}). Then we will present the terminology which we use to describe the blockchain protocol (\\ref{subsec:terms}). Finally, we will present the protocol and discuss its operation (\\ref{subsec:protocol}). Later in Section \\ref{sec:discussion}, we will discuss the various challenges and design considerations. \n\n\n\n\n\\subsection{Overview}\\label{subsec:overview}\nThe purpose of the framework is to provide a means for IoTs to perform anomaly detection on themselves, and to autonomously collaborate to find the anomaly detection model. \nFor example, a company may want gradually deploy thousands or millions of IoT devices. Each of the devices have an application, such as a web server (so that the user can interface and configure the device). The application may have un\/known vulnerabilities which can be exploited by an attacker to accomplish some nefarious task. To detect threats affecting the devices, the company installs an agent on each device, and has the agent monitor the application.\\footnote{An agent can cover multiple applications on a single device by maintaining separate models and blockchains. For simplicity, we will focus on protecting a single application.} \n\nThe job of an agent is to (1) learn the normal behavior of the application, and (2) report abnormal activity in the application (Algorithm \\ref{alg:anomDetect} on the local model $M^{(\\ell)}$), and (3) report abnormal agents compromised or infected with malware. \n\nEach agent then collaborates with the other agents by trying to figure out how to safely combine everybody's local models into a single global model $M^{(g_1)}$. Once the agents agree upon a global model, each device will replace their $M^{(\\ell)}$ with $M^{(\\mathit{g}_1)}$. The agents continue to update their $M^{(\\ell)}$ and collaborate on creating $M^{(\\mathit{g}_2)}$. This collaboration cycle repeats indefinitely.\n\nThe benefit of collaboration is:\n\\begin{enumerate}\n\t\\item An agent who has accidentally trained his $M^{(\\ell)}$ on malicious behaviors will now detect them as malicious.\n\t\\item The agents will benefit from the vast experience of all the devices together, and accurately classify rare benign events.\n\t\\item The agents will be able to identify rouge agents by detecting corrupt \\textit{partial-blocks} which fail model-attestation. \n\\end{enumerate}\n\nA critical part of the collaboration process is filtering out rare benign behaviors from possible malicious behaviors. \nThe difference between the two is that we expect to see rare benign behaviors among more devices than malicious behaviors, especially at the outset of an attack (e.g., the propagation of a worm). This is relative to the parameter $p_a$: we expect at least $p_a\\%$ of the agents to experience the rare-benign events, and less than $p_a\\%$ to be infected. Note that after $M^{(g)}$ converges the malicious behaviors are detected, and $M^{(\\ell)}$ is not updated with detected malicious behaviors (detailed in the protocol later on).\n\nSince agents do not update their $M^{(\\ell)}$ when an anomaly is detected, we expect each of the local models to remain pure.\nHowever, there are cases where an $M^{(\\ell)}$ can be corrupted. For example, when an agent launches after a malicious behavior begins, but before $M^{(\\mathit{g}_1)}$ has been created. \nTo protect the integrity of the next global model, when an agent which receives a set of local models (under collaboration to become the next global model), an agent will$\\ldots$\n\\begin{enumerate}\n\t\\item \\textbf{[\\textit{trust}]} $\\ldots$consider only sets which contain authenticated models from different agents.\n\t\\item \\textbf{[\\textit{filter}]} $\\ldots$combine the set into a potential $M^{(\\mathit{g})}$, and remove behaviors from $M^{(\\mathit{g})}$ which have not been reported by the majority of agents (\\textit{abnormality-filtration}).\n\t\\item \\textbf{[\\textit{attest}]} $\\ldots$accept the set of models as a potential $M^{(\\mathit{g})}$, if it does not conflict with the agent's current local model (\\textit{model-attestation}).\n\t\\item \\textbf{[\\textit{inform}]} $\\ldots$share the accepted set of models (including his own) with other agents, while reporting abnormal application behaviors and problematic agents (rejected \\textit{partial-blocks}).\n\\end{enumerate}\n\nThe following analogy provides some intuition for how the agents create $M^{(\\mathit{g})}$: \n\\begin{tcolorbox}[breakable,title=\\textit{Analogy}]\n\tA group of painters (agents) are looking at the same colored object (target application), and they are working together to select a single colored paint ($M^{(\\mathit{g})}$) to describe it. Each painter produces a bucket of paint ($M^{(\\ell)}$) based on their perception of the object's color. The painters then share their paint buckets with their neighbors, who mix the received paints together, while filtering out imperfections (\\textit{abnormality-filtration}), but only if they feel the resulting color will still resemble the colored object (\\textit{model-attestation}). The painters continue to adjust the paints, and after a set number of iterations of sharing, each painter pours some of the paint onto his\/her pallate, and uses it to paint (perform anomaly detection). Then, the cycle repeats as the painters continue to adjust, filter, and share the paints in hopes of perfecting the color.\n\\end{tcolorbox}\n\nTo enable this autonomous trusted distributed collaboration, we use a \\textit{blockchain}. In the following sections, we will detail how blockchain is used for this purpose.\n\n\\subsection{Terminology \\& Notation}\\label{subsec:terms}\nIn the framework, a blockchain is a linked list of sequential blocks, where each block contains a set of records (EMM models) acquired from different IoT devices of the same type (see Fig. \\ref{fig:block}). Each device maintains a copy of the latest chain, and collaborates on the next block.\n\nWe will now list the terminology and notations necessary to explain the framework in detail:\n\n\\begin{description}\n\t\\item[Model] A Markov chain anomaly detection model denoted $M$, where $N$ denotes the model in its EMM frequency matrix form. The model supports (1) the calculation of a distance between models, and (2) combining (merging) several models of the same type together. In this version, we use an EMM. We denote a model which is currently deployed on the local device as $N^{(\\ell)}$.\n\t\n\t\\item[Combined Model] A model created by merging a set of models together. The combined model only contains elements (transitions) which are present in at least $p_a$ percent of the models (see \\textit{abnormality-filtration} in Algorithm \\ref{alg:combine}). \n\t\n\t\\item[Verified Model] Let $d(M^{(i)},M^{(j)})$ be the distance between models $M^{(i)}$ and $M^{(j)}$. A model $M^{(i)}$ is said to be verified by a device if $d(M^{(i)},M^{(\\ell)}) < \\alpha$, where $\\alpha$ is a parameter given by the user (see \\textit{model-attestation} in (\\ref{eq:attest})).\n\t\n\t\\item[Record] A record is an entry in a block. A record consists of the model $N^{(i)}$ from device $i$, and a digital signature $S_{k_i}(\\texttt{m}, n, \\textbf{N})$, where $k_i$ is device $i$'s private key, \\texttt{m} is the blockchain's meta-data (hash of previous block, target application, version$\\ldots$), $\\textbf{N}$ is the set of models from the start of the current block up to and including $N^{(i)}$, and $n$ is a counter which is incremented with each new block. The purpose of $n$ is to track the length of the chain and to prevent replay attacks. A record is \\textit{valid} if the format is correct and the signature can be verified using device the corresponding device's public key. \n\t\n\t\\item[Block] A list of exactly $L$ records from different devices and some metadata. Each record is verified by the agent's digital signatures, where each agent's signature covers its model, all preceding models, the current block number ($n$), and its metadata (e.g., the agents' IP addresses). We denote the $i$-th record in a block as $r_i$. The models in a block, when combined, represent a collaborative model $M^{(\\mathit{g})}$ which can be used to replace a local model $M^{(\\ell)}$. A block is \\textit{valid} if the format is correct and contains valid records.\n\t\n\t\\item[Partial Block] The same as a block, but it is less than $L$ entries long. The combined models in a \\textit{partial-block} represent a proposed collaborative model $M^{(g)}$ in progress. An agent contributes (add its own model) to a \\textit{partial-block} only if (1) the \\textit{partial-block} is valid, (2) the agent does not already have a record there, and (3) the combined model, using the enclosed models, form a verified model (with respect to the agent's local model $N^{(\\ell)}$). The length of a \\textit{partial-block}, in the perspective of agent $i$, is the number of records in the \\textit{partial-block} minus $i$'s if it exists.\n\t\n\t\\item[Chain] A series of blocks (blockchain), where each block contains a hash of the previous block in \\texttt{m}, and where the counter $n$ is the index of the block in the chain ($n=1$ for the first block, etc.) A chain contains the current collaboration for the next $M^{(\\mathit{g})}$ (\\textit{partial-block}), the current model with consensus (the last block in the chain), and an optional history of collaboration used for analytical purposes (all other blocks). The length of a chain is defined as the total number of full blocks in that chain. Finally, a chain may have at most one \\textit{partial block} appended to the end of the chain. We denote the $i$-th block in a chain as $B_i$.\n\t\n\t\\item[Agent] A program that runs on an IoT device which is responsible for (1) training and executing the local model $N^{(\\ell)}$, (2) downloading more advanced broadcasted chains to replace $N^{(\\ell)}$ and the locally stored chain, (3) periodically broadcasting the locally stored chain, with the agent's latest $N^{(\\ell)}$ as a record in the \\textit{partial block}, and (4) reporting any anomalous behaviors\/blocks.\n\t\n\\end{description}\n\n\n\\begin{figure}[!t]\n\t\\centering\n\t\\includegraphics[width=.84\\columnwidth]{blockfig.pdf}\n\t\\caption{An example of a chain with two blocks and a partial block, where the device IDs are $\\{\\mathbf{a},\\mathbf{b},\\mathbf{c}\\ldots\\}$.}\n\t\\label{fig:block}\n\\end{figure}\n\n\\subsection{The Blockchain Protocol}\\label{subsec:protocol}\nBy using a \\textit{block-chain}, agents are able to collaborate autonomously in manner which is robust to adversarial attacks. Every agent maintains a local copy of the `best' chain. \n\nClosed blocks in the chain represent past completed global models, where the last completed block in the chain contains the most recently accepted model $M^{(\\mathit{g})}$. The next global model is collaborated via a \\textit{partial-block} appended to the chain. A \\textit{partial block} only grows if agents can verify that it contains a safe model that captures the training distribution (the target app's behaviors). This is accomplished through trust propagation: agents (1) broadcast their \\textit{partial block} to other agents, (2) replace their local \\textit{partial-block} with received ones if they are both longer and similar to $N^{(\\ell)}$ (same distribution check via \\textit{model attestation}), and (3) reject and report \\textit{partial-blocks} that are significantly different than $N^{(\\ell)}$.\n\n\n\n\nThe blockchain protocol is as follows (illustrated in the flow-chart of Fig. \\ref{LLD}):\n\\begin{tcolorbox}[breakable,title=\\textit{Blockchain Protocol}]\n\t\\singlespacing \\vspace{-1.5em}\n\t\\begin{enumerate}[leftmargin=*,label=\\Alph*.]\n\t\t\\item \\textbf{Initialize.} An agent starts with an empty chain (an empty \\textit{partial-block} with no preceding blocks) stored locally on its device, and initializes an empty local model $N^{(\\ell)}$. \n\t\t\\item \\textbf{Gather Intelligence (Monitor).} The agent (1) monitors the target application, (2) updates $N^{(\\ell)}$ incrementally, and (3) reports anomalies if $T_{grace}$ has passed (Algorithm \\ref{alg:monitor}). \n\t\t\\item \\textbf{Share Intelligence.} Every $T$ seconds:\n\t\t\\begin{enumerate}[label*=\\arabic*.]\n\t\t\t\\item \\label{step:add_self} The agent adds its own local model $N^{(\\ell)}$ to the \\textit{partial-block} as a record, if $M^{(\\ell)}$ is stable (passed $T_{grace}$), and does not yet exist in the \\textit{partial-block}. \n\t\t\t\\item \\label{step:broadcast} The agent shares its \\textit{block-chain} (\\textit{partial-block} and all preceding blocks) with $b$ other agents in a random order.\\footnote{The agent only needs to broadcast the chain to a few `neighboring' agents, similar to how Etherium and Bitcoin work.} \n\t\t\\end{enumerate} \n\t\t\n\t\t\\item \\textbf{Receive Intelligence.} When an agent receives a \\textit{block-chain}:\\footnote{To avoid DoS attacks, an agent will at most process $b$ chains once every $T$ seconds.}\n\t\t\\begin{enumerate}[label*=\\arabic*.]\n\t\t\t\\item \\textbf{If} the chain is shorter than the local chain: \\textit{then} the agent discards the received chain.\n\t\t\t\\item \\textbf{If} the chain is longer than the local chain: \\textit{then} the agent checks...\n\t\t\t\\begin{enumerate}[label*=\\arabic*.]\n\t\t\t\t\\item \\textbf{If} the last block is a valid block: \\textit{then} the received chain replaces the local chain, and the models $\\mathbf{N}$ in the last block are combined (\\textit{abnormality-filtration}) to form $N^{(\\mathit{g})}$ which replaces $N^{(\\ell)}$.\\footnote{The agent does not perform \\textit{model-attestation} on a valid block.}\\footnote{Option: Agents update $T$ to be a factor of the number of closed blocks in the local chain. Since $M^{(g)}$ converges over time, it is safer to prolong changes to the next version, increasing the response time when an attack on the blockchain is detected. See Section \\ref{subec:adversarial} for details.}\n\t\t\t\t\\item \\textbf{Else}: the agent discards the received chain.\n\t\t\t\\end{enumerate}\n\t\t\t\\item \\textbf{If} the chain has the same length as the local chain: \\textit{then} the agent checks...\n\t\t\t\\begin{enumerate}[label*=\\arabic*.]\n\t\t\t\t\\item \\label{step:pb_accept}\\textbf{If} (1) the received chain's \\textit{partial-block} is longer than the local chain's \\textit{partial-block} (excluding his own record from both), (2) the received \\textit{partial-block} is valid, and (3) the models $\\mathbf{N}$ in the \\textit{partial-block} form a combined model (\\textit{abnormality-filtration}) which the agent can attest is a verified model (\\textit{model-attestation}): \\textit{then} the received chain replaces the local chain.\n\t\t\t\t\\item \\label{step:pb_message} \\textbf{Else If} (1) the chain's \\textit{partial-block} has the same length as local chain's \\textit{partial-block} (excluding his own record), (2) the two \\textit{partial-blocks} have different agent IDs, (3) the \\textit{partial-block} is valid, and (4) this is the $k$-th received chain of equal length whose \\textit{partial-block} was that was not used: \\textit{then} send the local chain to the agent(s) in received \\textit{partial-block} who do not appear in the local \\textit{partial-block}.\\footnote{The received \\textit{partial-block} has the IP addresses of the target agents.} \n\t\t\t\t\\item \\label{step:pb_reject} \\textbf{Else}: (1) the agent discards the received chain, and (2) \\textbf{If} in steps \\ref{step:pb_accept} or \\ref{step:pb_message} the \\textit{partial-block} failed the validity check or failed the \\textit{model-attestation} to a significant degree, \\textit{then} report the block and sending agent.\\footnote{Alternative version: If the last block is valid yet different than the local chain's, then merge that block's combined model into $N^{(\\ell)}$. This helps form a more general $N^{(g)}$ without communities. A limitation must be placed on the number of merges per $T$ seconds.}\n\t\t\t\\end{enumerate} \n\t\t\\end{enumerate}\n\t\\end{enumerate}\n\\end{tcolorbox}\n\n\\begin{figure}[!t]\n\t\\centering\n\t\\includegraphics[width=\\textwidth]{Figure\/flow_chart_ABC.pdf}\n\t\\includegraphics[width=\\textwidth]{Figure\/flow_chart_D.pdf} \n\t\\caption{A flow-chart of the blockchain protocol.}\n\t\\label{LLD}\n\\end{figure}\n\\subsection{Proof of Cumulative Majority}\nIn blockchains, there is often some form of effort which deters an attacker from making false records. In systems like Etherium, it's the effort of solving a crypto challenge. This type of challenge is necessary in systems like Etherium, because there is a base assumption that all participants are untrusted from the start. In contrast, our system assumes that the majority participants (agents) are on uncompromised devices at the start, because they are deployed by the manufacture. This is a common assumption for IDS systems.\n\nTherefore, this blockchain uses ``proof of cumulative majority'' to deter attacks. The cumulative majority refers to the distributed consensus, or significant mass, achieved by accumulating $L$ the participants' signatures on a set of models to be combined as the next global model.\n\nConcretely, an agent only replaces its local \\textit{partial-block} with a received \\textit{partial-block} if it is similar to the behaviors is has seen locally (\\textit{model-attestation}). Therefore, a \\textit{partial-block} of length $L$ can only exist if $L$ agents can attest that the model is similar to their own model\/observations (i.e., there are $L$ compromised agents within $T$ seconds). Since $L$ is very large in practice (10k-100k), and \\textit{partial-blocks} are indiscriminately shared and propagated: (1) a closed block has majority trust on it, and (2) is unlikely to be malicious due to the attacker's significant challenge.\n\nThe attacker's challenge\/effort in this blockchain is to compromise a significant number of devices before $T$ seconds pass. Otherwise, the attack is reported in step \\ref{step:pb_reject} of the protocol. At which point, the attack is discovered and (1) the affected devices' keys can be invalidated, and (2) the devices can be cleaned and patched.\n\nWith this in mind, we can see how the proposed blockchain system achieves its objective as an IDS. When a device is compromised, either (1) the agent will detect an abnormal behavior and report it to the SOC, or (2) the model will be corrupted\/tainted by the latent behavior. In the latter case, if the compromised device publishes its model, it will be rejected by the other devices, because the tainted partial block (PB) will no longer be self-similar to the other devices' models in the \\textit{model-attestation} step. The other agents will then report rejected blocks, for example, to a Security Operations Center (SOC), and it will be clear who the infected device is (identified with problematic model's key from the reported PBs). The SOC can then invalidate that device's key and investigate the intrusion. Therefore, if the agent is compromised then the tainted model will be detected by the community, and if the model is corrupt (contains abnormal behaviors) then the agent will detect the intrusion when it replaces the local model with the next global model.\n\n\n\n\n\\subsection{Model Conflicts in Partial Blocks}\\label{subsec:conflicts}\nA concern might be that the agents will disagree on the models in the \\textit{partial-block} and not reach a consensus. However, all agents monitor the same application running on the same type of hardware. Therefore, their models are very similar to one another. This is intuitive because each agent's training data follows the same distribution, and the Markov chain captures the probabilities of PC transitions. \n\nSince the models are trained on the same distribution, any model formed by combining a subset of all agents' models will also be similar all agents' models. More formally, we observe that\n\\begin{equation}\n\td\\left(combine\\left(N_{i}^{(\\ell)}\\right),n_{j}^{(\\ell)}\\right)<\\alpha \\hspace{1em} \\forall i,j : n_{j}^{(\\ell)}\\in N^{(\\ell)},N_{i}^{(\\ell)}\\in \\mathbf{N}^{(\\ell)}\n\\end{equation}\nwhere $\\mathbf{N}^{(\\ell)}$ is the set of all agents' models, and $d$ is the average parameter distance defined in (\\ref{eq:attest}). This holds true since all agents are sampling from the same distribution (hardware and software). In our experiments, we were able to set $\\alpha$ to a low value because the agents' benign models were consistently very similar (Section \\ref{sec:eval}).\nTherefore, it is highly unlikely that the \\textit{partial-block} will be in conflict given a reasonable $\\alpha$. \n\n\\subsection{Deadlock Prevention}\\label{subsec:deadlocks}\nAs mentioned in the protocol, agents should only message a few other agents in step \\ref{step:broadcast} to minimize traffic overhead. However, a deadlock can occur if (1) connectivity between agents is incomplete (some agent's cannot directly message other agents), (2) all agents have their neighbor's records in their \\textit{partial-block}, and (3) all \\textit{partial-blocks} have the same length. Although it is very rare for this to occur (one in a million depending on the connectivity), step \\ref{step:pb_message} prevents any deadlocks that may happen.\n\nThe following is the formal proof that our revised system will not have any deadlocks in reaching a \\textit{partial-block} of length $L$. \n\nLet the undirected graph $G=(E,A)$ represent the agent's connectivity, where $i\\in A$ is the set of agent IDs. Let $pb_i$ be the \\textit{partial-block} of agent $i$ such that $pb_i \\subseteq A$. We denote the set of neighbors which are directly connected to agent $i$ as $\\Gamma_i$. Finally, we refer to an epoch as an iteration where all agents have broadcasted a their $pb$ to their neighbors (every $T$ seconds).\n\nIn our proof, we assume that $G$ forms a single connected component. We also assume that $L=|A|$ because if a $pb$ reaches length $|A|$ then it will reach all possible $L$, where $L\\leq |A|$. We also assume that all agents are drawing observations from the same distribution to train their models, and therefore will not have any issue during the $pb$ validation checks (Section \\ref{subsec:conflicts}). \n\nA deadlock occurs if $\\forall i\\in A:D(i)$ where the predicate $D$ is defined as $D(i) : pb_{i}^{(t)}=pb_{i}^{(t+1)} \\land |pb_{i}^{(t)}||pb_j|$ then there is only one case where $|pb_i \\oplus \\{i\\}|=|pb_j \\oplus \\{i\\}|$ resulting neither agent performing an update: $pb_i \\cap \\{j\\}=\\{j\\}$ and $|pb_i|=|pb_j|-1$. However, because $pb_j \\cap \\{j\\}=\\{j\\}$ (Lemma \\ref{lemma:have_own}), $|pb_j \\oplus \\{j\\}|<|pb_i \\oplus \\{j\\}|$ so agent $j$ would have replaced $pb_j$ with $pb_i$\nTherefore, we conclude that $\\forall i \\in A : D(i) \\rightarrow \\forall (i,j) \\in E : pb_i \\cap \\{i\\} \\cap pb_j=\\{i\\}$, so Lemma \\ref{lemma:have_eachother} holds true.\n\\end{proof}\n\n\\begin{lemma}\\label{lemma:same_len}\nLemma 3. If there was no update (deadlock) then all partial blocks have the same length. Formally, $\\forall i \\in A : D(i) \\rightarrow \\forall ij \\in A : |pb_i|=|pb_j|$\n\\end{lemma}\n\\begin{proof}\nLet's assume that $\\forall i \\in A : D(i)$ but $\\exists(i,j) \\in E : |pb_i|<|pb_j|$. However, $pb_i \\cap \\{i,j\\} \\cap pb_j=\\{i,j\\}$ (Lemma \\ref{lemma:have_eachother}). This means that $|pb_i \\oplus \\{i\\}|<|pb_j \\oplus \\{i\\}|$ so agent $i$ would have set $pb_i=pb_j$, and $\\forall i \\in A : D(i)$ would not hold true. Therefore, it must be that $|pb_i|=|pb_j|$.\n\\end{proof}\n\t\n\\begin{lemma}\\label{lemma:bad_neighbors}\nLemma 4. If there was no update (deadlock), then there exist two neighbors with different partial blocks, of same length. Formally, $\\forall i \\in A : D(i) \\rightarrow \\exists(i,j) \\in E : pb_i \\neq pb_j$.\n\\end{lemma}\n\\begin{proof}\nLet's assume $\\forall i \\in A : D(i)$ but $\\forall (i,j) \\in E : pb_i=pb_j$. According to Lemma \\ref{lemma:have_own}, all agents have their own ID in their partial block. However, if all agents have the same partial block, then that means that $|pb_i|=L$ and $\\forall i \\in A : D(i)$ does not hold true. Therefore, it must be that $\\exists (i,j) \\in E : pb_i \\neq pb_j$.\n\\end{proof}\n\n\\begin{theorem}\\label{theorem:nodeadlock_eqL}\nGiven a set of agents $A$, the connectivity network $G$, and $L=|A|$, there will never be a deadlock. Formally, $L=|A|\\rightarrow \\nexists i \\in A: D(i)$.\n\\end{theorem}\n\\begin{proof}\nLet's assume that $L=|A|$ but $\\forall i \\in A : D(i)$ (there is a deadlock). This would mean that $\\exists (i,j) \\in E : pb_i \\neq pb_j$ (Lemma \\ref{lemma:bad_neighbors}). If so, it must be that there is at least one ID in $pb_j$ that is not in $pb_i$ (via Lemmas \\ref{lemma:have_eachother} and \\ref{lemma:same_len}). Let's say that one of these IDs is that of agent $k$. When agent $j$ shared $pb_j$ with agent $i$ (step \\ref{step:broadcast} of the protocol), agent $i$ would have sent $pb_i$ directly to its non-neighbor $k$ (step \\ref{step:pb_message} of the protocol). Since $|pb_k|=|pb_i|$ (Lemma \\ref{lemma:same_len}), and $|pb_k \\oplus \\{k\\}|<|pb_i \\oplus \\{k\\}|$ because $pb_i$ does not have $k$, agent $k$ must have replaced $pb_k$ with $pb_i$. Therefore, it is impossible for $\\forall i \\in A : D(i)$ to hold true since in the next epoch, agent $k$ would have added itself to its partial block making $|pb_k|>|pb_i|$. \n\\end{proof}\nThe continuation can be seen through Lemma \\ref{lemma:same_len}: it must be that all other agents will grow their partial blocks to the same length as $pb_k$. Then, if there is another deadlock, the above process repeats until $\\exists i \\in A : |pb_i|=|A|$ and the block is closed.\n\n\\begin{corollary}\\label{corr:deadlock_degree}\nCorollary 1. Given a set of agents $A$, the connectivity network $G$, and $L \\leq |A|$, there will never be a deadlock. Formally, $L \\leq|A| \\rightarrow \\nexists i \\in A : D(i)$.\n\\end{corollary}\n\\begin{proof}\nThe proof is trivial via Theorem \\ref{theorem:nodeadlock_eqL} since there exists an agent that will reach a partial block length longer than $|A|$, and step \\ref{step:add_self} of the protocol ensures that partial block grow in length by one at time.\n\\end{proof}\n\nAs a side note, if step \\ref{step:pb_message} (direct messaging) is removed from the protocol, the system will reach a partial block length of the maximum degree plus one without any deadlocks:\n\\begin{theorem}\\label{theorem:nodeadlock_leqL}\nTheorem 2. Given a set of agents $A$, the connectivity network $G$, and $L=\\Delta(G)+1$, there will never be a deadlock. Formally, $L=\\Delta(G)+1 \\rightarrow \\nexists i \\in A : D(i)$.\n\\end{theorem}\n\\begin{proof}\nLet's assume that agent $i$ has the maximum degree. According to Lemma \\ref{lemma:have_eachother}, $pb_i$ must have all of its neighbor's IDs and $i$ before a deadlock can occur. Therefore, there can't be a deadlock because $|pb_i|=|\\Delta(G)+1|=L$. \n\\end{proof}\n\n\n\n\n\n\n\\subsection{Peer Discovery}\\label{subsec:peerdisc}\nTo broadcast the latest chain, an agent must know the IP addresses of the receiving agents. It is important to note that an agent does not need to broadcast to all other agents. Instead, an agent broadcasts to $b$ other agents where $b$ is much smaller than the population size. In practice, $b$ can be in the order a tens or hundreds where there is a trade-off between the rate at which information is shared across the network (iterations of $T$) and the amount of work that is put into each broadcast. Regarding the discovery and selection of peers, we suggest that the Ethereum's p2p discovery protocol \\cite{Discover45:online} be used and that an agent should periodically draw new peers at random.\n\n\\subsection{Maintaining Software Versions}\\label{subsec:branching}\nAs time goes on, the target application may receive software updates during its software life-cycle. Although the app's new behavior will be accepted as normal (due to the majority consensus), there may be other devices where not yet updated or may never be updated. To ensure that these outdated devices aren't `forced' to use an incompatible model, we suggest that blockchain should support branching. In this approach, the chain forms a version tree were devices with newer versions can `fork' off to. To enable this the following additions are made to the protocol: (1) the respective software version must be stored in the metadata of each block, (2) multiple partial blocks of different version can be stored at the end of a chain, (3) if a partial block is completed but it has a different version than the current branch, then a separate chain is `forked' from that point, and (4) agents always follow the longest chain with their version. \n\n\\section{System Evaluation}\\label{sec:eval}\nIn this section, evaluate the proposed collaboration framework: the experiment testbed, parameters, results, and observations. A video demo of the framework is available online.\\footnote{\\textit{The short demo of the framework protecting 48 Pis running web servers can be found at \\texttt{\\url{https:\/\/youtu.be\/T4t_SnTJV3w}}}}\n\n\n\\subsection{Experiment Setup}\nOur experiments were composed of four aspects: the (1) test environment, (2) implementation, (2) target applications, and (3) attack scenarios. We will now discuss each of these aspects in detail.\n\n\\subsubsection{Test Environment}\nWe built a LAN which served as a simulation platform for emulating a distributed IoT environment (Fig. \\ref{PiBoard}). \nThis network involves 48 Raspberry Pis connected together through a single large switch.\n\nIn our environment, each Raspberry Pi was equipped with additional boards (sheilds) and sensors. For example, the PiCamera and Pibrella Board\\footnote{\\textit{Pibrella module can be found at \\texttt{\\url{www.pibrella.com}}}} which provides programmatic access to three LED lamps and simple 8-bit PC speaker. For each experiment, a target application (IoT software) was loaded and executed on all of the devices, along with an agent.\n\nThe source code for the agent can be found on GitHub.\\footnote{The agent's code from the experiment can be found at \\texttt{https:\/\/git.io\/vAIvd}}\n\n\n\\subsubsection{Agent Implementation}\nTo implement Algorithm \\ref{alg:monitor} (monitor), we implemented the agent using OS and CPU features. Specifically, we used the performance counters API and Core-sight (on ARM) and Last-Branch (on Intel). By using these libraries and features, we were able to track the application's control-flow in an asynchronous manner.\n\nIn our implementation, the kernel fills a large ring-buffer with observed jump and branch addresses. \nWhen the OS scheduler switches to the agent, the agent iterates over the new entries in the buffer and updates $M^{(\\ell)}$ accordingly. To improve performance further, the agent was written entirely in C++. However, the code was not optimized to its full potential.\n\nThe underlying network protocol we used in our experiment was the UDP Multicast protocol, though in practice, the Bitcoin or Etherium P2P neighbor discovery algorithm should be used. The following lists the parameters used in all experiences, unless noted otherwise:\n\\begin{itemize}\n\t\\item \\textbf{\\boldmath$T$ (Processing interval)}: one minute\n\t\\item \\textbf{\\boldmath$L$ (Block size)}: $20$\n\t\\item \\textbf{\\boldmath$p_a$ (Percent of reporting devices required to include a transition)}: $25\\%$\n\t\\item \\textbf{\\boldmath$\\alpha$ (Verification distance)}: $0.05$\n\t\\item \\textbf{\\boldmath$p_{thr}$ (Anomaly score threshold)}: $0.012$\n\t\\item \\textbf{\\boldmath$k$ (Probability averaging window)}: $10,000$\n\t\\item \\textbf{Region size}: $256$ Bytes\n\\end{itemize}\n\n\n\\begin{figure*}\t\n\t\\centering\n\t\\includegraphics[width=\\textwidth]{Figure\/PiBoard.png}\n\t\\caption{IoT simulation testbed consisting of 48 Raspberry Pis}\n\t\\label{PiBoard}\n\\end{figure*}\n\n\\subsubsection{Target Applications}\nEvery application has a different control-flow, and reacts differently to environmental stimuli. Therefore, we evaluated the framework using several different target applications:\n\n\\begin{description}\n\t\\item[Smart Light] Smart lights can perform custom functionalities programmed by the user. By evaluating the framework on a smart light, we are able to determine whether each agent is able to learn its functionality, and how the propagation of these behaviors affect other agents.\n\tTo implement the smart light's software, we combined several Open-Source projects \\cite{mongoose, pibrellaGitHub, WiringPi}. The final application contained a vulnerable web-based interface for controlling the light's features.\n\t\n\t\\item[Smart Camera] Smart cameras often consume a significant amount of resources to perform real-time image processing. By monitoring such an application, we are able to evaluate how well the framework performs in resource heavy applications. The application which we used monitors a video feed and sends an alert when it detects a movement. The alert is sernt to a control server and is accompanied with a short video or image of the event. A user interfaces with the camera via the server, and can either (1) change its configuration or (2) view the camera's current frame. We included with the final application a null dereference vulnerability in the communication process with the control server.\n\t\n\t\\item[Router] Routers are widespread and provide Internet facing IPs (i.e., are not hidden behind a NAT). They are a good example of vulnerable IoTs which have been the target of many recent attacks (e.g., Mirai and the VPNFilter malware\\footnote{\\texttt{\\url{https:\/\/www.symantec.com\/blogs\/threat-intelligence\/vpnfilter-iot-malware}}}). By evaluating the framework on a router's software, we are able to consider how well our agent handles complex control-flows. Routers typically have a Linux kernel, and provide their functionality via several different applications. In our evaluation, we chose to target the Hostapd (Host access point daemon) applicaiton. Hostapd is a user space software access point capable of turning normal network interface cards into access points and authentication servers. We took version 2.6 of Hostapd which is vulnerable to a known replay attack.\\footnote{The code is available at \\texttt{\\url{https:\/\/github.com\/vanhoefm\/krackattacks-scripts}}}\n\\end{description}\n\n\\subsubsection{Attack Scenarios}\nTo understand the framework's detection capabilities, we evaluated how well the agents can detect the exploitation of different vulnerabilities and the execution of malicious code:\n\n\\begin{description}\n\t\\item[Buffer Overflow] When writing information into a buffer, without proper boundary checks, it is possible to write more data than the buffer's size. \n\tWhen this occurs, the data overflows and overwrites the code and variables in memory.\n\tIf executed correctly, a buffer overflow can be used to alter a programs code and alter the control-flow of the program. \n\tThis situation is dangerous because a crafted input data can contain machine instructions, thus causing the program to execute arbitrary code in the software's context \\cite{deckard2005buffer}. In this scenario, we (1) exploit a buffer overflow vulnerability in the application, (2) covertly have the app behave like a bot, and (3) preserve the application's original behavior. The bot attempted to connect with a C\\&C server once every minute.\n\t\n\t\\item[Code-Reuse] Instead of injecting new code into the program's memory layout, a code-reuse attack \\cite{prandini2012return,elreturn,bletsch2011jump} uses the existing code of the program to create a new logic, mostly by performing jumps to unusual places in the code. For example, jumping to the middle of functions or jumping multiple times to different instructions which perform the desired logic.\n\tThese attacks were proved to be, in many cases, tuning complete \\cite{tran2011expressiveness}. This means that an attacker can potentially cause a typical program to execute any desired logic.\n\tA common approach is called ``return-to-libc'' \\cite{elreturn} which reuses code in the libc library to execute the desired code. More advanced approaches are to use the ROP (Return-oriented programming \\cite{prandini2012return}) and JOP (Jump-oriented programming \\cite{bletsch2011jump}) techniques.\n\tIn this scenario, we attack perform a code-reuse attack on the target application in order to get the app to send sensitive data to a remote server.\n\t\n\t\\item[Replay Attack (Key Reinstallation Attack)] The Key Reinstallation Attack is a type of replay attack in which one or more protocol's messages are sent again in a different, unexpected, point of the protocol. The Key Reinstallation Attack tries to leak information about encrypted traffic by changing the application state in the middle of the encryption process. Unlike the previous two attacks, this attack does not execute new arbitrary logic within the application's memory space, but rather abuses the control-flow to reveal encryption secrets which can be used to decrypt a user's traffic off-site. \n\t\n\\end{description}\n\n\n\n\\subsubsection{The Experiments}\nTo evaluate the framework's anomaly detection capabilities with different applications and attacks, we used several different experiment setups summarized in Table \\ref{ExperimentsSummery}. We will refer to these experiments using their short-form notation from the table.\n\nUnless stated differently, for every experiment, the target application and a local agent were launched on 48 Raspberry Pis simultaneously. After two hours, we paused the training and began to record the performance for another two hours. Finally, at the start of the fifth hour, the specified attack was executed. Although it was not part of the protocol, we paused the training in order to observe the performance of a collaborative model which has been trained for exactly two hours. It is critical that the target application would not remain dormant, but rather, is exposed to normal interactions like an IoT device. Therefore, to successfully simulate a real environment, during all of our experiments we legitimately interacted with the target application manually, using random fuzzing, and previously recorded data on the application's input channels. For example, we used a prerecorded video stream in the experiments involving the smart camera.\n\n\\begin{table}[!t]\n\t\\begin{center}\n\t\t\\caption{Summary of Experiment Setups}\n\t\t\\begin{tabular}{c}\n\t\t\t\\includegraphics[width=.6\\columnwidth]{tab_case.pdf}\n\t\t\\end{tabular}\n\t\t\\label{ExperimentsSummery}\n\t\\end{center}\n\\end{table}\n\n\n\\subsection{Experiment Results}\nThe contributions of this paper are (1) a method for detecting abnormal control-flows (2) efficiently, and (3) a method for performing collaborative training (4) in the presence of an adversary. We will now present our results accordingly.\n\n\n\\subsubsection{Anomaly Detection}\\label{subsubsec:anom}\nWe will now evaluate the use of EMMs over regions of an application's memory space as a method for anomaly detection, on a \\textit{single} device.\n\nThe code injection attacks (buffer-overflow and code-reuse) were detected entirely with no false positives. Fig. \\ref{EMM_ON_REPLAY:a} plots the EMM probability scores $\\overline{Pr}(Q_{k})$ for Exp2.\nThe Key Reinstallation Attack (Exp5) was more difficult to detect (Fig. \\ref{EMM_ON_REPLAY:b}). This is because the attack does not inject own code, and the impact on the control-flow is very brief (a single step in the protocol). However, the attack still influences the probability scores, and we are able to detect the attack when $k$ is increased. Furthermore, when the train time is increased, the performance increases as well. This is evident in the collaborative training setting where two hours of training on 48 devices is equivalent to two days of training. In this case the EMM model yields perfect detection with no false positives. \n\nIn summary, given enough train time, our proposed anomaly detection method is capable of detecting arbitrary code injection attacks and other kinds of exploits (such as protocol exploits). \n\n\\begin{figure}[p]\n\t\\centering\n\t\\includegraphics[width=.8\\columnwidth]{Figure\/EMM_Eval_Camera.pdf}\n\t\\label{EMM_ON_REPLAY:a}\n\n\t\\caption{The probability scores of $M^{(\\ell)}$ from Exp2 after two hours of training, where the red area marks the attack period.}\n\t\\vspace{.3cm}\n\t\\centering\n\t\\includegraphics[width=.8\\columnwidth]{Figure\/EMM_Replay.pdf}\n\t\\label{EMM_ON_REPLAY:b}\n\n\t\\caption{The probability scores of $M^{(\\ell)}$ from Exp5 after two hours of training, where the red area marks the attack period.}\n\\end{figure}\n\n\n\n\\subsubsection{Collaboration Training}\nIn section \\ref{subsubsec:anom}, we showed how EMMs can detect a variety of attacks on IoT devices, given enough train time. However, an anomaly detection model is vulnerable during its \\textit{initial} train time ($T_{grace}$). Furthermore, a single device may not experience all possible behaviors in the alloted time. In contrast, collaborative training, using multiple IoT devices, can produce a model a shorter period of time which performs better.\n\n\\begin{description}\n\t\\item[Model Performance] By performing collaborative learning, the final model contains the collective experiences from many different devices. As a result, each device can better differentiate between rare-benign behaviors and malicious behaviors. Fig. \\ref{Collaborative_Training_Exp:a} shows that the same amount of train time distributed over 48 devices produces a model which can detect an attack sooner than when simply performing all of the train time on a single device. The reason for this is the distributed model captures a more diverse set of behaviors, which helps it differentiate better between malicious and benign. \n\t\\item[Model Train Time] Fig. \\ref{Collaborative_Training_Exp:b} shows that several models trained in parallel can produce a stronger model than a single model (Fig. \\ref{Collaborative_Training_Exp:a}) in the same amount of time. Thus, we see that $M^{(g)}$ converges at a rate which is inverse to size of the network. As a result, a large IoT deployment will obtain a strong model quickly, and is much less likely to fall victim to an adversarial attack.\n\\end{description}\n\n\n\n\\begin{table}[h]\n\t\\begin{center}\n\t\t\\caption{False Positive Rates with Collaborative Learning: All Attack Scenarios}\n\t\t\\begin{tabular}{c}\n\t\t\t\\includegraphics[width=.6\\columnwidth]{tab_fpr2.pdf}\n\t\t\\end{tabular}\n\t\t\\label{Collaborative_Training_ExpSummery}\n\t\\end{center}\n\\end{table}\n\n\\begin{figure}[p]\n\t\\centering\n\t\\includegraphics[width=.8\\columnwidth]{Figure\/CombinedModels1a.pdf}\n\t\\label{Collaborative_Training_Exp:a}\n\n\t\\caption{The probability scores of $M^{(\\ell)}$ with 48 minutes of training, and $M^{(g)}$ with one minute of training across 48 devices (Exp1).}\n\t\\vspace{.3cm}\n\t\\centering\n\t\\includegraphics[width=.8\\columnwidth]{Figure\/CombinedModels2a.pdf}\n\t\\label{Collaborative_Training_Exp:b}\n\n\t\\caption{The probability scores of $M^{(g)}$ with increasingly larger sets of models (devices) in the case of Exp1.}\n\\end{figure}\n\nIn Table \\ref{Collaborative_Training_ExpSummery}, we present the false positive rates (false alarm rates) of the framework with various numbers of devices and train time. The Table shows that just 48 devices training for two hours (2 days of experience) is enough to mitigate the false alarms. For the code-reuse and buffer-overflow attacks, there were no false negatives. However, in the replay-attack (Key-Reinstallation) there were a few false negatives. However, since the attacker sends a malformed packet multiple times, we ultimately detect the attack.\n\n\\subsubsection{Resilience Against Adversarial Attacks}\nSince agents are constantly learning (even after $T_{grace}$), it is important that the framework be resilient against accidentally learning malicious behaviors as benign (i.e., poisoning). The acceptance criteria of a partial block ensures that these behaviors are not incorporated into the global models.\n\nIf some of the IoT devices are infected after the publication of the first block, we expect the collaborated $N^{(g)}$ to detect the malware, and not learn from it by accident. However, let's say that some of the IoT devices were infected prior to the publication of the first block and the elapses of $T_{grace}$. When the infected agents add their poisoned model to the \\textit{partial-block}, other poisoned agents will reject their \\textit{partial-blocks} because the \\textit{model-attestation} step will reveal that the potential new $N^{(g)}$ is very different than their own local models $N^{(\\ell)}$. Fig. \\ref{Linear_Distance} visualizes this concept as heat maps, where the intensity of index $(i,j)$ represents the linear distance between the probabilities of transition $M^{(\\ell)}_{ij}$ and $M^{*}_{ij}$, where $M^{*}_{ij}$ is a combined model from a \\textit{partial-block}. In \\ref{Linear_Distance:a}, the \\textit{partial-block} has $10$ clean models, and in \\ref{Linear_Distance:a}, the \\textit{partial-block} has $10$ poisoned models. When an agent performs \\textit{model-attestation}, the agent will find that $d(N^{(\\ell)},N^*)<\\alpha$, and reject the \\textit{partial-block}. Assuming $L$ is large enough (e.g., $L=10,000$), and that a minority of agents are not infected, we expect that a poisoned \\textit{partial-block} will never be closed before a clean one achieves consensus. \n\nLet's say that $\\alpha$ was set too low, or that the malicious jump sequences were very similar to the legitimate ones. In this case, the \\textit{model-attestation} step will accept the \\textit{partial-block}, but the \\textit{abnormality-filtration} step will remove the malicious behaviors. This is assuming that less than $p_a$ percent of the models in the \\textit{partial-block} contain the malicious transitions. Fig. \\ref{Adversarial_evaluation} shows that with $L=20$ and $p_a=75\\%$, an attacker must poison $15\/20$ models (during $T_{grace}$) in order to evade the detection of the next $M^{(g)}$. This is very difficult for the attacker to achieve because (1) he must infect the IoT devices without detection, (2) there is a chance that not all infected models will appear together in a \\textit{partial-block} (e.g., with 48 or 1,000 devices), and (3) if he does not succeed before the first block if published, then it is likely that the new $M^{(g)}$, accepted among \\textit{all} agents, will detect the malware. \n\nAnother possibility is that the attacker may try and sabotage the agent via target application. However, by accessing the agent's memory from the monitored application will require additional exploits from the malware. Ultimately, the agent will detect either the initial intrusion, or the exploits used to gain access to the agent's memory space.\n\nAnother insight is that when a minority of models are infected yet the agent's \\textit{model-attestation} accepted the \\textit{partial-block}, the \\textit{abnormality-filtration} removes the malicious transitions but keeps the benign ones (observed by $p_a$ percent of the models). As a result, healthy information is retained from the poisoned models, while the abnormalities are filtered out.\n\n\n\\begin{figure}[p]\n\t\\centering{\n\t\t\\subfloat[Linear distance between a benign model and a clean combined model] \n\t\t{\\includegraphics[width=.8\\columnwidth]{Figure\/Exp2a_1.pdf}\n\t\t\t\\label{Linear_Distance:a}\n\t\t}\\quad\n\t\n\t\t\\subfloat[Linear distance between a benign model and a positioned combined model.]\n\t\t{\\includegraphics[width=.8\\columnwidth]{Figure\/Exp2b.pdf}\n\t\t\t\\label{Linear_Distance:b}\n\t\t}\n\t}\n\t\\caption{Heat maps of the linear distance between models in Exp4.}\n\t\\label{Linear_Distance}\n\\end{figure}\n\\begin{figure}[h]\n\t\n\t\\centering{\n\t\t\\includegraphics[width=.8\\columnwidth]{Figure\/Exp3_1.pdf}\n\t}\n\t\\vspace{-0.5cm}\n\t\\caption{The combined model normalized probability generated from the latest block $B$, where various numbers of the models in $B$ have been infected (attacked).}\n\t\\label{Adversarial_evaluation}\n\\end{figure}\n\n\n\n\n\\subsubsection{Baseline Comparisons}\nTo understand the capabilities of the proposed collaborative framework, we evaluate the selected the anomaly detection method (EMM over memory regions) and the entire host-based intrusion detection system (the blockchain framework) to their respective baselines. \n\nTo validate the use of the EMM, we compare its performance to two well-known sequence-based anomaly detection algorithms: t-STIDE and PST (see \\ref{sec:relworks}). For the PST we took a sequence length of 10. We also compare the EMM to the heatmap method proposed in \\cite{7167219}. In these experiments, we performed the buffer overflow attack in the Smart Light (Exp1), the code reuse attack on the Smart Camera (Exp4), and the replay attack on the router (Exp5). All of the algorithms were given the same 30 min of normal training data and then were tested on 20 min of normal data followed by 10 min of attacks.\n\nTo measure the performance we compute the area under the curve (AUC). The AUC is computed by plotting the true positive and false positive rates (TPR and FPR) for every possible threshold, and then by computing the area under the resulting curve. Intuitively, it provides a single measure for how well a classifier performs. A value of `1' indicates a perfect predictor and a value of `0.5' indicates that the predictor is guessing labels at random. Since the AUC measure ignores precision it is slightly misleading in the case of anomaly detection. Therefore, we also compute the average precision-recall curve (avPRC) which is computed in a similar manner.\n\nIn Fig. \\ref{fig:aucprc} we present the results from this baseline test. We found that although t-STIDE sometimes our performed the MC, the MC consistently provide the best performance for all target applications. This justifies our use of the EMM for our system. We also note that the PST took several hours to train on a strong PC, and therefore is not practical to train on an IoT.\n\n\n\\begin{figure}[h]\n\t\\centering\n\t\\includegraphics[height=.25\\textheight]{Figure\/auc3.pdf}\t\\includegraphics[height=.25\\textheight]{Figure\/prc3.pdf}\n\t\\caption{The AUC (left) and the PRC (right) of each algorithms for each attack\/target app.}\n\t\\label{fig:aucprc}\n\\end{figure}\n\n\nIn Fig. \\ref{fig:score_time} we plot the anomaly scores (predicted probabilities) of the algorithms over time during the attack phase. From the figure, it is clear why the MC consistently had a high avPRC since there is a clear separation between the anomalous scores and benign scores. This is important when deciding on a threshold. In practice, the threshold is determined based on a statistical measure given the benign data distribution.\n\n\n\\begin{sidewaysfigure}[p]\n\t\\centering\n\t\\includegraphics[width=\\textwidth]{Figure\/baselinesa.png}\n\t\\caption{The anomaly scores (predicted probabilities) of the algorithms over time during the attack phase. The actual attack periods are marked in red.}\n\t\\label{fig:score_time}\n\\end{sidewaysfigure}\n\n\nTo validate the use of entire framework, we evaluated our host-based intrusion detection system (H-IDS) in comparison to others. Since we targeting IoT devices, we selected H-IDSs which are well-known, operate on Linux, and can be compiled to run on an ARM processor: OSSEC, SAGAN, Samhain, and ClamAV. OSSEC is an open-source system which performs integrity checking, log analysis, rootkit detection, time-based alerting, and active response. We loaded OSSEC with all it's default detection rules. SAGAN is an open source multi-threaded system which performs real-time log analysis with a correlation engine. Sagan's structure and rules work similarly to the Sourcefire Snort IDS\/IPS, and we loaded it will all available community rules. \nTable \\ref{tab:hids} compares the H-IDSs to ours in the context of the content being monitored, and the intrusion detection mechanism used. Samhain is an integrity checker and host intrusion detection system. Finally, ClamAV is a free software open-source antivirus software which we loaded will all current virus signatures.\n\nOnce we loaded all four H-IDSs onto a Raspberry Pi, we launched each target application and performed the same attacks described above. We found that none of the four H-IDSs reported any alerts. This makes sense because these systems do not perform dynamic analysis on the target application's control flow. Therefore, the buffer overflow, code reuse, and replay attacks evaded detection.\n\n\n\n\\begin{table}[!t]\n\t\\begin{center}\n\t\t\\caption{The Host-based Intrusion Detection Systems compared to Ours}\n\t\t\\vspace{1em}\n\t\t\\begin{tabular}{c}\n\t\t\t\\includegraphics[width=.5\\columnwidth]{Figure\/hids.pdf}\n\t\t\\end{tabular}\n\t\t\\label{tab:hids}\n\t\\end{center}\n\\end{table}\n\n\n\\begin{figure}[!t]\n\t\\centering\n\t\\includegraphics[width=.9\\textwidth]{Figure\/cpu_mem_time.pdf}\n\t\\includegraphics[width=0.48\\textwidth]{Figure\/cpu.pdf}\n\t\\includegraphics[width=0.48\\textwidth]{Figure\/mem.pdf}\n\t\\caption{The resource utilization of the agent on a 500 MHz CPU. Top: Resource utilization over the first 15 minutes. Bottom: Resource utilization expressed as density plots.}\n\t\\vspace{-0.3cm}\n\t\\label{fig:benchmark}\n\\end{figure}\n\n\\subsection{Complexity Analysis \\& Benchmark}\\label{sec:complexity}\nThe time complexity of an agent can be broken down according to the three parallel processes in Fig. \\ref{LLD}. The Gather Intelligence process periodically receives a ring buffer from the kernel will the last $n$ jump operations, checks for anomalies, and updates the EMM. Therefore, It's complexity is $O(n)$. However, if an averaging window is used over the anomaly cores, then the complexity is $O(n+wn)$ where $w$ is the window size. However, $w<