id
stringlengths
40
40
text
stringlengths
9
86.7k
metadata
stringlengths
3k
16.2k
source
stringclasses
1 value
added
stringdate
2024-11-21 00:00:00
2024-12-12 00:00:00
created
stringdate
2024-11-21 00:00:00
2024-12-12 00:00:00
5cc41152c0dd743119c1252ceb4b06d24e591750
Abstract—For software testing, concolic testing reasons about data symbolically but enumerates program paths. The existing concolic technique enumerates paths sequentially, leading to poor branch coverage in limited time. In this paper, we improve concolic testing by bounded model checking (BMC). During concolic testing, we identify program regions that can be encoded by BMC on the fly so that program paths within these regions are checked simultaneously. We have implemented the new algorithm on top of KLEE and called the new tool LLSPLAT. We have compared LLSPLAT with KLEE using 10 programs from the Windows NT Drivers Simplified and 88 programs from the GNU Coreutils benchmark sets. With 3600 second testing time for each program, LLSPLAT provides on average 13% relative branch coverage improvement on all 10 programs in the Windows drivers set, and on average 16% relative branch coverage improvement on 80 out of 88 programs in the GNU Coreutils set. I. INTRODUCTION With the increasing power of computers and advances in constraint solving technologies, an automated dynamic testing technique called concolic testing [1], [2] has received much attention due to its low false positives and high code coverage [3], [4]. Concolic testing runs a program under test with a random input vector. It then generates additional input vectors by analyzing previous execution paths. Specifically, concolic testing selects one of the branches in a previous execution path and generates a new input vector to steer the next execution toward the opposite branch of the selected branch. By carefully selecting branches for the new inputs, concolic testing avoids generating redundant input vectors that execute the same program path, and thus enumerates all non-redundant program paths. In practice, concolic testing suffers from path explosion: it may enumerate exponentially many unique program paths one by one [3]–[6], which often leads to poor branch coverage in limited time. On the other hand, bounded model checking (BMC) [7]–[10] is a fully symbolic testing technique. Given a program under test and a bound \( k \), BMC unrolls loops and inlines function calls \( k \) times to construct an acyclic program which is an under-approximation of the original program. It then performs verification condition (VC) generation over the acyclic program to obtain a formula which encodes the acyclic program and a property to check. The formula is then fed into a SAT solver. If the formula is proved to be valid by the solver, the property holds. Otherwise, the solver provides a model from which we can extract an execution of the program that violates the property. BMC provides a way to encode and reason about multiple execution paths simultaneously using a single formula, but its scalability is often limited by deterministic dependencies between program paths and data values. A natural question is whether there is a way to improve concolic testing by BMC to alleviate path explosion and thus improve branch coverage? In this paper, we provide a positive answer and propose a concolic+BMC algorithm. Intuitively, given a program under test, the algorithm starts with the per-path search mode in concolic testing while referring to the control flow graph (CFG) of the program to identify easy-to-analyze portions of code that do not contain loops, recursive function calls, or other instructions that are difficult to generate formulas using BMC. Whenever a concolic execution encounters such a portion, the algorithm switches to the BMC mode and generates a BMC formula for the portion, and identifies a frontier of hard-to-analyze instructions. The BMC formula summarizes the effects of all execution paths through the easy-to-analyze portion up to the hard frontier. When the concolic execution reaches the frontier, the algorithm switches back to the per-path search mode to handle the cases that are difficult to summarize by BMC. We have implemented the concolic+BMC algorithm on top of KLEE [11] and called the new tool LLSPLAT. We have compared LLSPLAT with KLEE, using 10 programs from the Windows NT Drivers Simplified [12] and 88 programs from the GNU Coreutils used in [11]. With 3600 second testing time for each program, LLSPLAT provides on average 13% relative branch coverage improvement on the programs in the Windows NT drivers simplified set, and on average 16% relative branch coverage improvement on 80 out of 88 programs in the GNU Coreutils set. The rest of the paper is organised as follows. Section 2 provides a motivating example. Section 3 reviews concolic testing. Section 4 describes the concolic+BMC algorithm. Section 5 presents experimental results. Section 6 shows related work. Section 7 concludes this paper. II. A MOTIVATING EXAMPLE We illustrate the inadequacy of concolic testing, and the benefits of using BMC to improve concolic testing, using the function `foo` below. The function runs in an infinite loop, and receives two inputs in each iteration. One input `c` is a character and the other input `s` is a character array. The function `foo` reaches the label `L` if the variable `state` is 9, and the input array `s` holds the string “reset”. From the label `L`, there is a huge chunk of code consisting conditionals, loops, and procedure calls. Similar functions like `foo` are often generated by lexers. Concolic testing systematically explores all execution paths of the function. Since the function `foo` runs in an infinite loop, the number of distinct feasible executions is infinite. To perform concolic testing we need to bound the number of iterations of the loop if we perform a depth-first search of the execution paths. There are 17 possible choices of values of `c` and `s` that concolic testing would consider, and at least 9 iterations are required to reach the label `L`. Hence, concolic testing will explore about $17^9 \approx 10^{11}$ execution paths. It is unlikely that concolic testing can explore a path that reaches the label `L` and executes the code below the label `L` in a reasonable time budget. We confirm this fact by testing the function `foo` using KLEE [11]. It could not reach the label `L` in a day, which led to poor branch coverage. It is worth mentioning that, if there were buggy code after the label `L`, the situation would get even worse because concolic testing cannot reveal the bugs efficiently. ```c void foo() { char c, s[6]; int state = 0; while(1) { // Some dummy code c = input(); s = input(); if (c == 't' && state == 0) state = 1; if (c == 't' && state == 1) state = 2; if (c == 'a' && state == 2) state = 3; if (c == 'a' && state == 3) state = 4; if (c == 'x' && state == 4) state = 5; if (c == 'x' && state == 5) state = 6; if (c == 't' && state == 6) state = 7; if (c == 't' && state == 7) state = 8; } // A large chunk of code below. } ``` In our concolic+BMC approach, whenever a concolic execution encounters a conditional, it has a choice either to save a predicate representing that a particular branch is taken along the execution as concolic testing does, or to save a BMC formula, for example, that encodes the entire conditional. Which choice is taken depends on whether the conditional is “simple” enough to generate a BMC formula easily. For example, a conditional ```c P ::= (var g)^∗ · Fn^+ Fn ::= f((var p))^∗ · (var l)^∗ · BB^+ BB ::= Inst · TermInst Inst ::= x ← e | f(e^∗) | x ← input() TermInst ::= ret | br e BB1 BB2 | br BB | ERROR ``` is simple if there are no loops and recursive function calls\(^1\) inside it. Since all conditionals are simple in function `foo`, the concolic+BMC approach can easily generate a feasible path that reaches the label `L` and thus greatly shorten the time to reach the subsequent uncovered paths. We validated this fact by using LLSPLAT to test function `foo`. LLSPLAT could generate paths that reached the label `L` in 3s, which led to better branch coverage. III. CONCOLIC TESTING We first review the traditional concolic testing algorithm with depth-first path searching strategy, and then describe how LLSPLAT modifies it. A. Program Model We describe how concolic testing works on a simple language shown in Figure 1. A program consists of a set of global variables and a set of functions. Each function consists of a name, a sequence of formal parameters, a set of local variables, and a set of basic blocks representing the control flow graph (CFG) of the function. Each basic block consists of a list of instructions followed by a terminating instruction. There are three types of instructions: `x ← e` is an assignment, `f(e^∗)` is a function call, and `x ← input()` indicates that the variable `x` is a program input. There are four types of terminating instructions: `ret` is a return instruction, `br e BB1 BB2` is a conditional branch, `br BB` is an unconditional branch, and `ERROR` indicates program abortion. We omit an explicit syntax of expressions. We assume there is an entry function `main` that is not called anywhere. We also assume each function has an `entry` basic block, and every basic block of the function is reachable from it. B. The Concolic Testing Algorithm To test a program `P`, concolic testing tries to explore all execution paths of `P`. It first instruments the program `P` by Algo 1, and outputs an instrumented program `P'`. The red-highlighted lines(gray with monochrome printers) in the algorithms can be ignored for now because they are used in the concolic+BMC approach we describe later. Algo 2 repeatedly runs the instrumented program `P'`. Due to limited space, we omit the instrumentation for function calls, and the code that bounds the search depth in the search strategy — these are identical to previous work [1], [2]. Algo 1 first makes a copy `P''` of the program `P`, and inserts various global variables and function calls which are used\(^1\)The program size after function inlining can be exponentially larger than the size of the original program. 128 for the symbolic execution. It then returns the instrumented program $P'$. Algorithm 3 presents the definitions of the instrumented functions. The expressions enclosed in double quotes ("e") represent syntactic objects. We denote $\&x$ to be the address of a variable $x$. **Algorithm 1: Instrumentation** Program instrument($P$): $P' \leftarrow P$ Add to $P'$ global vars $i \leftarrow 0$, inputNo $\leftarrow 0$, symStore $\leftarrow \emptyset$, pathC $\leftarrow \emptyset$ Gows $\leftarrow \{BB \mid BB$ is a governor in $P\}$ Add to $P'$ global vars $bmcNo \leftarrow 0$, currGov $\leftarrow None$, init $\leftarrow None$ foreach $BB \in P'$ do if $BB \in GR(gov)$ for some $gov \in Gows$ then continue foreach $Inst \in BB$ do switch $Inst$ do case $x \leftarrow input()$ do Replace $Inst$ by $InitInput("x")$ case $x \leftarrow e$ do Add updateSymStore("x", "e") before $Inst$ case $br \leftarrow BB1$ $BB2$ do if $BB \in Goes$ then Add startBMC($BB$) before $Inst$ foreach $d \in Dests(BB)$ do Add endBMC($BB$, $d$) as the 1st instruction of $d$ else Add addPathConstraint("e", e) before $Inst$ case $Return$ do if $Inst$ is in the main function then Add solveConstraint() before $Inst$ case $ERROR$ do Add print("ERROR found") before $Inst$ return $P'$ **Algorithm 2: run_llsplat** void run_llsplat($P$): $I \leftarrow []$; branch_hist $\leftarrow []$; completed $\leftarrow false$ $CFG_{P} \leftarrow CFGofProgram(P)$ while $\neg completed$ do execute instrument($P$) **Algorithm 3: Concolic Testing** void $InitInput("x")$: $inputNo \leftarrow inputNo + 1$ void $addPathConstraint("e", b)$: if $b$ then pathC[i] $\leftarrow symexpr("e")$ else pathC[i] $\leftarrow \neg symexpr("e")$ if $i < \neg br_hist[i]$ then if $i = \neg br_hist[i] - 1$ then $br_hist[i].done \leftarrow true$ else $br_hist[i]$ $\leftarrow BNode(isCovered : b, done : false)$ void $SolveConstraint()$: while $j \geq 0$ do if $\neg br_hist[j].done$ then foreach $d$ such that $\neg br_hist[j].isCovered[d]$ do if $\forall c \leq i \leq j \exists pathC[k] \land$ $\land rmLastDest(pathC[c]) \land V_{c \in Edges_{d}[j]} \land$ $c$ has a solution $I'$ then $br_hist \leftarrow \neg br_hist[0..j] $I \leftarrow I'$ return else $br_hist[j].isCovered$ $\leftarrow \neg br_hist[j].isCovered$ $\neg pathC[j]$ $\leftarrow \neg pathC[j]$ if $pathC[0..j]$ has a solution $I'$ then $br_hist \leftarrow \neg br_hist[0..j] $I \leftarrow I'$ return else $j = j - 1$ if $j < 0$ then completed $\leftarrow true$ **IV. COMBINING CONCOLIC TESTING WITH BMC** Recall that the goal of our work is that, whenever a concolic run starts with some inputs, instead of using the path constraint to encode a single execution path, we plan to add BMC formulas to the path constraint so that it may encode (potentially exponentially) many execution paths. Note that the path constraint is used by a constraint solver to decide new runs in concolic testing. When we attempt to cover an uncovered instruction in the new run, the path constraint that encodes multiple execution paths enables the constraint solver to search for multiple paths leading to the instruction, instead of one path in the traditional concolic testing. To achieve the goal, given a program under test, we identify regions of the program for generating BMC formulas. A region of a program is a subgraph of the control flow graph of the program. We list the following requirements for identifying regions. 1) A region must be acyclic. It is required by any BMC procedure. 2) A region should not have function calls. It is desired because function inlining is required before generating BMC formula but the resulting BMC formula may be exponentially large in the size of the input program, which we want to avoid. 3) A region should be sufficiently large so that the cor- responding BMC formula covers more paths and fully exploits the power of a modern constraint solver. Most of the path constraints in those multiple paths are the same except for the constraints within the BMC regions, thus solving one concolic+BMC constraints representing multiple paths may take less time than solving multiple independent paths. In addition, given a region, it is also required that a desired BMC generation procedure be compatible with concolic testing. Unlike generating a formula for an entire program in existing BMC tools, we need to generate ones for regions of a program which lead to some specific issues, which BMC procedures in existing BMC tools need not and cannot handle. For example, a natural question would be that, after adding a BMC formula to the path constraint, how the symbolic store needs to be updated so that concolic testing proceeds. We now present the concolic+BMC algorithm. The key ob- ervation is that given a program \( P \) under test, the instrumented program for \( P \) can additionally refer to the (static) CFG of \( P \) and perform static analysis at run time. Section IV-A describes how to identify program portions for BMC formula generation. Section IV-B describes the BMC formula generation algorithm. Section IV-C integrates this with concolic testing. A. Identifying Program Portions for BMC a) Preliminaries: Given a CFG, a basic block \( m \) domi- nates a basic block \( n \) if every path from the entry basic block of the CFG to \( n \) goes through \( m \). We denote \( \text{Dom}(m) \) to be the set of basic blocks which \( m \) dominates. A depth-first search of the CFG forms a depth-first spanning tree (DFST). There are edges in CFG that go from a basic block \( m \) to an ancestor of \( n \) in DFST (possibly to \( m \) itself). We call these dependent paths. By [13], a directed graph is acyclic if a depth-first search yields no back edge. b) Governors, Governed Regions, and Destinations: Given a basic block \( m \), a basic block \( n \in \text{Dom}(m) \) is polluted in \( \text{Dom}(m) \) in the following four cases: (1) \( n \) contains function call instructions, (2) \( n \) has no successors, (3) \( n \) is the source or the target of a back edge, or (4) \( n \) is reachable from a polluted basic block \( k \in \text{Dom}(m) \). A basic block \( m \) effectively dominaates a basic block \( n \) if \( n \in \text{Dom}(m) \) and \( n \) is not polluted in \( \text{Dom}(m) \). We denote \( \text{Edom}(m) \) to be the set of basic blocks that \( m \) effectively dominates. A basic block \( m \) is called a governor candidate if (1) the terminating instruction of \( m \) is of the form \( \text{br} \in B1 B2 \), (2) \( m \) dominates both \( B1 \) and \( B2 \), and (3) \( \text{Edom}(B1) \) and \( \text{Edom}(B2) \) are not empty. Given a governor candidate \( m \) with its two successors \( B1 \) and \( B2 \), the governed region of \( m \), denoted by \( GR(m) \), is \( \text{Edom}(B1) \cup \text{Edom}(B2) \). A basic block \( n \) is a destination of \( GR(m) \) if \( n \notin GR(m) \) and \( n \) is a successor of some basic block \( k \in GR(m) \). Let the set \( \text{Dests}(m) \) be all destinations of \( GR(m) \). A basic block \( gov \) is a governor if \( gov \) is a governor candidate, and there is no governor candidate \( m \) with \( gov \in GR(m) \). For any governor \( gov \), \( GR(gov) \) is acyclic and does not have function calls, and gov dominates every basic block \( BB \in GR(gov) \). c) Example: Consider the program in Fig 2a. \( BB0 \) is a governor. Its governed region \( GR(BB0) \) includes \( BB1 \), \( BB2 \), \( BB4 \), \( BB5 \), and \( BB6 \), which are inside the red dash circle. \( BB3 \) and \( BB7 \) are the destinations in \( \text{Dests}(BB0) \). Though \( BB2 \) is a governor candidate, it is not a governor because it is in \( GR(BB0) \). ![Fig. 2: An Example](image) (a) A program under test (b) Variable renaming B. Translating Governed Regions to BMC Formulas A governed region is ideal for generating a BMC formula because it is acyclic, does not have function calls, and is “sufficiently” large in the sense that it includes as many (unpolluted) basic blocks as its governor governs. We present our algorithm that translates a governed region to a BMC formula, and provide an example. 1) The BMC Formula Generation Algorithm: Given a governor \( gov \), we construct a BMC formula \( \phi \) for \( GR(gov) \) in five steps: 1) Renaming variables in \( GR(gov) \) into an SSA-form. Since \( GR(gov) \) is acyclic, there exists a topological ordering over the basic blocks in \( GR(gov) \). Let \( \text{AccVars} \) be the set of variables accessed by the instructions in \( GR(gov) \), and let a version map \( V \) be a map from each variable Let \( x \in AccVars \) to a variable \( x_\alpha \) with a version \( \alpha \in \mathbb{N} \). We assign the version number \( \alpha \) to each variable in \( GR(gov) \) for renaming according to the topological order. 2) Create a boolean variable \( g_{BB} \) for each basic block \( BB \in GR(gov) \), which is called an execution guard. Our intention is that, if \( g_{BB} \) is true, then an execution represented by a model of the final BMC formula \( \phi \) goes through \( BB \). Otherwise, it does not goes through \( BB \). 3) Compute an edge map \( Edges \) that maps each basic block \( BB \in GR(gov) \cup Dests(gov) \) to a list of edge formulas. Each entry in the list represents the condition of hitting an incoming edge of a basic block. For each \( BB \in GR(gov) \), if its terminating instruction is \( br eBB1 BB2 \), then we add \( g_{BB} \land e \) to \( Edges[BB1] \), and add \( g_{BB} \land \neg e \) to \( Edges[BB2] \); if it is \( br BB1 \), then we add \( g_{BB} \) to \( Edges[BB1] \). If the terminating instruction belongs to a governor, we insert the condition pair \( e \) and \( \neg e \) to the corresponding \( Edges \) map directly. Let the governor's terminating instruction be \( br eBB1 BB2 \). Let \( e_0 \) be an expression obtained by replacing each variable \( x \) in \( e \) with \( x_0 \). We set \( Edges[BB1] = e_0 \) and \( Edges[BB2] = \neg e_0 \). 4) Compute a block map \( Blks \) that maps each basic block \( BB \in GR(gov) \) to a block formula. For each \( BB \in GR(gov) \), let \( I_1, I_2, \ldots, I_k \) be the non-terminating instructions in \( BB \). For each \( 1 \leq i \leq k \), if \( I_i \) is \( x_\alpha \leftarrow e \), we define an instruction formula \( c_i \) to be \( x_\alpha = \tau e(g_{BB}, e, x_\alpha - 1) \). We set \( Blks[BB] = \bigwedge_{1 \leq i \leq k} c_i \). 5) Create the final BMC formula \( \phi \), defined as follows: \[ \bigwedge_{BB \in GR(gov)} \left( g_{BB} = \bigvee_{c \in Edges[BB]} c \right) \land Blks[BB] \] Intuitively, \( \phi \) claims that for each basic block \( BB \in GR(gov) \), (1) \( BB \) is taken (i.e., \( g_{BB} \) is true) if one of its predecessor is taken, and (2) the block formula of \( BB \) must hold. Our BMC formula generation algorithm has the following important property. The proof is in our technical report\(^2\). **Theorem IV.1.** Let \( gov \) be a governor and \( T \) be an arbitrary topological ordering over \( GR(gov) \). After the BMC algorithm is done w.r.t. \( T \), for any destination \( d \in Dests(gov) \), (1) the formula \( \phi \land \bigvee_{c \in Edges[BB]} c \) encodes all executions from \( gov \) to \( d \), and (2) for every execution \( \rho \) from \( gov \) to \( d \), the final version of each variable \( x \) in \( \phi \) represents the value of \( x \) when \( \rho \) enters \( d \). \(^2\)http://zilongwang.github.io/papers/scam16_tr.pdf When \( \rho \) enters the destination \( BB_3 \), the largest version of \( x \) and \( y \) along \( \rho \) is \( x_3 \) and \( y_0 \), but their final versions in \( \phi \) are \( x_4 \) and \( y_1 \). However, since \( BB_2, BB_4, BB_5 \) and \( BB_6 \) are not taken along \( \rho \), we have \( x_4 = x_3, x_2 = x_1 = x_0 \), and \( y_1 = y_0 \). Since \( BB_1 \) is taken, we have \( x_3 = x_2 - y_0 \). Thus \( x_4 = x_0 - y_0 \) and \( y_1 = y_0 \). We conclude that \( x_4 \) and \( y_1 \) represent the values of \( x \) and \( y \) when \( \rho \) enters the destination \( BB_3 \). C. Integrating BMC Formulas with Concolic Testing To integrate BMC with concolic testing, we need to instrument function calls for BMC encoding, obtain program CFG for performing static analysis, and consider the way to update concolic data structures such as the worklist, the symbolic store and the branch history. Thus we add the red lines in Algo 1, 2, and 3 to reflect the integration. Once we meet a branch instruction, we need to check whether this instruction is a good candidate to perform BMC. During the instantiation in Algo 1, we first compute a set \( Govs \) of all governors of the program \( P \). Since basic blocks in governed regions are used to generate BMC formulas, we skip instrumenting them. When a basic block \( BB \) has two successors, if \( BB \) is a governor, we instrument a function call \( startBMC(BB) \) before \( BB \)’s terminating instruction, and for each destination \( d \) in \( Dests(BB) \), we instrument a function call \( endBMC(BB, d) \) as the first instruction of \( d \). If \( BB \) is not a governor, we perform the old instrumentation in concolic testing. BMC formulas generation in our algorithm requires static analysis result of a program under test. In Algo 2, we read the CFG of the uninstrumented program \( P \). This CFG is used to generate BMC formulas along concolic executions. Since a BMC region may contain multiple destinations, we need to instrument one \( startBMC(gov) \) call and multiple \( endBMC(gov, d) \) calls into the program to define a BMC governed region. The definition of \( startBMC(gov) \) is given in Algo 4. It saves the governor \( gov \) that will be used to generate a BMC formula using \( currGov \). Then it increments \( bmcNo \), which records the number of BMC formulas that have been generated so far along the concolic execution. It then uses \( init \) to “glue” the execution before entering \( GR(gov) \) with the BMC formula for \( GR(gov) \). More concretely, for each variable \( x \in AccVars(gov) \), an equation \( x_{bmcNo} = symStore[\&x] \) is created, and \( init \) is the conjunction of all such equations. The definition of \( endBMC(gov, d) \) is also given in Algo 4. If the passed-in governor \( gov \) is the one saved in \( currGov \), it performs the BMC generation algorithm described in ### TABLE I: Edge formulas and block formulas <table> <thead> <tr> <th>BB</th> <th>Edges[BB]</th> <th>Blks[BB]</th> </tr> </thead> <tbody> <tr> <td>BB1</td> <td>{( x_0 &gt; y_0 )}</td> <td>( x_0 = \tau e(g_{BB1}, x_2 = y_0, x_2) )</td> </tr> <tr> <td>BB2</td> <td>{( \neg(x_0 &gt; y_0))}</td> <td>( x_1 = \tau e(g_{BB2}, y_0 - x_0, x_0) )</td> </tr> <tr> <td>BB3</td> <td>{( g_{BB1}, g_{BB6} \land y_1 \neq 9 } }</td> <td>( x_4 = \tau e(g_{BB4}, y_0 - x_3, x_3) )</td> </tr> <tr> <td>BB4</td> <td>{( g_{BB2} \land x_1 &gt; y_0 )}</td> <td>( x_2 = \tau e(g_{BB5}, y_0 - x_1, x_1) )</td> </tr> <tr> <td>BB5</td> <td>{( g_{BB2} \land \neg(x_1 &gt; y_0))}</td> <td>( y_1 = \tau e(g_{BB6}, x_4, y_4) )</td> </tr> <tr> <td>BB6</td> <td>{( g_{BB4}, g_{BB5} \land x_2 \neq 0 )}</td> <td>( y_2 = \tau e(g_{BB5}, y_0 - x_1, x_1) )</td> </tr> <tr> <td>BB7</td> <td>{( g_{BB5} \land \neg(x_2 \neq 0), g_{BB6} \land \neg(y_1 \neq 9) }</td> <td>( y_3 = \tau e(g_{BB6}, x_4, y_4) )</td> </tr> </tbody> </table> Section IV-B to obtain a BMC formula $\phi$ for the governed region $GR(gov)$, the final version map $V_{final}$, and the edge map $Edges$. The coverage history $branch\_hist$ is updated in $endBMC(gov, d)$. We extend $branch\_hist$ to be a list of $BranchNode \cup BmcNode$. A BmcNode has three fields: $is\_covered$ records which destinations have been covered in prior runs, $Edges\_d$ maps each destination to its edge formulas, and $done$ records whether all destinations have been covered in prior runs. We then start to integrate BMC formulas into concolic testing. Given a formula $\psi$ and a number $j$, we denote $addSup(\psi, j)$ to be the formula obtained by replacing each variable $x$ in $\psi$ with a new variable $x'$. We first create a formula $\phi \land \bigwedge_{c \in Ends[dest]} c, bmcNo$ which represents all executions from the governor $gov$ to the destination $d$ by Theorem IV.1. Since the governed region may be reached multiple times along an execution, we compute a formula $\psi \equiv addSup(\phi \land \bigwedge_{c \in Ends[dest]} c, bmcNo)$ which specifies that $\psi$ is the $bmcNo$-th BMC formula along the execution. We then add $init \land \psi$ to the path constraint. Finally, to let the concolic execution proceed, for each variable $x \in AccVars(gov)$, we update the symbolic store so that $symStore[kx]$ represents the value of $x$ when the execution enters the destination $d$. The function $SolveConstraint$ is extended as shown in Alg 3. If the node $branch\_hist[i]$ is a BmcNode, we find an uncovered destination $d$, and asks if there is an execution that goes to $d$. The formula $rmLastDest(pathC[i])$ is defined by removing the disjunction of edge formulas of $d'$ from pathC[i] where $d'$ is the destination covered by the just terminating execution. If there are new inputs $I'$ for such an execution to $d$, a new run is started with inputs $I'$. 1) Example: We again reuse the example in Fig 2a. Suppose LLSPLAT randomly generates $x = 10$ and $y = 5$ in the first run. When the run terminates, the path constraint is of size 1, and $pathC[0] = init \land \phi \land \psi$, defined as follows. Note that the superscript 1 of the variables in $pathC[0]$ represents that it is the first BMC formula generated along the run. The symbolic variables $sym1$ and $sym2$ are created for $x$ and $y$ when $InitInput("x")$ and $InitInput("y")$ are called. $$init \equiv x_0^1 = sym1 \land y_0^1 = sym2$$ $$\phi \equiv \left[ \begin{array}{c} g_{BB1} = x_0^1 > y_0^1 \land \\ g_{BB2} = \neg (x_0^1 > y_0^1) \land \\ g_{BB4} = (g_{BB2} \land x_0^1 > y_0^1) \land \\ g_{BB5} = (g_{BB2} \land \neg (x_0^1 > y_0^1)) \land \\ g_{BB6} = (g_{BB4} \lor (g_{BB5} \land g_{BB2} \neq 0)) \\ x_0^1 = ite(g_{BB2}, x_0^1 > y_0^1, x_0^1) \land \\ x_0^1 = ite(g_{BB2}, y_0^1 \land \neg (x_0^1 > y_0^1), x_0^1) \land \\ y_0^1 \equiv \neg (g_{BB6} \land y_0^1 \neq 9) \\ \right] \land \neg \psi_d$$ The coverage history $branch\_hist$ is of size one. $branch\_hist[0]$ is a BmcNode defined below: $$branch\_hist[0].is\_covered = [BB3 \Leftarrow true, BB7 \Leftarrow false]$$ $$branch\_hist[0].done = false$$ $$branch\_hist[0].Edges\_d = [BB3 \Rightarrow \{g_{BB1}, g_{BB6} \land y_0^1 \neq 9\}, BB7 \Rightarrow \{g_{BB5} \land \neg (x_0^1 \neq 0), g_{BB6} \land \neg (y_0^1 \neq 9)\}]$$ Now LLSPLAT searches for new inputs for the next run. Since $BB7$ is the only uncovered destination based on $branch\_hist[0].is\_covered$, LLSPLAT solves the formula $init \land \phi \land \bigwedge_{c \in branch\_hist[0].Edges\_d[BB7]} c$, that is, LLSPLAT tries to find a feasible execution path that leads to $BB7$ containing ERROR. Note that there are three execution paths to $BB7$, and the formula encodes all. V. Experiments We have built our tool LLSPLAT to implement the concolic+BMC algorithm on top of KLEE (LLVM version 3.4). To verify whether the algorithm can increase branch coverage of concolic testing in practice, we designed our experiments to compare the branch coverage between LLSPLAT and KLEE. A. Experiment Settings We chose two sets of benchmarks to perform the comparison. The first benchmark set is the Windows NT Drivers Simplified set containing 10 C programs from [12], and the second benchmark set is the GNU Coreutils tested in [11] that contains 88 C programs. Each program in Windows NT Drivers Simplified set ranges between 2344 and 6444 lines of LLVM-IR code, and that of the GNU Coreutils set contains approximately 200,000 lines of code in LLVM-IR level per benchmark including library code. All the experiments were performed on a 2 core Intel Xeon E5-2667 v2 CPU machine with 256GB memory and 64-bit Linux (Debian/Jessie). Both LLSPAT and KLEE ran with original KLEE arguments. We conducted the experiments 10 times and then calculated the average coverage because the coverage depends on the initial random input vector. All the benchmarks in the Windows NT Drivers Simplified set are tested by calling LLSPAT and KLEE with maximum run time of 3600s and maximum memory of 1600MB. All the benchmarks in the GNU Coreutils set are tested using the following command: ``` ./<tool-name> --libc=uclibc --posix-runtime --no-output --max-memory=1600 --max-time=3600 ./file_under_test --sym-args 1 10 2 --sym-files 2 8 ``` Using these options, we ran each benchmark that contained a minimum of 1 argument, and a maximum 10 of arguments with each argument containing at most 2 characters for 3600s. ### B. Experimental Results Table II shows the branch coverage of all 10 benchmarks in the Windows NT Drivers Simplified benchmark set. For example, KLEE covered 270 branches while LLSPAT covered 319 branches with relative branch coverage improvement of 18.14% on `cdaudio_s1_f`. Relative branch coverage improvement is defined by the difference between the branch coverage of LLSPAT and the branch coverage of KLEE divided by the branch coverage of KLEE. The results in Table II show that LLSPAT achieves better branch coverage than KLEE for all 10 benchmarks in the set with 13% relative branch coverage improvement. We conclude that the concolic+BMC algorithm improves the branch coverage of this benchmark set. <table> <thead> <tr> <th>Benchmark</th> <th>KLEE Branch covered</th> <th>KLEE Time(s)</th> <th>LLSPAT Branch covered</th> <th>LLSPAT Time(s)</th> </tr> </thead> <tbody> <tr> <td><code>cdaudio_s1_f</code></td> <td>270</td> <td>2.26</td> <td>319</td> <td>61.06</td> </tr> <tr> <td><code>cdaudio_s1_t</code></td> <td>268</td> <td>2.47</td> <td>317</td> <td>61.46</td> </tr> <tr> <td><code>diskperf_s1_t</code></td> <td>114</td> <td>3614.35</td> <td>132</td> <td>3602.78</td> </tr> <tr> <td><code>floppy_s3_f</code></td> <td>142</td> <td>1.55</td> <td>156 (+9.85%)</td> <td>20.92</td> </tr> <tr> <td><code>floppy_s3_t</code></td> <td>142</td> <td>1.57</td> <td>155 (+9.15%)</td> <td>22.36</td> </tr> <tr> <td><code>floppy_s4_f</code></td> <td>224</td> <td>3.69</td> <td>238 (+6.25%)</td> <td>31.99</td> </tr> <tr> <td><code>floppy_s4_t</code></td> <td>224</td> <td>3.57</td> <td>236 (+5.35%)</td> <td>33.80</td> </tr> <tr> <td><code>kblitrl_s1_t</code></td> <td>93</td> <td>0.42</td> <td>111 (+19.35%)</td> <td>1.62</td> </tr> <tr> <td><code>kblitrl_s2_f</code></td> <td>159</td> <td>1.11</td> <td>181 (+13.83%)</td> <td>4.98</td> </tr> <tr> <td><code>kblitrl_s2_t</code></td> <td>159</td> <td>1.11</td> <td>182 (+14.47%)</td> <td>4.58</td> </tr> </tbody> </table> **TABLE II**: Branch coverage comparison between LLSPAT and KLEE on the Windows NT Drivers Simplified The programs in the GNU Coreutils benchmark set are larger than that of the Windows NT Driver Simplified benchmark set. We would like to evaluate them to check whether LLSPAT can still achieve higher branch coverage than KLEE. Figure 3 shows the result of relative branch coverage improvement for all 88 programs from the GNU Coreutils benchmark set where each bar represents relative branch coverage improvement of one benchmark. A bar above zero indicates by how much LLSPAT wins over KLEE; a bar below shows the opposite. Bars are sorted in ascending order. The result shows that LLSPAT outperforms KLEE in terms of branch coverage on most of the benchmarks: 80 out of 88 benchmarks tested with LLSPAT have higher branch coverage than KLEE. Average improvement for all benchmarks is 13% and 16% for the 80 improved benchmarks. Among all the benchmarks 65 have more than 10% increases. Table III provides detailed branch coverage information of 10 randomly selected benchmarks. The number of encoded BMC governed regions is also provided in Table III to show the involvement of BMC encoding in this benchmark set. Note that a governed region can be encoded multiple times since it can be reached multiple times during one single execution path. <table> <thead> <tr> <th>Benchmark</th> <th>KLEE</th> <th>LLSPAT</th> <th>Number of governed regions</th> </tr> </thead> <tbody> <tr> <td><code>cspill</code></td> <td>1015</td> <td>955 (+12.78%)</td> <td>54059</td> </tr> <tr> <td><code>chown</code></td> <td>883</td> <td>1000 (+13.25%)</td> <td>55485</td> </tr> <tr> <td><code>shred</code></td> <td>734</td> <td>762 (+3.81%)</td> <td>85194</td> </tr> <tr> <td><code>dd</code></td> <td>647</td> <td>811 (+25.34%)</td> <td>38815</td> </tr> <tr> <td><code>cut</code></td> <td>651</td> <td>728 (+11.82%)</td> <td>39396</td> </tr> <tr> <td><code>echo</code></td> <td>258</td> <td>301 (+16.67%)</td> <td>108079</td> </tr> <tr> <td><code>uniq</code></td> <td>686</td> <td>700 (+12.4%)</td> <td>44827</td> </tr> <tr> <td><code>link</code></td> <td>431</td> <td>518 (+20.1%)</td> <td>79621</td> </tr> <tr> <td><code>nice</code></td> <td>481</td> <td>581 (+20.7%)</td> <td>94622</td> </tr> <tr> <td><code>df</code></td> <td>844</td> <td>907 (+7.46%)</td> <td>81981</td> </tr> </tbody> </table> **TABLE III**: Branch coverage comparison between LLSPAT and KLEE and the number of encoded governed regions on 10 randomly selected benchmarks from the GNU Coreutils A natural question that arises is when LLSPAT’s branch coverage exceeds KLEE’s result. We compute the crossing time from which LLSPAT always outperforms KLEE on the improved benchmarks from the GNU Coreutils. More concretely, for each benchmark, we analyzed a graph that describes how branch coverage evolves in 3600s using LSPLAT and KLEE, and recorded the time when the branch coverage reported by LSPLAT is always higher than the one reported by KLEE. Table IV shows the result statistics. The crossing time of 46 and 68 benchmarks is below 60s and 120s, respectively. This fact implies that our method is preferable over KLEE on these benchmarks given a tight time budget. <table> <thead> <tr> <th>Crossing Time(s)</th> <th>0-60</th> <th>60-120</th> <th>120-180</th> <th>&gt;180</th> </tr> </thead> <tbody> <tr> <td>Number of Benchmarks</td> <td>46</td> <td>22</td> <td>1</td> <td>11</td> </tr> </tbody> </table> TABLE IV: Crossing time statistics of improved benchmarks on the GNU Coreutils In conclusion, the concolic+BMC algorithm has a benefit of increasing branch coverage of all 10 programs in the Windows NT Drivers Simplified benchmark set, and 80 out of 88 programs in the GNU Coreutils benchmark set. C. Threats to Experiment Validity We identified the following threats to the validity of our experiment: - **Test benchmarks used in the experiment may not be representative of all programs.** We chose the Windows NT Drivers Simplified set from [12] since three programs in this benchmark set are used in [14] to evaluate context-guided concolic testing. Thus we evaluated all programs in this benchmark set. To make our benchmark selection more unbiased, we chose 88 programs from the GNU Coreutils benchmark set used in [11] to evaluate KLEE. Even though we used 98 C programs with diverse sources, they may not be representative of all programs. - **More LLVM-IR types may yield different results.** The current implementation of LSPLAT only deals with LLVM-IR of non-complex constant expression type and non-floating type during the BMC encoding procedure. The experimental results might be different with more other type of LLVM-IR instructions. - **Large governed region size may yield different results.** In the GNU coreutils experiment, there are 8 benchmarks where LSPLAT performed worse than KLEE. We observe the BMC formulas in those benchmarks are complex. Thus the STP solver used in LSPLAT and KLEE might not be smart enough to solve them efficiently. Under such cases avoiding to encode complex governed regions or breaking complex regions into a few small regions could help improve the result. It remains as our future work to identify BMC formulas of acceptable complexity to avoid solving hard formulas. VI. RELATED WORK a) **Concolic Testing:** Several approaches analyze states (i.e., path constraint and symbolic store) maintained by concolic testing so as to explore the search space efficiently. Godefroid [5] introduced compositional concolic testing. The work was later expended to do compositional concolic testing on demand [15]. The main idea is to generate function summaries for an analyzed function based on the path constraint, and to reuse them if the function is called again with similar arguments. Instead of computing dynamic underapproximations of summaries, we compute exact summaries of governed regions using the static representation of the CFG. Kuznetsov et al. [16] introduced the dynamic state-merging (DSM) technique. DSM maintains a history queue of states. Two states may merge (depending on a separate and independent heuristic for SMT query difficulty) if they coincide in the history queue. Our concolic+BMC approach is different because we do not analyze the states to merge execution paths. Moreover, several approaches combine other testing techniques with concolic testing together. Majumdar and Sen introduced hybrid concolic testing [17] that combines random testing and concolic testing. Boonstoppel et al. proposed RWSet [18], a path pruning technique identifying redundant execution paths based on similarity of their live variables. Jaffar et al. [19] used interpolation to subsume execution paths that are guaranteed not to hit a buggy location. Agerino et al. [20] combined static data-flow program analysis techniques with concolic testing. Santelices et al. [21] introduced a technique that merges multiple execution paths based on the control dependency graph of a program. Recently there are some other trials on the combination use of concolic testing and model checking. Daca et al. [22] proposed an approach combining model checking and concolic testing whose framework is similar to [17]. It ran concolic testing first to generate test cases. When it failed to meet certain goals, it switched to model checking to prove path feasibility to reduce searching space. Jaffar et al. [23] used conditional model checking to construct a residual program that is fed into a concolic testing tool to reduce testing effort. Gonzalez-de-Aledo et al. [24] exploited static analysis to zoom into potential bug candidates and concolic execution to confirm these bugs. Our method is different from these methods because our model checking targets at the loop-free fragment of the code such that we can encode multiple paths on the fly to alleviate path explosion and increase branch coverage. Several heuristic-based approaches have been proposed to guide an execution toward a specific branch. CREST [25] introduced four search strategies, as already shown in the experiments. SAGE [26] introduced generational search that selects all the branches in an execution path and generates a set of inputs. Xie et al. [27] proposed a fitness-guided search that calculates fitness values of execution paths to guide the next execution towards a specific branch. Li et al. [28] proposed a subpath-guided search which steers symbolic execution to less traveled paths. Seo and Kim [14] introduced context-guided search that selects branches in a new context to help prevent the continuous selecting of the same branch. KLEE [11] used a meta-strategy which combines several search strategies in a round robin fashion to avoid cases where one strategy gets stuck. Conceptually, our concolic+BMC approach is compatible with the above search heuristics. In essence, concolic testing is to cover both branches of a conditional, which can be regarded as two destinations. Then the goal of concolic+BMC is to cover all destinations in a program. b) Bounded Model Checking: VC generation approaches in modern BMC tools can be classified into two categories. The first one is based on weakest preconditions [29] by performing a demand-driven backward analysis from the points of interest [30]–[33]. The other one encodes a program in a forward manner, such as CBMC [2], ESBMC [2], and LLBMC [11]. We are inspired by the VC generation algorithm of CBMC, and thus conceptually it is the closest work to our BMC algorithm. The VC generation of CBMC differs from ours in four ways. First, though CBMC also does variable renaming, it does it using a fixed order of basic blocks. We relax this requirement and prove that any topological order works for variable renaming. This is important to us, because we do not have to follow the fixed order CBMC uses. In fact, we use the reverse post order of a governed region as our topological order for variable renaming because it has been computed during the construction of depth first spanning tree which identifies back edges. We save the computation time in this way. Secondly, though the VC generation of CBMC also computes edge formulas for each basic block in a given acyclic program, all predecessors of the basic block contribute to deriving edge formulas. However, this is not the case in ours. For example, suppose that gov is governor, d is a destination of GR(gov), and there is a predecessor BB ∈ GR(gov) of d. This case may happen because BB is polluted. Then our BMC algorithm does not derive an edge formula from BB for d. Thirdly, CBMC does not have the notion of destinations. Since a governed region may have multiple destinations, it is not clear that no matter which destination is chosen, whether the final version of variables in the formula \( \phi \) that encodes the governed region always represents the value of the variables when the destination is reached. We prove this fact in our paper. Lastly, since CBMC encodes the entire program, it does not identify acyclic portions of a program using the notions such as governors. It also does function inlining and loop unrolling, which we do not. ESBMC follows the VC generation algorithm of CBMC. It extends BMC to check concurrent programs. LLBMC explicitly models the memory as a variable representing an array of bytes, which requires LLBMC to distinguish if a little-endian or big-endian architecture is analyzed. They are orthogonal to LLSPLAT. c) Software Model Checking: Large-block encoding [34] is widely used in software model checkers. It encodes control flow edges into one formula, for computing the abstract successor during predicate abstraction. Selective enumeration using SAT solvers [35] and symbolic encodings for program regions, e.g., to summarize loops [36], have been successfully exploited in software model checking. VII. CONCLUSION Since concolic testing suffers from path explosion, we introduce the concolic+BMC algorithm that applies BMC locally targeting at loop-free code fragment during concolic testing to alleviate path explosion, and thus improve branch coverage. Our experiments show that the concolic+BMC algorithm increases branch coverage of the two test benchmark sets. It is also worth mentioning that, if we notice that there is a BMC region containing a potential error after concolic+BMC, and we want to check exactly which branch in the region leads to the error, we can always set that region to do concolic execution while keeping the remaining regions performing BMC. We believe some future work can be achieved on top of our algorithm. Specifically, the implementation of LLSPLAT performs BMC encoding if there exists an acyclic graph containing a few merging basic blocks without function calls inside of the graph. We avoid encoding function calls because it may incur exponential blowup in the BMC formula generation. We would like to come up with a clever evaluation procedure that identifies “cheap” function calls that can be encoded. In addition, solving functions of large scale may yield long time being spent in the SMT solver. We would also like to investigate whether there exists a low cost governed region overhead estimation method to make the selection of BMC regions more intelligent. REFERENCES
{"Source-Url": "http://zilongwang.github.io/papers/scam16.pdf", "len_cl100k_base": 12493, "olmocr-version": "0.1.53", "pdf-total-pages": 10, "total-fallback-pages": 0, "total-input-tokens": 43244, "total-output-tokens": 14089, "length": "2e13", "weborganizer": {"__label__adult": 0.0003161430358886719, "__label__art_design": 0.0002751350402832031, "__label__crime_law": 0.0002703666687011719, "__label__education_jobs": 0.0004014968872070313, "__label__entertainment": 5.125999450683594e-05, "__label__fashion_beauty": 0.0001327991485595703, "__label__finance_business": 0.0001609325408935547, "__label__food_dining": 0.0002956390380859375, "__label__games": 0.0006251335144042969, "__label__hardware": 0.0008077621459960938, "__label__health": 0.00030922889709472656, "__label__history": 0.00019097328186035156, "__label__home_hobbies": 7.742643356323242e-05, "__label__industrial": 0.0002970695495605469, "__label__literature": 0.0002267360687255859, "__label__politics": 0.0002135038375854492, "__label__religion": 0.00040030479431152344, "__label__science_tech": 0.00984954833984375, "__label__social_life": 6.490945816040039e-05, "__label__software": 0.0046539306640625, "__label__software_dev": 0.9794921875, "__label__sports_fitness": 0.0002751350402832031, "__label__transportation": 0.0004117488861083984, "__label__travel": 0.00018537044525146484}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 48639, 0.03076]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 48639, 0.52514]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 48639, 0.84431]], "google_gemma-3-12b-it_contains_pii": [[0, 4758, false], [4758, 10219, null], [10219, 13107, null], [13107, 18911, null], [18911, 25915, null], [25915, 30501, null], [30501, 35701, null], [35701, 41822, null], [41822, 48639, null], [48639, 48639, null]], "google_gemma-3-12b-it_is_public_document": [[0, 4758, true], [4758, 10219, null], [10219, 13107, null], [13107, 18911, null], [18911, 25915, null], [25915, 30501, null], [30501, 35701, null], [35701, 41822, null], [41822, 48639, null], [48639, 48639, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 48639, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 48639, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 48639, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 48639, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 48639, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 48639, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 48639, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 48639, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 48639, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 48639, null]], "pdf_page_numbers": [[0, 4758, 1], [4758, 10219, 2], [10219, 13107, 3], [13107, 18911, 4], [18911, 25915, 5], [25915, 30501, 6], [30501, 35701, 7], [35701, 41822, 8], [41822, 48639, 9], [48639, 48639, 10]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 48639, 0.10619]]}
olmocr_science_pdfs
2024-12-10
2024-12-10
8f75caf27ab083e45125db75d37955b362cfea33
Taking Stock Estimating Vulnerability Rediscovery Trey Herr Bruce Schneier Christopher Morris About the Authors Trey Herr, Post-Doctoral Fellow Belfer Center Cyber Security Project, Harvard Kennedy School trey_herr@hks.harvard.edu Bruce Schneier, Research Fellow and Lecturer Belfer Center Cyber Security Project, Harvard Kennedy School schneier@schneier.com Christopher Morris, Research Assistant Harvard School of Engineering and Applied Sciences christophermorris@college.harvard.edu Acknowledgments This paper acknowledges support from the Belfer Family and the Flora and William Hewlett Foundation. The dataset and the resulting paper would not have been possible without Eduardo Vela Nava and Andrew Whalley of Google; Casey Ellis and Payton O’Neal of Bugcrowd; Rich Salz of OpenSSL; Richard Barnes, Dan Veditz, and Al Billings of Mozilla; and Art Manion and Allen Householder of CERT/CC. Special thanks are also owed to Martin Shelton, Katherine Bjelde, and Jim Waldo for their help cleaning and formatting the data. The authors would additionally like to thank Beth Friedman, Annie Boustead, Sasha Romanosky, Jay Healey, Mailyn Fidler, Thomas Dullien, Herb Lin, Fabio Massacci, Gary Belvin, Beau Woods, Tudor Dumitras, Ben Laurie, Tod Beardsley, and the Belfer Cyber Security team for their feedback. Table of Contents Abstract ...................................................................................................................................1 1 Introduction ..........................................................................................................................2 2 Background ..........................................................................................................................3 Value of Rediscovery ..........................................................................................................5 Rediscovery and Previous Literature ..................................................................................6 3 Methodology and Data ........................................................................................................9 Counting Duplicate Vulnerabilities ...................................................................................9 Coding and Data Sources ..................................................................................................11 4 Analysis .............................................................................................................................15 Vulnerability Rediscovery in the Aggregate ....................................................................15 Multiple Rediscovery .......................................................................................................16 Vulnerability Rediscovery Lag .........................................................................................18 Rediscovery Over Time .....................................................................................................20 5 Limitations of the Dataset .................................................................................................22 6 Implications .......................................................................................................................25 7 Conclusions .......................................................................................................................31 // This code is specific to the Windows-only EmbeddedBrowser launch script. // factoryTime will always return a pointer to the same histogram object, // if passed by its name. There's no need for us to store it explicitly anymore. // Add histogram to kuma::TargetedHistogramMap base::Histogram::FactoryTimeGet( name, who, who, buckets, base::Histogram::kUmaTargetedHistogramMap) master->AddTime(time); chrome_browser { // This error message is not localized because we failed to load the // localization data files. nsresult nserr = nsresult LýlocaleDataTitle[] = "Missing File Error"; LýlocaleDataMessage[] = "Unable to find locale data files. Please reinstall." ); chrome_browser ChromeBrowserMainParts::ChromeBrowserMainParts( parameters) (parameters.command_line), result_code, STARTUP_STATE_NORMAL_EXIT), StartupTimeBomb(), ShutdownWatcherHelper(), FORinta, FORintb, FORintc, FORintd, FORinte, FORintf, FORintg, FORInth, FORINTI, FORINTJ, FORINTK, FORINL, FORINM, FORINN, FORINTO, FORINTP, FORINTQ, FORINTR, FORINTS, FORINTT, FORINTU, FORINTV, FORINTW, FORINTX, FORINTY, FORINTZ, FORINTAA, FORINTAB, FORINTAC, FORINTAD, FORINTAE, FORINTAF, FORINTAG, FORINTAH, FORINTAI, FORINTAJ, FORINTAK, FORINTAL, FORINTAM, FORINTAN, FORINTAO, FORINTAP, FORINTAQ, FORINTAR, FORINTAS, FORINTAT, FORINTAU, FORINTAV, FORINTAW, FORINTAX, FORINTAY, FORINTAZ, FORINTBA, FORINTBB, FORINTBC, FORINTBD, FORINTBE, FORINTBF, FORINTBG, FORINTBH, FORINTBI, FORINTBJ, FORINTBK, FORINTBL, FORINTBM, FORINTBN, FORINTBO, FORINTBP, FORINTBQ, FORINTBR, FORINTBS, FORINTBT, FORINTBU, FORINTBV, FORINTBW, FORINTBX, FORINTBY, FORINTBZ, FORINTCA, FORINTCB, FORINTCC, FORINTCD, Abstract How often do multiple, independent, parties discover the same vulnerability? There are ample models of vulnerability discovery, but little academic work on this issue of rediscovery. The immature state of this research and subsequent debate is a problem for the policy community, where the government’s decision to disclose a given vulnerability hinges in part on that vulnerability’s likelihood of being discovered and used maliciously by another party. Research into the behavior of malicious software markets and the efficacy of bug bounty programs would similarly benefit from an accurate baseline estimate for how often vulnerabilities are discovered by multiple independent parties. This paper presents a new dataset of more than 4,300 vulnerabilities, and estimates vulnerability rediscovery across different vendors and software types. It concludes that rediscovery happens more than twice as often as the 1-9% range previously reported. For our dataset, 15% to 20% of vulnerabilities are discovered independently at least twice within a year. For just Android, 13.9% of vulnerabilities are rediscovered within 60 days, rising to 20% within 90 days, and above 21% within 120 days. For the Chrome browser we found 12.57% rediscovery within 60 days; and the aggregate rate for our entire dataset generally rises over the eight-year span, topping out at 19.6% in 2016. We believe that the actual rate is even higher for certain types of software. When combined with an estimate of the total count of vulnerabilities in use by the NSA, these rates suggest that rediscovery of vulnerabilities kept secret by the U.S. government may be the source of up to one-third of all zero-day vulnerabilities detected in use each year. These results indicate that the information security community needs to map the impact of rediscovery on the efficacy of bug bounty programs and policymakers should more rigorously evaluate the costs of non-disclosure of software vulnerabilities. 1 Introduction Vulnerabilities are an important resource. Both intelligence and law enforcement activities increasingly emphasize the use of software vulnerabilities to gain access to targeted systems. These same software flaws are also a critical piece of defensive information, granting companies like Apple and open source projects like Apache insight into where there are holes in their software in need of repair. Left unfixed, software vulnerabilities provide malicious parties a point of access into any computer system running the software. Programs to pay researchers and others who disclose vulnerabilities to software developers, so-called bug bounties, are an increasingly popular way for companies to discover flaws in their code. Underlying the choices to pay for a software vulnerability, as well as government decisions to keep some a secret, are assumptions about how often those same software flaws could be discovered by someone else, a process called rediscovery. There is very little rigorous research into how often rediscovery takes place, and yet we know it happens, sometimes in high-profile ways. For example, the Heartbleed vulnerability in OpenSSL lay dormant for three years, and yet was discovered twice within just a few days, by both Neel Mehta of Google and researchers at the Finnish information security firm Codenomicon. ¹ This rediscovery rate becomes particularly important if the software in question is a widely used open source project or a cryptographic library. This paper introduces the issue of vulnerability rediscovery, our research, and addresses some of the larger questions raised by this scholarly collision. A particularly challenging issue with rediscovery is that this rate changes over time and varies for different types of software. We collected data from multiple software vendors and an open source project to track vulnerability records and look for duplicates, where a single software flaw had been disclosed multiple times. We then used those duplicates to estimate the rate at which vulnerabilities were discovered more than once by independent parties. We also use this data to track how the rediscovery rate can grow over time and to measure rediscovery lag, the time between when a vulnerability is first disclosed and subsequent duplicate disclosures. The paper begins with background information on vulnerabilities and their discovery, along with a review of relevant literature and previous work. This leads into a discussion of the data collected for this project and our methodology, including the challenges present in counting vulnerabilities and measuring rediscovery. Following this are several analyses of this data, considering variation such as the vendor in question and change over time as well as other measures such as rediscovery over time and rediscovery lag. The final two sections discuss some of the paper’s limitations and then conclude by suggesting implications of this work for scholarly and policy communities. 2 Background Software vulnerabilities are flaws or features in code that allow a third party to manipulate the computer running this software. The level of design security in major commercial software products varies widely, from the vulnerability-rich history of Adobe’s products to Apple’s comparatively locked-down iOS operating system. Such design insecurity is generally the result of poorly secured software, insecure programming languages, the growing complexity of commercial code bases, and simple human error, among a host of other causes. For example, a program that expects to retrieve a simple image file but fails to check the supplied file type might return an executable software program instead. The procedure to retrieve an image is intentional, but failing to check the file type allows a third party to manipulate it. The Love Letter virus of 2000 relied on the fact that Windows 2000 and XP hid known file extensions when reading file names from right to left. The virus file (LOVE-LETTER-FOR-YOU.TXT.vbs) hid itself by putting the executable file extension (.vbs) outside of a benign one (.txt), so Windows would only show .txt and the user would be none the wiser.2 Vulnerabilities may also be introduced directly to hardware through --- compromises in chip design or manufacture somewhere along the supply chain.\(^3\) Not all vulnerabilities are created equal—some are easier to find than others and only a small number will provide easy access to the best-secured software. What this means is that not all groups looking for vulnerabilities are necessarily looking for the same vulnerabilities. An intelligence organization is likely to have the engineering and mathematics capacity to take low-value or difficult-to-use vulnerabilities and combine them into a working exploit. Less capable groups may have to wait until they find a vulnerability which can immediately be used to gain access to a computer system to develop a useful exploit. The knowledge of a vulnerability’s existence is valuable information, with similar properties to the location of buried treasure on a map or a secret told to a friend. The bug hunter’s challenge is to choose who to whisper their secret to, along with proof-of-concept code that proves their secret is in fact true. This secret is a source of value and creates a dilemma: malicious actors who wish to gain access to a vulnerability are almost always willing to pay more than the software’s original vendor—sometimes a great deal more.\(^4\) Because a vulnerability is something embedded in a piece of software, a person who independently discovers it has no guarantee of being the only one who knows about its existence. Every passing day brings a higher probability that someone else working to find vulnerabilities in the same piece of software will stumble upon the bug, leading to rediscovery. This leads to an economy of buying and selling vulnerability information among criminal groups, companies, and governments.\(^5\) Value of Rediscovery Because vulnerabilities are non-rivalrous, they can be discovered and held by more than one party simultaneously. A rediscovered vulnerability may be the same as the original, or a closely related flaw deemed similar enough to be identical. Rediscovery describes the likelihood that two independent parties will discover the same flaw in a piece of software. This is slightly different from a bug collision, which is when a vulnerability which had previously only been known to a single party enters the public domain. Asking about the rate of rediscovery only assumes that the two groups that find the same bug are independent of each other. Rediscovery is an important issue for the cybersecurity community, perhaps most prominently in the debate over how government should balance the choice to keep secret or disclose vulnerabilities to software developers. In the United States, the Vulnerabilities Equities Process (VEP) is the inter-agency process intended to make decisions about the disclosure of software vulnerabilities known by U.S. government agencies and organizations. The key choice for this VEP process is whether to keep the vulnerability secret or disclose the flaw to its developer, whereupon the government loses the opportunity to use the vulnerability (though the time this takes to happen can vary dramatically). Measuring the cost of disclosure vs. non-disclosure involves a range of factors but an important factor is the likelihood that a vulnerability, kept secret from a vendor and unpatched, might be rediscovered by another party and used against U.S. citizens. The answer is critical to determining the cost of non-disclosure of a vulnerability. If a vulnerability in the possession of the U.S. government is not likely to be discovered by another party, then the risk of keeping it a secret is lower than if the likelihood of rediscovery is high. However, there is more value in the question of rediscovery than just the VEP. Rediscovery can impact how the software security industry thinks about bug-bounty programs, which pay researchers in exchange Taking Stock: Estimating Vulnerability Rediscovery for disclosure of a software flaw. In paying for a vulnerability, companies expect that it can be patched (fixed). As these patches accumulate and users apply them, one of two things should happen: either these companies slowly reduce the total number of flaws in their codebase, or they find and fix enough old bugs to keep pace with new ones created as software is updated over time. Understanding the speed of rediscovery helps inform companies, showing how quickly a disclosed but unpatched bug could be rediscovered by a malicious party and used to assault the company’s software. This information should drive patch cycles to be more responsive to vulnerabilities with short rediscovery lag, while allowing more time for those where the lag is longer. With additional work, rediscovery may also contribute to more accurate estimates of the density of vulnerabilities in software. Academic research into the malware markets is also likely to benefit from better estimates of vulnerability rediscovery. Rediscovery impacts the lifespan of a vulnerability; the likelihood of its being disclosed to or discovered by the vendor grows with every instance of rediscovery. Just as one can compare a supermarket’s need to renew its stock of bread vs. salted herring, some vulnerabilities are likely to “go stale,” and thus be of little value, much faster than others.⁸ Estimating rediscovery can help shed light on which types of vulnerabilities are more likely to decay relative to others, based on the frequency with which they are discovered by multiple parties. Rediscovery and Previous Literature Despite the importance of this issue, the academic record on rediscovery is relatively sparse.⁹ A 2005 paper by Andy Ozment applied software reliability growth models to vulnerability discovery to gauge the total population of software vulnerabilities in the operating system BSD.¹⁰ This paper also --- ⁸ A vulnerability can rise in value if integrated with many others as part of an exploit kit, a mechanism to deploy malicious software using dozens of vulnerabilities, or if few targets apply the patch that fixes the corresponding flaw. ⁹ There is an ample literature on vulnerability discovery that deals with an important but slightly different question from this paper’s focus on rediscovery. For a detailed literature review, see Fabio Massacci and Viet Hung Nguyen, “An Empirical Methodology to Evaluate Vulnerability Discovery Models,” IEEE Transactions on Software Engineering 40, no. 12 (2014): 1147–1162. addressed rediscovery, using a collection of vulnerability bulletins from Microsoft between 2002 and 2004 to catalogue when the company credited more than one disclosing party. Ozment found an average rediscovery rate of just under 8%, aggregated over different types of software, including operating systems, applications, and supporting libraries. Writing in 2013, Finifter et al. looked at the relative cost efficiency of vulnerability reward programs against directly employing security personnel. Looking at Firefox and Chrome, they found that most vulnerabilities are reported from within firms, though by 2012 this trend had shifted for critical vulnerabilities in Chrome and more were reported from outside the company. In a small section looking at rediscovery, the group’s paper calculated a mean rediscovery rate for Chrome of 4.6% and provided anecdotal evidence of similar rates in Firefox.11 A collaboration between the bug bounty company HackerOne and researchers at Harvard and MIT produced a system dynamics model of the vulnerability discovery and stockpiling process.12 As part of this work, the group presented results of a random discovery simulation at RSA that showed a 9% rediscovery rate for immature software and less than 1% for “hardened” or more mature codebases. Unfortunately, no formal paper describing the methodology and data employed in this study has yet been published. In each of these instances, the question of rediscovery was tangential to a different debate. Ozment’s work was a response to Eric Rescorla’s contention that there was little long-term utility to vulnerability discovery and patching.13 Finifter and his group were studying the efficacy of bounties over hiring security talent as full-time employees, and the HackerOne estimate of rediscovery came in the context of discussing the relative density of vulnerabilities in old vs. new software. In each of these, there was little actual data available to judge the rate of rediscovery and other potentially interesting characteristics. Most recently, a 2017 study from the RAND Corporation used a small private dataset to evaluate the nature and behavior of zero-day vulnerabilities—those used by attackers before the vendors learn about them.\textsuperscript{14} The study found that over the span of a year, on average only 5.76\% of vulnerabilities were rediscovered in the public domain, while for 90 days or less the figure was less than 1\%. This is much lower than our findings that 13\% to 20\% of vulnerabilities are rediscovered within a year, including more than 21\% in the Android operating system. While the two papers are scoped to different ends, much of the distinction is likely attributable to differences in data sources and methodology. For more on these differences, see Section 6. 3 Methodology and Data This paper addresses a gap in the literature by integrating vulnerabilities reported in several different codebases, including the browsers Firefox and Chrome, the open source project OpenSSL, and the Android operating system to generate estimates of vulnerability rediscovery and related measures such as rediscovery lag. The goal in selecting these codebases was to cover more than one software type, span multiple vendors, and have the best possible access to complete data. Counting Duplicate Vulnerabilities Measuring rediscovery is difficult because once the original vulnerability is disclosed and made public, there is little incentive for anyone to come forward and make a new disclosure about the same vulnerability, except where to do so might result in reputational rewards. The dataset collected here, and all those that look at disclosure records, don’t measure discovery directly. Instead, this data captures disclosure as a proxy for disclosure. This limits the “rediscovery window” to capture rediscovery for each vulnerability record to the period between an initial vulnerability disclosure and public notice of the bug’s existence. Limiting our data to this rediscovery window has some benefit as well. Looking at rediscovery, there is a reasonable assumption that over a long enough period any vulnerability will be discovered multiple times. Because the window in which we can observe rediscovery is effectively limited to the period between initial disclosure and when a patch is made publicly available, there is a natural time constraint. This is built on Ozment’s method of counting multiple credited discoverers, a record-keeping process that would end with a patch being made available to the public. --- 15 A codebase is the collection of code used to develop a piece of software, including both current and previous versions. 16 All the data we used is available in our GitHub repository (https://github.com/mase-gh/Vulnerability-Rediscovery), and we continue to work to expand this dataset to include closed source software and other open source projects. Within this rediscovery window, our method of tabulating the discovery of a rediscovered vulnerability looks for two criteria: are there multiple parties given credit for independently disclosing the same vulnerability and/or has the bug been marked a duplicate and merged with another? We employ one or both approaches with each codebase. More detail on the specific method of counting duplicates for each piece of software can be found below. Calculating rediscovery, we take measure of the number of all vulnerability records with duplicates as a proportion of all vulnerability records. In a given period, if there are ten different vulnerability records and one of those records has received duplicate disclosures, then only one vulnerability record has a duplicate. As a result, the rediscovery rate is 1/10 or 10%.\textsuperscript{17} In our estimates, we collect the total population of vulnerabilities and sample those of high or critical severity to measure this rediscovery rate. The other two measures presented in this paper, rediscovery over time and rediscovery lag, are derived from the same data. The likelihood of rediscovery appears to grow in the months after a vulnerability’s initial disclosure, eventually leveling off within a few months. Rediscovery over time measures this rate of change, the brevity of which suggests that the distribution of discovery attention is not uniform and changes over time. Rediscovery lag measures the time between an original disclosure and any subsequent duplicate disclosures; e.g., the time between Disclosure\textsubscript{Original} and Disclosure\textsubscript{DuplicateA} is X and time between Disclosure\textsubscript{DuplicateA} and Disclosure\textsubscript{DuplicateB} is Y. Thus, the rediscovery lag for DuplicateA would be X while the lag for DuplicateB would be X + Y. \textsuperscript{17} This 10% figure shows the proportion of vulnerabilities that are rediscovered and not the total number of duplicates. If that same vulnerability was rediscovered 10 more times, for a total of 20 vulnerability disclosures, the rediscovery rate is unchanged in this methodology. This is not to say these additional duplicates aren’t of interest; we address their frequency and significance in Multiple Rediscovery in Section 4 below. Coding and Data Sources In each source of data for vulnerability rediscovery, we used only vulnerabilities of high or critical severity to improve the quality of our data and impact of our analysis. Software bugs are generally given a severity score to help organize them and prioritize which need to be fixed first. The definitions of high and critical severity vary somewhat between organizations but generally settle on critical including anything that allows the execution of arbitrary code while high covers most instances where an attacker could manipulate software functions or operate without restriction if local to the targeted computer. For example, Google defines severity as: - **Critical:** “issues allow an attacker to run arbitrary code on the underlying platform with the user’s privileges in the normal course of browsing.” - **High:** “…vulnerabilities allow an attacker to execute code in the context of, or otherwise impersonate other origins. Bugs which would normally be critical severity with unusual mitigating factors may be rated as high severity.” By constraining this dataset to high and critical vulnerabilities, the paper offers analyses based on the most impactful software flaws. This means that the dataset comprises only a subset of the total population of vulnerabilities but emphasizes those most critical to developers and policymakers. This has also generally improved the quality of data, as record keeping appears to be most detailed for these most important bugs. We intend to expand to medium- and low-severity bugs, and their equivalent naming conventions across different vendors, in future work. Data for this range of products and vendors came from four sources that we integrated into a single dataset. There are numerous challenges in counting vulnerabilities, and the variable state of record keeping discovered across vendors and open source projects only underlines this. By --- limiting our collection to these high- and critical-severity vulnerabilities, the dataset is made less generalizable but more reliable. - Firefox: The Firefox dataset is scraped from records in the Bugzilla bug tracker for Firefox and related software dependencies.\(^{19}\) This data constitutes all bugs labeled as high-priority or critical in the Severity field from Extended Service Release (ESR) advisories for Firefox between 2012 and 2016 and comprises 473 vulnerability records and 81 records with duplicates. Firefox presented a challenge in how to create a working subset of only those vulnerabilities from the total pool of bug records. Firefox has nightly builds—new versions of the codebases with small changes or trial features—and many of the vulnerabilities discovered in Firefox are found there and fixed immediately. This dataset does not include these vulnerabilities, since they are never exposed to the public as part of an Extended Stable Release (ESR), and are thus unlikely to represent bugs that might be independently rediscovered. By counting only bugs from ESRs, we could obtain a subset of vulnerabilities that were exposed for discovery and exploitation by all users. In Bugzilla, each vulnerability record has a report page, with a Tracker subsection. For some vulnerabilities, that Tracker subsection contains a Duplicates field with a record of associated bug codes and their status. Those records with data in the Duplicates field were what was coded as duplicates. - Chrome: The Chrome dataset is scraped from bugs collected for Chromium, an open source software project whose code constitutes most the Chrome browser.\(^{20}\) On top of Chromium, Google adds a few additional features, such as a PDF viewer, but there is substantial overlap, so we treat this as essentially identical to Chrome.\(^{21}\) Chrome presented a similar problem to Firefox, so to --- \(^{21}\) Others have previously made this same choice, including Finifter, Akhawe, and Wagner, “An Empirical Study of Vulnerability Rewards Programs.” record only vulnerabilities with a reasonable likelihood of public discovery, we limited our collection to bugs labeled as high or critical severity from the Chromium bug tracker. This portion of the dataset comprises 3,397 vulnerability records of which there are 468 records with duplicates. For Chrome, we coded a vulnerability record as a duplicate if it had been merged with another, where merges were noted in the comments associated with each vulnerability record, or marked as a Duplicate in the Status field. - OpenSSL: Our data comprises all vulnerability records from 2014 to 2016 for the OpenSSL project. The start time for this window is the disclosure of Heartbleed. Based on conversations with members of the OpenSSL community, the consistency of record keeping appears to have improved commensurate with a new influx of resources after the Heartbleed disclosure in April 2014. This portion of the dataset comprises 85 vulnerability records of which 2 have duplicate disclosures. In OpenSSL, vulnerabilities are noted as a duplicate if they credit two separate disclosers for the bug. Records with an ‘and’ between credited reporters are coded as a collaboration and so not duplicate disclosures. Records with an ‘&’ between reporters are coded as independent discoveries and thus duplicates. - Android: We were provided access to data from Google’s tracking systems for Android vulnerabilities: the public system, CodeSite, and an internal-use-only platform called Issue Tracker. The internal site track used by Google employees tracks disclosures from within the company as well as some from outside while CodeSite records disclosures from the public. This data provides a glimpse into rediscovery rates for Android over a 17-month time frame between July 2015 and November 2016. A member of the Google security team downloaded bugs from both tracking systems, then correlated them to remove identical records that existed in both systems. This individual then added a CVE ID 23 Underlining the record-keeping issue—neither of these disclosures includes the Heartbleed bug, which was discovered twice within the span of a few days and reported in April 2014. 24 This is possible because Google maintains both respective tracking systems’ vulnerability ID value for all records on both platforms. for all records, to replace the internal tracking IDs. Instances of rediscovery, duplicate disclosures, were coded when a vulnerability record in CodeSite was noted as a duplicate and linked to a report credited to a separate researcher(s) from the original. Duplicates were also coded if two bugs were merged together. The Android portion of the paper’s dataset comprises 352 vulnerability records where 77 records had at least 1 duplicate. Table 1—Dataset Summary <table> <thead> <tr> <th>Source</th> <th>Date Range</th> <th>Total Population</th> <th>Sample Vulnerabilities</th> <th>Sample Duplicates</th> <th>Rediscovery Rate</th> </tr> </thead> <tbody> <tr> <td>Google—Chrome</td> <td>2009–2016</td> <td>6817</td> <td>3397</td> <td>468</td> <td>13.8%</td> </tr> <tr> <td>Mozilla—Firefox</td> <td>2012–2016</td> <td>1112</td> <td>473</td> <td>81</td> <td>17.1%</td> </tr> <tr> <td>Google—Android</td> <td>2015–2016</td> <td>682*</td> <td>352</td> <td>77</td> <td>21.9%</td> </tr> <tr> <td>OpenSSL</td> <td>2014–2016</td> <td>85</td> <td>85</td> <td>2</td> <td>2.4%</td> </tr> <tr> <td>Total</td> <td>2009–2016</td> <td>8696</td> <td>4307</td> <td>628</td> <td>14.6%</td> </tr> </tbody> </table> The above table summarizes the four sources for this paper’s dataset, covering more than 4,300 vulnerability records over eight years from four different software projects. - Source—the software these vulnerabilities come from, explained in detail above - Date Range—the time range for the population of vulnerabilities and our sample - Total Population—the total number of vulnerabilities available from each of the four data sources, of all criticality levels, from the date range specified. - Sample Vulnerabilities—our sample of high and critical vulnerabilities, a subset of the total population of vulnerabilities for the source software * Because of our inability to directly access Google’s records for the total population of Android vulnerabilities, we use here the total number for Android reported to the National Vulnerability Database in the specified date range. • Sample Duplicates—the number of vulnerability record from our sample which had duplicates; see above for more detailed explanation of what constitutes a duplicate for each source • Rediscovery Rate—the proportion of vulnerabilities from each source with at least one duplicate disclosure. 4 Analysis Our analysis covers vulnerabilities in a range of software types, including standalone applications like Chrome and Firefox, and the library OpenSSL. The first section of analysis takes all this software together, producing an aggregate measure of vulnerability rediscovery. Following this is an analysis of multiple rediscovery (where there are multiple duplicate bugs), evaluating trends in specific codebases, and then an analysis of rediscovery lag, the time between initial disclosure and the first duplicate report. The final subsection evaluates rediscovery over time. Each section draws from all or part of the dataset, with explanations for the use of subsets where appropriate. Vulnerability Rediscovery in the Aggregate Vulnerabilities in the eight-year span of this dataset see an aggregate 14.9% rate of rediscovery. This is higher than previous open-source estimates, which ranged from 6.84% in early empirical work to 9% in more recent simulations. Figure 1 below charts the annualized discovery rate over the whole dataset. This sample of high and critical vulnerability records shows a rate of rediscovery that is twice as high as previously thought, and which has been steadily increasing over the past decade in the software we examined. Multiple Rediscovery This section looks at the rate of rediscovery by codebase and the phenomenon of multiple rediscovery, where more than two parties disclose the same vulnerability. While we are not able to control for each vendor characteristic individually—for example, the difference between bug bounty payouts or secure coding practices—this section demonstrates that there are relatively consistent trends in multiple rediscovery rates between the vendors in our sample. Across this paper’s entire dataset, where rediscovery did take place, one duplicate was the norm, though some vulnerabilities saw as many as four, five, and even one case of 11 duplicate disclosures. The three charts below in Figures 2–4 describe this multiple rediscovery, putting it in context across Firefox, Chrome, and Android. Each pie chart has three values: - No Duplicates: vulnerabilities for which there was only a single disclosure - 1 Duplicate: vulnerabilities with an initial disclosure and one duplicate - 2 or more Duplicates: vulnerabilities with an initial disclosure and more than one duplicate. Note that this counts all vulnerability records with more than 1 duplicate, not the total of all these duplicates together. We break the three biggest codebases out below, to show trends and differences in rediscovery, including distinctions between vulnerabilities with one duplicate and those with two or more. **Figure 2—Firefox Vulnerability Rediscovery** ![Firefox Vulnerability Rediscovery Chart] **Figure 3—Chrome Vulnerability Rediscovery** ![Chrome Vulnerability Rediscovery Chart] Looking at the three codebases, there is a trend where small increases in the overall rediscovery rate are largely accounted for by vulnerabilities with two or more instances of rediscovery. That is, newly rediscovered vulnerabilities appear to be shallow and more likely to be found by multiple parties. **Vulnerability Rediscovery Lag** Rediscovery can be a useful metric, but we should also consider the element of time and its impact on subsequent additional discoveries of the same vulnerability. This section looks at the time between original and duplicate disclosure, “the rediscovery lag.” Where that lag is longer, it suggests discoverers are stumbling across the same bug with something approximating truly independent discovery. This section uses the Chrome and Android data both to highlight differences between software types and to make use of the more complete timing data available for both. Rediscovery lag was calculated by taking the absolute time difference between original vulnerability disclosure and subsequent duplicates. For additional duplicates after the first, the time lag was measured between their disclosure date and that of the original. The Android data for this paper was made available with assistance from Google and comes from a combination of public and internal bug tracking systems. This section presents the Android data sorted into discrete monthly categories because of the inability to collect original and duplicate disclosure dates for each vulnerability record. So, if a vulnerability is discovered at \( t_0 \), rediscovered once at \( t_{30} \), and then rediscovered again at \( t_{60} \), the chart would include both disclosures—one each in the one- and two-month categories. In looking at Android, the average time between initial discovery and rediscovery was two months, though a sizable number also occurred within the same month as the original disclosure (0 months). Figure 5 shows a distribution of Android rediscovery lag for all duplicates, including vulnerabilities with multiple duplicates, covering 112 duplicates for 77 distinct vulnerabilities. **Figure 5—Android Rediscovery Lag** The disclosure of most duplicate vulnerabilities in Android takes place months later than the original, while only 20% occur in the same month. This pushes back on the notion of rediscovery as being largely “simultaneous discovery” and suggests instead a more independent activity. Figure 6 shows the time from original to first rediscovery for a subset of the vulnerabilities in Chrome. There is a wider distribution, including multiple vulnerabilities spread all the way to eight months, but a strong concentration in the first seven days after the original. This may suggest greater communication within the Chrome security community either directly or through more transparency in the Chromium bug tracker. Rediscovery Over Time While the rediscovery lag can give some picture of how long it takes to find a vulnerability, another way to consider the problem is what proportion are likely to be rediscovered within a given time? This section looks at data for Android and Chrome to show the same differences between codebase as in rediscovery lag. With Chrome, nearly 40% of vulnerabilities are reported within the same 24-hour period, rising quickly to the Chrome lifetime average of about 14% rediscovery, as shown in Figure 7. Figure 7—Chrome Aggregate Rediscovery Over Time For Android, that rediscovery is slower to increase but ends up higher. While the Android data is sorted into months and so does not cover the week-to-week detail in the first month as does the Chrome data, there is a nearly identical rate of same-day rediscovery, while the following two months take more time to reach the near peak rate at 19%. Rediscovery rates rise quickly in the first 90 days, then largely level off as shown below in Figure 8. Figure 8—Android Aggregate Rediscovery Rate For a more direct comparison of these two, look to Figure 9 (page 28), where data from Chrome is sorted into months in a similar fashion as Android and the rediscovery over time charts for both are overlaid. 5 Limitations of the Dataset This research deals with several limitations. First, vulnerabilities are variably difficult to discover and exploit, which may influence discovery behavior and undermine the feasibility of aggregating them. Second, we only consider vulnerabilities with high or critical severity, which limits the generalizability of our results. There are additional factors that influence our result over which we had no control. Failure to Report: The ability to count duplicate reports of a single vulnerability assumes people will continue to disclose their discoveries. This may be the case before the original vulnerability is made public, but will likely drop sharply afterward. This is generally because once a patch is available (even if not yet broadly applied), additional disclosures add little marginal value. For individuals with an interest in disclosure, the time to observe duplicates is during this rediscovery window between the original vulnerability’s disclosure and the developer making a patch available. Comparatively longer patch windows for some codebases could increase that time to capture duplicates, increasing the total number observed and skewing the rediscovery rate for that software. Conversely, short rediscovery windows censor data that might otherwise be valid. One person affiliated with OpenSSL suggested that for open source projects, this patch window could be as short as seven days, leaving little chance for multiple parties to disclose.26 The length of this rediscovery window is unlikely to impact criminal groups and others with much less interest in disclosing vulnerabilities. This leads to higher rates of rediscovery than are observed just from tracking disclosures. The format of disclosure behavior can also impact results; for example, differences may emerge between independent disclosure, bounty programs, and time-dependent events such as competitions and private bounty events. Discovery from an internal team may follow a different pattern altogether, as recording a vulnerability allows employees to note the existence of the bug and pass it off to someone else. 26 Author Communication, 18 Oct 2016. Many of the same caveats that apply to Ozment’s original analysis of Microsoft’s vulnerability bulletins remain an issue here, “...the multiple individuals/organizations credited may have collaborated on finding the vulnerability, rather than identifying it independently. Furthermore, the... window of time for recording independent rediscoveries is [short].”27 The dataset collected for this paper attempts to account for some of these concerns but is likely to lead to underestimates regardless. *Failure to Record:* Vulnerabilities are also fixed by internal quality assurance and security teams before they ever reach public versions of software or duplicates not recorded after the original disclosure. In talking to individuals affiliated with companies like Cisco and Apple, as well as open source projects like OpenSSL, many suggested these internal fixes might go unrecorded. Where the public does find, and disclose, a vulnerability that has also been discovered internally, many groups are unlikely to record the subsequent disclosure as a duplicate. This failure to record vulnerabilities isn’t limited to internal discovery. Groups sometimes differ on which bugs constitute vulnerabilities or fail to record additional disclosure after the original. OpenSSL provides a good case in point; we know from press reporting that two separate groups discovered the Heartbleed bug in April 2014, within days of each other, but only one group is credited for disclosure in the OpenSSL records. There are likely additional cases like this across vendors and open source projects. There are also differences in the rediscovery rates of vulnerabilities at different severity levels, with some evidence that lower severity flaws are rediscovered more often. Bugcrowd, a firm that helps integrate companies with a labor market for vulnerability discovery, found that rediscovery happened least often with their highest severity bugs, 16.9% of the time. For second- and third-tier vulnerabilities (based on a five-tier system), the rediscovery rate jumped to 28.1% and 25.8%, respectively.28 This suggests that rediscovery is more likely with less severe bugs—but this paper and the associated dataset are focused on the rediscovery rate and resulting policy implications from high- and critical-severity vulnerabilities. This is largely because of the potential consequence these vulnerabilities --- 28 These figures were provided by Bugcrowd as an analysis of its internal reporting data, which integrates participants from both its public and private programs. could have if used against computing systems and the Internet more broadly. The difference, at least in a narrow sample, between critical- and medium-severity vulnerability rediscovery rates does suggest that the estimates generated in this paper are lower than for the larger population of vulnerabilities. Some factors contribute to over-, rather than under-estimation. With bug bounty programs, disclosers will sometimes attempt to game the system by creating multiple aliases and submitting the same vulnerability repeatedly. In addition, at least one company’s public bug tracking system aggregated duplicates by linking separate vulnerability records and manually integrating them. This requires an analyst to discern the duplication and purposefully account for it. The degree to which bugs are duplicative can vary with individual judgment. Thus, our estimate of vulnerability records with two or more duplicates may be high. The results of this analysis are significant as a baseline estimate representative of high- and critical-severity vulnerabilities. That the rediscovery rate for a broader set of software vulnerabilities may be higher only reinforces the utility of having a starting point to work from. The policy community doesn’t address the issue of rediscovery in any way informed by empirics, and the scope of this dataset is far larger and more diverse than previous work. In addition, because of the emphasis on high- and critical-severity vulnerabilities, this paper prioritizes analysis of those bugs of greatest interest to the information security community. 6 Implications This section deals with implications from this research and addresses the results of a similar and more recent study. There are three principle implications for the rediscovery rates we find in this paper, looking at how companies handle bug bounties, academic research into the malware markets, and for government’s handling of bugs in the vulnerability equities process (VEP). Patching from Bug Bounties Bug bounties drive vulnerability disclosure to firms, a major way for companies to identify bugs to be patched. The volume of these bugs can be overwhelming leading to prioritization of some patches to be completed more rapidly than others. Rediscovery rates can help drive that prioritization, pushing bugs with a higher chance of being discovered by other parties while in the patching process towards the top of the list. Rediscovery rates of 15 to 20% in this paper help set the parameters for what companies running bounty programs could expect – establishing a potential upper bound for vulnerabilities, especially those in open source software. Studying the Malware Markets Looking at the malware markets, rediscovery rates can help estimate product life cycles in malicious software. Higher rates of rediscovery will drive greater churn as exploit kits and other products dependent on vulnerabilities need to be refreshed more rapidly. At the rates of rediscovery found for this paper, nearly a fifth of all vulnerabilities may become known to a vendor or competitor in these markets every year. This discovery by other parties depresses the value of a vulnerability. These rates may also help inform a value curve for software vulnerabilities; as rediscovery rates go up the period of high value shortens and absolute value may increase owing to scarcity in these flaws. The Vulnerability Equities Process (VEP) The VEP presents a balancing issue, between public security realized through updated and well-maintained software and that obtained by vigorous intelligence and law enforcement activity. In deciding to disclose a vulnerability, the government must weigh the relative costs of using a vulnerability and not disclosing it against turning that vulnerability over to a vendor so that it may be patched. If a vulnerability in the possession of the U.S. government is independently rediscovered by another party, the risk associated with keeping it secret is much higher than if it is never rediscovered. Rediscovery rate becomes particularly important if the software in question is a widely used open source project or a cryptographic library. Here, the ripple effects of non-disclosure could impact a far larger number of people. What do the rediscovery rates from this paper tell us about VEP? There is little systematic transparency into the types or number of vulnerabilities held by the U.S. government, but by combining our work with a report produced by Columbia University, which estimates the U.S. government retains no more than 50 to 250 vulnerabilities for use at any given time, we can offer some answers. Using the aggregate rediscovery rate for our entire dataset, 14.9%, means that in a given year, somewhere between 8 and 37 vulnerabilities kept secret by the U.S. will be rediscovered by other parties. Not every one of these vulnerabilities, in active use by law enforcement and the intelligence community, may be rediscovered, or could be capably employed, by potential adversaries. Making a conservative assumption, that only 50% of these rediscovered flaws are both useful and in the hands of malicious actors, a 15% rediscovery rate still leaves 4 to 18 high value software flaws in the wild every year, and likely to be discovered by attackers before software vendors, potentially a major source of new zero-days. In 2016, Symantec reported that there had been 54 zero-day vulnerabilities 29 Assessing the entire chain of decision making in the mind of a notional attacker is impractical. Rediscovery is a critical point in the event chain. Without knowledge of a vulnerability, none of the other points about a potential attacker—motivation, skill, preferences—are relevant. In this scenario, a U.S. government agency is aware of the vulnerability and potentially has it in active use, leading to a decision not to disclose the information to the affected software’s vendor. While in use, this vulnerability is then discovered by a malicious party. This rediscovery means the vulnerability information is in several people’s hands and no longer exclusive to the U.S. used in 2015. This means that the rediscovery of vulnerabilities kept secret by the U.S. government for operational use could contribute anywhere from 7.5% to 33% of this 2015 zero-day population. Without accounting for the unintentional proliferation of new vulnerabilities from leaks like the Equation Group tools released by Shadow Brokers, this proportion of zero-days potentially left unpatched and exploited while their underlying vulnerabilities are in use by the U.S. government is significant. These findings suggest that policymakers should reevaluate current practice in use and retention of vulnerabilities, that up to a 1/3 of all zero-days in use by other states and criminal groups may come from U.S. failure to disclose vulnerabilities to vendors changes the state of the debate. These findings should also motivate critical discussion on the standards of vulnerability disclosure review and prompt support for new research, preferably unclassified, about how these rediscovery rates differ for high-consequence software such as common cryptographic or common software libraries for embedded systems. Analysis in the Context of Recent Work The RAND Corporation published a study on zero-day vulnerabilities a few days after this paper began circulating for comment. Though dealing with a larger range of issues in the development and use of vulnerabilities, the RAND study also addressed bug collisions, a similar topic to vulnerability rediscovery, which has led many to compare results from the two. This paper finds that 15% to 20% of vulnerabilities are rediscovered within a year, but the RAND study finds the rate to be about 6%. Though the two papers are asking slightly different questions, as explained below, we disagree with their conclusion that the rediscovery rate is as low as 6% over a year and especially that it remains below 1% within 90 days of initial discovery. Figure 9 shows our data on the rediscovery rate over time for both Android and Chrome, overlaid on each other. While the discovery rate at a month or less hovers between 2% and 5%, the rate rises quickly for both codebases—rising to just above 13% in Chrome and above 21% in Android.34 Figure 9—Android and Chrome Rediscovery Rates over Time The disagreement between these two studies largely stems from differences in their questions and methodology. The RAND team worked with a vulnerability research group to construct a sample matching what might be found in the intelligence or military community. From their study: “We believe these data are relatively representative of what a sophisticated nation-state might have in its arsenal...applying wide generalizations to other datasets may be misleading, as generalizations to other data can only be drawn if the data are similar in nature to ours.”35 This issue in data source is not an inconsiderable one; vulnerabilities discovered and reported directly to a vendor (whether through a bounty or not) will cover a wider array of bug types and severity than those selected strictly for operational use. It’s not clear to what extent this overlap is addressed by our sample being constrained to high- and critical-severity vulnerabilities. 34 The Chrome data has been sorted in the same way as Android for purposes of comparison here. 35 Ibid., 61. There are other differences, rooted in the data used by each study. RAND’s total dataset constitutes only 207 vulnerabilities spanning 14 years, and accurate information on dates such as vulnerability birth and maturity were only available for 61% of these bugs, thus potentially reducing the useful dataset size for this rediscovery question to approximately 127 vulnerabilities, or 9 per year.\textsuperscript{36} Our study includes 4,307 vulnerabilities, spanning 8 years, from open source software, including Chrome and the Android operating system. Every vulnerability record used in our analysis, with a minimum of their corresponding CVE or bug number, severity score, and dates for disclosure and duplicates are available in a GitHub repository, along with all the scripts used to extract, clean, and organize this data.\textsuperscript{37} While the RAND dataset hasn’t been made public, summary statistics from the paper indicate approximately 60% of the vulnerabilities affect closed source systems, predominantly Microsoft products, while another 35% are open source and 5% of undeclared origin.\textsuperscript{38} In terms of the VEP, a key question is this: how often is a vulnerability held in secret by the U.S. government going to be found by another party, whether state or non-state? To answer this, the two studies end up asking slightly different questions of their data. This paper looks at independent rediscovery of vulnerabilities: instances where two independent parties disclose the same vulnerability to a vendor. This data represents high and critical vulnerabilities and measures the instance of independent discovery of the same bug between two parties, without making any claim about their capability to discover or use a vulnerability. RAND looked at the frequency with which vulnerabilities in the public domain collided with previously known vulnerabilities in a private dataset. Their key claim is that this dataset more closely represents what an intelligence agency might use, thus measuring the chance for two unequal parties to find the same vulnerability: a government and researchers/criminals. Given the lack of a systematic model for how the capability (and capacity) to discover vulnerabilities is distributed across the malware markets, including state organizations and \textsuperscript{36} Ibid., 15. \textsuperscript{38} Ibid., 101. companies, we should hesitate to make strong claims about how one group might represent another.\textsuperscript{39} It is difficult to say with precision what systematic differences exist between vulnerabilities collected by the intelligence community and our dataset. Estimating rediscovery matters for a range of topics, including the VEP, research on the malware markets, and analyzing the efficacy of bug bounty programs. In looking at VEP, there is reason to believe that vulnerabilities collected and employed by the intelligence community are not a simple cross-section of all vulnerabilities. Software flaws in use by the intelligence community are likely to skew towards those most useful for gaining and maintaining access to the computer systems of intelligence collection targets. They may also be influenced by the individuals and techniques used in discovery vulnerabilities. A common refrain is that the National Security Agency (NSA) places a significant emphasis on mathematical capabilities in vulnerability discovery. This emphasis could result in NSA’s collection of vulnerabilities containing far more cryptographic flaws than would be found in a random sample of software vulnerabilities anywhere in the public domain. The same is likely true to some degree of law enforcement organizations. The vulnerabilities examined in this paper are from open source software, including Chromium and the Android operating system, which means they represent only a portion of the total population of software. Vulnerabilities in both systems would be useful to gain access to protected information such as in Chrome, where our sample includes several sandbox escapes.\textsuperscript{40} Our analysis does not presume that we know either party involved in rediscovery other than that they are working independently. Because of this, we cannot characterize that rediscovery is more or less likely to impact the vulnerabilities held by an intelligence or law enforcement organization. \textsuperscript{40} Includes CVE-2016-1706 and 2014-5332 There is very little data on vulnerability rediscovery or collision, however framed, and so we must be careful about data and our methodologies. The RAND team sourced its data from a private organization, and some of the vulnerabilities in the dataset may have been in use or for sale, but the study disclosed little more than summary statistics about their data. The small size of the dataset as well as its continued secrecy makes effective peer-review or replication very difficult. That said, the RAND paper is additive, including substantial material on the life and times of zero-day vulnerabilities, which will benefit policymakers and scholars alike. 7 Conclusions This paper provides the first empirical study of vulnerability rediscovery in multiple types of software and across different vendors, considering the rate of discovery, the impact of time, the length of lag between original and duplicate discoveries, and the variation of each of these factors across different vendors. Where previous work has estimated rediscovery rates for software between 5% and 9% largely unbounded by time, this paper demonstrates that rates for high- and critical-severity bugs are higher, as much as 23% within a year for Android. Table 2 summarizes annual rediscovery rates for Chrome, Firefox, and Android. Table 2—Rediscovery Rates by Codebase <table> <thead> <tr> <th></th> <th>Chrome</th> <th>Firefox</th> <th>Android</th> </tr> </thead> <tbody> <tr> <td>2009</td> <td>2%</td> <td></td> <td></td> </tr> <tr> <td>2010</td> <td>9.1%</td> <td></td> <td></td> </tr> <tr> <td>2011</td> <td>11%</td> <td></td> <td></td> </tr> <tr> <td>2012</td> <td>10.7%</td> <td>14.6%</td> <td></td> </tr> <tr> <td>2013</td> <td>10.8%</td> <td>14.3%</td> <td></td> </tr> <tr> <td>2014</td> <td>16.5%</td> <td>19%</td> <td></td> </tr> <tr> <td>2015</td> <td>17.6%</td> <td>18.9%</td> <td>15.4%</td> </tr> <tr> <td>2016</td> <td>19.1%</td> <td>17.4%</td> <td>23.3%</td> </tr> </tbody> </table> The fact that these rediscovery rates are trending higher and, in some cases, are two to three times previous estimates, is important. The impact of rediscovery scales with the number of vulnerabilities in a codebase. Looking at Chrome, for example, in 2014 there were 600 recorded high- and critical-severity vulnerabilities. At a rediscovery rate of 6%, closer to Ozment’s original estimates, Google should expect that at least 36 vulnerabilities known to them in 2014 will have been discovered by another party, potentially before being disclosed. Using the rate we found above, 16.5%, that number jumps to 99 vulnerabilities. This means more than 60 additional software vulnerabilities are discovered each year above previous estimates, many of which could be used by criminal groups or states before the developer patches them. The presence of these vulnerabilities in the malware markets means they may also be integrated into other malicious tools and see their lifespans extended even further. For the scholarly community, the current state of practice in tracking vulnerability disclosures and rediscovery is poor. This undermines the community’s ability to track the longer-term efficacy of investment in secure development practices and bug bounty programs. It bears on the discussion as well that even when there is a patch available, many vulnerabilities don’t immediately become useless, as users and organizations often delay applying patching for months or longer. Thus, a patched vulnerability still can still have operational utility. The relatively long lag time between original disclosure and rediscovery, more than two months on average across data from Android and the Chrome browser, suggests that many rediscoveries are truly independent. When the rediscovery window is short or nearly zero, it suggests that discoverers communicated about, or were aware of, each other’s efforts. This would inflate the rediscovery rate but hide the fact that many were working from the same information. Because the time lag is so long, it suggests many of these rediscoveries are truly independent and thus a more accurate model of the behavior of malicious third parties. These findings do not consider classified data. It is possible that the intelligence, defense, or law enforcement communities have conducted studies of rediscovery and reached different conclusions; however, there is no evidence of this in the public domain. Our estimates are based on data available to all researchers and evaluate software in common use by U.S. citizens and many government employees. While secret studies may exist, the data in this paper includes software that would have to be part of any such study. Thus, while we can only claim that our estimates are higher than previously reported in scholarship available to the public, these findings should also speak directly to the policy community, regardless of classification. There are many reasons to believe that the rediscovery rates presented in this paper are an underestimate of the true rate of rediscovery. Records from Bugcrowd discussed previously indicate that low- and medium-severity vulnerabilities are rediscovered more frequently than the high- and critical-severity bugs to which this study is constrained. As it is, the 15% to 20% estimate is substantially higher than previously seen. This is a first effort, but one which attempts to bring some empirical work to bear on an issue of interest to both the research and policy communities.
{"Source-Url": "https://www.blackhat.com/docs/us-17/thursday/us-17-Herr-Bug-Collisions-Meet-Government-Vulnerability-Disclosure-Taking%20Stock%20-%20Vulnerability-Rediscovery-HKS.pdf", "len_cl100k_base": 12655, "olmocr-version": "0.1.49", "pdf-total-pages": 42, "total-fallback-pages": 0, "total-input-tokens": 75427, "total-output-tokens": 16856, "length": "2e13", "weborganizer": {"__label__adult": 0.0007357597351074219, "__label__art_design": 0.0008263587951660156, "__label__crime_law": 0.01108551025390625, "__label__education_jobs": 0.004482269287109375, "__label__entertainment": 0.0003886222839355469, "__label__fashion_beauty": 0.0003635883331298828, "__label__finance_business": 0.0021953582763671875, "__label__food_dining": 0.0005240440368652344, "__label__games": 0.004058837890625, "__label__hardware": 0.001922607421875, "__label__health": 0.0013294219970703125, "__label__history": 0.0010166168212890625, "__label__home_hobbies": 0.00021088123321533203, "__label__industrial": 0.0006499290466308594, "__label__literature": 0.001255035400390625, "__label__politics": 0.0015125274658203125, "__label__religion": 0.0005812644958496094, "__label__science_tech": 0.356689453125, "__label__social_life": 0.00029277801513671875, "__label__software": 0.09564208984375, "__label__software_dev": 0.51318359375, "__label__sports_fitness": 0.0003261566162109375, "__label__transportation": 0.000576019287109375, "__label__travel": 0.0002772808074951172}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 72750, 0.02222]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 72750, 0.45611]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 72750, 0.9185]], "google_gemma-3-12b-it_contains_pii": [[0, 0, null], [0, 0, null], [0, 96, false], [96, 1316, null], [1316, 3437, null], [3437, 5397, null], [5397, 7383, null], [7383, 9751, null], [9751, 11964, null], [11964, 15218, null], [15218, 17803, null], [17803, 20541, null], [20541, 23069, null], [23069, 24169, null], [24169, 26286, null], [26286, 28579, null], [28579, 30678, null], [30678, 33173, null], [33173, 35600, null], [35600, 37768, null], [37768, 39115, null], [39115, 40444, null], [40444, 40925, null], [40925, 41980, null], [41980, 43364, null], [43364, 44657, null], [44657, 45073, null], [45073, 47252, null], [47252, 49925, null], [49925, 51514, null], [51514, 53320, null], [53320, 56156, null], [56156, 58719, null], [58719, 60287, null], [60287, 62847, null], [62847, 65730, null], [65730, 67480, null], [67480, 70791, null], [70791, 72750, null], [72750, 72750, null], [72750, 72750, null], [72750, 72750, null]], "google_gemma-3-12b-it_is_public_document": [[0, 0, null], [0, 0, null], [0, 96, true], [96, 1316, null], [1316, 3437, null], [3437, 5397, null], [5397, 7383, null], [7383, 9751, null], [9751, 11964, null], [11964, 15218, null], [15218, 17803, null], [17803, 20541, null], [20541, 23069, null], [23069, 24169, null], [24169, 26286, null], [26286, 28579, null], [28579, 30678, null], [30678, 33173, null], [33173, 35600, null], [35600, 37768, null], [37768, 39115, null], [39115, 40444, null], [40444, 40925, null], [40925, 41980, null], [41980, 43364, null], [43364, 44657, null], [44657, 45073, null], [45073, 47252, null], [47252, 49925, null], [49925, 51514, null], [51514, 53320, null], [53320, 56156, null], [56156, 58719, null], [58719, 60287, null], [60287, 62847, null], [62847, 65730, null], [65730, 67480, null], [67480, 70791, null], [70791, 72750, null], [72750, 72750, null], [72750, 72750, null], [72750, 72750, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 72750, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 72750, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 72750, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 72750, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 72750, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 72750, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 72750, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 72750, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 72750, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 72750, null]], "pdf_page_numbers": [[0, 0, 1], [0, 0, 2], [0, 96, 3], [96, 1316, 4], [1316, 3437, 5], [3437, 5397, 6], [5397, 7383, 7], [7383, 9751, 8], [9751, 11964, 9], [11964, 15218, 10], [15218, 17803, 11], [17803, 20541, 12], [20541, 23069, 13], [23069, 24169, 14], [24169, 26286, 15], [26286, 28579, 16], [28579, 30678, 17], [30678, 33173, 18], [33173, 35600, 19], [35600, 37768, 20], [37768, 39115, 21], [39115, 40444, 22], [40444, 40925, 23], [40925, 41980, 24], [41980, 43364, 25], [43364, 44657, 26], [44657, 45073, 27], [45073, 47252, 28], [47252, 49925, 29], [49925, 51514, 30], [51514, 53320, 31], [53320, 56156, 32], [56156, 58719, 33], [58719, 60287, 34], [60287, 62847, 35], [62847, 65730, 36], [65730, 67480, 37], [67480, 70791, 38], [70791, 72750, 39], [72750, 72750, 40], [72750, 72750, 41], [72750, 72750, 42]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 72750, 0.05296]]}
olmocr_science_pdfs
2024-11-26
2024-11-26
99bf97498eab74cb89b27744d5584d683bc90af3
A Prototypical Java-like Language with Records and Traits This is a pre print version of the following article: Original Citation: A Prototypical Java-like Language with Records and Traits / Lorenzo Bettini; Ferruccio Damiani; Ina Schaefer; Fabio Strocco. - (2010), pp. 129-138. ((Intervento presentato al convegno 8th International Conference on the Principles and Practice of Programming in Java tenutosi a Vienna, Austria nel September 15-17, 2010. Availability: This version is available http://hdl.handle.net/2318/81755 since Publisher: ACM Published version: DOI:10.1145/1852761.1852780 Terms of use: Open Access Anyone can freely access the full text of works made available as "Open Access". Works made available under a Creative Commons license can be used according to the terms and conditions of said license. Use of all other works requires consent of the right holder (author or publisher) if not exempted from copyright protection by the applicable law. (Article begins on next page) A Prototypical Java-like Language with Records and Traits Lorenzo Bettini1 Ferruccio Damiani1 Ina Schaefer2 † Fabio Strocco1 1 Dipartimento di Informatica, Università di Torino, C.so Svizzera, 185 - 10149 Torino, Italy 2 Chalmers University of Technology, 421 96 Gothenburg, Sweden Abstract Traits have been designed as units of fine-grained behavior reuse in the object-oriented paradigm. In this paper, we present the language SUGARED WELTERWEIGHT RECORD-TRAIT JAVA (SWRTJ), a JAVA dialect with records and traits. Records have been devised to complement traits for fine-grained state reuse. Records and traits can be composed by explicit linguistic operations, allowing code manipulations to achieve fine-grained code reuse. Classes are assembled from (composite) records and traits and instantiated to generate objects. We present the prototypical implementation of SWRTJ using XTEXT, an Eclipse framework for the development of programming languages as well as other domain-specific languages. Our implementation comprises an Eclipse-based editor for SWRTJ with typical IDE functionalities, and a stand-alone compiler, which translates SWRTJ programs into standard JAVA programs. Categories and Subject Descriptors D.1.5 [Programming Techniques]: Object-oriented Programming; D.2.6 [Programming Environments]: Integrated environments; D.3.3 [Programming Languages]: Language Constructs and Features; F.3.3 [Studies of Program Constructs]: Type Structure General Terms Design, Languages Keywords Java, Trait, Type System, Implementation, Eclipse 1. Introduction The term trait was used by Ungar et al. [51] in the dynamically-typed prototype-based language SELF to denote a parent object to which an object may delegate some of its behavior. Subsequently, traits have been introduced by Schärl et al. [23, 45] in the dynamically-typed class-based language SQUEAK/SMALLTALK to play the role of units for behavior fine-grained reuse, in order to counter the problems of class-based inheritance with respect to code reuse (see, e.g., [19, 23, 36] for discussions and examples). A trait is a set of methods, completely independent from any class hierarchy. The common behavior (i.e., the common methods) of a set of classes can be factored into a trait, and traits can be composed to form other traits or classes. Two distinctive features of traits are that traits can be composed in arbitrary order and that composed traits or classes must resolve possible name conflicts explicitly. These features make traits more flexible and simpler than mixins [6, 17, 25, 28, 33]. Various formulations of traits in a JAVA-like setting can be found in the literature (see, e.g., [14, 15, 34, 37, 44, 46]). The recent programming language FORTRESS [5] incorporates a form of trait construct, while the “trait” construct incorporated in SCALA [38] is indeed a form of mixin. Records have been proposed in [14] as the counterpart of traits, with respect to state, to play the role of units for state fine-grained reuse. A record is a set of fields, completely independent from any class hierarchy. The common state (i.e., the common fields) of a set of classes can be factored into a record. In this paper, we present the programming language SUGARED WELTERWEIGHT RECORD-TRAIT JAVA (SWRTJ), a JAVA dialect using traits and records as composable units of behavior and state reuse, respectively, and aiming at interface-based polymorphism. SWRTJ is based on the calculus presented in [11] whose complete formalization and proof of type safety is available as a technical report in [10]. In SWRTJ, the declarations of object type, state, behavior and instance generation are completely separated. SWRTJ considers: - Interfaces, as pure types, defining only method signatures. - Records, as pure units of state reuse, defining only fields. - Traits, as pure units of behavior reuse, defining only methods. - Classes, as pure generators of instances, implementing interfaces by using traits and records, and defining constructors. In SWRTJ, like in FORTRESS, there is no class hierarchy and consequently no class-based inheritance. Multiple inheritance with respect to methods is obtained via the trait construct, and multiple inheritance with respect to fields is obtained via the record construct. Thus, multiple inheritance is subsumed by ensuring that, in the spirit of the original trait proposal in SQUEAK/SMALLTALK, the composite unit has complete control over the composition and must resolve conflicts explicitly. Although SWRTJ rules out class-based inheritance and relies on traits and records as the reuse mechanisms, class-based inheritance could be encoded with the existing concepts of SWRTJ as a syntactic sugar construct, as we will explain in Section 5. However, this “shortcut” might undermine the code reuse potential provided by traits and records leading back to the pitfalls of standard class- † This author has been supported by the Deutsche Forschungsgemeinschaft (DFG). Permission to make digital or hard copies of all or part of this work for personal or classroom use is granted without fee provided that copies are not made or distributed for profit or commercial advantage and that copies bear this notice and the full citation on the first page. To copy otherwise, to republish, to post on servers or to redistribute to lists, requires prior specific permission and/or a fee. PPSJ ’10, September 15–17, 2010, Vienna, Austria. Copyright © 2010 ACM 978-1-4503-0269-2/10...$10.00 1 WELTERWEIGHT refers to fact that the “weight” of SWRTJ lies between the weight of LIGHTWEIGHT JAVA [49] and MIDDLEWEIGHT JAVA [12], while SUGARED describes that the implemented language contains syntactic sugar not present in the underlying calculus [10, 11]. based inheritance. Furthermore, the introduction of class-based inheritance in SWRTJ is not necessary, since a SWRTJ program can be used in conjunction with any standard JAVA program. SWRTJ is a JAVA-dialect, and the SWRTJ compiler generates standard JAVA classes that do not depend on a specific library. Thus, a JAVA program can reuse SWRTJ interfaces and create standard JAVA objects using the code generated by the SWRTJ compiler. This technique can be used to combine code written in SWRTJ with JAVA libraries whose sources cannot be changed. For instance, SWRTJ objects can be passed to standard JAVA code provided the respective interfaces are compatible. The possibility of combining SWRTJ generated JAVA code with standard JAVA code can also be used to incrementally refactor JAVA class hierarchies into trait and record-based code. The refactoring can be done along the lines of [9], where we present an approach for identifying the methods in a JAVA class hierarchy that can be good candidates to be refactored in traits. SWRTJ is equipped with a JAVA-like nominal type system where the only user-defined types are interface names. This supports typechecking traits in isolation from traits and classes using them. In SCALA [38] and FORTRESS [5], each trait, as well as each class, also defines a type. But the role of unit of reuse and the role of type are competing, as already pointed out by Snyder [47] and Cook et al. [22]. In order to be able to define the subtyping relation on traits such that a trait is always a subtype of the component traits, both SCALA and FORTRESS rule out the method exclusion operation. (Method exclusion forms a new trait by removing a method from an existing trait.) However, without method exclusion, the reuse potential of traits is restricted. In SWRTJ, traits (as well as records and classes) do not define types. Thus, in SWRTJ method exclusion is supported and enhances the reuse potential of traits. This will be illustrated in Example 1 of Section 2. We present the implementation of SWRTJ using XTTEXT [4], a framework for the development of programming languages as well as other domain-specific languages (DSLs). The syntax of SWRTJ is defined in XTTEXT using an EBNF grammar. The XTTEXT generator creates a parser, an AST-meta model (implemented in EMF [48]) as well as a full-featured Eclipse-based editor for SWRTJ. Using the SWRTJ compiler, a SWRTJ program is translated into a standard JAVA program. The SWRTJ compiler can also be used as a command-line program, outside of the Eclipse IDE. The implementation described in the paper is based on [50]. The implementation of SWRTJ is available as an open source project at http://swrtj.sourceforge.net. Organizational Paper. In Section 2 we illustrate record and traits as supported in SWRTJ. In Section 3 and Section 4 we describe SWRTJ and its implementation. In Section 5 we discuss the features of our language and its impact on programming, and report on our experience with XTTEXT. Related work is discussed in Section 6. We conclude by outlining some future work. 2. Traits and Records in SWRTJ In this section we illustrate record and traits as supported in SWRTJ. We refer to Section 6 for a comparison of our features with respect to other trait constructs present in the literature. In SWRTJ, a trait consists of provided methods (i.e., methods defined in the trait), of required methods which parametrize the behavior, and of required fields that can be directly accessed in the body of the methods, along the lines of [11, 15]. Traits are building blocks to compose classes and other, more complex, traits. A suite of trait composition operations allows the programmer to build classes and composite traits. A distinguished characteristic of traits is that the composite unit (class or trait) has complete control over conflicts that may arise during composition and must solve them explicitly. Traits do not specify any state. Therefore a class composed by using traits has to provide the required fields through records, as explained in the following. The trait composition operations considered in SWRTJ are as follows: - A basic trait defines a set of methods and declares the required fields and the required methods. - The symmetric sum operation, +, merges two traits to form a new trait. It requires that the summed traits must be disjoint (that is, they must not provide identically named methods) and have compatible requirements (two requirements on the same method/field name are compatible if they are identical). - The operation exclude forms a new trait by removing a method from an existing trait. - The operation aliasAs forms a new trait by giving a new name to an existing method. When a recursive method is aliased, its recursive invocation refers to the original method (as in [23]). - The operation renameTo creates a new trait by renaming all the occurrences of a required field name or of a required/provided method name from an existing trait. Therefore, in SWRTJ, the actual names of the methods defined in a trait (and also the names of the required methods and fields) are irrelevant, since they can be changed by the renameTo operation. Records are building blocks to compose classes and other, more complex, records by means of operations analogous to the ones described above for traits. The record composition operations considered in SWRTJ are as follows: - A basic record defines a set of fields. - The symmetric sum operation, +, merges two disjoint records to form a new record. - The operation exclude forms a new record by removing a field from a record. - The operation renameTo creates a new record by renaming a field in a record. SWRTJ fosters the programming methodology based on design by interface, starting from declaring the services (methods) that our implementation components provide using a separate mechanism (the interface) which has only that aim; this naturally turns the interface in the only means to declare a type. The state and the implementations of such services are once again split into two different entities which can be reused separately, i.e., records and traits, respectively. Note that these blocks, records and traits, are pure units of reuse, and cannot be instantiated directly (this would undermine their usability). However, they can be used by the classes, which are the only means to assemble records and traits in order to implement interfaces and to instantiate objects. In the following, we illustrate the record and traits constructs of SWRTJ through examples (inspired by [15]) concerning the implementation of simple data structures. Example 1. Consider the task of developing a class Stack that implements the interface: ```java interface IStack { boolean isEmpty(); void push(Object o); Object pop(); } ``` In JAVA, the corresponding implementation would be a class as follows: ```java class Stack implements IStack { List l; Stack () { l = new ArrayList(); } boolean isEmpty () { return l.size () == 0; } void push (Object o) { l.add (First); } Object pop () { Object o = l.getFirst (); l.removeFirst (); return o; } } ``` Suppose that afterward a class implementing the following interface should be developed: interface ILifo { boolean isEmpty(); void push(Object o); void pop(); Object top(); } In JAVA there is no straightforward way to reuse the code in class Stack, as it would not be possible to override the pop method changing the return type from Object to void. In a language with traits and records, the fields and the methods of the class can be defined independently from the class itself. If the class Stack was originally developed in SWRTJ, it would have been written as follows (the interface IList and the class CArrayList, not shown here, have all the standard methods of lists and are part of the library of the language; they correspond to List and ArrayList in JAVA): record RElements is { IList l; } trait TStack is IList l; /* required field */ boolean isEmpty() { return (l.size() == 0); } void push(Object o) { l.addLast(o); } Object pop() { Object o = l.getLast(); l.removeFirst(); return o; } } class Stack implements IStack by RElements and TStack { Stack() { l = new CArrayList(); } } The record RElements and the trait TStack are completely independent from the code of class Stack. SWRTJ extends method reusability of traits to state reusability of records and fosters a programming style relying on small components that are easy to reuse. Because of the trait and record operations to exclude and rename methods and fields, they can be reused to develop completely unrelated classes. Based on this, a programmer would be able to write a class Lifo implementing the interface ILifo by reusing the record RElements and by defining a trait TLifo that reuses the trait TStack by exploiting the method exclusion operation: trait TLifo is (TStack[exclude pop]) + { IList l; /* required field */ boolean isEmpty(); /* required method */ boolean isNotEmpty() { return !isEmpty(); } void pop() { l.removeFirst(); } Object top() { return l.getFirst(); } } class Lifo implements ILifo by RElements and TLifo { Lifo() { l = new CArrayList(); } } The body of trait TLifo satisfies the requirements of trait sum operation described at the beginning of the section: the method pop is excluded thus it does not generate a conflict and the field requirement is identical to the one of TStack. This is a paradigmatic example of trait composition that does not preserve structural subtyping. If traits were types and composed traits were subtypes of the component traits (as in SCALA and FORTRESS), then the declaration of the trait TLifo would not typecheck, since: • the trait TLifo should provide all the methods provided by TStack, and • a method with signature Object pop() and a method with signature void pop() could not belong to the same trait/class. EXAMPLE 2. A class Queue that implements the interface interface IQueue { boolean isNotEmpty(); void enqueue(Object o); Object dequeue(); } can be written by defining a trait TQueue that reuses the record RElements and the trait TStack by renaming the method pop, excluding the method push and providing the methods enqueue and isNotEmpty: trait TQueue is (TStack[pop renameTo dequeue, exclude push]) + { IList l; /* required field */ boolean isEmpty(); /* required method */ boolean isNotEmpty() { return !isEmpty(); } void enqueue(Object o) { l.addLast(o); } } class Queue implements IQueue by RElements and TQueue { Queue() { l = new CArrayList(); } } Again, if traits were types and composed traits were subtypes of the component traits, then the declaration of the trait TQueue would not typecheck. SWRTJ traits and records satisfy the so called flattening principle, that has been introduced in the original formulation of traits in SQUEAK/SMALLTALK [23] (see also [30, 31, 37]) in order to provide a canonical semantics for traits. According to the flattening principle, the semantics of a method/field introduced in a class by a trait/record is identical to the semantics of the same method/field defined directly within the class. For instance, the semantics of the class Queue of Example 2 is identical to the semantics of the JAVA class: class Queue implements IQueue { List l; Queue() { l = new CArrayList(); } boolean isEmpty() { return (l.size() == 0); } boolean isNotEmpty() { return !isEmpty(); } void enqueue(Object o) { l.addLast(o); } Object dequeue() { Object o = l.getFirst(); l.removeFirst(); return o; } } We conclude this Section showing some possible alternative implementations of the data structures of Example 1. EXAMPLE 3. The class TLifo could be implemented, in terms of TStack also using renameTo: trait TLifo is (TStack[pop renameTo old_pop]) + { IList l; /* required field */ Object old_pop(); /* required method */ boolean isEmpty(); /* required method */ boolean isNotEmpty() { return !isEmpty(); } void pop() { old_pop(); } Object top() { return l.getFirst(); } } Alternatively, we could start by implementing TLifo and then implement TStack in terms of TLifo: trait TLifo is { IList l; /* required field */ boolean isEmpty() { return (l.size() == 0); } boolean isNotEmpty() { return !isEmpty(); } void push(Object o) { l.addLast(o); } void pop() { l.removeFirst(); } Object top() { return l.getFirst(); } } trait TStack is (TLifo[pop renameTo old_pop]) + { void old_pop(); /* required method */ Note that this alternative implementation is smaller, reuses more code, and makes the trait TStack independent from the actual IList field. 3. The SWRTJ Programming Language In this section we describe the syntax and semantics of the SWRTJ programming language, and we sketch the main features of its type system. Syntax. The syntax of SWRTJ is illustrated in Table 1 (without primitive types and file imports that are not relevant for this description). An interface can extend one or more interfaces. A class must implement one or more interfaces. In the syntax, the overline bar indicates a (possibly empty) list, as in FEATHERWEIGHT JAVA [29]. For instance, \( I = \overline{I_1, \ldots, I_n}, \ n \geq 0 \). The parameter declarations are denoted by \( \overline{x_1, \ldots, x_n} \) to indicate \( I_1 x_1, \ldots, I_n x_n \). The same notation can be applied to the other lists. In the syntax, \( m \) denotes a method name, \( f \) a field name and \( \alpha \) a local variable or parameter. Note that the grammar contains only the field access \( \texttt{this.}f \) (even for field assignment) because a field can be used only within a method (trait method or constructor) due to its private visibility. Variables and methods can only have an interface type. Trait expressions in trait composition operations do not have to be names of already defined traits: they can also be “anonymous” traits \( \{ \overline{F, S, H} \} \). The same holds for record expressions. This is in particular useful for traits, when a trait expression has to define some “glue” code for other traits used in a trait composition operation. In this way, there is no need to define a trait with a name only for that. An example of such usage is in the stream scenario, shown later, and in the examples of Section 2. The entry point of an SWRTJ program is specified by ``` program <name> { <expression> } ``` In the scope of the program, the implicit object \( \texttt{args} \) is the list of the program’s command line arguments. In SWRTJ traits, records and classes are not types in order to subdivide the roles of the different constructs. Moreover, as illustrated in Example 1, traits and records support exclusion operations that violate subtyping. Therefore, a type can be only an interface or a primitive type (e.g., int, boolean etc.). For simplicity, method overloading is not supported. Constructor overloading allows only the definition of constructors with different numbers of parameters within a class. Visibility modifiers are ruled out since they are not necessary. The traditional visibility modifiers are implied by the constructs used in SWRTJ as follows: - **private**: every instance variable is private. Since class is not a type, fields can be accessed only from the \( \texttt{this} \) parameter. Every provided method is private if it does not appear in the interfaces implemented by a class. Interfaces are the only way to make a method accessible from the outside. - **protected**: is not necessary since inheritance is ruled out. - **public**: every method declared in the interface implemented by a class is public. Fields cannot be public in order to support information hiding. The system library of SWRTJ provides interfaces such as IObject (implicitly extended by every interface), IInteger, IString etc. Every interface has a corresponding class implementing it, e.g., CObject, CInteger, etc. For synchronization mecha- isms, we provide the interface ILock (and the corresponding class CLock) with methods lock and unlock avoiding to introduce specific concurrency features in the language. In order to deal with collections, IList is an interface with typical list operations. CArrayList is the corresponding implementation class. The interfaces IPrintStream and IScanner, and their implicit “global” instances out and in can be used to perform basic operations such as writing to standard output and reading from standard input, respectively. Standard basic types, such as int, boolean, etc., are also provided. Methods can be declared as void with the usual meaning. Semantics. The semantics of SWRTJ is specified through a flattening function \( \llbracket \cdot \rrbracket \), given in Table 2, that translates a SWRTJ class declaration into a JAVA class declaration, a record expression into a sequence of fields declarations, and a trait expression into a sequence of method declarations. The clauses in Table 2 are self-explanatory. Note that, in the translation of trait expressions, the clause for field renaming is simpler than the clause for method renaming (which uses the auxiliary function \( \texttt{mR} \)); this is due to the fact that fields can be accessed only on \( \texttt{this} \). Type System. In this paper, we do not present the meta-theory of SWRTJ. We refer to [10] for the formalization of the FRTJ calculus on which SWRTJ is based. In this section, we provide an introduction to the typing of SWRTJ intended for the programmer. For simplicity, we will not consider void. The SWRTJ type system supports type-checking records and traits in isolation from classes that use them. Therefore, each trait and record definition has to be typechecked only once, i.e., every class can use a trait or a record without type-checking it again. This is more efficient and convenient in practice, e.g., if the trait/record source is not available. The basic idea of the type system is to collect constraints when checking traits and records, and to establish that these constraints hold when a class is declared, in order to ensure that the pseudo-variable \( \texttt{this} \) in all the methods of used traits can be used safely. In the SWRTJ type system, a nominal type is either a class name or an interface name. Note that in SWRTJ classes are not source types. Class names cannot be used as types in the code written by the programmer, but are used only internally by the compiler to type object creation expressions (\( \texttt{new C(\ldots)} \)). The type of \( \texttt{this} \) is an inferred structural type. The syntax for expression types is as follows \( \theta ::= I \mid C \mid (F \sigma) \) where \( I \) is an interface name, \( C \) is a class name and the \( (F \sigma) \) is the structural type for \( \texttt{this} \), which contains all the fields \( F \) and the signatures \( \sigma \) of the methods that can be selected on \( \texttt{this} \) in the context where the expression occurs. If the expression is a constructor call, such as \( \texttt{new C()} \), its type is the class \( C \); if the expression is \( \texttt{this} \), its type is \( (F \sigma) \); otherwise, the type of the method is an interface, for instance, if the expression is a method call, such as \( x.m() \), the type is the interface \( I \) declares as return type of the method \( m \). SWRTJ type system checks all requirements by inferring constraints. A constraint is a triple \( (F \sigma I) \) consisting of required fields, method signatures and interfaces collected while analyzing an expression. The constraints contain the types of every field and method selected on \( \texttt{this} \) and the name of every interface used, either as type in the methods parameters to which \( \texttt{this} \) is passed as argument or as return type in the methods in which \( \texttt{this} \) is returned. The subtyping relation is the reflexive and transitive closure of the immediate subinterfacing relation declared by the extends clauses in the interface definitions. The subtyping relation for nominal types is the reflexive and transitive closure of the relation obtained by extending subinterfacing with the interface implementa- In this section, we describe the implementation of SWRTJ using the Xtext [4] framework for Eclipse. Although Eclipse itself provides a framework for implementing an IDE for programming languages, this procedure is still quite laborious and requires a lot of manual programming. Xtext eases this task by providing a high- level framework that generates most of the typical and recurrent artifacts necessary for a fully-fledged IDE on top of Eclipse. The first task in Xtext is to write the grammar of the language using an EBNF-like syntax. Starting from this grammar, Xtext generates an ANTLR parser [39]. The generation of the abstract syntax tree is handled by Xtext as well. In particular, during parsing, the AST is generated in the shape of an EMF model (Eclipse Modeling Framework [48]). Thus, the manipulation of the AST can use all mechanisms provided by EMF itself. There is a direct correspondence between the names used in the rules of the grammar and the generated EMF model JAVA classes. For instance, if we have the following grammar snippet, ``` Message : MethodInvocation | FieldAccess; MethodInvocation : method=ID '('. argumentList=Expression ')'; ``` the Xtext framework generates the following EMF model JAVA interface (and the corresponding implementation class): ```java public interface MethodInvocation extends Message { MethodName getMethodName(); EList<Expression> getArgumentList(); } ``` Besides, Xtext generates many other classes for the editor for the language to be defined. The editor contains syntax highlighting, background parsing with error markers, outline view, code completion. Further, Xtext provides the infrastructure for code generation. Most of the code generated by Xtext can already be used off the shelf, but other parts can or have to be adapted by customizing some classes used in the framework. The usage of the customized classes is dealt with by relying on Google-Guice [1], so that the programmer does not have to maintain custom abstract factories [26]. In this way it is very easy to insert custom implementations into the framework (“injected” in Google-Guice terminology), with the guarantee that the custom classes will be used consistently throughout the code of the framework. The validation mechanisms for the language must be provided by the language developer. In our case, this is the SWRTJ type system. Implementing the validation mechanism in a compiler usually requires to write specific visitors for the abstract syntax tree. EMF already simplifies this task by providing a switch-like functionality to efficiently execute methods with dynamic dispatch according to the actual type of an AST node. Thus, there is no need to add code ### Table 1. SWRTJ syntax | ID | ::= | interface I extends I { S, } | interface definition | | RD | ::= | record R is RE | record definition | | TD | ::= | trait T is TE | trait definition | | CD | ::= | class C extends C by RE and TE { R } | class definition | | RE | ::= | [ F ] | trait expression | | TE | ::= | [ F, S, ] | trait expression | | R0 | ::= | exclude f if renameTo f | record field operation | ### Table 2. Flattening SWRTJ to JAVA | class C implements I by RE and TE { R } | = | | class C implements I { [RE] [TE] } | | [F:] | = | F | | R | = | [RE] | if RT(R) = record R is RE | | RE1 + RE2 | = | [RE1] | [RE2] | | RE|exclude f | = | exclude [RE],f | | RE|if renameTo f | = | [RE]''/''f | | [F; S; ] | = | H | | T | = | [TE] | if TT(T) = trait T is TE | | TE1 + TE2 | = | [TE1] | [TE2] | | TE|exclude m | = | exclude [TE],m | | TE|aliasAs m'' | = | M :: (m''(I x) MB) | | mR(I n(I x) MB),m,m' | = | I n''(I x) MB(this.m''/this.m) | | mR(M1;..;Mn,m,m'') | = | (mR(M1,m,m'')) .. (mR(Mn,m,m'')) | ### Example A classical example to show how traits can deal with situations where other mechanisms such as class inheritance do not fit well for code reuse, is the stream scenario, as in [23]. In Listing 1, we show the interfaces, records and traits for implementing a stream library, together with the corresponding classes and the main program. Note that the `ReadWriteStream` reuses the previously defined traits and resolves conflicts by method renaming. Furthermore, it contains “glue” code (in an anonymous trait) for the initialization of the fields of the composed traits. Similarly, the record `ReadWriteResource` reuses the resources defined in the records `ReadResource` and `WriteResource` by renaming the field `resource`. Note that, to keep the example simple, in the implementation of input methods, we simply assigned the global instances in and out for standard input and standard output, respectively. ### 4. Implementing SWRTJ In this section, we describe the implementation of SWRTJ using the Xtext [4] framework for Eclipse. Although Eclipse itself provides a framework for implementing an IDE for programming languages, this procedure is still quite laborious and requires a lot of manual programming. Xtext eases this task by providing a high- --- 2 The reader who is familiar with ANTLR will note that the syntax of Xtext grammars is very similar to ANTLR's syntax. to implement a visitor structure [26]. XTEXT leverages this mechanism by only requiring methods with a @Check annotation, that will be called automatically for validating the model according to the type of the AST node being checked. The validation takes place in the background, together with parsing, while the user is writing a SWRTJ program, so that an immediate feedback is available, as usually in IDEs. For instance, the following method in the SwrtjJavaValidator checks that the this variable is not used in the program context (i.e., that this can be used only in method bodies): ```java @Check public void thisCheck(ThissRule) { if((lookup.getOwner(thisRule) instanceof Program)) { showError("'this' is not allowed in program context", thisRule); } } ``` Note that the only important things in this method definition are the @Check annotation and the parameter: the internal validator of XTEXT will invoke this method when it needs to validate an AST node representing an occurrence of this, which is declared in the grammar as the This non-terminal symbol (remember that given a grammar symbol, XTEXT will generate a corresponding class for the AST with the same name). Binding the symbols (e.g., the binding of a field reference to its declaration) is important in compiler development. EMF uses "proxies" to represent references. It can delay the resolution (binding) of references when they are accessed. XTEXT already provides an implementation for binding references, which basically binds a reference to a symbol n to the first element definition with name n occurring in the model. This usually has to be adapted in order to take the visibility of names in a program into account. For instance, a field is visible only in the methods of a class, such that different hierarchies can safely have fields with the same name. XTEXT supports the customization of binding in an elegant way with the abstract concept of "scope". The actual binding is still performed by XTEXT, but it can be driven by providing the scope of a reference, i.e., all declarations that are available in the current context of a reference. Note that this also permits to filter out elements according to their kind, e.g., in order not to mix field names with method names if we need to resolve a reference to a field. The programmer can provide a customized AbstractDeclarationScopeProvider. XTEXT will search for methods to invoke, using reflection, according to a convention on method name signatures. Suppose, we have a rule ContextRuleName with an attribute ReferenceAttributeName assigned to a cross reference with TypeToReturnType type, that is used by the rule ContextType. You can create one or both of the following two methods ```java IView view, <ContextRuleName>, <ReferenceAttributeName> (<ContextType> ctx, IReferenceRef) ``` IView scope, <TypeToReturnType>(<ContextType> ctx, IReferenceRef) The XTEXT binding mechanism looks for the first method (by reflection), if this does not exist, then it looks for the second. If no such method exists, the default linking semantics (see above) is used. For instance, if we consider the grammar rule for method invocation illustrated at the beginning of this section, we can drive the resolution of the method name in a method invocation statement in any expression where such statement can occur by defining the following method (The code should be understandable without the knowledge of XTEXT): ```java public IView scope, MethodInvocation_method(Invocation context, EReferenceRef) { MethodType methodType = ExpressionType.createInstance(context.getMethod()); Collection<MethodDeclaration> methodList = methodType.getInvokableMethods(); methodList = new LinkedList<>(methodList); return Scopes.scopeFor(methodList); } ``` The scope provider will be used by XTEXT not only to solve references, but also to implement code completion. Thus, a programmer achieves two goals by implementing the abstract concept of scope. Note that the code above can also return an empty scope, e.g., if the receiver expression in a method call cannot be typed. In that case, the XTEXT framework generates an error due to an unresolved method name during validation, and an empty code completion list in case the programmer requests content assistance when writing the method name of a method invocation expression. This mechanism is handled by the framework itself, so that the programmer is completely relieved from these issues, once the correct scope provider is implemented. XTEXT provides a (mostly) automatic support for file import/inclusion in the developed language by using grammar rules like the following: ``` Import : 'import' importURI=STRING; ``` SWRTJ programs can be split into separate files, and include other SWRTJ files using the `import` keyword. The corresponding dependencies among source files are handled by XTEXT itself. Thus, the EMF model for the AST corresponding to an included file is available automatically in the current edited source. Moreover, the modification of an included file f automatically triggers the re-validation of all the files including f. Finally, the code generation phase is dealt with in XTEXT by relying on XPAND [5], a code generation framework based on "templates", specialized for code generation based on EMF models. This generation phase reuses the lookup functions and the type system functions used during validation. In our implementation of SWRTJ, code generation produces standard Java programs, which do not need any additional libraries to be compiled and executed. Our code generation phase implements the flattening procedure sketched in Section 2. However, by providing different templates, we could also generate C++ code (this is subject of future work), or code in another (possibly class-based) existing language. The following code is the main XPAND template for generating the Java code corresponding to a SWRTJ class: ``` <DEFINE class FOR Class --> <FILE this.uriToPackage() + "\" + this.name + ", " + java " --> package <this.uriToName>(); <EXPAND Commons::import FOREACH this.uriToNames()> public class <this.name> implements -->IF !this.implmentsList.isEmpty <EXPAND implements FOREACH this.implmentsList SEPARATOR ", " <<ENDIF>> <EXPAND Record::recordExpression FOR this.recordExpression --> <EXPAND constructorList FOR this.constructorList --> <EXPAND Trait::traitExpression FOR this.traitExpression --> <ENDIF> ``` An XPAND template consists of verbatim parts which will be output as they are and of parts to be expanded, enclosed in the special characters « and ». These parts can refer to other template files. Without getting into details of XPAND, it should be quite clear from the above code how the generation of a standard Java class is carried out, i.e., by copying the fields and methods of the records and traits, respectively, used by a SWRTJ class (with further adjustments not explained here). XTEXT generates three plugin projects: one for the language parser and corresponding validators, one for the code generator, and one for the user interface IDE parts. The first two plugins do not depend on the third. Thus, it is straightforward to build a standalone compiler for SWRTJ to be executed outside Eclipse on the command line, which we also provide. Figure 1 shows a screenshot of the SWRTJ editor. Note the code completion functionalities, the outline, and the error markers. The project view also shows the generated `JAVA` files. Our experience with XTEXT was in general quite positive. As usual, some time is required to get acquainted with the concepts of the framework. In particular, XTEXT relies on EMF. Thus, one should be familiar with EMF concepts as well, especially, when it comes to analyze the model for validation and code generation. However, after this knowledge is achieved, developing a language compiler and an IDE using XTEXT is extremely fast. XTEXT seems to be the right tool to experiment with language design and to develop implementations of languages. Furthermore, experimenting with new constructs in the language being developed can be handled straightforwardly. It requires to modify the grammar, regenerate XTEXT artifacts and to deal with the cases for the new constructs. Finally, XTEXT leaves the programmer with the possibility of customizing every aspect of the developed language implementation by specialized code (which is flexibly "injected" in XTEXT using Google Guice), even though XTEXT hides many internal details of IDE development with Eclipse. Even, EMF mechanisms are still open to adaptation. For instance, we developed a customized EMF resource factory for synthesizing the interfaces and classes of the internal library described in Section 3. This facilitates making interfaces and classes such as `IList` and `CArrayList` transparently available in every program (represented as an EMF model), without having to treat them differently in program validation. Concerning the performance of the generated `JAVA` code we did not experience any difference with respect to a possible manually implemented version. Indeed traits and records (and the SWRTJ versions of classes and interfaces) are static constructs which do not have any overhead in the generated `JAVA` code. With respect to XTEXT, there are other tools for implementing text editors (and IDE functionalities) in Eclipse. Tools like IMP (The IDE Meta-Tooling Platform) [2] and DLTK (Dynamic Languages Toolkit) [20] only deal with IDE functionalities and leave the parsing mechanism completely to the programmer, while XTEXT starts the development cycle right from the grammar itself. Another framework, closer to XTEXT is EMFText [27]. EMFText basically provides the same functionalities. But, instead of deriving a meta-model from the grammar, it does the opposite, i.e., the language to be implemented must be defined in an abstract way using an EMF meta model. (A meta model is a model describing a model, e.g., an UML class diagram describing the classes of a model). Note that XTEXT can also connect the grammar rules to an existing EMF meta model, instead of generating an EMF meta model starting from the grammar. XTEXT seems to be better documented than EMFText (indeed, both projects are still young and always under intense development), and more flexible, especially since it relies on Google Guice. On the other hand, EMFText offers a "language zoo" with many examples that can be used to start the development of another language. In this respect, the examples of languages implemented using XTEXT, that we found on the web, are simpler DSLs, and not programming languages like SWRTJ. Thus, this paper can also be seen as a report of effective usage of XTEXT for implementing more complex programming languages. 5. Discussion SWRTJ programs may look more verbose than standard class-based programs. However, the degree of reuse provided by records and traits is higher than the reuse potential of standard static class-based hierarchies. The distinction of each programming concept in a separate entity pays off in the long run, since each component is reusable in different contexts, in an unanticipated way. This does not happen so easily with standard class-based OO linguistic constructs. Class hierarchies need to be designed from the start with a specific reuse scenario in mind. In particular, for single inheritance, precise design decisions should be made from the very beginning. This design might be hard to change, if not impossible, forcing either to refactoring or to code duplication [36]. Our linguistic constructs are lower-level than standard OO mechanisms. However, some syntactic sugar can be added to reduce the amount of code to write in some situations. For instance: fields might also be declared directly in classes (thus encompassing the JAVA-like calculus proposed in [15]), class names might be used as types, etc. Along the same lines, we can simulate class inheritance with our linguistic constructs (thus encoding JAVA dialects, like [46], and programming environments, like [41], where traits coexist with class inheritance). This can be easily achieved by inverting the “flattening” concept. For instance, if we start from the JAVA-style class Stack given at the beginning of Example 1 in Section 2, we can easily separate fields and methods into automatically generated records and traits, and generate the corresponding SWRTJ class declaration. Similarly, inheritance and method overriding can be simulated with inherited interfaces and trait method renaming, respectively. The super call can be simulated with a call to the renamed version of the method. However, this would decrease the level of reuse for such components. This issue of having these additional constructs in the language is related to the debate of whether it is better to have a pure or hybrid programming language. In this respect, the purity of a language usually imposes more verbose solutions than a hybrid language. For instance, consider the amount of code for writing the main static public method of a public class in JAVA, and compare it to the simple form of the corresponding function in C++ which also provides functions besides classes and methods. The goal of reducing verbosity often led to additional language constructs which may break the pure linguistic features, e.g., the addition of imperative features to a purely functional language (see, e.g., OBJECTIVE CAML [42]). The general debate between pure and hybrid languages is out of the scope of the present paper. Nonetheless, we argue that having linguistic constructs for reusable code development eases adding other high-level linguistic constructs which otherwise may often only be possible at the cost of code duplication and of the resulting complexity of code maintenance. We might also introduce other syntactic sugar constructs to ease the programming with our language; for instance, instead of writing the required methods in a trait, we could group the required methods in a specific interface and let the trait “implement” that interface meaning that the trait requires all the methods specified in the interface. However, this would not make traits types, since as we stressed throughout the paper, not having traits types enhances their reuse potential. ### 6. Related Work Traits are well suited for designing libraries and enable clean design and reuse which has been shown using SMALLTALK/SQUEAK e.g., [13, 18]. Recently, [8] pointed out limitations of the trait... model caused by the fact that methods provided by a trait can only access state by accessor methods (which become required methods of the trait). To avoid this, traits are made stateful (in a SMALLTALK/SQUEAK-like setting) by adding private fields that can be accessed from the clients possibly under a new name or merged with other variables. In SWRTJ traits are stateless. By their required fields, however, it is possible to directly access state within the methods provided by a trait. Moreover, the names of required fields (in traits) and provided fields (in records) are unimportant because of the field rename operation. Since field renaming works synergically with method renaming, exclusion and aliasing, SWRTJ has more reuse potential. Concerning field requirements, they are not present in most formulation of traits in the SMALLTALK/SQUEAK-like and JAVA-like settings. They were introduced in the formulation of traits in a structurally typed setting by Fisher and Reppy [24]. SWRTJ requires that the summed traits must be disjoint. The disjoint requirement for composed traits was proposed by Snyder [47] for multiple class-based inheritance (see also the JIGSAW framework [16]). According to other proposals, two methods with the same name do not conflict if they are syntactically equal [23, 37] or if they originate from the same subtrait [34]. When a recursive method is aliased in our language, its recursive invocation refers to the original method (as in [23]). The variant of aliasing proposed in [34] (where, when a recursive method is aliased, its recursive invocation refers to the new method) can be straightforwardly encoded by exclusion, renaming and symmetric sum. Concerning method renaming and required field renaming, they are not present in most formulation of traits in the SMALLTALK/SQUEAK-like and JAVA-like settings. Method renaming has been introduced in the formulation of traits in a structurally typed setting by Reppy and Turon [43]. Renaming operations were already present in the JIGSAW framework [16] in connection with module composition and in the EIFFEL language [35] in connection with multiple class-based inheritance. In [44], a variant of traits that can be parametrized by member names (field and methods), types and values is proposed. Thus, the programmer can write trait functions that can be seen as code templates to be instantiated with different parameters. This enhances the code reuse provided by traits already. It could be interesting to adapt this approach to our context and to extend the parametrization functionalities also to interfaces, records and classes. This will be the subject of future work. However, an important difference between our proposal and the one in [44] is that, in the latter, traits play also the competing role of type, which is avoided in SWRTJ. Another feature of SWRTJ is that structural types are used only "internally" on this, i.e., the programmer works with nominal types (interfaces) alone. We believe this is an important feature from a practical point of view, as it reduces the distance between the classical JAVA-like languages and our linguistic constructs, from the perspective of the programmer. In [41] an Eclipse plugin is presented that supports JAVA programmers with using trait-like mechanisms for JAVA classes. JAVA is not extended: traits are modeled as (possibly) abstract classes and trait method requirements as abstract methods. The plugin also aims at helping the programmer to refactor JAVA hierarchies with traits: the programmer can select a set of methods to be extracted into stateless classes that play the role of traits. When a class uses a trait, the methods provided by the trait are copied into that class; the programmer then has to use this plugin to keep track of the actual source of a method, in order not to accidentally change the copy of a method and to be aware of what to change: either the copy of the class or the original method in the trait. Thus the programmer has to rely on this plugin completely, while in our case the SWRTJ compiler can be used also outside from Eclipse. The work of [41] starts from the one in [40] where traits are implemented directly as an extension of a subset of the JAVA language, and a compiler translates such programs into standard JAVA programs. The authors, however, state that such approach requires a strong effort to be conservative with respect to JAVA since, in order to generate well typed JAVA code, many type checking functionalities for JAVA related code must be implemented in their compiler. Such extension, moreover, lacks a formalization, thus no property of type safety for such language extension is available. In our approach, since we deal with a JAVA dialect, we can concentrate on the linguistic parts that are characteristic of our own language, without re-implementing JAVA checks. However, the code generated by our compiler is standard JAVA code, and our formalization guarantees that such code will be type correct with respect to the JAVA compiler (starting from a well-typed SWRTJ program). 7. Conclusions and Future Work In this paper, we presented the programming language SWRTJ and its implementation. SWRTJ is based on the calculus presented in [11]. In that paper, we considered mechanisms for code reuse for implementing Software Product Lines (a set of software systems with well-defined commonalities and variabilities [21]). We explored a novel approach to the development of SPL, which provides flexible code reuse with static guarantees. In order to be of effective use for SPL, the type-checking has to facilitate the analysis of newly added parts without re-checking already existing products. The SWRTJ type system (Section 3) satisfies this requirement since it supports type-checking records and traits in isolation from classes that use them. A special form of reuse is at the base of the contemporary agile software development methodologies, which are based on an iterative approach, where each iteration may include all of the phases necessary to release a small increment of a new functionality: planning, requirements analysis, design, coding, testing, and documentation. Another example is the use of Extreme Programming [7], where team members work on activities simultaneously. While an iteration may not add enough functionality to guarantee the release of a final product, an agile software project intends to be capable of releasing new software at the end of every iteration. However, this means that the next iteration will reuse the software produced in the previous ones. We believe that an interesting future research direction is to investigate whether the programming language features proposed in this paper may help in writing software following an agile methodology. In [9], we presented a tool for identifying the methods in a JAVA class hierarchy that could be good candidates to be refactored in traits (by adapting the SMALLTALK analysis tool of [32] to a JAVA setting). It will be interesting to investigate the application of this approach also for detecting possible candidates for records and traits in the context of porting existing JAVA code to SWRTJ code. Acknowledgments. We are grateful to the developers of XTEXT, in particular, Sven Efftinge and Sebastian Zarnekow, for their prompt help and support during the development of SWRTJ. We thank Viviana Bono for many discussions on the subject of this paper, Stéphane Ducasse for interesting discussions about traits, and Alexandre Bergel for insightful comments on the technical report [10]. References
{"Source-Url": "https://iris.unito.it/retrieve/handle/2318/81755/10990/main.pdf", "len_cl100k_base": 11647, "olmocr-version": "0.1.53", "pdf-total-pages": 11, "total-fallback-pages": 0, "total-input-tokens": 39760, "total-output-tokens": 12578, "length": "2e13", "weborganizer": {"__label__adult": 0.0003848075866699219, "__label__art_design": 0.0002275705337524414, "__label__crime_law": 0.0002307891845703125, "__label__education_jobs": 0.0004963874816894531, "__label__entertainment": 4.6193599700927734e-05, "__label__fashion_beauty": 0.0001360177993774414, "__label__finance_business": 0.00014209747314453125, "__label__food_dining": 0.000324249267578125, "__label__games": 0.00034880638122558594, "__label__hardware": 0.00043320655822753906, "__label__health": 0.0003006458282470703, "__label__history": 0.0001766681671142578, "__label__home_hobbies": 6.0617923736572266e-05, "__label__industrial": 0.00025081634521484375, "__label__literature": 0.0002287626266479492, "__label__politics": 0.0002199411392211914, "__label__religion": 0.00045609474182128906, "__label__science_tech": 0.0021610260009765625, "__label__social_life": 7.677078247070312e-05, "__label__software": 0.0029239654541015625, "__label__software_dev": 0.98974609375, "__label__sports_fitness": 0.0002803802490234375, "__label__transportation": 0.0003826618194580078, "__label__travel": 0.0001962184906005859}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 54691, 0.01038]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 54691, 0.6156]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 54691, 0.89203]], "google_gemma-3-12b-it_contains_pii": [[0, 1005, false], [1005, 6772, null], [6772, 14037, null], [14037, 19482, null], [19482, 27171, null], [27171, 32302, null], [32302, 36298, null], [36298, 43728, null], [43728, 46882, null], [46882, 54691, null], [54691, 54691, null]], "google_gemma-3-12b-it_is_public_document": [[0, 1005, true], [1005, 6772, null], [6772, 14037, null], [14037, 19482, null], [19482, 27171, null], [27171, 32302, null], [32302, 36298, null], [36298, 43728, null], [43728, 46882, null], [46882, 54691, null], [54691, 54691, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 54691, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 54691, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 54691, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 54691, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 54691, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 54691, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 54691, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 54691, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 54691, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 54691, null]], "pdf_page_numbers": [[0, 1005, 1], [1005, 6772, 2], [6772, 14037, 3], [14037, 19482, 4], [19482, 27171, 5], [27171, 32302, 6], [32302, 36298, 7], [36298, 43728, 8], [43728, 46882, 9], [46882, 54691, 10], [54691, 54691, 11]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 54691, 0.07047]]}
olmocr_science_pdfs
2024-12-04
2024-12-04
e66826ffebb024266a1568995591a1e313faa445
# Short Contents 1 Introduction ....................................................... 1 2 Code that Interacts with the User .......................... 3 3 Frontend Data Structures ................................. 5 4 Internals of Fortran 2003 OOP Features .............. 11 5 Generating the intermediate language for later stages. . 13 6 The LibGFortran Runtime Library ..................... 15 GNU Free Documentation License ............................... 17 Index .................................................................. 25 Table of Contents 1 Introduction ..................................... 1 2 Code that Interacts with the User .......... 3 2.1 Command-Line Options ...................... 3 2.2 Error Handling ................................ 3 3 Frontend Data Structures .................. 5 3.1 gfc_code ........................................ 5 3.1.1 IF Blocks ................................. 6 3.1.2 Loops ....................................... 6 3.1.3 SELECT Statements ...................... 6 3.1.4 BLOCK and ASSOCIATE .................. 6 3.2 gfc_expr ......................................... 7 3.2.1 Constants .................................. 7 3.2.2 Operators .................................. 7 3.2.3 Function Calls ........................... 7 3.2.4 Array- and Structure-Constructors ....... 8 3.2.5 Null ......................................... 8 3.2.6 Variables and Reference Expressions .... 8 3.2.7 Constant Substring References ........ 9 4 Internals of Fortran 2003 OOP Features .... 11 4.1 Type-bound Procedures ..................... 11 4.1.1 Specific Bindings ......................... 11 4.1.2 Generic Bindings .......................... 11 4.1.3 Calls to Type-bound Procedures .......... 11 4.2 Type-bound Operators ....................... 12 5 Generating the intermediate language for later stages.................................. 13 5.1 Basic data structures ....................... 13 5.2 Converting Expressions to tree ............ 13 5.3 Translating statements ..................... 14 5.4 Accessing declarations ..................... 14 6 The LibGFortran Runtime Library ............ 15 6.1 Symbol Versioning ............................. 15 GNU Free Documentation License ................ 17 ADDENDUM: How to use this License for your documents .... 24 Index ............................................. 25 1 Introduction This manual documents the internals of gfortran, the GNU Fortran compiler. Warning: This document, and the compiler it describes, are still under development. While efforts are made to keep it up-to-date, it might not accurately reflect the status of the most recent GNU Fortran compiler. At present, this manual is very much a work in progress, containing miscellaneous notes about the internals of the compiler. It is hoped that at some point in the future it will become a reasonably complete guide; in the interim, GNU Fortran developers are strongly encouraged to contribute to it as a way of keeping notes while working on the compiler. Chapter 2: Code that Interacts with the User 2 Code that Interacts with the User 2.1 Command-Line Options Command-line options for `gfortran` involve four interrelated pieces within the Fortran compiler code. The relevant command-line flag is defined in `lang.opt`, according to the documentation in Section “Options” in GNU Compiler Collection Internals. This is then processed by the overall GCC machinery to create the code that enables `gfortran` and `gcc` to recognize the option in the command-line arguments and call the relevant handler function. This generated code calls the `gfc_handle_option` code in `options.c` with an enumerator variable indicating which option is to be processed, and the relevant integer or string values associated with that option flag. Typically, `gfc_handle_option` uses these arguments to set global flags which record the option states. The global flags that record the option states are stored in the `gfc_option_t` struct, which is defined in `gfortran.h`. Before the options are processed, initial values for these flags are set in `gfc_init_option` in `options.c`; these become the default values for the options. 2.2 Error Handling The GNU Fortran compiler’s parser operates by testing each piece of source code against a variety of matchers. In some cases, if these matchers do not match the source code, they will store an error message in a buffer. If the parser later finds a matcher that does correctly match the source code, then the buffered error is discarded. However, if the parser cannot find a match, then the buffered error message is reported to the user. This enables the compiler to provide more meaningful error messages even in the many cases where (erroneous) Fortran syntax is ambiguous due to things like the absence of reserved keywords. As an example of how this works, consider the following line: ``` IF = 3 ``` Hypothetically, this may get passed to the matcher for an `IF` statement. Since this could plausibly be an erroneous `IF` statement, the matcher will buffer an error message reporting the absence of an expected ‘(’ following an `IF`. Since no matchers reported an error-free match, however, the parser will also try matching this against a variable assignment. When `IF` is a valid variable, this will be parsed as an assignment statement, and the error discarded. However, when `IF` is not a valid variable, this buffered error message will be reported to the user. The error handling code is implemented in `error.c`. Errors are normally entered into the buffer with the `gfc_error` function. Warnings go through a similar buffering process, and are entered into the buffer with `gfc_warning`. There is also a special-purpose function, `gfc_notify_std`, for things which have an error/warning status that depends on the currently-selected language standard. The `gfc_error_check` function checks the buffer for errors, reports the error message to the user if one exists, clears the buffer, and returns a flag to the user indicating whether or not an error existed. To check the state of the buffer without changing its state or reporting the errors, the `gfc_error_flag_test` function can be used. The `gfc_clear_error` function will clear out any errors in the buffer, without reporting them. The `gfc_warning_check` and `gfc_clear_warning` functions provide equivalent functionality for the warning buffer. Only one error and one warning can be in the buffers at a time, and buffering another will overwrite the existing one. In cases where one may wish to work on a smaller piece of source code without disturbing an existing error state, the `gfc_push_error`, `gfc_pop_error`, and `gfc_free_error` mechanism exists to implement a stack for the error buffer. For cases where an error or warning should be reported immediately rather than buffered, the `gfc_error_now` and `gfc_warning_now` functions can be used. Normally, the compiler will continue attempting to parse the program after an error has occurred, but if this is not appropriate, the `gfc_fatal_error` function should be used instead. For errors that are always the result of a bug somewhere in the compiler, the `gfc_internal_error` function should be used. The syntax for the strings used to produce the error/warning message in the various error and warning functions is similar to the `printf` syntax, with `%`-escapes to insert variable values. The details, and the allowable codes, are documented in the `error_print` function in ‘error.c’. 3 Frontend Data Structures This chapter should describe the details necessary to understand how the various gfc_* data are used and interact. In general it is advisable to read the code in ‘dump-parse-tree.c’, as its routines should exhaust all possible valid combinations of content for these structures. 3.1 gfc_code The executable statements in a program unit are represented by a nested chain of gfc_code structures. The type of statement is identified by the op member of the structure, the different possible values are enumerated in gfc_exec_op. A special member of this enum is EXEC_NOP which is used to represent the various END statements if they carry a label. Depending on the type of statement some of the other fields will be filled in. Fields that are generally applicable are the next and here fields. The former points to the next statement in the current block or is NULL if the current statement is the last in a block, here points to the statement label of the current statement. If the current statement is one of IF, DO, SELECT it starts a block, i.e. a nested level in the program. In order to represent this, the block member is set to point to a gfc_code structure whose next member starts the chain of statements inside the block; this structure’s op member should be set to the same value as the parent structure’s op member. The SELECT and IF statements may contain various blocks (the chain of ELSE IF and ELSE blocks or the various CASEs, respectively). These chains are linked-lists formed by the block members. Consider the following example code: ```fortran IF (foo < 20) THEN PRINT *, "Too small" foo = 20 ELSEIF (foo > 50) THEN PRINT *, "Too large" foo = 50 ELSE PRINT *, "Good" END IF ``` This statement-block will be represented in the internal gfortran tree as follows, were the horizontal link-chains are those induced by the next members and vertical links down are those of block. ‘==|’ and ‘--|’ mean NULL pointers to mark the end of a chain: ``` ... ==> IF ==> ... | | +--> IF foo < 20 ==> PRINT *, "Too small" ==> foo = 20 ==| | | +--> IF foo > 50 ==> PRINT *, "Too large" ==> foo = 50 ==| | | | +--> ELSE ==> PRINT *, "Good" ==| | | +--| | | | +---| | | | +---| +--| ``` 3.1.1 IF Blocks Conditionals are represented by `gfc_code` structures with their `op` member set to `EXEC_IF`. This structure’s `block` member must point to another `gfc_code` node that is the header of the if-block. This header’s `op` member must be set to `EXEC_IF`, too, its `expr` member holds the condition to check for, and its `next` should point to the code-chain of the statements to execute if the condition is true. If in addition an `ELSEIF` or `ELSE` block is present, the `block` member of the if-block-header node points to yet another `gfc_code` structure that is the header of the elseif- or else-block. Its structure is identical to that of the if-block-header, except that in case of an `ELSE` block without a new condition the `expr` member should be `NULL`. This block can itself have its `block` member point to the next `ELSEIF` or `ELSE` block if there’s a chain of them. 3.1.2 Loops `DO` loops are stored in the tree as `gfc_code` nodes with their `op` set to `EXEC_DO` for a `DO` loop with iterator variable and to `EXEC_DO_WHILE` for infinite `DO`s and `DO WHILE` blocks. Their `block` member should point to a `gfc_code` structure heading the code-chain of the loop body; its `op` member should be set to `EXEC_DO` or `EXEC_DO_WHILE`, too, respectively. For `DO WHILE` loops, the loop condition is stored on the top `gfc_code` structure’s `expr` member; `DO` forever loops are simply `DO WHILE` loops with a constant `.TRUE.` loop condition in the internal representation. Similarly, `DO` loops with an iterator have instead of the condition their `ext.iterator` member set to the correct values for the loop iterator variable and its range. 3.1.3 SELECT Statements A `SELECT` block is introduced by a `gfc_code` structure with an `op` member of `EXEC_SELECT` and `expr` containing the expression to evaluate and test. Its `block` member starts a list of `gfc_code` structures linked together by their `block` members that stores the various `CASE` parts. Each `CASE` node has its `op` member set to `EXEC_SELECT`, too, its `next` member points to the code-chain to be executed in the current case-block, and `extx.case_list` contains the case-values this block corresponds to. The `block` member links to the next case in the list. 3.1.4 BLOCK and ASSOCIATE The code related to a `BLOCK` statement is stored inside an `gfc_code` structure (say `c`) with `c.op` set to `EXEC_BLOCK`. The `gfc_namespace` holding the locally defined variables of the `BLOCK` is stored in `c.ext.block.ns`. The code inside the construct is in `c.code` `ASSOCIATE` constructs are based on `BLOCK` and thus also have the internal storage structure described above (including `EXEC_BLOCK`). However, for them `c.ext.block.assoc` is set additionally and points to a linked list of `gfc_association_list` structures. Those structures basically store a link of associate-names to target expressions. The associate-names themselves are still added to the `BLOCK`’s namespace as ordinary symbols, but they have their `gfc_symbol`’s member `assoc` set also pointing to the association-list structure. This way associate-names can be distinguished from ordinary variables and their target expressions identified. For association to expressions (as opposed to variables), at the very beginning of the BLOCK construct assignments are automatically generated to set the corresponding variables to their target expressions' values, and later on the compiler simply disallows using such associate-names in contexts that may change the value. 3.2 gfc_expr Expressions and “values”, including constants, variable-, array- and component-references as well as complex expressions consisting of operators and function calls are internally represented as one or a whole tree of gfc_expr objects. The member expr_type specifies the overall type of an expression (for instance, EXPR_CONSTANT for constants or EXPR_VARIABLE for variable references). The members ts and rank as well as shape, which can be NULL, specify the type, rank and, if applicable, shape of the whole expression or expression tree of which the current structure is the root. where is the locus of this expression in the source code. Depending on the flavor of the expression being described by the object (that is, the value of its expr_type member), the corresponding structure in the value union will usually contain additional data describing the expression’s value in a type-specific manner. The ref member is used to build chains of (array-, component- and substring-) references if the expression in question contains such references, see below for details. 3.2.1 Constants Scalar constants are represented by gfc_expr nodes with their expr_type set to EXPR_CONSTANT. The constant’s value shall already be known at compile-time and is stored in the logical, integer, real, complex or character struct inside value, depending on the constant’s type specification. 3.2.2 Operators Operator-expressions are expressions that are the result of the execution of some operator on one or two operands. The expressions have an expr_type of EXPR_OP. Their value.op structure contains additional data. op1 and optionally op2 if the operator is binary point to the two operands, and operator or uop describe the operator that should be evaluated on these operands, where uop describes a user-defined operator. 3.2.3 Function Calls If the expression is the return value of a function-call, its expr_type is set to EXPR_FUNCTION, and symtree must point to the symtree identifying the function to be called. value.function.actual holds the actual arguments given to the function as a linked list of gfc_actual_arglist nodes. The other members of value.function describe the function being called in more detail, containing a link to the intrinsic symbol or user-defined function symbol if the call is to an intrinsic or external function, respectively. These values are determined during resolution-phase from the structure’s symtree member. A special case of function calls are “component calls” to type-bound procedures; those have the expr_type EXPR_COMPCALL with value.compcall containing the argument list and the procedure called, while symtree and ref describe the object on which the procedure was called in the same way as a EXPR_VARIABLE expression would. See Section 4.1 [Type-bound Procedures], page 11. ### 3.2.4 Array- and Structure-Constructors Array- and structure-constructors (one could probably call them “array-” and “derived-type constants”) are gfc_expr structures with their expr_type member set to EXPR_ARRAY or EXPR_STRUCTURE, respectively. For structure constructors, symtree points to the derived-type symbol for the type being constructed. The values for initializing each array element or structure component are stored as linked-list of gfc_constructor nodes in the value.constructor member. ### 3.2.5 Null NULL is a special value for pointers; it can be of different base types. Such a NULL value is represented in the internal tree by a gfc_expr node with expr_type EXPR_NULL. If the base type of the NULL expression is known, it is stored in ts (that’s for instance the case for default-initializers of ALLOCATABLE components), but this member can also be set to BT_UNKNOWN if the information is not available (for instance, when the expression is a pointer-initializer NULL()). ### 3.2.6 Variables and Reference Expressions Variable references are gfc_expr structures with their expr_type set to EXPR_VARIABLE; their symtree should point to the variable that is referenced. For this type of expression, it’s also possible to chain array-, component- or substring-references to the original expression to get something like ‘struct%component(2:5)’, where component is either an array or a CHARACTER member of struct that is of some derived-type. Such a chain of references is achieved by a linked list headed by ref of the gfc_expr node. For the example above it would be (‘==|’ is the last NULL pointer): ``` EXPR_VARIABLE(struct) ==> REF_COMPONENT(component) ==> REF_ARRAY(2:5) ==| ``` If component is a string rather than an array, the last element would be a REF_SUBSTRING reference, of course. If the variable itself or some component referenced is an array and the expression should reference the whole array rather than being followed by an array-element or -section reference, a REF_ARRAY reference must be built as the last element in the chain with an array-reference type of AR_FULL. Consider this example code: ```fortran TYPE :: mytype INTEGER :: array(42) END TYPE mytype TYPE(mytype) :: variable INTEGER :: local_array(5) CALL do_something (variable%array, local_array) ``` The gfc_expr nodes representing the arguments to the ‘do_something’ call will have a reference-chain like this: ``` EXPR_VARIABLE(variable) ==> REF_COMPONENT(array) ==> REF_ARRAY(FULL) ==| EXPR_VARIABLE(local_array) ==> REF_ARRAY(FULL) ==| ``` 3.2.7 Constant Substring References EXPR_SUBSTRING is a special type of expression that encodes a substring reference of a constant string, as in the following code snippet: ```c x = "abcde"(1:2) ``` In this case, `value.character` contains the full string’s data as if it was a string constant, but the `ref` member is also set and points to a substring reference as described in the subsection above. 4 Internals of Fortran 2003 OOP Features 4.1 Type-bound Procedures Type-bound procedures are stored in the `tb_sym_root` of the namespace `f2k_derived` associated with the derived-type symbol as `gfc_symtree` nodes. The name and symbol of these symtrees corresponds to the binding-name of the procedure, i.e. the name that is used to call it from the context of an object of the derived-type. In addition, this type of symtrees stores in `n.tb` a struct of type `gfc_typebound_proc` containing the additional data needed: The binding attributes (like `PASS` and `NOPASS`, `NON_OVERRIDABLE` or the access-specifier), the binding’s target(s) and, if the current binding overrides or extends an inherited binding of the same name, `overridden` points to this binding’s `gfc_typebound_proc` structure. 4.1.1 Specific Bindings For specific bindings (declared with `PROCEDURE`), if they have a passed-object argument, the passed-object dummy argument is first saved by its name, and later during resolution phase the corresponding argument is looked for and its position remembered as `pass_arg_num` in `gfc_typebound_proc`. The binding’s target procedure is pointed-to by `u.specific`. `DEFERRED` bindings are just like ordinary specific bindings, except that their `deferred` flag is set of course and that `u.specific` points to their “interface” defining symbol (might be an abstract interface) instead of the target procedure. At the moment, all type-bound procedure calls are statically dispatched and transformed into ordinary procedure calls at resolution time; their actual argument list is updated to include at the right position the passed-object argument, if applicable, and then a simple procedure call to the binding’s target procedure is built. To handle dynamic dispatch in the future, this will be extended to allow special code generation during the trans-phase to dispatch based on the object’s dynamic type. 4.1.2 Generic Bindings Bindings declared as `GENERIC` store the specific bindings they target as a linked list using nodes of type `gfc_tbp_generic` in `u.generic`. For each specific target, the parser records its symtree and during resolution this symtree is bound to the corresponding `gfc_typebound_proc` structure of the specific target. Calls to generic bindings are handled entirely in the resolution-phase, where for the actual argument list present the matching specific binding is found and the call’s target procedure (value.compcall.tbp) is re-pointed to the found specific binding and this call is subsequently handled by the logic for specific binding calls. 4.1.3 Calls to Type-bound Procedures Calls to type-bound procedures are stored in the parse-tree as `gfc_expr` nodes of type `EXPR_COMPCALL`. Their `value.compcall.actual` saves the actual argument list of the call and `value.compcall.tbp` points to the `gfc_typebound_proc` structure of the binding to be called. The object in whose context the procedure was called is saved by combination of `symtree` and `ref`, as if the expression was of type `EXPR_VARIABLE`. For code like this: ```fortran CALL myobj%procedure (arg1, arg2) ``` the `CALL` is represented in the parse-tree as a `gfc_code` node of type `EXEC_COMPCALL`. The `expr` member of this node holds an expression of type `EXPR_COMPCALL` of the same structure as mentioned above except that its target procedure is of course a `SUBROUTINE` and not a `FUNCTION`. Expressions that are generated internally (as expansion of a type-bound operator call) may also use additional flags and members. `value.compcall.ignore_pass` signals that even though a `PASS` attribute may be present the actual argument list should not be updated because it already contains the passed-object. `value.compcall.base_object` overrides, if it is set, the base-object (that is normally stored in `symtree` and `ref` as mentioned above); this is needed because type-bound operators can be called on a base-object that need not be of type `EXPR_VARIABLE` and thus representable in this way. Finally, if `value.compcall.assign` is set, the call was produced in expansion of a type-bound assignment; this means that proper dependency-checking needs to be done when relevant. ### 4.2 Type-bound Operators Type-bound operators are in fact basically just `GENERIC` procedure bindings and are represented much in the same way as those (see Section 4.1 [Type-bound Procedures], page 11). They come in two flavours: User-defined operators (like `.MYOPERATOR.`) are stored in the `f2k_derived` namespace’s `tb_uop_root` symtree exactly like ordinary type-bound procedures are stored in `tb_sym_root`; their symtrees’ names are the operator-names (e.g. ‘`myoperator`’ in the example). Intrinsic operators on the other hand are stored in the namespace’s array member `tb_op` indexed by the intrinsic operator’s enum value. Those need not be packed into `gfc_symtree` structures and are only `gfc_typebound_proc` instances. When an operator call or assignment is found that cannot be handled in another way (i.e. neither matches an intrinsic nor interface operator definition) but that contains a derived-type expression, all type-bound operators defined on that derived-type are checked for a match with the operator call. If there’s indeed a relevant definition, the operator call is replaced with an internally generated `GENERIC` type-bound procedure call to the respective definition and that call is further processed. 5 Generating the intermediate language for later stages. This chapter deals with the transformation of gfortran’s frontend data structures to the intermediate language used by the later stages of the compiler, the so-called middle end. Data structures relating to this are found in the source files ‘trans*.h’ and ‘trans-* .c’. 5.1 Basic data structures Gfortran creates GENERIC as an intermediate language for the middle-end. Details about GENERIC can be found in the GCC manual. The basic data structure of GENERIC is a tree. Everything in GENERIC is a tree, including types and statements. Fortunately for the gfortran programmer, tree variables are garbage-collected, so doing memory management for them is not necessary. Tree expressions are built using functions such as, for example, fold_build2_loc. For two tree variables a and b, both of which have the type gfc_arr_index_type, calculation c = a * b would be done by \[ c = \text{fold\_build2\_loc (input\_location, \text{MULT\_EXPR}, gfc\_array\_index\_type, a, b);}\] The types have to agree, otherwise internal compiler errors will occur at a later stage. Expressions can be converted to a different type using fold_convert. Accessing individual members in the tree structures should not be done. Rather, access should be done via macros. One basic data structure is the stmtblock_t struct. This is used for holding a list of statements, expressed as tree expressions. If a block is created using gfc_start_block, it has its own scope for variables; if it is created using gfc_init_block, it does not have its own scope. It is possible to - Add an expression to the end of a block using gfc_add_expr_to_block - Add an expression to the beginning of a block using void gfc_prepend_expr_to_block - Make a block into a single tree using gfc_finish_block. For example, this is needed to put the contents of a block into the if or else branch of a COND_EXPR. Variables are also tree expressions, they can be created using gfc_create_var. Assigning to a variable can be done with gfc_add_modify. An example: Creating a default integer type variable in the current scope with the prefix “everything” in the stmt_block block and assigning the value 42 would be ```c tree var, *block; /* Initialize block somewhere here. */ var = gfc_create_var (integer_type_node, "everything"); gfc_add_modify (block, var, build_int_cst (integer_type_node, 42)); ``` 5.2 Converting Expressions to tree Converting expressions to tree is done by functions called gfc_conv_*. The central data structure for a GENERIC expression is the gfc_se structure. Its expr member is a tree that holds the value of the expression. A gfc_se structure is initialized using gfc_init_se; it needs to be embedded in an outer gfc_se. Evaluating Fortran expressions often require things to be done before and after evaluation of the expression, for example code for the allocation of a temporary variable and its subsequent deallocation. Therefore, `gfc_se` contains the members `pre` and `post`, which point to `stmt_block` blocks for code that needs to be executed before and after evaluation of the expression. When using a local `gfc_se` to convert some expression, it is often necessary to add the generated `pre` and `post` blocks to the `pre` or `post` blocks of the outer `gfc_se`. Code like this (lifted from `trans-expr.c`) is fairly common: ```c /* cont_var = is_contiguous (expr); */ gfc_init_se (&cont_se, parmse); gfc_conv_is_contiguous_expr (&cont_se, expr); gfc_add_block_to_block (&se->pre, &(&cont_se)->pre); gfc_add_modify (&se->pre, cont_var, cont_se.expr); gfc_add_block_to_block (&se->pre, &(&cont_se)->post); ``` Conversion functions which need a `gfc_se` structure will have a corresponding argument. `gfc_se` also contains pointers to a `gfc_ss` and a `gfc_loopinfo` structure. These are needed by the scalarizer. ### 5.3 Translating statements Translating statements to `tree` is done by functions called `gfc_trans_*`. These functions usually get passed a `gfc_code` structure, evaluate any expressions and then return a `tree` structure. ### 5.4 Accessing declarations `gfc_symbol`, `gfc_charlen` and other front-end structures contain a `backend_decl` variable, which contains the `tree` used for accessing that entity in the middle-end. Accessing declarations is usually done by functions called `gfc_get*`. Chapter 6: The LibGFortran Runtime Library 6 The LibGFortran Runtime Library 6.1 Symbol Versioning In general, this capability exists only on a few platforms, thus there is a need for configure magic so that it is used only on those targets where it is supported. The central concept in symbol versioning is the so-called map file, which specifies the version node(s) exported symbols are labeled with. Also, the map file is used to hide local symbols. Some relevant references: - GNU ld manual - ELF Symbol Versioning - Ulrich Depper - How to Write Shared Libraries - Ulrich Drepper (see Chapter 3) If one adds a new symbol to a library that should be exported, the new symbol should be mentioned in the map file and a new version node defined, e.g., if one adds a new symbols foo and bar to libgfortran for the next GCC release, the following should be added to the map file: ```plaintext GFORTRAN_1.1 { global: foo; bar; } GFORTRAN_1.0; ``` where GFORTRAN_1.0 is the version node of the current release, and GFORTRAN_1.1 is the version node of the next release where foo and bar are made available. If one wants to change an existing interface, it is possible by using some asm trickery (from the ld manual referenced above): ```plaintext __asm__(".symver original_foo,foo@") __asm__(".symver old_foo,foo@VERS_1.1") __asm__(".symver old_foo1,foo@VERS_1.2") __asm__(".symver new_foo,foo@VERS_2.0") ``` In this example, foo@ represents the symbol foo bound to the unspecified base version of the symbol. The source file that contains this example would define 4 C functions: original_foo, old_foo, old_foo1, and new_foo. In this case the map file must contain foo in VERS_1.1 and VERS_1.2 as well as in VERS_2.0. GNU Free Documentation License Version 1.3, 3 November 2008 http://fsf.org/ Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. 0. PREAMBLE The purpose of this License is to make a manual, textbook, or other functional and useful document free in the sense of freedom: to assure everyone the effective freedom to copy and redistribute it, with or without modifying it, either commercially or non-commercially. Secondarily, this License preserves for the author and publisher a way to get credit for their work, while not being considered responsible for modifications made by others. This License is a kind of “copyleft”, which means that derivative works of the document must themselves be free in the same sense. It complements the GNU General Public License, which is a copyleft license designed for free software. We have designed this License in order to use it for manuals for free software, because free software needs free documentation: a free program should come with manuals providing the same freedoms that the software does. But this License is not limited to software manuals; it can be used for any textual work, regardless of subject matter or whether it is published as a printed book. We recommend this License principally for works whose purpose is instruction or reference. 1. APPLICABILITY AND DEFINITIONS This License applies to any manual or other work, in any medium, that contains a notice placed by the copyright holder saying it can be distributed under the terms of this License. Such a notice grants a world-wide, royalty-free license, unlimited in duration, to use that work under the conditions stated herein. The “Document”, below, refers to any such manual or work. Any member of the public is a licensee, and is addressed as “you”. You accept the license if you copy, modify or distribute the work in a way requiring permission under copyright law. A “Modified Version” of the Document means any work containing the Document or a portion of it, either copied verbatim, or with modifications and/or translated into another language. A “Secondary Section” is a named appendix or a front-matter section of the Document that deals exclusively with the relationship of the publishers or authors of the Document to the Document’s overall subject (or to related matters) and contains nothing that could fall directly within that overall subject. (Thus, if the Document is in part a textbook of mathematics, a Secondary Section may not explain any mathematics.) The relationship could be a matter of historical connection with the subject or with related matters, or of legal, commercial, philosophical, ethical or political position regarding them. The “Invariant Sections” are certain Secondary Sections whose titles are designated, as being those of Invariant Sections, in the notice that says that the Document is released under this License. If a section does not fit the above definition of Secondary then it is not allowed to be designated as Invariant. The Document may contain zero Invariant Sections. If the Document does not identify any Invariant Sections then there are none. The “Cover Texts” are certain short passages of text that are listed, as Front-Cover Texts or Back-Cover Texts, in the notice that says that the Document is released under this License. A Front-Cover Text may be at most 5 words, and a Back-Cover Text may be at most 25 words. A “Transparent” copy of the Document means a machine-readable copy, represented in a format whose specification is available to the general public, that is suitable for revising the document straightforwardly with generic text editors or (for images com- posed of pixels) generic paint programs or (for drawings) some widely available drawing editor, and that is suitable for input to text formatters or for automatic translation to a variety of formats suitable for input to text formatters. A copy made in an otherwise Transparent file format whose markup, or absence of markup, has been arranged to thwart or discourage subsequent modification by readers is not Transparent. An image format is not Transparent if used for any substantial amount of text. A copy that is not “Transparent” is called “Opaque”. Examples of suitable formats for Transparent copies include plain ascii without markup, Texinfo input format, LaT\TeX{} input format, SGML or XML using a publicly available DTD, and standard-conforming simple HTML, PostScript or PDF designed for human modification. Examples of transparent image formats include PNG, XCF and JPG. Opaque formats include proprietary formats that can be read and edited only by proprietary word processors, SGML or XML for which the DTD and/or processing tools are not generally available, and the machine-generated HTML, PostScript or PDF produced by some word processors for output purposes only. The “Title Page” means, for a printed book, the title page itself, plus such following pages as are needed to hold, legibly, the material this License requires to appear in the title page. For works in formats which do not have any title page as such, “Title Page” means the text near the most prominent appearance of the work’s title, preceding the beginning of the body of the text. The “publisher” means any person or entity that distributes copies of the Document to the public. A section “Entitled XYZ” means a named subunit of the Document whose title either is precisely XYZ or contains XYZ in parentheses following text that translates XYZ in another language. (Here XYZ stands for a specific section name mentioned below, such as “Acknowledgements”, “Dedications”, “Endorsements”, or “History”.) To “Preserve the Title” of such a section when you modify the Document means that it remains a section “Entitled XYZ” according to this definition. The Document may include Warranty Disclaimers next to the notice which states that this License applies to the Document. These Warranty Disclaimers are considered to be included by reference in this License, but only as regards disclaiming warranties: any other implication that these Warranty Disclaimers may have is void and has no effect on the meaning of this License. 2. VERBATIM COPYING You may copy and distribute the Document in any medium, either commercially or noncommercially, provided that this License, the copyright notices, and the license notice saying this License applies to the Document are reproduced in all copies, and that you add no other conditions whatsoever to those of this License. You may not use technical measures to obstruct or control the reading or further copying of the copies you make or distribute. However, you may accept compensation in exchange for copies. If you distribute a large enough number of copies you must also follow the conditions in section 3. You may also lend copies, under the same conditions stated above, and you may publicly display copies. 3. COPYING IN QUANTITY If you publish printed copies (or copies in media that commonly have printed covers) of the Document, numbering more than 100, and the Document’s license notice requires Cover Texts, you must enclose the copies in covers that carry, clearly and legibly, all these Cover Texts: Front-Cover Texts on the front cover, and Back-Cover Texts on the back cover. Both covers must also clearly and legibly identify you as the publisher of these copies. The front cover must present the full title with all words of the title equally prominent and visible. You may add other material on the covers in addition. Copying with changes limited to the covers, as long as they preserve the title of the Document and satisfy these conditions, can be treated as verbatim copying in other respects. If the required texts for either cover are too voluminous to fit legibly, you should put the first ones listed (as many as fit reasonably) on the actual cover, and continue the rest onto adjacent pages. If you publish or distribute Opaque copies of the Document numbering more than 100, you must either include a machine-readable Transparent copy along with each Opaque copy, or state in or with each Opaque copy a computer-network location from which the general network-using public has access to download using public-standard network protocols a complete Transparent copy of the Document, free of added material. If you use the latter option, you must take reasonably prudent steps, when you begin distribution of Opaque copies in quantity, to ensure that this Transparent copy will remain thus accessible at the stated location until at least one year after the last time you distribute an Opaque copy (directly or through your agents or retailers) of that edition to the public. It is requested, but not required, that you contact the authors of the Document well before redistributing any large number of copies, to give them a chance to provide you with an updated version of the Document. 4. MODIFICATIONS You may copy and distribute a Modified Version of the Document under the conditions of sections 2 and 3 above, provided that you release the Modified Version under precisely this License, with the Modified Version filling the role of the Document, thus licensing distribution and modification of the Modified Version to whoever possesses a copy of it. In addition, you must do these things in the Modified Version: A. Use in the Title Page (and on the covers, if any) a title distinct from that of the Document, and from those of previous versions (which should, if there were any, be listed in the History section of the Document). You may use the same title as a previous version if the original publisher of that version gives permission. B. List on the Title Page, as authors, one or more persons or entities responsible for authorship of the modifications in the Modified Version, together with at least five of the principal authors of the Document (all of its principal authors, if it has fewer than five), unless they release you from this requirement. C. State on the Title page the name of the publisher of the Modified Version, as the publisher. D. Preserve all the copyright notices of the Document. E. Add an appropriate copyright notice for your modifications adjacent to the other copyright notices. F. Include, immediately after the copyright notices, a license notice giving the public permission to use the Modified Version under the terms of this License, in the form shown in the Addendum below. G. Preserve in that license notice the full lists of Invariant Sections and required Cover Texts given in the Document’s license notice. H. Include an unaltered copy of this License. I. Preserve the section Entitled “History”, Preserve its Title, and add to it an item stating at least the title, year, new authors, and publisher of the Modified Version as given on the Title Page. If there is no section Entitled “History” in the Document, create one stating the title, year, authors, and publisher of the Document as given on its Title Page, then add an item describing the Modified Version as stated in the previous sentence. J. Preserve the network location, if any, given in the Document for public access to a Transparent copy of the Document, and likewise the network locations given in the Document for previous versions it was based on. These may be placed in the “History” section. You may omit a network location for a work that was published at least four years before the Document itself, or if the original publisher of the version it refers to gives permission. K. For any section Entitled “Acknowledgements” or “Dedications”, Preserve the Title of the section, and preserve in the section all the substance and tone of each of the contributor acknowledgements and/or dedications given therein. L. Preserve all the Invariant Sections of the Document, unaltered in their text and in their titles. Section numbers or the equivalent are not considered part of the section titles. M. Delete any section Entitled “Endorsements”. Such a section may not be included in the Modified Version. N. Do not retitle any existing section to be Entitled “Endorsements” or to conflict in title with any Invariant Section. O. Preserve any Warranty Disclaimers. If the Modified Version includes new front-matter sections or appendices that qualify as Secondary Sections and contain no material copied from the Document, you may at your option designate some or all of these sections as invariant. To do this, add their titles to the list of Invariant Sections in the Modified Version’s license notice. These titles must be distinct from any other section titles. You may add a section Entitled “Endorsements”, provided it contains nothing but endorsements of your Modified Version by various parties—for example, statements of peer review or that the text has been approved by an organization as the authoritative definition of a standard. You may add a passage of up to five words as a Front-Cover Text, and a passage of up to 25 words as a Back-Cover Text, to the end of the list of Cover Texts in the Modified Version. Only one passage of Front-Cover Text and one of Back-Cover Text may be added by (or through arrangements made by) any one entity. If the Document already includes a cover text for the same cover, previously added by you or by arrangement made by the same entity you are acting on behalf of, you may not add another; but you may replace the old one, on explicit permission from the previous publisher that added the old one. The author(s) and publisher(s) of the Document do not by this License give permission to use their names for publicity for or to assert or imply endorsement of any Modified Version. 5. COMBINING DOCUMENTS You may combine the Document with other documents released under this License, under the terms defined in section 4 above for modified versions, provided that you include in the combination all of the Invariant Sections of all of the original documents, unmodified, and list them all as Invariant Sections of your combined work in its license notice, and that you preserve all their Warranty Disclaimers. The combined work need only contain one copy of this License, and multiple identical Invariant Sections may be replaced with a single copy. If there are multiple Invariant Sections with the same name but different contents, make the title of each such section unique by adding at the end of it, in parentheses, the name of the original author or publisher of that section if known, or else a unique number. Make the same adjustment to the section titles in the list of Invariant Sections in the license notice of the combined work. In the combination, you must combine any sections Entitled “History” in the various original documents, forming one section Entitled “History”; likewise combine any sections Entitled “Acknowledgements”, and any sections Entitled “Dedications”. You must delete all sections Entitled “Endorsements.” 6. COLLECTIONS OF DOCUMENTS You may make a collection consisting of the Document and other documents released under this License, and replace the individual copies of this License in the various documents with a single copy that is included in the collection, provided that you follow the rules of this License for verbatim copying of each of the documents in all other respects. You may extract a single document from such a collection, and distribute it individually under this License, provided you insert a copy of this License into the extracted document, and follow this License in all other respects regarding verbatim copying of that document. 7. AGGREGATION WITH INDEPENDENT WORKS A compilation of the Document or its derivatives with other separate and independent documents or works, in or on a volume of a storage or distribution medium, is called an “aggregate” if the copyright resulting from the compilation is not used to limit the legal rights of the compilation’s users beyond what the individual works permit. When the Document is included in an aggregate, this License does not apply to the other works in the aggregate which are not themselves derivative works of the Document. If the Cover Text requirement of section 3 is applicable to these copies of the Document, then if the Document is less than one half of the entire aggregate, the Document’s Cover Texts may be placed on covers that bracket the Document within the aggregate, or the electronic equivalent of covers if the Document is in electronic form. Otherwise they must appear on printed covers that bracket the whole aggregate. 8. TRANSLATION Translation is considered a kind of modification, so you may distribute translations of the Document under the terms of section 4. Replacing Invariant Sections with translations requires special permission from their copyright holders, but you may include translations of some or all Invariant Sections in addition to the original versions of these Invariant Sections. You may include a translation of this License, and all the license notices in the Document, and any Warranty Disclaimers, provided that you also include the original English version of this License and the original versions of those notices and disclaimers. In case of a disagreement between the translation and the original version of this License or a notice or disclaimer, the original version will prevail. If a section in the Document is Entitled “Acknowledgements”, “Dedications”, or “His- tory”, the requirement (section 4) to Preserve its Title (section 1) will typically require changing the actual title. 9. TERMINATION You may not copy, modify, sublicense, or distribute the Document except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense, or distribute it is void, and will automatically terminate your rights under this License. However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, receipt of a copy of some or all of the same material does not give you any rights to use it. 10. FUTURE REVISIONS OF THIS LICENSE The Free Software Foundation may publish new, revised versions of the GNU Free Documentation License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. See http://www.gnu.org/copyleft/. Each version of the License is given a distinguishing version number. If the Document specifies that a particular numbered version of this License “or any later version” applies to it, you have the option of following the terms and conditions either of that specified version or of any later version that has been published (not as a draft) by the Free Software Foundation. If the Document does not specify a version number of this License, you may choose any version ever published (not as a draft) by the Free Software Foundation. If the Document specifies that a proxy can decide which future versions of this License can be used, that proxy’s public statement of acceptance of a version permanently authorizes you to choose that version for the Document. 11. RELICENSING “Massive Multiauthor Collaboration Site” (or “MMC Site”) means any World Wide Web server that publishes copyrightable works and also provides prominent facilities for anybody to edit those works. A public wiki that anybody can edit is an example of such a server. A “Massive Multiauthor Collaboration” (or “MMC”) contained in the site means any set of copyrightable works thus published on the MMC site. “CC-BY-SA” means the Creative Commons Attribution-Share Alike 3.0 license published by Creative Commons Corporation, a not-for-profit corporation with a principal place of business in San Francisco, California, as well as future copyleft versions of that license published by that same organization. “Incorporate” means to publish or republish a Document, in whole or in part, as part of another Document. An MMC is “eligible for relicensing” if it is licensed under this License, and if all works that were first published under this License somewhere other than this MMC, and subsequently incorporated in whole or in part into the MMC, (1) had no cover texts or invariant sections, and (2) were thus incorporated prior to November 1, 2008. The operator of an MMC Site may republish an MMC contained in the site under CC-BY-SA on the same site at any time before August 1, 2009, provided the MMC is eligible for relicensing. ADDENDUM: How to use this License for your documents To use this License in a document you have written, include a copy of the License in the document and put the following copyright and license notices just after the title page: Copyright (C) year your name. Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.3 or any later version published by the Free Software Foundation; with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts. A copy of the license is included in the section entitled "GNU Free Documentation License". If you have Invariant Sections, Front-Cover Texts and Back-Cover Texts, replace the "with...Texts." line with this: with the Invariant Sections being list their titles, with the Front-Cover Texts being list, and with the Back-Cover Texts being list. If you have Invariant Sections without Cover Texts, or some other combination of the three, merge those two alternatives to suit the situation. If your document contains nontrivial examples of program code, we recommend releasing these examples in parallel under your choice of free software license, such as the GNU General Public License, to permit their use in free software. ## Index **D** - data structures ........................................ 5 **F** - FDL, GNU Free Documentation License .......... 17 **G** - gfc_code .................................................. 5 - gfc_expr .................................................. 7 **S** - statement chaining ....................................... 5 - struct gfc_code ......................................... 5 - struct gfc_expr ......................................... 7
{"Source-Url": "https://gcc.gnu.org/onlinedocs/gfc-internals.pdf", "len_cl100k_base": 11761, "olmocr-version": "0.1.53", "pdf-total-pages": 32, "total-fallback-pages": 0, "total-input-tokens": 64417, "total-output-tokens": 13219, "length": "2e13", "weborganizer": {"__label__adult": 0.0002715587615966797, "__label__art_design": 0.0003974437713623047, "__label__crime_law": 0.0003261566162109375, "__label__education_jobs": 0.0004777908325195313, "__label__entertainment": 5.97834587097168e-05, "__label__fashion_beauty": 6.222724914550781e-05, "__label__finance_business": 0.0002942085266113281, "__label__food_dining": 0.0001919269561767578, "__label__games": 0.0004911422729492188, "__label__hardware": 0.0003390312194824219, "__label__health": 9.614229202270508e-05, "__label__history": 0.00012010335922241212, "__label__home_hobbies": 4.2438507080078125e-05, "__label__industrial": 0.0001666545867919922, "__label__literature": 0.0002187490463256836, "__label__politics": 0.0001289844512939453, "__label__religion": 0.0002287626266479492, "__label__science_tech": 0.001946449279785156, "__label__social_life": 4.13060188293457e-05, "__label__software": 0.0114593505859375, "__label__software_dev": 0.982421875, "__label__sports_fitness": 0.00011050701141357422, "__label__transportation": 0.00018477439880371096, "__label__travel": 0.00011342763900756836}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 54093, 0.02275]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 54093, 0.39617]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 54093, 0.88049]], "google_gemma-3-12b-it_contains_pii": [[0, 0, null], [0, 0, null], [0, 542, false], [542, 542, null], [542, 2499, null], [2499, 2499, null], [2499, 3160, null], [3160, 3160, null], [3160, 6201, null], [6201, 7674, null], [7674, 9966, null], [9966, 13185, null], [13185, 16148, null], [16148, 18916, null], [18916, 19322, null], [19322, 19322, null], [19322, 22395, null], [22395, 24785, null], [24785, 27552, null], [27552, 29164, null], [29164, 30903, null], [30903, 30903, null], [30903, 33907, null], [33907, 37232, null], [37232, 40550, null], [40550, 43514, null], [43514, 46643, null], [46643, 49931, null], [49931, 52365, null], [52365, 53628, null], [53628, 54093, null], [54093, 54093, null]], "google_gemma-3-12b-it_is_public_document": [[0, 0, null], [0, 0, null], [0, 542, true], [542, 542, null], [542, 2499, null], [2499, 2499, null], [2499, 3160, null], [3160, 3160, null], [3160, 6201, null], [6201, 7674, null], [7674, 9966, null], [9966, 13185, null], [13185, 16148, null], [16148, 18916, null], [18916, 19322, null], [19322, 19322, null], [19322, 22395, null], [22395, 24785, null], [24785, 27552, null], [27552, 29164, null], [29164, 30903, null], [30903, 30903, null], [30903, 33907, null], [33907, 37232, null], [37232, 40550, null], [40550, 43514, null], [43514, 46643, null], [46643, 49931, null], [49931, 52365, null], [52365, 53628, null], [53628, 54093, null], [54093, 54093, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, false], [5000, 54093, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 54093, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 54093, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 54093, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 54093, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 54093, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 54093, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 54093, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 54093, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 54093, null]], "pdf_page_numbers": [[0, 0, 1], [0, 0, 2], [0, 542, 3], [542, 542, 4], [542, 2499, 5], [2499, 2499, 6], [2499, 3160, 7], [3160, 3160, 8], [3160, 6201, 9], [6201, 7674, 10], [7674, 9966, 11], [9966, 13185, 12], [13185, 16148, 13], [16148, 18916, 14], [18916, 19322, 15], [19322, 19322, 16], [19322, 22395, 17], [22395, 24785, 18], [24785, 27552, 19], [27552, 29164, 20], [29164, 30903, 21], [30903, 30903, 22], [30903, 33907, 23], [33907, 37232, 24], [37232, 40550, 25], [40550, 43514, 26], [43514, 46643, 27], [46643, 49931, 28], [49931, 52365, 29], [52365, 53628, 30], [53628, 54093, 31], [54093, 54093, 32]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 54093, 0.02108]]}
olmocr_science_pdfs
2024-12-11
2024-12-11
03e1fdfdc645765127265c4dc0140d67fccc1e76
[REMOVED]
{"len_cl100k_base": 8469, "olmocr-version": "0.1.53", "pdf-total-pages": 15, "total-fallback-pages": 0, "total-input-tokens": 31928, "total-output-tokens": 10203, "length": "2e13", "weborganizer": {"__label__adult": 0.0005164146423339844, "__label__art_design": 0.0103759765625, "__label__crime_law": 0.0003337860107421875, "__label__education_jobs": 0.0114593505859375, "__label__entertainment": 0.00022912025451660156, "__label__fashion_beauty": 0.0003120899200439453, "__label__finance_business": 0.0004382133483886719, "__label__food_dining": 0.0003676414489746094, "__label__games": 0.000988006591796875, "__label__hardware": 0.001956939697265625, "__label__health": 0.0005168914794921875, "__label__history": 0.00079345703125, "__label__home_hobbies": 0.0002092123031616211, "__label__industrial": 0.00045228004455566406, "__label__literature": 0.001255035400390625, "__label__politics": 0.00029587745666503906, "__label__religion": 0.0007524490356445312, "__label__science_tech": 0.06646728515625, "__label__social_life": 0.00017845630645751953, "__label__software": 0.05584716796875, "__label__software_dev": 0.84521484375, "__label__sports_fitness": 0.00022232532501220703, "__label__transportation": 0.0005965232849121094, "__label__travel": 0.00023233890533447263}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 46001, 0.02124]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 46001, 0.71232]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 46001, 0.96472]], "google_gemma-3-12b-it_contains_pii": [[0, 3080, false], [3080, 6077, null], [6077, 8842, null], [8842, 11726, null], [11726, 15227, null], [15227, 18322, null], [18322, 21499, null], [21499, 24527, null], [24527, 27588, null], [27588, 31113, null], [31113, 34697, null], [34697, 37734, null], [37734, 40799, null], [40799, 43613, null], [43613, 46001, null]], "google_gemma-3-12b-it_is_public_document": [[0, 3080, true], [3080, 6077, null], [6077, 8842, null], [8842, 11726, null], [11726, 15227, null], [15227, 18322, null], [18322, 21499, null], [21499, 24527, null], [24527, 27588, null], [27588, 31113, null], [31113, 34697, null], [34697, 37734, null], [37734, 40799, null], [40799, 43613, null], [43613, 46001, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 46001, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 46001, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 46001, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 46001, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 46001, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 46001, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 46001, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 46001, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 46001, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 46001, null]], "pdf_page_numbers": [[0, 3080, 1], [3080, 6077, 2], [6077, 8842, 3], [8842, 11726, 4], [11726, 15227, 5], [15227, 18322, 6], [18322, 21499, 7], [21499, 24527, 8], [24527, 27588, 9], [27588, 31113, 10], [31113, 34697, 11], [34697, 37734, 12], [37734, 40799, 13], [40799, 43613, 14], [43613, 46001, 15]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 46001, 0.0]]}
olmocr_science_pdfs
2024-12-10
2024-12-10
1f6e94bf27887af451bce88525cd86bd7e50beb9
Validation Support for Distributed Real-Time Embedded Systems in VDM++ John S. Fitzgerald Newcastle University, UK John.Fitzgerald@ncl.ac.uk Peter Gorm Larsen Engineering College of Aarhus, Denmark pgl@iha.dk Simon Tjell University of Aarhus, Denmark tjell@daimi.au.dk Marcel Verhoef Chess and Radboud University Nijmegen, NL Marcel.Verhoef@chess.nl Abstract We present a tool-supported approach to the validation of system-level timing properties in formal models of distributed real-time embedded systems. Our aim is to provide system architects with rapid feedback on the timing characteristics of alternative designs in the often volatile early stages of the development cycle. The approach extends the Vienna Development Method (VDM++), a formal object-oriented modeling language with facilities for describing real-time applications deployed over a distributed infrastructure. A new facility is proposed for stating and checking validation conjectures (assertions concerning real-time properties) against traces derived from the execution of scenarios on VDM++ models. We define validation conjectures and outline their semantics. We describe the checking of conjectures against execution traces as a formally-defined extension of the existing VDM++ tool set, and show tools to visualise traces and validation conjecture violations. The approach and tool support are illustrated with a case study based on an in-car radio navigation system. 1 Introduction The development of real-time embedded control systems to high levels of assurance is a major technical challenge, particularly when software is to be distributed over networked processors. The early development phases of such systems are also often characterised by complexity and volatility of requirements. In this environment, developers require tools that support the rapid evaluation of design models against system-level temporal and functional properties. Such a validation activity helps to identify requirements and design defects before a commitment is made to a particular design strategy. In these early development phases, when developer time is at a premium, the cost effectiveness and ease of use of validation tools is significant, as well as the level of rigour supplied by the modeling language and environment. Our current work aims to use formal techniques in an accessible and cost-effective manner to support validation for models of distributed and embedded real-time systems. The approach is based on the Vienna Development Method (VDM), an established formal method which has been extended to support modeling of concurrent object-oriented systems (VDM++ [5]) and real-time and distributed systems [20]. In this paper we define new extensions to the modeling language and tools to permit the expression of system-level timing properties and support their validation against timed traces derived from the execution of scenarios on VDM++ models. The novel features of this work are the language and semantics of validation conjectures over timed distributed VDM++ models and their implementation in a proof-of-concept tool. The impact of the work is primarily on model developers and analysts, enabling explicit consideration of system-level properties during modeling process. Section 2 introduces the current state of VDM++ technology. The extensions to accommodate checking of system-level timing properties, called validation conjectures, are shown in Section 3. These consist of language extensions to allow the specification of validation conjectures (Section 4) and formally specified tools extensions to identify conjecture violations in the execution traces (Section 5). We interleave the description of the language and tool extensions with an example based on a distributed in-car radio navigation system, introduced informally in the remainder of this section. Finally the approach and further work are discussed (Section 6). 1.1 Example: an In-car Radio Navigation System Our example, based on an in-car radio navigation system, was introduced in the context of performance analysis [21, 12] and also as a case study in the extension of VDM++ to model timing requirements and distributed architecture [20]. The navigation system consists of several software applications running on a common distributed hardware platform. The design challenge is to develop an architecture capable of satisfying the requirements of the individual applications. In developing such an architecture, the designer will need feedback on system-level timing properties of alternative models. The model presented here reflects one of the proposals that was considered during design. It consists of three CPUs on an internal communication bus (Fig.1). **Figure 1. Informal overview of the case study** There are two applications, ChangeVolume and ProcessTMC, represented by the upper and lower groups of gray boxes in Fig. 1. Each application consists of three tasks. The ChangeVolume application increases the radio volume in response to a user pressing a “volume up” key. Within this application, the task HandleKeyPress takes care of user interface input handling, AdjustVolumeUp modifies the volume accordingly and UpdateScreen displays the new volume setting on the screen. The ProcessTMC application handles Traffic Message Channel (TMC) messages. TMC messages arrive at the HandleTMC task where they are checked and forwarded to the DecodeTMC task to be translated into human readable text which is displayed on the screen by the UpdateTMC task. The environment of the system is modeled by two additional applications which inject stimuli and observe the system response. The vBUS and vCPU0 are the virtual bus and CPU on which the environment processes and the environment-system communications take place. Before embarking on a potentially expensive rigorous development process, the system architect may wish to explore whether a given design alternative, such as the one shown above, will respect important system-level constraints. These constraints may be derived from requirements of potentially competing applications. We will use the term validation conjecture to mean a property to be checked against a model and the term validation to cover the checking process. Some examples of validation conjectures for the in-car navigation example are listed below: - **C1:** A volume change must be reflected in the display within $35\text{ ms}$. - **C2:** The screen should be updated no more than once every $500\text{ ms}$. - **C3:** If the volume is to be adjusted upward and is not currently at the maximum, the audible change should occur within $100\text{ ms}$. - **C4:** The volume is only allowed to be at the maximum level for at most $10000\text{ ms}$. Validation conjectures may be inconsistent, possibly pointing to inconsistencies between applications’ requirements. The validation process should help to identify such issues, and suggest strengthening or weakening of the conjectures against a specific design model. 2 VDM++ Technology VDM++ is an object-oriented and model-based specification language based on the Vienna Development Method. It has a formally defined syntax, static and dynamic semantics which extend those of the ISO Standard VDM-SL language [1]. For a detailed introduction to VDM++, the reader is referred to current texts [5] and the VDM Portal [14]. VDM++ supports the construction of abstract system models composed of class specifications, each of which contains definitions of data types, instance variables and operations. Abstraction in data is provided through the use of unconstrained types and abstract collections such as sets, mappings and sequences. Functionality is modeled abstractly in terms of operations which may be described explicitly, or may be underspecified, and may even be characterised solely by postconditions. Data types may be constrained by predicate invariants and the invocation of operations may be restricted by predicate preconditions. The language is thus not in general executable, but has an executable subset. Extensions have recently been proposed to VDM++ in order to better support the description and analysis of real-time embedded and distributed systems [18, 19]. These include primitives for modeling deployment to a distributed hardware architecture and support for asynchronous communication. 2.1 Example VDM++ model This section contains extracts from the VDM++ model of the in-car navigation example initially presented in [20]. We focus on the system model rather than the environment model. There are two independent applications that consist of three tasks each. Tasks can be triggered sporadically (by external stimuli or by receiving messages from other tasks) or periodically (checking for available data on an input source or delivering data to an output). Note that task activation by external stimuli can be used to model interrupt handling. The interface handling tasks HandleKeyPress and HandleTMC tasks belong to this category. The other tasks in our system model are message triggered. Application tasks are modeled by asynchronous operations in VDM++. For example, Fig. 2 shows the definitions of AdjustVolumeUp and HandleTMC, which are grouped together in the Radio class. The AdjustVolumeUp operation increases the instance variable representing the volume and then asynchronously invokes the operation UpdateScreen in the MMI object. Note the reference to the RadNavSys class, which represents the system as a whole. ```vdm class Radio values public MAX : nat = 10 instance variables public volume : nat := 0 operations async public AdjustVolumeUp: nat ==> () AdjustVolumeUp (pno) == if volume <= MAX then (volume := volume + 1; RadNavSys'mmi.UpdateScreen(1,pno)); async public HandleTMC: nat ==> () HandleTMC (pno) == RadNavSys'navigation.DecodeTMC(pno); ... end Radio ``` Figure 2. The Radio class At the system level, the model must show the allocation of tasks to computation resources. A special class CPU is provided to create computation resources; each resource is characterised by its processing capacity, specified by the number of available cycles per unit of time and the scheduling policy. Throughout this paper, the time unit is milliseconds. For this case study, fixed priority preemptive scheduling is used, although our approach is not restricted to any policy in particular. A special class BUS is provided to create communication resources, each characterised by its throughput, specified by the number of messages that can be handled per unit of time and the scheduling policy that is used to determine the order of the messages being exchanged. The granularity of a message can be determined by the user. For example, it can represent a single byte or a complete Ethernet frame, whatever is most appropriate for the problem under study. For this case study, we use First Come First Served scheduling, but again the approach is not restricted to any policy in particular. An overview of the VDM++ system model is presented in Fig. 3. ```vdm system RadNavSys instance variables -- create the application tasks static public mmi := new MMI(); static public radio := new Radio(); static public navigation := new Navigation(); -- create CPU (policy, capacity) CPU1 : CPU := new CPU(<FP>, 22E6); CPU2 : CPU := new CPU(<FP>, 11E6); CPU3 : CPU := new CPU(<FP>, 113E6); -- create BUS -- (policy, capacity, topology) BUS1 : BUS := new BUS(<FCFS>, 72E3, {CPU1, CPU2, CPU3}) operations -- the constructor of the system model public RadNavSys: () ==> RadNavSys RadNavSys () == (CPU1.deploy(mmi); CPU2.deploy(radio); CPU3.deploy(navigation) ) end RadNavSys ``` Figure 3. System model for the case study 2.2 Tool Support for VDM++ VDM++ is supported by an industry-strength tool set, called VDMTools, which is currently owned and further developed by CSK Systems [2]. VDM++ and VDMTools have been used successfully in several large-scale industrial projects [17, 8, 10, 4]. The tools offer syntax, type and static checking capabilities, code generators, a pretty printer and an application programmer interface. The main support for validation is by means of an interpreter allowing the execution of VDM++ models written within the executable subset of the language. An important principle in the development of VDMTools has been that of ‘taking one’s own medicine’. Most of the components of VDMTools, including the type checker and interpreter, are specified in VDM and VDM++. For example, the specification of the interpreter embodies the operational semantics of the language. When extensions are proposed, it is necessary to first develop formal specifications for them and integrate them with the existing specifications before developing the implementation. This formal approach has proved particularly valuable in mastering the implementation complexity of some components of the tool set, and has in turn influenced the development of the language. We return to this point when we describe tool extensions to support validation in Section 5. Scenarios defined by the user are essentially test cases consisting of scripts invoking the model’s functionality. The interpreter executes the script over the model and returns observable results as well as an execution trace containing, for each internal or bus event, a time stamp and an indication of the part of the model in which it appeared. A separate tool (an Eclipse plug-in) called showtrace has been developed for reading execution traces, displaying them graphically so that the user can readily inspect behaviour after the execution of a scenario, and thereby gain insight into the ordering and timing of exchange of messages, activation of threads and invocation of operations. 2.3 Example Analysis of Radio Navigation System Model In order to illustrate how the VDMTools interpreter can be used to examine different scenarios consider Fig. 4. This is a small scenario including two tasks in the environment for changing the volume and sending a TMC message. The VolumeUpKey and TransmitTMC objects belong to the environment. Each object is started and, once the system has responded to their stimuli, various performance characteristics are evaluated and returned. In addition to yielding a result, the execution of the scenario produces an execution trace. Note that our examples here deal with the execution of a single scenario at a time. Interleaving of scenarios is also possible and can be defined as a separate test case. 3 Extensions to Support Validation The existing VDM++ and VDMTools framework has been extended so that explicit logical statements of system-level timing properties (validation conjectures) can be checked against execution traces. Fig. 5 shows the showtrace output resulting from the analysis of the four case study validation conjectures C1-C4 using the extended framework and the execution scenario defined in Section 2.3. ```java class World operations public RunScenario1: () => map seq of char to perfdata RunScenario1 () => { addEnvironmentTask("VolumeUpKey", new VolumeUpKey(10)); addEnvironmentTask("TransmitTMC", new TransmitTMC(10)); return { name |-> envTasks(name).getMinMaxAverage() | name in set dom envTasks } ); Figure 4. Scenario for Radio Navigation System Model The main window shows a fragment of the execution trace. The times of significant events are displayed on the horizontal axis. Processing on each architectural unit is shown by coloured horizontal lines (colours are used to denote thread activities, including start-up, kill and scheduling). The thin arrows that go to and from buses indicate message passing whereas the fat arrows going up and down indicate thread swapping out and in respectively. The features supporting validation are the list of conjectures at the bottom of the window and the circular marks on the traces that show conjecture violations. In Fig. 5, all the conjectures have been checked against the execution trace. In the example, based on the scenario shown above, conjectures C1 and C2 are violated and C3 and C4 have passed. The user can select one of the violated validation conjectures and then the appropriate point in the visualisation is displayed. In Fig. 5 this is done for conjecture C1 (see the circles with ‘C1’ next to them). Here the first C1 circle indicates the occurrence of the first of the events in the given validation conjecture while the second one indicates the occurrence of the second event violating the constraint (in this case a deadline that is not met). In order to graphically visualise the place where a violation takes place it is easy to do so when it is possible to always relate two event occurrences with each other and that is the case with the different forms of validation conjectures that is supported at the moment. This paper describes how the extended framework is constructed to support the form of validation illustrated above. The two main elements of Fig. 5 are the validation conjectures and the results of their evaluation. Section 4 gives an informal overview of validation conjectures. The semantics of the conjectures (the result of their evaluation over an execution trace) are embodied in the formal specification of the extended tools, described in Section 5. 4 Validation Conjectures Validation conjectures describe the temporal relationships between system-level events that can be observed in an execution trace. An execution trace may be thought of as a finite sequence of records, one for each time unit. We use a discrete abstraction of time by using natural numbers as time values. Each record contains a set of event names for the events that occurred at that time, and a snapshot of the values of the instance variables in the system model at that time. Events are simply temporal markers; they use up no system resources. Each event has a unique name and may occur many times in an execution trace. However, at any one time, there may be at most one occurrence of a given event. Two kinds of system-level event are detectable in an execution trace generated from a VDM++ model: operation events and state transition events. Operation events occur when operations are requested, activated, or terminated (denoted #req(Op), #act(Op) and #fin(Op) respectively). State transition events occur when a predicate over the instance variables of a model becomes true. Validation conjectures are predicates over execution traces. We will write \( O(e, i, t) \) to indicate that the \( i \)th occurrence of event \( e \) takes place at time \( t \). The variable \( i \) ranges over the non-zero natural numbers \( \mathbb{N}_1 \), and \( t \) representing time, ranges over the indices of the trace. For example, the simple conjecture \[ O(\#\text{fin}(\text{MMI}^\text{UpdateScreen}), 1, 50) \] is true in a trace where the first occurrence of the event marking the termination of the \text{UpdateScreen} operation is at exactly time unit 50. Note that distinct occurrences of an event must happen at different times and that the occurrence numbers increase incrementally over time\(^1\). It is often necessary to check a conjecture that relates to the specific values of some instance variables. For example, a designer may wish to check that a variable reaches a certain value at a specified time. In order to do this conveniently, we introduce the notion of a state predicate. A state predicate is a predicate over the instance variables of the system model. We will write \( E(p, t) \) to mean that the state predicate \( p \) is true of the variables in the execution trace at time \( t \). In stating a conjecture, it may be necessary to mark the times at which a predicate becomes true. In order to support this, we introduce the notion of a state transition event which contains a predicate and which occurs at any time when the predicate becomes true. The concepts defined so far are sufficient to construct useful validation conjectures. In order to allow more efficient detection and appropriate display of violations, we also identify specific forms or pattern of conjecture. When such standard forms are used, we can invoke efficient detection and display functions. In this section, we intro- --- \(^1\)The relation \( O \) is similar to the occurrence relation \( \Theta \) in Real-Time Logic (RTL)[9], but we do not claim here to be using full RTL. The formal definition of conjecture evaluation is given in VDM-SL for uniformity with the tools framework (Section 5). duce three such forms: separations, required separations and deadlines. It should be stressed that these are not intended to form a comprehensive language of validation conjectures. However, they illustrate the way in which formal tool support can be tailored to situations in which such standard formats are used. Intuitively, separation conjectures describe a minimum separation between specified events, should the events occur. Required separations are separations in which the second event is required to occur at or after the minimum separation. Deadline conjectures state that the second event must occur before a deadline is reached after the occurrence of the first event. Below, each conjecture pattern and its semantics are introduced in turn. A separation conjecture is a 5-tuple $\text{Separate}(e_1, c, e_2, d, m)$ where $e_1$ and $e_2$ are the names of events, $c$ is a state predicate, $d$ is the minimum acceptable delay between an occurrence of $e_1$ and any following occurrence of $e_2$ provided that $c$ evaluates to true at the occurrence time of $e_1$. If $c$ evaluates to false when $e_1$ occurs, the validation conjecture holds independently of the occurrence time of $e_2$. The Boolean flag $m$ is called the ‘match flag’, when set to true, indicates a requirement that the occurrence numbers of $e_1$ and $e_2$ should be equal. This allows the designer to record conjectures that describe some coordination between events. For example, we may wish to state that a stimulus and response events occur together in pairs within some time bounds, so the ith occurrence of the stimulus is always followed by the jth occurrence of the response. A validation conjecture $\text{Separate}(e_1, c, e_2, d, m)$ evaluates true over an execution trace if and only if: $$\forall i_1, t_1 : \mathcal{O}(e_1, i_1, t_1) \land \mathcal{E}(c, t_1) \Rightarrow \neg \exists i_2, t_2 : \mathcal{O}(e_2, i_2, t_2) \land t_1 \leq t_2 < t_1 + d \land (m \Rightarrow i_1 = i_2) \land (e_1 = e_2 \Rightarrow i_2 = i_1 + 1)$$ We want to allow this and the following expressions to be used for the specification of conjectures concerning both two occurrences of different event types ($e_1 \neq e_2$) and two occurrences of the same event type ($e_1 = e_2$). In the latter case, we distinguish the first and the second instances of the same event type by a requirement to their occurrence numbers ($e_1 = e_2 \Rightarrow i_2 = i_1 + 1$). The match flag should be used with caution in this case, since it does not make sense to combine the requirement about matching occurrence numbers with an expression about two instances of the same event type. The required separation conjecture is similar to the separation conjecture but additionally requires that the $e_2$ event does occur. A conjecture $\text{SepRequire}(e_1, c, e_2, d, m)$ evaluates to true over an execution trace if and only if: $$\forall i_1, t_1 : \mathcal{O}(e_1, i_1, t_1) \land \mathcal{E}(c, t_1) \Rightarrow \neg \exists i_2, t_2 : \mathcal{O}(e_2, i_2, t_2) \land t_1 \leq t_2 < t_1 + d \land (m \Rightarrow i_1 = i_2) \land (e_1 = e_2 \Rightarrow i_2 = i_1 + 1)$$ The Deadline conjecture places a maximum delay on the occurrence of the reaction event. Again, the match option may be used to link the occurrence numbers of the stimulus and reaction events. A validation conjecture $\text{DeadlineMet}(e_1, c, e_2, d, m)$ consists of a stimulus event, condition and reaction event; if $c$ holds, $d$ is the maximum tolerable delay between stimulus and reaction. The conjecture evaluates true over an execution trace if and only if: $$\forall i_1, t_1 : \mathcal{O}(e_1, i_1, t_1) \land \mathcal{E}(c, t_1) \Rightarrow \exists i_2, t_2 : \mathcal{O}(e_2, i_2, t_2) \land t_1 \leq t_2 \leq t_1 + d \land (m \Rightarrow i_1 = i_2) \land (e_1 = e_2 \Rightarrow i_2 = i_1 + 1)$$ These basic forms of validation conjection can be combined. For example, a conjecture to validate the periodic character of an event might take the form $\text{Periodic}(e, p, j)$ where $e$ is the periodic event, $p$ is the period and $j$ the allowable jitter. The conjecture might be defined to be true in a given execution trace if and only if: $$\text{DeadlineMet}(e, \text{true}, e, p + j, \text{false}) \land \text{Separate}(e, \text{true}, e, p - j, \text{false})$$ evaluates to true over the same trace. The three forms of conjecture identified above are by no means exhaustive. For example, one might wish to state that the non-occurrence of an event in a specified period should trigger the occurrence of some other event. Expression of non-standard conjectures will likely entail the use of the basic occurrence relation. Nevertheless, the approach of defining common forms of conjecture is extensible and allows for tailored tool support of the kind discussed in Section 5. 4.1 Example Validation Conjectures It is possible to use the simple language of validation conjectures to state system-level timing properties in the case study. In the following, we give concrete syntax representations for the conjectures C1–C4 introduced in Section 1. In most cases, the state predicate component of the conjecture is omitted and treated as true. In all cases, the match component $m$ is omitted and defaults to false. **C1:** A volume change must be reflected in the display within 35 ms. In the Radio class, the AdjustVolumeUp operation invokes the UpdateScreen operation in the MMI. The conjecture is interpreted formally as a deadline on the completions of AdjustVolumeUp and the next screen update MMI.UpdateScreen. This is a weak statement in that it does not tie the screen update to the specific volume change event. It could be strengthened by adding operation parameters to the conjecture to link the stimulus and response. This can be done using the formal definitions in Section 5. However, we omit this for simplicity. deadlineMet(#fin(Radio'AdjustVolumeUp), #fin(MMI'UpdateScreen), 35) C2: The screen should be updated no more than once every 500 ms. This is interpreted as a separation constraint on the MMI 'UpdateScreen screen operation completions. separate(#fin(MMI'UpdateScreen), #fin(MMI'UpdateScreen), 500) As a result of formalising and validating the conjecture, the architect may observe the inconsistency between C1 and C2 that can arise if a screen update has to be performed in response to a volume change at a time less than 500 ms from the last screen update. It may be appropriate to negotiate a weakening in requirements in such a case. C3: If the volume is to be adjusted upward and is not currently at the maximum, the audible change should occur within 100 ms. The current volume is modeled by the value of the instance variable (RadNavSys'radio.volume). The request to adjust the volume is interpreted as a deadline. The noticing of the audible change is interpreted as the termination of the Radio 'AdjustVolumeUp operation. deadlineMet( #req(Radio'HandleKeyPress), RadNavSys'radio.volume < Radio'MAX, #fin(Radio'AdjustVolumeUp), 100) Here again the architect may observe that the formalised conjecture may be weak by allowing many key presses to be serviced by only one volume adjustment event. A revised, stronger, conjecture linking occurrences might be appropriate here. C4: The volume is only allowed to be at the maximum level for at most 10000 ms. It is interesting to note that we do not distinguish between the initiators in controlling the volume but merely observe the resulting level. The maximum amount of time in which the volume is allowed to be at the maximum level is set at 10000 ms. deadlineMet( RadNavSys'radio.volume >= Radio'MAX, RadNavSys'radio.volume<Radio'MAX, 10000) 5 Extended Tool Support for Validation Conjectures The VDMTools interpreter has been extended to record additional data in the execution trace generated by running a scenario and to use this to evaluate validation conjectures. A further extension to showtrace allows violations to be identified and explored. In this section, we describe these extensions, focussing on those aspects that are relevant to the efficient analysis of the validation conjecture forms identified in Section 4. In accordance with the 'taking one’s own medicine’ principle for developing VDMTools, we began from the formal specification of the interpreter before developing the code to implement our extensions. The interpreter specification is substantial – over 500 pages of VDM-SL interleaved with informal explanatory text. Thus, VDM is used both as the meta-language as well as the source language in the part described in this section. One additional module called VC has been added containing the formal descriptions of data structures and operations for logging execution trace data and for evaluating validation conjectures. The VC module is only 400 lines of VDM-SL and below we will show extracts from this. The intention is that, once a scenario has been executed, it should be possible to evaluate a set of validation conjectures over the execution trace. A further extension of the showtrace tool permits the graphical indication of conjecture violations on top of the visualisation of the simulation of the deployed applications. This is intended to speed up the error detection and correction cycle at the abstract design level because the detected violations act as counter examples that are easy to understand. The VC module specifies efficient operations that can determine the validity of a validation conjecture over a given execution trace. If a violation is detected it will yield a tuple of information that uniquely identifies for showtrace the point at which the violation takes place. In order to provide for efficient checking of conjectures, the large execution trace file is not searched directly. Instead, the trace is represented in an optimised form. The VC module state has the following form: state VCState of ophistmap : map AS 'Name to OpHist instvarhistmap : map AS 'Name to InstVarHist end The state contains a mapping from operation names to operation histories (Ophist), and from instance variable names to their histories (InstVarHist). The Ophist type splits the execution trace for a given operation into traces of the request, activation and finish events. Each event trace is a sequence of records, each containing a timestamp and record of the operation inputs (for a request --- 2The abstract syntax of VDM++ is described in a module called AS, in which names of identifiers are denoted by the type Name. event) or result (for a finish event) as well as a thread identifier. The history of changes made to instance variables is stored with the actual value assigned to it (a semantic value, denoted as VAL). Formally: \[ \begin{align*} \text{OpHist} &::= \text{reqs} : \text{seq of Req} \\ & \quad \text{acts} : \text{seq of Act} \\ & \quad \text{fins} : \text{seq of Fin}; \\ \text{Req} &::= \text{tim} : \text{nat} \\ & \quad \text{arg} : [\text{seq of VAL}] \\ & \quad \text{thrid} : \text{nat}; \\ \text{Act} &::= \text{tim} : \text{nat} \\ & \quad \text{thrid} : \text{nat}; \\ \text{Fin} &::= \text{tim} : \text{nat} \\ & \quad \text{result} : [\text{VAL}] \\ & \quad \text{thrid} : \text{nat}; \\ \text{InstVarHist} &::= \text{seq of InstVar}; \\ \text{InstVar} &::= \text{tim} : \text{nat} \\ & \quad \text{val} : \text{VAL} \\ & \quad \text{thrid} : \text{nat}; \\ \end{align*} \] All these type definitions include a field called \text{thrid} that is used to keep track of the thread identification of the requesting thread which is used when the threads and flow of control is presented visually. Having separated out the execution trace information in this fashion one can check for possible violations of a given validation conjecture. For example, the operation performing the check for a violation of a deadline conjecture on the VC module state is defined as follows: \[ \text{EvalDeadlineMet}::= \text{DeadlineMet} \Rightarrow \\ [ \text{nat} \times \text{ThreadId} \times \\ [\text{nat}] \times [\text{ThreadId}] ] \] \[ \text{EvalDeadlineMet} (\text{mk_DeadlineMet}(\text{ev1}, p, \text{ev2}, \text{max}, \text{match})) = \\ \quad \text{if match} \\ \quad \text{then} \\ \quad \text{MatchCheck}(\text{ev1}, p, \text{ev2}, \text{max}, \text{<MAX>}, \text{false}) \\ \quad \text{else} \\ \quad \text{AnyCheck}(\text{ev1}, p, \text{ev2}, \text{max}, \text{<MAX>}, \text{false}); \] Different checks are made depending upon the match value in the conjecture. If no violation is found, the operation yields a \text{nil} value. Otherwise, it returns a tuple indicating the location of a violation. This tuple contains the time and thread identifier indicating the first event in the validation conjecture \text{ev1} and also the time and thread identifier of the second event \text{ev2} (if it does not occur at all the special value \text{nil} is used again). Auxiliary operations extract lists of events of interest and use these to evaluate whether a violation occurred. As an example, consider the \text{MatchCheck} operation presented below. This operation performs a check for a violation of a conjecture in which the \text{m} flag is true. Thus, we expect occurrence numbers of the events linked in the conjecture to be the same. \[ \begin{align*} \text{MatchCheck}: \text{EventExpr} \times \text{Pred} \times \text{EventExpr} \times \\ \quad [\text{nat} \times \text{ThreadId} \times \\ \quad [\text{nat}] \times [\text{ThreadId}] ] \\ \text{MatchCheck}(\text{ev1}, \text{pred}, \text{ev2}, \text{delay}, \text{kind}, \text{req}) = \\ \quad \text{let list1} = \text{FindList}(\text{ev1}), \\ \quad \text{list2} = \text{FindList}(\text{ev2}) \\ \quad \text{in} \\ \quad (\text{for index} = 1 \text{ to len list1 do} \\ \quad \text{let t1} = \text{list1(index)}.\text{tim}, \\ \quad \quad \text{t2} = \text{if index in set inds list2} \\ \quad \quad \text{then list2(index)}.\text{tim} \\ \quad \quad \text{else <INF>} \\ \quad \text{in} \\ \quad (\text{if not PredSatisfied(pred, t1)} \\ \quad \text{then skip} \\ \quad \quad \text{elseif t2} = <\text{INF}> \text{ and req} \\ \quad \quad \quad \text{then return} \\ \quad \quad \quad \text{mk}_{(\text{t1}, \text{list1(index)}.\text{thrid},} \\ \quad \quad \quad \text{\text{nil}, \text{nil}}) \\ \quad \quad \text{elseif t2} < <\text{INF}> \text{ and} \\ \quad \quad \quad \text{\text{Violation}(t1, t2, \text{delay}, \text{kind})} \\ \quad \quad \quad \text{then return} \\ \quad \quad \quad \text{mk}_{(\text{t1}, \text{list1(index)}.\text{thrid},} \\ \quad \quad \quad \text{\text{t2}, \text{list2(index)}.\text{thrid})} \\ \quad \quad \text{)}; \\ \text{return nil}) \end{align*} \] Within \text{MatchCheck}, the auxiliary operation \text{FindList} extracts the list of a particular event’s occurrences, so the variable \text{index} corresponds to the occurrence number. This checks all instances of the first event \text{ev1} and looks for a violation in the matching occurrence of \text{ev2} (or if no matching is present whether \text{ev2} is required). This operation illustrates violation checking; the other algorithms are similar in nature. The violation information for each validation conjecture is handed over to the \text{showtrace} tool for visualisation. If there were no need for predicates very efficient solvers for propositional logic could be used. However, we need the possibility to express the validation conjectures in a simple form. The checking of predicates is carried out using the \text{PredSatisfied} operation. It takes a predicate and the time at which the predicate needs to be checked. This is defined as follows: \[ \begin{align*} \text{PredSatisfied}: \text{Pred} \times \text{nat} \Rightarrow \text{bool} \\ \text{PredSatisfied}(\text{pred}, \text{t}) = \\ \text{let mk_Pred(var, op, num) = pred} \\ \quad \text{in} \\ \quad \text{if var in set dom instvarhistmap} \\ \quad \text{then} \end{align*} \] Liu’s work based on the SOFL language [11], which con- contains elements derived from VDM, also supports direct animation of models, in this case from systematically derived execution scenarios. The aim of our work has been to support the validation of system-level temporal properties in an accessible and cost-effective manner. How far have we gone towards achieving this? The approach has a formal basis, but the goal is pragmatic. Building on an existing modeling framework in VDM++ [20], we have presented a new semantically well-founded facility for stating and checking system-level validation conjectures against traces derived from the execution of models that describe distributed real-time systems. Tool extensions have been defined formally and have been implemented to proof-of-concept level. The outcomes of each trace analysis are made accessible by using a graphical display and exploiting defined validation conjecture forms for which specific violation detection and display features have been defined. Together, these facilities enable the system architect to adjust the functionality, its deployment, the architecture or the conjecture itself. It should be stressed that the validation of execution traces does not replace formal verification: a failing conjecture is the symptom of a possible design defect but a passing conjecture is not a proof of correctness with respect to the real-time constraints. Our objective here is to provide rapid assessment of the key properties of a design model, helping to identify deficiencies in requirements and system-level conjectures in the very early phases of a high assurance development process. There are some limitations to the framework as developed so far. First, although our models are loosely specified, each scenario execution produces only one execution trace because the implementation of the operational semantics enforces determinism in order to ensure reproducibility over multiple traces. Within a single execution, we do allow non-determinism. Second, the tools do not yet support on-the-fly evaluation of validation conjectures, although this could readily be accommodated. Third, we need to widen the range of conjecture forms for which specialised checking and display tools are available. There are several other directions in which the proof of concept work reported here might be extended. Once conjectures have been defined and have been used to validate the execution of the model (which also serves as a validation of the conjectures themselves), they can be used (with event transformation) to validate log files generated by the final implementation of a system. A further important task is to begin to evaluate the reliability of the results as an aid to decision-making among design alternatives. Further, the validation framework discussed here might be extended to support the evaluation of fault tolerance strategies at the architectural level. Experiments combining the interpreter (executing a model of a controller) with a continuous time 6 Concluding Remarks There is a considerable body of work extending formal model-oriented specification languages to allow the expression of temporal properties alongside functionality. Some, in common with VDM++, aim to combine the expression of temporal behaviour with object-oriented or modular structuring. Possibly the closest examples are Timed RSL [6], combinations of Timed CSP with Object-Z [3] and Timed extensions to B such as [15]. The majority of these works focus on support for verification of design steps by model checking and proof rather than validation in early development stages. None of them deal explicitly with deployment. In the context of UML, the strand of research on validation of timed system models based on a real-time profile [13, 7] proposes the statement of ‘duration constraints’ between events by means of observer state machines or OCL-like expressions. Work on the UniFrame framework [16] places a VDM++ model of a distributed real-time system as part of a chain of formalisms for handling functional and non-functional properties. The proposed tool chain includes timed trace analysis based on VDM++ models, although this proposal has not been implemented. There has been considerable interest in the analysis of formal models by animation based on the direct execution of models (rather than a translated model or execution of code derived from a model). There have been recent industrial successes. For example, animation (extensive testing) of an executable model plays a vital role in the validation of an embedded integrated circuit for cellular telephones [10]. The predicate is set to be false if the time requested is before the instance variable in question has been initialised. Otherwise it looks through the list of updates that has been made to the instance variable and evaluates the operator at the time requested. ``` let hist = instvarhistmap(var), mk_InstVar(firstt,-,-) = hd hist in if t < firstt then return false else (for i = 2 to len hist do if hist(i-1).tim <= t and t < hist(i).tim then return EvalOp(hist(i-1).val, op,num); return EvalOp(hist(len hist).val, op,num) ) else return false; ``` simulator suggest that it is possible to model faults at the interface between the two without clouding the models of either the controller or the environment process. Finally, we are investigating the provision of automated proof of validation conjectures on models in constrained situations. The purpose of the work reported here has been to enhance the range of tools available to designers of distributed embedded real-time systems in early development stages. The approach is based on the use of abstract system models that have a formal basis and so can benefit from rigorous analysis. The priority has been to provide rapid feedback on the timing properties of abstract system models by exploiting information gathered during the execution of scenarios. This form of validation is not seen as a solitary technique, but can be used in conjunction with other forms of analysis to support design-time trade-off and decision-making. Acknowledgments The authors wish to thank Jozef Hooman, Jeremy Bryans, Cliff Jones and the anonymous reviewers for valuable input on this and previous drafts. Fitzgerald is grateful to the European Network on Resilience for Survivability in IST (ReSIST) and the EPSRC Platform project on Trustworthy Ambient Systems. References
{"Source-Url": "https://repository.ubn.ru.nl/bitstream/handle/2066/36669/36669.pdf?sequence=1", "len_cl100k_base": 9614, "olmocr-version": "0.1.53", "pdf-total-pages": 11, "total-fallback-pages": 0, "total-input-tokens": 37353, "total-output-tokens": 11798, "length": "2e13", "weborganizer": {"__label__adult": 0.0003948211669921875, "__label__art_design": 0.0004649162292480469, "__label__crime_law": 0.0003807544708251953, "__label__education_jobs": 0.0005259513854980469, "__label__entertainment": 7.683038711547852e-05, "__label__fashion_beauty": 0.00018703937530517575, "__label__finance_business": 0.0002906322479248047, "__label__food_dining": 0.000335693359375, "__label__games": 0.0007710456848144531, "__label__hardware": 0.0029144287109375, "__label__health": 0.0004684925079345703, "__label__history": 0.00032138824462890625, "__label__home_hobbies": 0.00010782480239868164, "__label__industrial": 0.0007491111755371094, "__label__literature": 0.0002110004425048828, "__label__politics": 0.0003447532653808594, "__label__religion": 0.0005674362182617188, "__label__science_tech": 0.07208251953125, "__label__social_life": 6.598234176635742e-05, "__label__software": 0.007465362548828125, "__label__software_dev": 0.90966796875, "__label__sports_fitness": 0.0003483295440673828, "__label__transportation": 0.00112152099609375, "__label__travel": 0.0002341270446777344}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 47613, 0.01815]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 47613, 0.41656]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 47613, 0.86214]], "google_gemma-3-12b-it_contains_pii": [[0, 0, null], [0, 3933, false], [3933, 8379, null], [8379, 12372, null], [12372, 17432, null], [17432, 20667, null], [20667, 26389, null], [26389, 31235, null], [31235, 36653, null], [36653, 42006, null], [42006, 47613, null]], "google_gemma-3-12b-it_is_public_document": [[0, 0, null], [0, 3933, true], [3933, 8379, null], [8379, 12372, null], [12372, 17432, null], [17432, 20667, null], [20667, 26389, null], [26389, 31235, null], [31235, 36653, null], [36653, 42006, null], [42006, 47613, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 47613, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 47613, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 47613, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 47613, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 47613, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 47613, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 47613, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 47613, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 47613, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 47613, null]], "pdf_page_numbers": [[0, 0, 1], [0, 3933, 2], [3933, 8379, 3], [8379, 12372, 4], [12372, 17432, 5], [17432, 20667, 6], [20667, 26389, 7], [26389, 31235, 8], [31235, 36653, 9], [36653, 42006, 10], [42006, 47613, 11]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 47613, 0.0]]}
olmocr_science_pdfs
2024-12-09
2024-12-09
ef0aa9a594f22fe2081464a724f8b8a507ebc5ce
Evolutionary Feature Evaluation for Online Reinforcement Learning Julian Bishop, Risto Miikkulainen Department of Computer Science The University of Texas at Austin 2317 Speedway, Stop D9500, Austin, TX, USA {julian, risto}@cs.utexas.edu Abstract—Most successful examples of Reinforcement Learning (RL) report the use of carefully designed features, that is, a representation of the problem state that facilitates effective learning. The best features cannot always be known in advance, creating the need to evaluate more features than will ultimately be chosen. This paper presents Temporal Difference Feature Evaluation (TDFE), a novel approach to the problem of feature evaluation in an online RL agent. TDFE combines value function learning by temporal difference methods with an evolutionary algorithm that searches the space of feature subsets, and outputs a ranking over all individual features. TDFE dynamically adjusts its ranking, avoids the sample complexity multiplier of many population-based approaches, and works with arbitrary feature representations. Online learning experiments are performed in the game of Connect Four, establishing (i) that the choice of features is critical, (ii) that TDFE can evaluate and rank all the available features online, and (iii) that the ranking can be used effectively as the basis of dynamic online feature selection. Keywords—Reinforcement Learning; online learning; Evolutionary Algorithms; feature selection; Connect Four. I. INTRODUCTION Reinforcement Learning (RL) [1] is a potentially powerful way to discover effective behavior in games. An RL agent attempts to change its policy in order to maximize its rate of reward. RL takes place online if the agent must learn from playing real games, and the quality of its performance in those games matters. Therefore an online agent must balance exploitation of what it has learned so far with effective exploration of alternative actions. Typically, an RL agent perceives the state of the game as a one-dimensional array of real numbers called features. A feature is any intrinsic state-variable of the game, or any real-valued function taking some subset of the state-variables as its domain. An important challenge for RL is that of feature selection, in which some available features are ignored because they would harm the agent's performance, not help it. Feature selection can be further decomposed into two sub-problems: First, evaluate the available features for their potential utility and, second, apply some decision process based on the evaluations to pick which features will be ignored. This paper presents a novel approach to the first of these sub-problems, called Temporal Difference Feature Evaluation (TDFE). TDFE ranks features from best to worst, but does not specify a decision process for picking which features will be ignored. Although a decision process must be implemented in order to use TDFE as part of an agent, this paper does not advocate for any particular decision process or agent design. Instead, it demonstrates that feature evaluation matters, and that TDFE is an effective way to do it. TDFE is intended for use in an online RL agent that uses features as inputs to a value function which it updates by temporal difference algorithms [1]. TDFE evaluates multiple feature subsets in parallel and uses an evolutionary algorithm to find combinations of features that work well together. Statistical estimates about each subset are combined to generate a ranking over the available features. TDFE is unique in that it combines three useful properties. First, TDFE is scalable: The ranking induced includes all the features that are available to the agent, which is typically more features than the agent is actually using to learn its policy in the game. Moreover, increasing the number of available features does not increase the number of game-states that the agent needs to sample in order to compute the ranking. This property is desirable for online learning because the speed of improvement with respect to the number of games played matters. Although the cost per sampled state of computing the ranking does increase with the number of available features, the issue can be mitigated because TDFE is amenable to distribution across parallel hardware. Second, the ranking induced by TDFE is dynamic: All the statistics needed to compute the ranking are updated incrementally after each sampled game-state, which allows the ranking to be adjusted at arbitrary time intervals. A dynamic ranking is desirable because the relative importance of the agent's available features can change over time. For example, as the agent learns to play better, it begins to encounter new game-states in which a previously irrelevant feature becomes useful. Alternatively, other players in the game could change their policies causing a similar effect. Or, if the agent attempts a search in the space of possible features, then some old features could be replaced with newly constructed ones which will then need to be included in the ranking. Third, TDFE makes no assumptions about the underlying function representation of any features. For example, TDFE can evaluate a set of features containing a mixture of Neural Networks, Decision Trees, and Genetic Programs on a level playing field, and include them all in the same ranking. Representation-agnostic feature evaluation is desirable because the best features in different games may be based on different function representations. Online learning experiments were performed in the game of Connect Four to test the benefit of TDFE. A simple RL agent's performance using TDFE was almost as good as when it was provided with the best possible choice of features in advance. II. RELATED WORK Some recent RL algorithms have adapted techniques from Supervised Learning to the RL problem. LARS-TD [2] combines LARS (Least Angle Regression) and LSTD for finding the $l_1$-regularized fixed point value function. EGD (Equi-Gradient Descent) [3] adapted LARS for minimizing the Bellman residual for temporal difference learning. OMP (Orthogonal Matching Pursuit) is a greedy feature-selection algorithm for regression which uses the correlation between the residual and the candidate features to decide which feature to add next. OMP has been adapted to RL in OMP-BRM and OMP-TD [4]. Unlike TDFE, the applicability of the above methods to online learning is limited by two factors: First, they rely upon batch updates, meaning that the agent does not modify its policy until a sufficient number of game states have been sampled, which increases the amount of time during which the agent's policy is fixed. Second, these methods assume a set of features that does not change while the agent learns, which is particularly significant for the greedy algorithms because they offer no natural way to backtrack and revise earlier feature selection decisions. Some methods attempt to obviate the problem of feature selection by constructing and/or tuning only a minimal set features and simply using all of them. Examples include Proto-Reinforcement Learning (PRL) [5], Bellman Error Basis Functions [6], and Adaptive Bases [7]. Unlike TDFE, these methods are tied to specific function representations for their features and hence are not representation-agnostic. Evolutionary algorithms are typically applied to feature evaluation as an offline method. That is, the learning task is used as a wrapper to provide the fitness function for evolving features and feature subsets. Examples include FS-NEAT [8], and variants of Genetic Programming [9]. These offline methods have been adapted to RL by using the performance of an RL agent as the wrapper. Examples include Pittsburgh-style Learning Classifier Systems [10], and agents that use Genetic Programming [11]. Unlike TDFE, the wrapper approaches are of limited use for online RL because they are based on a population of policies each of which needs to be independently evaluated. This requirement causes the overall sample complexity to be multiplied by the population size. NEAT+Q [12] attempts to mitigate this problem but must still evaluate a population of policies. A Michigan-style Learning Classifier System [10] avoids the sample multiplier by being a complete RL agent in which feature evaluation is an integral part of the value function. In contrast, TDFE is not an agent, it is a method for performing feature evaluation as a separate module from the agent's value function. III. TEMPORAL DIFFERENCE FEATURE EVALUATION Fig. 1 depicts the four-stage process that TDFE iterates over to evaluate features. Stages A-D are described in the next four sub-sections. A. Feature Subset Population (FSP) The benefit of any particular feature may depend upon which other features it is used in conjunction with. For example, consider a feature that only has predictive power in some subset of the agent's state space. Whether or not those states are even reached by the agent depends upon its policy, which in turn depends upon all the features it is using. Furthermore, temporal difference learning's ability to address the temporal credit assignment problem relies on features whose contributions can reduce the magnitude of the temporal difference error in sequences of states that lead to reward. Therefore some feature subsets may support one path to reward while other feature subsets support a different path. For these reasons, feature evaluation and selection in online RL are intertwined with the exploration-exploitation problem [1], and evaluating only a single feature subset is insufficient. Initialization of the FSP is controlled by three system parameters. PopSize sets the number of subsets to be created, and InitSubsetMean and InitSubsetSD set the mean and standard deviation of a normal distribution that is sampled to choose the cardinality of each subset. Each subset is initialized by uniform randomly picking features without replacement from the available feature universe until the target cardinality is reached. B. Feature Subset Evaluation In TDFE, each feature subset in the FSP is connected to its own value function approximator, called a Feature Subset Evaluator (FSE). So if there are 100 feature subsets in the FSP, then there are 100 FSEs, and they are all updated in parallel along with the agent's value function. All the FSEs use the same kind of function approximator as the agent's value function, and they are updated using the same algorithm. The motivation for these similarities is to evaluate features in a way that is directly relevant to the agent. In this paper the agent is assumed to be using a linear value function with gradient descent weight updates guided by Q-Learning [1] and state-action pairs represented as after-states. Extending TDFE to more sophisticated RL agents and/or value function approximators is left for future work. The FSEs do not participate in the agent's action selection (i.e. policy); their sole purpose is to evaluate features. Consequently, each feature subset is evaluated in the context of the same policy, i.e. the agent's policy, whatever that happens to be. Therefore the FSE must be updated by an off- Fig. 1. TDFE. (A) Consider multiple different feature subsets in parallel. (B) Evaluate each feature subset in the setting of the learning algorithm used by the agent, updating statistical estimates incrementally. (C) Combine all statistical estimates into a single feature-quality score and rank all features (FSP is the set of feature subsets that include \( f_i \)). (D) Search the space of feature subsets to find better combinations of features for the next iteration. policy RL algorithm [1]. That is, an algorithm that can (in theory) learn the optimal value function while the agent continues to follow a sub-optimal policy. Although this limits the choice of algorithm, the benefit is that the number of states the agent needs to experience in order to update the FSEs is independent of the number of FSEs. By distributing FSEs across parallel hardware, the number of features that TDFE can evaluate simultaneously can be further scaled up. For each after-state \( s \) selected by the agent’s policy, the weight updates reduce the difference between an FSE’s value estimate and a target value. The target value depends on information from the next time step. Hence the term temporal difference error, or TDE: \[ TDE(s) = \text{TargetValue}(s) - \text{CurrentEstimate}(s) = \text{reward} + \gamma \cdot \max_{s'} Q(s') - Q(s). \tag{1} \] The extent to which TDE can be minimized is dependent upon the quality of the features \( f_i \). Hence a measure of the magnitude of the TDE can be interpreted as a measure of the quality of the feature subset in the context of the policy that induced the agent’s state trajectory. In TDFE the measure chosen is the mean squared TDE: \[ \text{MSTDE} = \frac{1}{t_2 - t_1 + 1} \sum_{t=t_1}^{t_2} \text{TDE}(s_t)^2, \tag{2} \] where \( t_1 \) and \( t_2 \) denote the time interval of interest. TDFE uses the heuristic that within each FSE, the more important features will tend to have weights of greater magnitude and stability. The stability of a signal can be measured by its coefficient of variation which is the ratio between its standard deviation and mean: \[ \text{CV}(X) = \frac{\sigma_X}{\bar{X}}. \tag{3} \] All the statistics computed within each FSE are either means or can be calculated from means. Means are tracked incrementally using the exponentially decaying recency-weighted average update rule [1]. Recency-weighting in the means is important because they all change with time as the weights in the FSE are updated under learning. C. Feature Evaluation The formula defined in Fig. 1(C) is used to assign a score to every feature. For feature \( f_i \), the summation includes one term for each subset that includes \( f_i \). Each term is the product of a subset-score and three penalty functions, \( p_1, p_2 \) and \( p_3 \). The subset-score is defined as: \[ \text{SubsetScore}(FSE) = \sqrt{|FSP| - \text{Rank}(FSE)}, \tag{4} \] where \( \text{Rank}(FSE) \) is zero for the best FSE (lowest MSTDE) and the cardinality of the FSP for the worst. The square-root is chosen only because it is a slow-growing function. The three penalty functions (equations 5-7) are used to normalize into \([0, 1]\) the penalties for features having too constant values, unstable weights, and smaller weights, respectively: \[ p_1(x) = \begin{cases} |x|, & |x| < 0.5 \\ 1, & \text{otherwise} \end{cases} \tag{5} \] \[ p_2(x) = \text{MAX}(0, 1 - |x|) \tag{6} \] \[ p_3(x) = \text{MIN}(1, |x|/\text{RewardRange}) \tag{7} \] where \( \text{RewardRange} \) is the difference between the most extreme rewards the agent has experienced. All the features are then sorted by their scores, and the resulting ranking is the output of TDFE. D. Subset Search GA Algorithm 1 implements one generation of evolution, and is run at a regular interval set by the system parameter \( \text{GamesPerGeneration} \). TDFE evolves subsets of features, not value functions or policies. Each newly created subset always gets a new FSE with weights initialized to zero. In short, TDFE uses Darwinian evolution, not Lamarckian. The fitness of a feature subset is the MSTDE of its FSE, which measures how self-consistently and accurately its value function makes predictions about long-term future reward given the agent’s policy. The benefit of the GA is to find combinations of features that work well together, which improves the quality of TDFE’s feature ranking in stage (C). TDFE employs a steady-state population model, i.e. only a small fraction of the population are replaced in each generation. Consequently the population contains individuals of different ages: Some FSEs have undergone more generations of weight optimization than others, and a fair comparison of their MSTDE is difficult. Algorithm 1 resolves this in line 4 by applying a fixed survivor rate within each age group. In increasing order of age, the sizes of the age groups form a simple geometric series with the survivor rate as the common ratio. The final age group combines all ages from which the expected number of survivors is less than one, and forms a natural hall of generation champions. This scheme delays the need to distinguish between the best subsets until their MSTDE estimates are more refined, and allows evolution to remove the worst subsets meanwhile. Recombination and mutation are both implemented by the \( \text{EDIT extunderscore WALK} \) function, which performs a random walk in the space of subsets with a sequence of edit operations. Starting at the first parent, each edit is either the removal or addition (equally likely) of a feature chosen at random. The system parameters \( \text{EditsMean} \) and \( \text{EditsSD} \) set the mean and standard deviation of a normal distribution that is sampled to choose the number of edits. If a second parent is specified, it serves as an attractor for the random walk by restricting the cuts and adds to those that reduce the edit distance between the two parents. \( \text{EDIT extunderscore WALK} \) has no bias towards subsets of any particular cardinality. IV. EXPERIMENTAL DOMAIN: CONNECT FOUR Connect Four has been a fun and interesting real world game since before personal computers were invented. Fig. 2 outlines the rules of the game. Connect Four is suitable for testing TDFE for several reasons: First, the game is difficult enough to be an open problem for online RL, and also for human learners. Second, the state-space is small enough (~4.5e12 [13]) that is has been solved by exhaustive methods [14], and therefore it is possible to measure the quality of an agent’s learned policy on an absolute scale between random and optimal play. Third, Connect Four strategy has been thoroughly studied [15], and many board features are known to be important for strong play. Such features should be highly ranked by any good system of feature evaluation. Two players take turns dropping their colored counter into one of seven columns on the board. Dropped counters fall down the column as if under gravity. The goal is to make four-in-a-row on a horizontal, vertical or diagonal line. In the game shown the second player to move has won with a diagonal. A draw occurs if neither player makes 4-in-a-row before the board becomes full. Algorithm 1: Makes the next generation of subsets: fixed survival rate within age groups, tournament selection (size 2) of parents from survivors, edit-walk crossover and mutation. 1. Evolve(): 2. \( \text{FSP\textunderscore SORT\textunderscore BY}(\text{fse}\text{.age, fse\text{.MSTDE}}) \) 3. for each \( \text{fse in FSP} \): 4. if \( \text{fse\text{.ELITE\text{.IN\text{.AGE\text{.GROUP}}}(\text{survivorRate})}} : \) 5. \( \text{.age} \text{+= 1} \) 6. else: 7. \( \text{.age} \text{=} 0 \) 8. Survivors = [\text{FSP where .age} > 0] 9. Children = [\text{FSP where .age} = 0] 10. for \( i = 1 \) to \( |\text{Children}| - 1 \) step 2: 11. \( p1 = \text{SELECT\text{.PARENT\text{.FROM}(Survivors)} \) 12. \( p2 = \text{SELECT\text{.PARENT\text{.FROM}(Survivors)} \) 13. if RANDOM\_REAL\( (0, 1) < \text{probCrossover} \): 14. \( \text{Child1Subset} \text{=} \text{EDIT\text{.WALK}(p1, p2)} \) 15. \( \text{Child2Subset} \text{=} \text{EDIT\text{.WALK}(p2, p1)} \) 16. else: 17. \( \text{Child1Subset} \text{=} \text{EDIT\text{.WALK}(p1, nil)} \) 18. \( \text{Child2Subset} \text{=} \text{EDIT\text{.WALK}(p2, nil)} \) 19. \( \text{Children}[i - 1].\text{initialize(Child1Subset)} \) 20. \( \text{Children}[i].\text{initialize(Child2Subset)} \) 21. if \( i \text{=} |\text{Children}| \) 22. \( \text{pLast} = \text{SELECT\text{.PARENT\text{.FROM}(Survivors)} \) 23. \( \text{LastSubset} \text{=} \text{EDIT\text{.WALK}(pLast, nil)} \) 24. \( \text{Children}[i - 1].\text{initialize(LastSubset)} \) A. Features The most basic set of features is an enumeration of the contents of the 42 board cells. With respect to Fig. 2, a 1, -1 or 0 denote black, gray or empty, respectively. Such a naive board-vector considers each board cell in isolation, yet success in the game depends upon exploiting patterns over adjacent board cells. Therefore there is no reason to expect the board-vector to facilitate learning a good policy by itself. In addition to the board vector, 26 hand-coded features were implemented as a best effort to generalize over board positions that are equivalently good. The hand-coded features are similar to those suggested by Allen [15] and are listed in Table I where the following terminology applies: A threat for a player is an empty cell that could be part of a four-in-a-row for that player. A level **n-threat** is a threat for which *n* members of the four-in-a-row are already present. The **perimeter** is all the cells in which the next counter could be placed. An **on-perimeter threat** is a threat in one of the perimeter cells. An **off-perimeter threat** is a threat not in one of the perimeter cells. A player **controls a column** if it has the lowest off-perimeter 3-threat. An **adjacent threat** is two vertically adjacent cells that are both threats for the same player. An **adjacent threat score** is the sum of the threat levels in an adjacent threat. A **trap** is an adjacent threat score of six. A **playable trap** is a trap in a column controlled by the player who has the trap. **TABLE I. HAND-CODED FEATURES, COMPUTED FOR BOTH PLAYERS.** <table> <thead> <tr> <th>Feature Description</th> </tr> </thead> <tbody> <tr> <td>Number of on-perimeter 1-threats</td> </tr> <tr> <td>Number of on-perimeter 2-threats</td> </tr> <tr> <td>Number of on-perimeter 3-threats</td> </tr> <tr> <td>Number of off-perimeter 1-threats, each weighted by $1/(2^h_1)$</td> </tr> <tr> <td>Number of off-perimeter 2-threats, each weighted by $1/(2^h_2)$</td> </tr> <tr> <td>Number of off-perimeter 3-threats (max 1 per cell), weighted by $1/(2^h_3)$</td> </tr> <tr> <td>Highest adjacent threat score on the board</td> </tr> <tr> <td>Sum over all adjacent threats of $1/(4^{\text{height of threat or trap above the perimeter}})$</td> </tr> <tr> <td>Maximum over all playable traps of $1/(8^\text{height of threat or trap above the perimeter})$</td> </tr> <tr> <td>Number of controlled columns</td> </tr> <tr> <td>Win-next-move flag: 1 if player is guaranteed to win next turn, 0 otherwise</td> </tr> <tr> <td>Four-in-a-row flag: 1 if player has four-in-a-row, 0 otherwise</td> </tr> <tr> <td>Win-forced-by-turn flag: binary flag indicating that if no new 3-threats are created then opponent will be forced by turn taking to give player a win.</td> </tr> </tbody> </table> --- **B. Performance Measure** Three fixed-policy agents are important for defining the performance measure that appears on the y-axis of all the learning curves presented in this paper: 1) **Random**: always selects a move uniformly-randomly from among the legal moves. 2) **Simpleton**: If a move to make four-in-a-row and win is present, the agent selects it. If no four-in-a-row move is present but a move is present to block the opponent from making four-in-a-row on its next turn, the agent selects it. Otherwise the agent selects a move uniformly-randomly, excluding any move that immediately creates a trap in a column controlled by the opponent. A move to make four-in-a-row on its next turn. 3) **Genius**: always selects an optimal move. An optimal move will lead to a game outcome (win, lose or draw) at least as good as any other move under the assumption of optimal play by both players until the end of the game. Ties between winning moves are broken uniformly randomly. Ties between drawing or losing moves are broken using a variant of the Expectimax algorithm [16], by computing the probability of a Simpleton opponent making a sub-optimal move thereafter. Using the Simpleton as an opponent model results in selecting moves that maximize the sub-optimal proportion of the opponent’s responses, which is a sensible strategy in the absence of the true opponent model. A log containing nine million solved board positions was generated by recording games between two augmented Genius agents. An augmented Genius is forced to move as a Random player with probability *p*. Twelve values for *p* were used to create twelve Player1 Geniuses and twelve Player2 Geniues: 0.00, 0.05, 0.10, 0.15, 0.20, 0.25, 0.30, 0.35, 0.40, 0.45, 0.50, 0.55. Three thousand games were recorded for each of the 144 possible pairings of a Player1 with a Player2, making a total of 432,000 games in the log, comprised of about six million distinct board positions distributed over nine million played positions. The duplicate positions are desirable because they naturally attribute more weight to board positions that occur more often. For each board position, the legal moves were ranked by a Genius agent. To evaluate a candidate Connect Four policy using the log, the following procedure is followed: For each applicable position in the log (Player-1 or Player-2), the candidate is asked for its move, and the probability that a Random agent would have made a better move is computed from the move rankings. The average of these probabilities over all applicable positions in the log is denoted $\Pr(\text{CandidateWTR})$, where $WTR$ stands for Worse-Than-Random. Two moves are equal in rank with probability 0.3. Hence $\Pr(\text{RandomWTR}) = 0.35$, and any candidate such that $\Pr(\text{CandidateWTR}) > 0.35$ is truly worse than a Random agent. Consequently the value of $\Pr(\text{CandidateWTR})$ is rescaled into a metric called $WTR$: $$WTR(\text{Candidate}) = \frac{\Pr(\text{RandomWTR}) - \Pr(\text{CandidateWTR})}{\Pr(\text{RandomWTR})}. \quad (8)$$ By definition, $WTR(\text{Random}) = 0$, and $WTR(\text{Genius}) = 1$ which is the best possible score. Even a highly random player such as a Simpleton receives a very consistent $WTR$ score: 0.1624 ± 0.00011 as Player-1, 0.1829 ± 0.00016 as Player-2 (99% confidence intervals). **V. EXPERIMENTS** Experiments with TDFE require a decision process for picking which features will be ignored based on the TDFE feature ranking, and an online RL agent that uses the remaining features as inputs to its value function. These details are presented next, followed by the results obtained in two sets experiments: one with TDFE disabled as a baseline, and one with TDFE enabled. **A. RL Agents** A canonical RL agent is needed to serve as a platform for testing TDFE. The agent chosen is a Q-Learning agent, with after-states representing state-action pairs, a linear value-function approximator trained by gradient descent weight updates, and e-greedy action selection [1]. This formulation of an RL agent is one of the oldest and best understood and it has some limited convergence guarantees. Game features are normalized into the range [-1, 1] and used as inputs to the agent’s value function. Fig. 3 shows how the Canonical RL agent (green box) was combined with TDFE. The Feature Selection module in Fig. 3 resets which features will be ignored at the start of each new game based on the dynamic feature ranking from TDFE: Features are selected greedily from the feature ranking. The initial number of features used by the agent is based on the average cardinality of the evolving feature subsets. In addition, a pool of candidate features is selected by continuing greedily down the feature ranking until a cost limit is reached. As the agent Fig. 3. System diagram for the online RL agent comprised of the Canonical Agent, a Feature Selection module, and TDFE. The models are used by the agent to obtain a list of legal moves in the current state, and to compute the after-state of any action. In this paper the Environment is Connect Four. On each discrete time-step in the game, the agent has access to the current state 'S' and a reward signal 'r'. The agent executes its chosen action 'a'. When it is the agent's turn to act again, it sees the next state and reward, S' and r'. The agent learns, estimates are made of the Pearson correlation coefficient between the agent's temporal difference error and each candidate feature's potential contribution to that error (which is similar to OMP-BRM [4]). If the most correlated candidate feature satisfies a selection condition it is added to the agent's value function and all correlation estimates are re-estimated from scratch in the context of the new value function until the selection condition is satisfied again. If the MSTDE of the agent's value function exceeds that of any feature universe the policy learned is human-competitive. Given only the hand-vector, the policy learned is worse than a random player. The union of all features results in worse learned policy than the hand-coded features alone. B. Baseline Experiments As a baseline for experiments with TDFE, the canonical agent's ability to learn a good Connect Four policy online was tested with TDFE and feature selection both disabled, i.e. the agent used all available features unconditionally. The same experiment was repeated three times varying only the set of features given to the agent: first with the board-vector only, second with the hand-coded features only, and third with the union of the board-vector and hand-coded features. All three experiments involve two canonical RL agents, one as Player-1 and a separate one as Player-2. The two agents learned while playing 8000 games against each other. Each game was treated as a separate learning episode with zero reward except in the terminal states which gave +100 for a win, -100 for a loss, and 0 for a draw. The discount factor γ was set to 1 because the problem is episodic. The exploration rate ε was set to 0.1. The learning rate α was set to 1/n, where n is the number of features. This makes the maximum rate by which the value function's output can change independent of n. The average learning curves for Player-1 are shown in Fig. 4 (results for Player-2 are similar and omitted). Each data-point and its accompanying error bars show the mean and standard deviation of WTR score. This setup was run 20 times for each feature set. The baseline experiment in which the agent was given the board-vector and hand-coded features only, was tested with TDFE and feature selection both disabled, and then enabled. C. TDFE Experiments The baseline experiment in which the agent was given the union of all H26-B42 features was repeated with TDFE and feature selection enabled. An equivalent experiment was also performed in each of two additional feature universes, first with TDFE and feature selection disabled, and then enabled. Fig. 5. Comparing the performance of the canonical RL agent with and without TDFE and Feature Selection enabled in three different feature sets. All three feature sets include the 26 hand-coded features (H26), and the learning curve of the canonical agent using only H26 is repeated in each sub-plot as a referent. H26-B42 (a) is the same as in the baseline experiments. H26-U74 (b) includes 74 uniformly distributed random variables. H26-SN74 (c) includes 74 standard normally distributed random variables. In both additional feature universes, the 42 board-vector features were replaced with 74 independent identically distributed random variables, introduced as features that are pure noise, i.e. bearing no relation to the state of the game. In H26-U74, each random variable samples a uniform distribution on the interval [-1, 1]. In H26-SN74, each random variable samples a standard normal distribution. In all runs, the TDFE system parameters were set as follows: PopSize = 100, GamesPerGeneration = 100, SurvivorRate = 0.8, InitSubsetMean = 3.25, InitSubsetSD = 1, ProbCrossover = 0.5, EditsMean = 10, EditsSD = 3. The average learning curves for Player-1 are shown in Fig. 5 (again the Player-2 curves are similar). All three sub-plots include the canonical agent's performance when using only the hand-coded features (H26) as a referent for the best performance that the TDFE agent could hope to achieve. Fig. 5(a) shows that the agent's performance in H26-B42 is significantly better with TDFE and feature selection enabled. In that case the agent's average final performance is 6.9% worse than the level associated with selecting H26 exclusively. However, its average best performance is within 1.9% of the H26 level, indicating that the TDFE agent peaks close to the H26 level but is less stable. These differences are statistically significant at the 0.05 level. Fig. 5(b) shows that the agent's performance in H26-U74 is significantly better with TDFE and feature selection enabled. The difference between the TDFE agent and the H26 level is not statistically significant. Fig. 5(c) shows that the agent's performance in H26-SN74 is no better with TDFE and feature selection enabled. Interestingly, there is no statistically significant difference between the TDFE agent in H26-U74 and H26-SN74, showing that it is insensitive to the distribution of noise. However, the change from uniform to normal random variables greatly improves the canonical agent's baseline performance, such that the only negative impact of the 74 normal variables is to slow down learning. This result is explained by feature normalization, but is useful for showing the effect of TDFE on the agent's performance in a feature universe that has relatively little need for feature selection. VI. DISCUSSION AND FUTURE WORK The experiments in Section V establish that the performance of online RL in Connect Four depends upon the available features. Given a well-engineered set of features based upon established heuristics, even a very basic RL agent can bootstrap itself up from an initially random policy to a human-competitive level guided only by a reward signal that is zero everywhere except states having 4-in-a-row. In contrast, given only the vector of board cells, the same canonical agent is unable to improve and actually performs worse than randomly due to the misleading nature of those features. These bad features are not irrelevant: They are a perfect noiseless encoding of the game-state, and indeed are the domain of all functions found to be good features. Despite their relevance, they significantly harm the agent's performance even when all the good features are present. The effect of irrelevant noisy features on the canonical agent The experiments in Section V establish that the performance of online RL in Connect Four depends upon the available features. Given a well-engineered set of features based upon established heuristics, even a very basic RL agent can bootstrap itself up from an initially random policy to a human-competitive level guided only by a reward signal that is zero everywhere except states having 4-in-a-row. In contrast, given only the vector of board cells, the same canonical agent is unable to improve and actually performs worse than randomly due to the misleading nature of those features. These bad features are not irrelevant: They are a perfect noiseless encoding of the game-state, and indeed are the domain of all functions found to be good features. Despite their relevance, they significantly harm the agent's performance even when all the good features are present. The effect of irrelevant noisy features on the canonical agent The experiments in Section V establish that the performance of online RL in Connect Four depends upon the available features. Given a well-engineered set of features based upon established heuristics, even a very basic RL agent can bootstrap itself up from an initially random policy to a human-competitive level guided only by a reward signal that is zero everywhere except states having 4-in-a-row. In contrast, given only the vector of board cells, the same canonical agent is unable to improve and actually performs worse than randomly due to the misleading nature of those features. These bad features are not irrelevant: They are a perfect noiseless encoding of the game-state, and indeed are the domain of all functions found to be good features. Despite their relevance, they significantly harm the agent's performance even when all the good features are present. The effect of irrelevant noisy features on the canonical agent The experiments in Section V establish that the performance of online RL in Connect Four depends upon the available features. Given a well-engineered set of features based upon established heuristics, even a very basic RL agent can bootstrap itself up from an initially random policy to a human-competitive level guided only by a reward signal that is zero everywhere except states having 4-in-a-row. In contrast, given only the vector of board cells, the same canonical agent is unable to improve and actually performs worse than randomly due to the misleading nature of those features. These bad features are not irrelevant: They are a perfect noiseless encoding of the game-state, and indeed are the domain of all functions found to be good features. Despite their relevance, they significantly harm the agent's performance even when all the good features are present. The effect of irrelevant noisy features on the canonical agent depends upon the distribution of the noise: Uniformly distributed random variables significantly harm the agent's learned policy, but normally distributed random variables only delay learning. TDFE was presented as a novel way to evaluate and rank all available features online, i.e. while the agent is learning in the actual game. The canonical agent was modified to dynamically adjust its feature selection at the start of each game based upon the current TDFE rankings. The resulting performance is close to that of using only the best available features and unaffected by whether the other available features are relevant yet harmful, irrelevant harmful noise, or irrelevant yet mostly harmless noise. In all cases, the good features were in the minority. An inspection of the TDFE feature-ranking (not shown) revealed that the hand-coded features for detecting winning moves and blocking the opponent's winning moves are always in the top-three ranked features by the end of every run. Although this evidence is anecdotal, it is encouraging that such domain-critical features are reliably identified by TDFE without the use of a domain- specific heuristic. The primary line of future work is for the TDFE feature ranking to guide an evolutionary search over the space of possible features as part of an online RL agent. TDFE is representation-agnostic with respect to features, so any evolvable function representations can be used side-by-side. TDFE's feature ranking is dynamic, so newly constructed features can be naturally included. TDFE does not treat the game as a wrapper for evaluating multiple policies, and so it will avoid the sample complexity multiplier associated with most evolutionary methods. This paper has not attempted to show that TDFE is the only or even the best way to do feature evaluation in online RL. However, none of the other methods surveyed in Section II have all of the desirable properties explained in Section I. Those properties make TDFE of unique interest as a platform for this project's future work. VII. CONCLUSION This paper has shown that performing feature evaluation as part of an online RL agent matters, and that it can be performed in a way that is scalable, sample efficient, dynamic, and agnostic with respect to any feature's underlying function representation. The resulting method is called Temporal Difference Feature Evaluation or TDFE, and will serve as a stepping stone to future work on automatic feature construction in an online RL agent. ACKNOWLEDGMENT Thanks to James D. Allen and John Tromp for providing a C++ program that functions as a Connect-4 oracle capable of solving the game from any board position. Thanks to Matthew Hausknecht for multiple supporting references. REFERENCES least-squares temporal difference learning,” in Proceedings of the 26th international Conference on Machine Learning (ICML'09), 2009, pp. 521-528. learning using LASSO,” in Proceedings of IEEE international Symposium on Approximate Dynamic Programming and Reinforcement Learning,” in Proceedings of the Twenty-Ninth learning,” in Proceedings of the 22nd International Conference on Machine learning (ICML'05), Bonn, Germany, 2005, pp. 553-560. feature generation for value-function approximation,” in Proceedings of the 24th international conference on Machine learning, Corvalis, learning,” in Proceedings of the 2010 European conference Machine Learning and Knowledge Discovery in Databases, 2010, pp. 312-327. “Automatic Feature Selection via Neuroevolution,” in Genetic and algorithm for feature construction and selection,” Genetic Programming and Evolvable Machines, vol. 6, no. 3, pp. 265-281, 2005. Forrest, R. Riolo, R. Smith, P. Lanzi, W. Stolzmann, and S. Wilson, “What Is a Learning Classifier System?,” Learning Classifier Systems, Lecture Notes in Computer Science, Lecture Notes in learning using genetic programming,” in Proc. 11th European for Reinforcement Learning,” Journal of Machine Learning Two-Player Games," KI 2008: Advances in Artificial Intelligence, Lecture Notes in Computer Science A. Dengel, K. Berns, T. Breuel, F. Bomarius and T. Roth-Berghofer, eds., pp. 185-192: Springer is solved: White wins. Master's thesis, Faculty of Mathematics and Computer Science, Free University, Amsterdam, 1988.
{"Source-Url": "http://www.cs.utexas.edu/users/ai-lab/downloadPublication.php?filename=http%3A%2F%2Fnn.cs.utexas.edu%2Fdownloads%2Fpapers%2Fbishop.cig2013.pdf&pubid=127484", "len_cl100k_base": 9394, "olmocr-version": "0.1.48", "pdf-total-pages": 8, "total-fallback-pages": 0, "total-input-tokens": 29829, "total-output-tokens": 10528, "length": "2e13", "weborganizer": {"__label__adult": 0.0010395050048828125, "__label__art_design": 0.0009365081787109376, "__label__crime_law": 0.0013141632080078125, "__label__education_jobs": 0.0032215118408203125, "__label__entertainment": 0.0004835128784179687, "__label__fashion_beauty": 0.0006260871887207031, "__label__finance_business": 0.0008273124694824219, "__label__food_dining": 0.001285552978515625, "__label__games": 0.039398193359375, "__label__hardware": 0.0028858184814453125, "__label__health": 0.00200653076171875, "__label__history": 0.0011463165283203125, "__label__home_hobbies": 0.0003578662872314453, "__label__industrial": 0.0015268325805664062, "__label__literature": 0.0010280609130859375, "__label__politics": 0.0009059906005859376, "__label__religion": 0.0010728836059570312, "__label__science_tech": 0.3916015625, "__label__social_life": 0.0002474784851074219, "__label__software": 0.00861358642578125, "__label__software_dev": 0.53515625, "__label__sports_fitness": 0.001983642578125, "__label__transportation": 0.0015687942504882812, "__label__travel": 0.0005564689636230469}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 42951, 0.0303]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 42951, 0.1768]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 42951, 0.92439]], "google_gemma-3-12b-it_contains_pii": [[0, 5079, false], [5079, 11236, null], [11236, 14726, null], [14726, 20810, null], [20810, 27345, null], [27345, 30530, null], [30530, 37091, null], [37091, 42951, null]], "google_gemma-3-12b-it_is_public_document": [[0, 5079, true], [5079, 11236, null], [11236, 14726, null], [14726, 20810, null], [20810, 27345, null], [27345, 30530, null], [30530, 37091, null], [37091, 42951, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 42951, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 42951, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 42951, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 42951, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 42951, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 42951, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 42951, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 42951, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 42951, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 42951, null]], "pdf_page_numbers": [[0, 5079, 1], [5079, 11236, 2], [11236, 14726, 3], [14726, 20810, 4], [20810, 27345, 5], [27345, 30530, 6], [30530, 37091, 7], [37091, 42951, 8]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 42951, 0.05882]]}
olmocr_science_pdfs
2024-11-24
2024-11-24
803e1a40aa6c598ce5faca8afc322b6b0f7711ae
17 MACHINE LEARNING APPROACHES Walter Daelemans 17.1 INTRODUCTION The usefulness and feasibility of *automatically training* a syntactic wordclass tagger instead of hand-crafting it motivated a large body of work on statistical and rule-learning approaches to the problem. Syntactic wordclass taggers trained on corpora are claimed to be equally accurate as, and more robust and more portable than, hand-crafted systems\(^1\). Moreover, development time is considerably faster. Recently, inductive machine learning approaches such as connectionist learning algorithms, decision tree induction and case-based learning have also been applied to the syntactic wordclass disambiguation problem. In some cases these approaches have interesting properties not present in existing statistical and rule-based approaches. A successful inductive machine learning algorithm works by extracting generalizations from a set of examples of a desired input-output mapping. The relations between input and output, implicit in these examples, are discovered by the algorithm and are used to predict the correct output when presented with a new, previously unseen, input. \[^1\] Although we will report published accuracy figures for the taggers discussed, we should be cautious about them. Evaluation of the different methods has not been achieved the same way in each case. Table 17.1 Tagging as a mapping from sentences to tag strings. <table> <thead> <tr> <th>Input</th> <th>Output</th> </tr> </thead> <tbody> <tr> <td>John will join the board</td> <td>np md vb dt nn</td> </tr> </tbody> </table> Table 17.2 Tagging as a mapping from focus words with context to tags. <table> <thead> <tr> <th>Left context</th> <th>Focus</th> <th>Right context</th> <th>Output</th> </tr> </thead> <tbody> <tr> <td>=</td> <td>=</td> <td>will</td> <td>join</td> </tr> <tr> <td>=</td> <td>John</td> <td>will</td> <td>join</td> </tr> <tr> <td>John</td> <td>will</td> <td>join</td> <td>the</td> </tr> <tr> <td>will</td> <td>join</td> <td>the</td> <td>board</td> </tr> <tr> <td>join</td> <td>the</td> <td>board</td> <td>=</td> </tr> </tbody> </table> pattern. In other words, the algorithm classifies a new input pattern as belonging to a particular output category. Many problems in Natural Language Processing (NLP), especially disambiguation problems, can be formulated as classification tasks (Magerman 1994; Daelemans 1995; Cardie 1996). Tagging, e.g., can be seen as a mapping from sentences to strings of tags. In syntactic wordclass tagging, abbreviated tagging from here, a sentence should be mapped into a string of morphosyntactic tags (table 17.1). By approximating this mapping with a function from a focus word and its context to the disambiguated tag belonging to the focus word in that context (table 17.2), the mapping becomes a classification task amenable to symbolic and connectionist Machine Learning (ML) approaches. Context size can vary from one word at each side of the focus word (comparable to trigram models in statistics) to the complete sentence. Some machine learning methods dynamically determine the context size needed to disambiguate a particular focus word. The information provided to the learning algorithm can consist also of ‘morphological’ features (suffixes, presence or absence of a hyphen, a capital or a digit), syntactic information (features representing the syntactic context in which a word has to be tagged), or any other available linguistic information. In general, there will be as many examples for the learning algorithm as there are words in the training corpus. In this chapter, we will provide an overview of basic concepts in inductive learning methods and discuss recent research on the application of these methods to tagging. We will discuss case-based classifiers, decision tree induction methods and neural networks. Another promising approach is Inductive Logic Programming (ILP; e.g. Muggleton and De Raedt 1994), in which background knowledge and positive and negative examples are used to induce a logic program compatible with the background knowledge and all of the positive examples, but none of the negative examples. The induced logic programs are more expressive than the propositional language of feature vectors, which makes the approach potentially interesting to induce recursive tagging rules. See Cussens (1997) for an early example of this approach. 17.2 INDUCTIVE LEARNING FROM EXAMPLES 17.2.1 Concepts Machine Learning (ML) is a sub-discipline of Artificial Intelligence (AI) which studies algorithms that can learn either from experience or by reorganizing the knowledge they already have. See Langley (1996) and Carbonell (ed.) (1990) for introductory material, Weiss and Kulikowski (1991) for methodological issues and Natarajan (1991) for a formal-theoretical approach. Conceptually, a learning system consists of a performance component which achieves a specific task (given an input, it produces an output) and a learning component which modifies the performance component on the basis of its experience in such a way that performance of the system in doing the same or similar tasks improves (figure 17.1). Experience is interpreted rather narrowly here and is represented as a set of examples used to train the system. Examples usually take the form of pairs of inputs with their associated desired output. In tagging, the input is (a description of) a focus word and its context and the desired output is the disambiguated tag to be assigned to the focus word. To achieve its task, the performance component uses an internal representation. The task of the learning component may therefore be construed as a search in the space of possible representations for a representation that is optimal for performing the mapping. In this chapter, we will consider decision trees, case bases and sets of connection weights as types of languages/formalisms for internal representations for trainable taggers. In most cases, finding the optimal representation given a set of examples and a representation language is computationally intractable. Some form of heuristic search is therefore used by all learning systems. In Machine Learning, the concept of bias refers to domain-dependent constraints on the search process: knowledge about the task may be used to make the search simpler. There may also be bias in the way the experience presented to the learning component (the training examples) is preprocessed. The addition of linguistic bias to a learning system is the obvious way to let learning taggers profit from linguistic knowledge about the task. 17.2.2 Classification of learning methods Given this very general model of inductive learning, a number of dimensions can be distinguished that should be considered in comparing and experimenting with these techniques. - **Amount of Supervision.** In supervised learning, experience takes the form of examples of inputs and the corresponding desired output for each of these inputs. The examples are presented to the system in a training phase. In unsupervised learning, examples are presented without information about the desired output. It is up to the system to find similarities in the examples in such a way that they can be exploited by the performance component to solve the task. In reinforcement learning, no examples are given; only an indication of the correctness of the output the performance component produces given an input (feedback). Most of the research described in this chapter concerns supervised approaches (learning from examples). - **Input Representation.** Representations used in the ML literature include vectors of bits, vectors of feature-value pairs (numeric or nominal values; compare ‘flat’ feature structures in linguistics) and complex recursive representations such as... Table 17.3 Comparison of inductive learning methods discussed in this chapter. <table> <thead> <tr> <th></th> <th>Decision Tree</th> <th>Case-based</th> <th>Neural Network</th> </tr> </thead> <tbody> <tr> <td>Supervised</td> <td>YES</td> <td>YES</td> <td>YES</td> </tr> <tr> <td>Input Rep.</td> <td>feature value vector</td> <td>feature value vector</td> <td>bit string</td> </tr> <tr> <td>Output Rep.</td> <td>symbolic category</td> <td>symbolic category</td> <td>bit string</td> </tr> <tr> <td>Internal Rep.</td> <td>tree</td> <td>cases</td> <td>connection weights</td> </tr> <tr> <td>Incremental</td> <td>NO/yes²</td> <td>YES</td> <td>NO</td> </tr> <tr> <td>Noise tolerant</td> <td>YES</td> <td>YES</td> <td>YES</td> </tr> </tbody> </table> semantic nets (compare recursive feature structures in linguistics). For tagging problems, vectors of bits and of nominal feature-value pairs have been proposed. - **Output Representation.** Output can be a binary category (yes/no) decision, a symbolic category (a finite, discrete set of labels), a continuous category (a real number) or a vector of any of these. In machine learning for tagging, vectors of binary categories and symbolic categories are used (see also Chapter 4). - **Internal Representation.** The representation used by the performance component, and optimized by the learning component, can be numeric (e.g. connection weights with neural networks) or symbolic (semantic nets, rules, decision trees, examples, ...). - **Incremental Learning.** A learning system can be incremental. In that case, relevant information in additional examples can be integrated by the learning component into the performance component without re-learning everything from scratch. In non-incremental or batch learning systems (such as neural networks), this is not possible. In batch learning, the complete set of examples has to be inspected (sometimes several times) before learning is completed and addition of new examples makes complete relearning necessary. - **Noise Tolerance.** Different algorithms can be more or less sensitive to noise in the input (wrongly coded examples, missing values, or even ambiguous examples, i.e. examples which have been assigned contradictory outputs in the training set). Algorithms dealing with linguistic data should be noise-resistant. Table 17.3 gives a characterization of the different inductive learning algorithms discussed in this chapter along these dimensions. ² In most versions, the decision tree learning algorithm is batch learning, but incremental versions have been developed (e.g. Utgoff 1989). 17.2.3 Performance evaluations The success of a learning component in improving performance can be evaluated using a number of different quantitative and qualitative measures: - **Generalization accuracy.** Performance accuracy of the system on previously unseen inputs (i.e. inputs it was not trained on). This aspect of learning is of course crucial: it gives an indication of the quality of the *inductive leap* made by the algorithm on the basis of the examples. A good generalization accuracy indicates that the learning system has not *overfit* its training examples, as would happen by generalizing on the basis of errors or exceptions present in them. To get a good estimate of the real generalization accuracy, *cross-validation* can be used, e.g. in 10-fold cross-validation an algorithm is tested on ten different partitions (90% training material, 10% testing material) of the full data set available. Each data item occurs once in one of the test sets. The average generalization accuracy on the ten test sets is then a good statistical estimate of the real accuracy (see also Chapter 6). - **Space and time complexity.** The amount of storage and processing involved in learning (training the system) and performance (producing output given the input). - **Explanatory Quality.** Usefulness of the representations found by the learning system as an explanation of the way the task is achieved. 17.2.4 Overview of methods To sum up this introductory section, we will give an intuitive description of how each of the studied algorithms works, using tagging as an example application. We discuss the algorithms in an order of increasing abstraction of the internal representation used by the performance component and created by the learning component. We start from storage and *table-lookup* of the ‘raw’ examples as a non-learning baseline. - **Table Look-Up.** Store all examples (patterns of target words with their context and their corresponding disambiguated tag) in a table. When a new input pattern is given to the performance system, look it up in the table and retrieve the output of the stored example. In this approach the system does not actually learn anything and it fails miserably whenever an input pattern is not present in the table (there is no generalization). - **Case-Based Learning.** Store all examples in a table. When a new input pattern is given to the performance system, look up the most *similar examples* (in terms of number of feature values common to the stored pattern and the new pattern, for example) and extrapolate from the tags assigned to these nearest matches. to the new case. Various statistical and information-theoretic techniques can be used to design the similarity metric. The similarity metric is also a place where linguistic bias can be introduced in the learning algorithm. - **Rule and Decision Tree Induction.** Use similarities and differences between examples to construct a decision tree or a rule set (these two are largely equivalent and can be translated to each other) and use this constructed representation to assign a tag to a new input pattern. Forget the individual examples. - **Connectionism, Neural Networks.** Use the examples to train a network. In back-propagation learning, this training is done by repeatedly iterating over all examples, comparing for each example the output predicted by the network (random at first) to the desired output and changing connection weights between network nodes in such a way that performance increases. Keep the connection weight matrix and forget the examples. The place of stochastic (statistical) approaches deserves some discussion at this point. In this popular approach to tagging, statistical models (e.g. about the N-grams occurring in a language) are computed on the examples (the corpus) and these are used to extrapolate to the most probable analysis of new input. In terms of abstraction versus data-orientation, stochastic, neural network and rule induction approaches are greedy learning techniques. These techniques abstract knowledge from the examples as soon as they are presented. Case-Based Learning is a lazy learning technique: generalization only occurs when a new pattern is offered to the performance component and abstraction is therefore implicit in the way the contents of the case base and the similarity metric interact. One succesful statistical approach, recently applied to the tagging problem, is Ratnaparkhi’s use of Maximum Entropy Models (1996). In this classification-based approach, diverse sources of contextual information (comparable to those used by the machine learning approaches discussed below) are expressed as binary features, and are combined in a statistical model that makes no further distributional assumptions on the training data by maximizing the entropy of the distribution subject to the constraints of the training data. The model parameters for the distribution are estimated using an iterative procedure called generalized iterative scaling. In the remainder of this chapter, we will discuss each of the learning methods and their application to tagging in turn. We conclude with a general discussion and evaluation of the methods described. ### 17.3 CASE-BASED LEARNING The case-based learning paradigm is founded on the hypothesis that performance in cognitive tasks (in our case language processing) is based on reasoning on the basis of analogy of new situations to stored representations of earlier experiences rather than on the application of mental rules abstracted from representations of earlier experiences as in rule induction and rule-based processing. The concept has appeared in several AI disciplines (from computer vision to robotics) several times, using apart from case-based also labels such as similarity-based, example-based, exemplar-based, analogical, nearest-neighbour, instance-based and memory-based (Stanfill and Waltz 1986; Kolodner 1993; Aha et al. 1991; Salzberg 1990). These different names are conveniently captured under the term lazy learning (Aha 1997). 17.3.1 Algorithm Examples are represented as a vector of feature values with an associated category label. Features define a pattern space. During training, a set of examples (the training set) is presented in an incremental fashion to the learning algorithm and added to memory. During processing, a vector of feature values (a previously unseen test pattern) is presented to the system. Its distance to all examples in memory is computed using a similarity metric and the category of the most similar instance(s) is used as a basis to predict the category for the test pattern. In this type of lazy learning, performance crucially depends on the similarity metric used. The most straightforward metric for a problem like tagging with nominal (non-numeric) feature values would be an overlap metric: similarity is defined as the number of feature values that are equal in two patterns being compared. In such a distance metric, all features describing an example are interpreted as being equally important in solving the classification problem, but this is not necessarily the case: the category of the word immediately before a word to be tagged is obviously more important than the category of the word three positions earlier in the sentence. We call this problem the feature relevance problem. Various feature weighting and selection methods have been proposed to differentiate between the features on the basis of their relevance for solving the task (see Wettscherek et al. (1996) for an overview). Another addition to the basic algorithm that has proved relevant for many natural language processing tasks is a value difference metric (Stanfill and Waltz 1986; Cost and Salzberg 1993). Such a metric assigns different distances to pairs of values for the same feature. In tagging, e.g., such a metric would assign a smaller distance between \textit{np} and \textit{nn} than between \textit{nn} and \textit{vbg}. These biases can of course also be added by hand to the learner (e.g. by a domain expert). Several other improvements and modifications to the basic case-based learning scheme have been proposed and should be investigated for linguistic problems. Two promising further extensions are weighting the examples in memory and minimizing storage by keeping only a selection of examples. In example weighting, examples are differentiated according to their quality as predictors for the category of new input patterns. This quality can be based on their typicality or on their actual performance as predictors on a held-out test set. In example selection, memory is pruned by deleting those examples which are bad predictors or which are redundant. ### 17.3.2 Case-based tagging Kenmore (Cardie 1994, 1996) is presented as a general framework for knowledge acquisition for NLP using different symbolic machine learning techniques. As an instance of this general methodology, a case-based learning approach is suggested for both morphosyntactic and semantic tagging. The architecture presupposes a corpus, a sentence analyser and a learning algorithm. During knowledge acquisition (training) for a specific disambiguation task (e.g., tagging), a case is created for each instance of the problem in the corpus. Each case is an example of the input-output mapping to be learned; the input part is a context describing the ambiguity and the output part is the solution to the particular ambiguity. The examples may be produced from an annotated version of the corpus or through human interaction. During application, the case-base is used to predict the solution to a new instance of the ambiguity given the input (the context) without intervention. In a tagging experiment based on 2056 cases from the Tipster JV corpus, a fairly complex case representation based on output from the CIRCUS conceptual sentence analyser is used. Figure 17.2 shows the case representation containing context features of the focus word “parts”, for which the word sense and the part of speech has to be decided. Local context features describe the syntactic and semantic information about a five-word window centered on the word to be tagged (the words themselves, their part of speech and their word sense). Global context features provide information about the major constituents parsed already (word sense of the subject and type, concept and semantic feature associated with the last parsed constituent). The class to be predicted is the part of speech and the semantic sense of the middle word. All words (except 129 function words) are initially assumed unknown. As a solution to the feature relevance problem, Cardie (1993) applies a decision tree learning algorithm (see below) to the dataset and uses only those features which have been selected by the decision tree induction algorithm as being relevant during similarity comparison. This turns out to be an effective way to discard irrelevant features. MBT (Memory-Based Tagging; Daelemans 1995; Daelemans et al. 1996) is a case-based approach in which the feasibility of the approach on a larger scale is investigated, with simpler case representations and with a more elegant solution to the feature rele- --- 3 Reprinted from Cardie (1996) with permission. In order to adopt the memory-based approach to the problem of tagging, the following procedure is used: **Lexicon Construction.** A lexicon is extracted from the training corpus by computing for each word the number of times it occurs with each category. A new, possibly ambiguous tag (e.g. N-V for words which can be both a noun and a verb) is assigned to each word based on this lexical definition. --- 4 ACL Data Collection Initiative CD-ROM 1, September 1991; the tagset is the Penn Treebank tagset, consisting of 40 tags. See Appendix 17.6 for a full list. Case-Base Construction. Two case bases are constructed, one for known words and one for unknown words. The former contains as information the possibly ambiguous category of the word to be tagged (the focus word) and of one context word to the right and the disambiguated category of two words to the left. The latter contains the same context information, but instead of the ambiguous category of the focus word (which is unknown), the first letter and the last three letters of the focus word are added as features. These features provide information about the ‘morphology’ of the word. The unknown-words case base is constructed on the basis of open class words only. Tables 17.4 and 17.5 list samples of the known-words and unknown-words case bases for part of the first sentence of the corpus. In the first table, we use the following abbreviations for the known-words case base: \( f \) for focus word (the word to be disambiguated, represented by its ambiguous category), \( d \) for disambiguated word (a previously contextually disambiguated word to the left of the focus word), \( a \) for ambiguous word, a still to be disambiguated word to the right of the focus word, represented by its ambiguous category, and \( t \) for the target, disambiguated, category of the focus word. In the unknown-words case base, we find features for left (\( d \)) and right (\( a \)) context, and instead of the lexical representation of the focus word, we have features representing prefix letters (\( p \)) and suffix letters (\( s \)) of the focus word. Tagging. In tagging, new input text is transformed into case representations for case-based reasoning on the basis of either the known- or unknown-words case base. In MBT, the feature relevance problem is solved by weighting each feature with the average amount of case base information entropy reduction it can provide (i.e. its Information Gain, IG; see Daelemans et al. (1996) for more information). The weights for the different features are also listed in tables 17.4 and 17.5. They express the relative relevance of the features and are used as a weight during similarity computation. Advantages of this approach (compared to Kenmore’s) are that feature relevance is not interpreted as a yes/no property but as a gradual one and that it does not presuppose using two inductive classification learning algorithms (decision tree induction and case-based learning), one of which is only used for feature selection. To solve the computational complexity problem inherent in matching all feature values of a new case to the corresponding values of all stored cases, MBT uses IGTREE, a memory- and processing-time-saving heuristic implementation of memory-based reasoning. This formalism (fully described in Daelemans et al. 1996, 1997) compresses a memory base into a tree using an information-theoretic heuristic, reducing storage and retrieval complexity considerably without an adverse effect on generalization accuracy. An additional advantage is that this tree structure allows dynamic selection of context width (see also 17.4 below on decision trees). Table 17.4 Case representation and information gain pattern for known words. <table> <thead> <tr> <th>Word</th> <th>Case Representation</th> </tr> </thead> <tbody> <tr> <td>IG</td> <td>.06 .22 .82 .23</td> </tr> <tr> <td>Pierre</td> <td>= = np np np</td> </tr> <tr> <td>Vinken</td> <td>= np np , np</td> </tr> <tr> <td>61</td> <td>np np , cd nns cd</td> </tr> <tr> <td>years</td> <td>, cd nns jj-np nns</td> </tr> <tr> <td>old</td> <td>cd nns jj-np , jj</td> </tr> </tbody> </table> Table 17.5 Case representation and information gain pattern for unknown words. <table> <thead> <tr> <th>Word</th> <th>Case Representation</th> </tr> </thead> <tbody> <tr> <td>IG</td> <td>.21 .21 .15 .20 .32 .14</td> </tr> <tr> <td>Pierre</td> <td>= P r r e np np</td> </tr> <tr> <td>Vinken</td> <td>np V k e n , np</td> </tr> <tr> <td>61</td> <td>, 6 = 6 l nns cd</td> </tr> <tr> <td>years</td> <td>cd y a r s jj-np nns</td> </tr> <tr> <td>old</td> <td>nns o o l d , jj</td> </tr> </tbody> </table> ### 17.3.3 Evaluation In the experiment with **kenmore**, accuracy of tagging turned out to be 95% overall and 91% on contents words only. In **mbt** on the Wall Street Journal corpus, overall generalization accuracy was 96.4% (96.7% on known words, 90.6% on unknown words). The level of accuracy attained by probabilistic taggers seems to be well in reach of case-based taggers. Already at small data set sizes, performance is relatively high. We obtained similar scores when adapting the tagger architecture to Dutch by training it on a Dutch tagged corpus. An important advantage of the case-based approach is the flexibility of case representations: there are several types of information which can be stored in the memory base, ranging from the words themselves to intricate lexical representations. Combined with feature-weighting approaches, this flexibility offers a new approach to informa- tion source integration (data fusion) in tagging. The unknown-words case base in mbt, e.g., integrates context information and 'morphological' information (suffix letters) in a smooth way. It would be impossible at present, for reasons of sparseness of data and computational complexity, to estimate probabilities for such intricate contexts in a stochastic approach. Additional advantages include incremental learning (new cases can be added incrementally to the case bases without need for relearning\(^5\)), explanation capabilities (the best memory matches serve as explanations for the tagging behaviour of the system) and, at least in mbt, fast learning and tagging (more than 1000 words per second). ### 17.4 DECISION TREE INDUCTION The decision tree learning paradigm is based on the assumption that similarities between examples can be used to automatically extract decision trees and categories with explanatory and generalization power. In other words, the extracted structure can be used to solve new instances of a problem and to explain why a performance system behaves the way it does. In this paradigm, learning is greedy and abstraction occurs at learning time. There are systematic ways in which decision trees can be transformed into rule sets (the two representations are equivalent). Decision tree induction is a well-developed field within AI. See, e.g., Quinlan (1993) for a synthesis of major research findings. More ancient statistical pattern recognition work (such as Hunt et al. 1966; Breiman et al. 1984) also still makes for useful reading. #### 17.4.1 Algorithm A decision tree is a data structure in which nodes represent tests, and arcs between nodes represent possible answers to tests. Leaf nodes represent answers to problems. A problem is solved by following a path from the root node through the decision tree until a leaf node is reached. The path taken depends on the answers that a particular problem provides to the tests at the nodes. Decision tree learning works by repeatedly dividing the set of examples into subsets according to whether the examples in a particular subset have a feature-value pair in common, until the subsets are homogeneous, i.e. all examples in the subset have the same category. The algorithm achieves this according to the simplified recursive scheme in Figure 17.3. To classify new input patterns with a decision tree, start at the root node of the tree and find the value in the input pattern for the corresponding feature. Take the branch corresponding to that value and perform this process recursively until a leaf node is reached. The category corresponding to this leaf node is the output. --- \(^5\) Computation of feature weights is not incremental, it presupposes access to a complete batch of training examples, but usually, the weight values become stable after only a few hundred training examples. Given a set of examples $T$ If $T$ contains one or more cases all belonging to the same class $C_j$, then the decision tree for $T$ is a leaf with category $C_j$. If $T$ contains different classes then - Choose a feature, and partition $T$ into subsets that have the same value for the feature chosen. The decision tree consists of a node containing the feature name and a branch for each value leading to a subset. - Apply the procedure recursively to subsets created this way. Figure 17.3 Recursive scheme for constructing decision trees. Again, we are confronted with a feature relevance problem in this approach. In order to obtain a concise tree with good generalization performance (i.e. a tree reflecting the structure of the domain), we have to select at each recursion of the above algorithm a test which is optimal in achieving this goal. The algorithm is non-backtracking and considering all trees consistent with the data is an NP-complete problem, so a reliable heuristic feature selection criterion is essential. Information-theoretic or statistical techniques maximizing homogeneity of subsets by selecting a particular feature are usually applied to this end. Several variants and extensions have been developed to the basic algorithm for pruning (making the tree more compact by cutting off subtrees on the basis of a statistical criterion), grouping similar values of a feature into classes, making tree building incremental, etc. 17.4.2 Decision tree tagging Work on parsing (including tagging) of text with decision trees was pioneered at IBM (Black et al. 1992; Magerman 1994, 1995). SPATTER (Magerman 1995) starts from the premise that a parse tree can be viewed as the result of a series of classification problems (tagging, choosing between constituents, labelling constituents, etc.). The most probable sequence of decisions for a sentence, given a training corpus, is its most probable analysis. In the statistical decision tree technology used (based on Breiman et al. 1984), decision trees are constructed for each sub-problem in the parsing task (tagging is one of them). In such a decision tree, leaf nodes contain distributions over categories instead of a single category. E.g., in tagging, the feature associated with the root node of the decision tree might be the word to be tagged. In case its value is “the”, the category “article” can be returned with certainty. In case its value is “house”, a test at the next level of the tree corresponds to the feature “tag of the previous word”. In case its value is “article”, the probability distribution returned by the decision tree would be “noun (.8); verb (.2)” (Magerman 1995). In practice, SPATTER uses binary trees, however. Searching for the most probable tag series for a sentence is done by means of stack decoder search with a breadth-first algorithm and probabilistic pruning. Figure 17.4 shows such a tree, based on Magerman (1995). Schmid (1994b) describes TREETAGGER, a tagger which takes basically the same approach as SPATTER. Transition probabilities between tags in a tag sequence are estimated using a decision tree induced from a set of N-grams occurring in the Penn Treebank corpus. The features are the tags of the words preceding the word to be tagged. He experimented with one, two and three such context features. The category to be predicted is the tag of the focus word. Using an information-theoretic heuristic feature selection method, the tree is built using the recursive algorithm discussed earlier. As in SPATTER, all tests have binary results. Instead of having a subtree for each possible tag in a context position, corresponding to questions like “what is the tag of the word before the target?”, tests are instead individual feature-value combinations with a binary branching, corresponding to questions like “is the tag of the word before the target equal to ADJ?”. This results in deeper trees. Again as in SPATTER, at the leaf nodes a probability distribution over the categories is given for those patterns for which the sequence of tests leading to this leaf node are true. The information-theoretic feature selection method ensures that the test chosen maximizes the distinctiveness of the probability distribution of the subtrees. For pruning the resulting decision tree, an information-theoretic heuristic is used as well. Finally, the Viterbi algorithm (Viterbi 1967; see also Chapter 16) is used to find the best tag sequence for a sentence, given the probability distributions obtained by decision tree lookup. The approach is com- bined with a lexicon system containing a priori tag probabilities for each word and a probabilistic suffix analyser. 17.4.3 Evaluation Decision tree models are equivalent in expressive power to interpolated N-gram models (Magerman 1995), but whereas in N-gram models the number of parameters to be estimated grows exponentially with \( N \), in decision-tree learning, the size of the model depends on the number of training examples and remains constant with the number of decisions taken into account. Also, the decision tree approach automatically selects relevant context size: uninformative context positions are not used in the tree and because of its computational properties (constant with wider context) larger contexts (corresponding to 4 or 5-grams) can initially be considered. That way, decision tree approaches are potentially more sensitive to context and therefore better equipped to solve long-distance dependencies. Finally, Schmid also reports robustness relative to training set size: \textsc{treetagger} ‘degrades gracefully’ with smaller training set sizes. As far as performance is concerned, decision tree methods seem to be comparable to stochastic approaches: Schmid reports 96.4\% generalization on the Penn Treebank using 4-grams (0.3\% better than a similar probabilistic trigram tagger, which, however, uses a different lexicon system). Magerman reports 96.5\% for sentences up to 40 words in length in the Wall Street Journal corpus. Schmid also reports fast tagging speed performance (10,000 words per second). In the examples discussed here, decision tree technology does not deliver a solution to the complete tagging problem. The tag probabilities returned by the tree are used by a search mechanism (stack decoder or Viterbi) to find the best series of tags. Also, both versions of the decision tree approach are not completely non-parametric; \textsc{spat-ter} requires smoothing of the decision trees and \textsc{treetagger} requires a pruning threshold. In principle, however, it would be possible to produce a complete tagger on the basis of a learned statistical decision tree. Recently, this approach has indeed been explored (Marquez & Rodriguez, 1998). 17.5 NEURAL NETWORK METHODS Multilayer Perceptrons (Rumelhart et al. 1986) are the most popular neural network architecture. As an inductive learning technique, supervised neural network learning is a greedy learning approach. During learning, the set of examples is repeatedly inspected to find an optimal set of connection weights between layers of simple units. The training material is thus abstracted into a set of numeric weights which is then used to predict the output of new input patterns. There is an immense literature on neural network algorithms (see Aleksander and Morton 1990, Bishop 1995 and Fausett 1994 for recent introductions). There is also a considerable body of research on applying neural network technology to language processing problems (Reilly and Sharkey (eds.) 1992; Sharkey 1992). 17.5.1 Algorithm A multilayer perceptron consist of an input and an output layer of simple processing units and one or more intermediate, ‘hidden’ layers (figure 17.5). The input layer is used to code the input part of an example, the output layer to encode the output part. We will assume a single hidden layer here. All adjacent layers are fully interconnected, i.e. each unit in each layer connected to each unit in the next layer. Each unit has an activation and a threshold. Each connection between two units has a weight. Activation can be expressed as 1 or 0, or as a real number; thresholds and connection weight are usually expressed as real numbers. Activation flows from the input layer to the output layer via the hidden layer. Two simple rules govern the training and use of a multilayer perceptron. The activation rule is a local rule which is used by each unit to compute its activation. Consider for instance the activation flow from input layer to hidden layer. The input activation of a particular unit of the hidden layer \( a_j \), is equal to \( \sum_i a_i \times w_{i,j} \), where the \( a_i \) are the activations of the units in the input layer connected to that unit at the hidden layer and the \( w_{i,j} \) are the weights of the connections from those input layer units to that hidden layer unit. The threshold value determines whether, given the input activation to a unit, that unit will become active (if the input activation exceeds the threshold the unit becomes active, otherwise it stays ‘off’). By making use of such a threshold value, the activation of a unit is a non-linear function of activation values of the units in the previous layer connected to it. The learning rule (in this case back-propagation learning) incrementally adapts the connection weights until an acceptable performance is reached by the system (this involves repeatedly cycling through all training examples). This adaptation process works by changing the connection weights depending on the quality of the output of the network (i.e. the activation pattern at the output layer). The output of the network is compared to the desired output. Those connections that contributed to the wrong activation of an output unit are weakened, those that were responsible for not activating an output unit that should have been active are strengthened. These error corrections are also ‘back-propagated’ to the connections between input and hidden layer. 17.5.2 Neural network tagging netgram (Nakamura et al. 1980) is a multilayer neural network for word category prediction in the context of a speech recognition system. The input consists of the category of two (or more) preceding words, the output is the category of the current word. Words are encoded the following way. Each word is represented by a number of units equal to the number of categories. The unit associated with the category of the word is made active, the other units are inactive. Given two words preceding context and 89 categories, the network has an input layer of 178 units and an output layer of 89 units. Back-propagation is used to train the network. When an input is presented to the network, the two input units corresponding to the categories of the two preceding words are made active and the output unit with the highest activation is taken as the category of the current word. net-tagger (Schmid 1994a) also used back-propagation learning, but in this case the problem handled is disambiguation (tagging) rather than tag prediction. In the input layer, information about the word to be tagged and one or more preceding and following words is encoded. Again, for each tag and each word pattern position, a unit is created. E.g., supposing 40 tags, 3 words left context, a focus word and 2 words right context, an input layer of 240 ($40 \times 6$) units is needed. For the left context words, the previous output of the network (the activation levels of the output layer units) is used as input. For the focus word and the right context, the lexical probabilities of the words are used. Adding a hidden layer to a two-layer network did not improve performance. The output layer has one unit for each possible wordclass. The output unit with the highest activation, given an input pattern, is interpreted as the tag of the focus word. In order to attach lexical probabilities to words, a lexicon system based on Cutting et al. (1992) is used, combined with an unknown-word guesser using information about suffix letters. 17.5.3 Evaluation Accuracy of netgram and net-tagger is comparable to stochastic trigram methods, the main advantage being that unseen patterns are interpolated effectively, without requiring expensive special interpolation methods as in stochastic approaches. Connectionist approaches also require the computation of fewer parameters (weights) than statistical models (N-gram probabilities), which becomes especially useful when considering a wider context than trigrams. The number of weight-parameters grows quadratic with the number of input nodes. As in the learning methods discussed earlier, it is possible to output more than one possible tag for a word, e.g. a list of tags ordered according to their likelihood. 17.6 DISCUSSION With the availability of only a relatively small body of empirical data and theoretical analysis on the applicability of inductive machine learning techniques to tagging, it is too early for strong conclusions. On the empirical side, there is a hard-felt need for a methodologically sound, reliable, empirical comparison of statistical and machine learning approaches to automatic tagging. On the theoretical side, there is a need for more insight into the differences and similarities in how generalization is achieved in this area by different statistical and machine learning techniques. In the absence of this knowledge, our discussion will necessarily turn out to be preliminary and superficial. Our discussion will take the form of a number of theses. - Learning is preferable to programming. Compared to hand-crafted rule-based (or constraint-based approaches), an inductive learning approach, such as in the methods discussed here and in stochastic approaches, provides a solution to the knowledge-acquisition and reusability bottlenecks and to robustness and coverage problems. As an example, a fast and accurate tagger for Dutch was learned with the MBT tagger-generator in half a day, with a minimum of linguistic engineering. On the other hand, it should be noted that the accuracy which can be obtained using hand-crafted constraint-based methods (cf. Chapter 14) still seems to be out of reach for automatic learning approaches. - Machine learning is a different type of statistics. Decision tree induction, case-based learning and neural networks are statistical methods, but they use a different kind of statistics than the well-known maximum-likelihood and Markov model methods, e.g. in case-based learning, no assumptions are made about the distribution of the data whereas most statistical techniques presuppose normal distributions. Different statistical methods have different properties which make them more or less suited for a particular type of application. If only for that reason, the applicability of all types of statistics to the tagging problem should be studied thoroughly. Already from the preliminary empirical data, important advantages of these methods compared to current statistical methods suggest themselves: 1. They require less training data. 2. They require less parameters to be computed and can therefore take into account more context. 3. They provide elegant and computationally attractive solutions to the smoothing problem and to the integration of different information sources. 4. Training is often much faster. Abstraction can be harmful. In many linguistic tasks, we have found (see Daelemans, Van den Bosch and Zavrel 1999) that an approach keeping complete memory of all training data provides better performance than techniques that abstract from low-frequency and exceptional events, such as rule(learning)-based systems. Neural networks and stochastic approaches are similar to rule- and decision-tree-induction methods in that they abstract from their experience (to a matrix of connection weights in neural networks, to a set of probabilities in stochastic approaches and to a set of rules in rule-induction approaches) and forget about the original data on which these abstractions were based. The effect that full memory of all examples yields better generalization is probably related to the fact that natural language processing tasks such as morphosyntactic disambiguation can be characterised by the interaction of regularities, sub-regularities and pockets of exceptions. Abstracting away from these exceptions causes a performance degradation because new similar exceptions are overgeneralized: being there is better than being probable. Compared to the well-developed theoretical and empirical foundations of statistical approaches to tagging, the machine learning approach to this problem has only just started. In all methods described, there is still a lot of room for improvement, especially in three areas: exploring variations or extensions of the basic algorithms, adding linguistic bias to the learning algorithms and combining them with other approaches in hybrid architectures. A fourth area where machine learning methods may provide increased tagging accuracy is in the development of machine learning algorithms that take as input the outputs of different taggers (trained, statistical or even hand-crafted) and learn when to trust which tagger. Initial work on this approach is described by van Halteren, Zavrel and Daelemans (1998) and by Brill and Wu (1998).
{"Source-Url": "https://www.clips.uantwerpen.be/~walter/papers/1999/d99-2.pdf", "len_cl100k_base": 9952, "olmocr-version": "0.1.53", "pdf-total-pages": 20, "total-fallback-pages": 0, "total-input-tokens": 44011, "total-output-tokens": 10549, "length": "2e13", "weborganizer": {"__label__adult": 0.0004935264587402344, "__label__art_design": 0.0007915496826171875, "__label__crime_law": 0.0006661415100097656, "__label__education_jobs": 0.00609588623046875, "__label__entertainment": 0.0003483295440673828, "__label__fashion_beauty": 0.0003476142883300781, "__label__finance_business": 0.0004320144653320313, "__label__food_dining": 0.0005970001220703125, "__label__games": 0.0013742446899414062, "__label__hardware": 0.0011854171752929688, "__label__health": 0.0012369155883789062, "__label__history": 0.0005154609680175781, "__label__home_hobbies": 0.0002058744430541992, "__label__industrial": 0.0008363723754882812, "__label__literature": 0.004241943359375, "__label__politics": 0.0005679130554199219, "__label__religion": 0.0007948875427246094, "__label__science_tech": 0.457275390625, "__label__social_life": 0.00023186206817626953, "__label__software": 0.0277862548828125, "__label__software_dev": 0.492431640625, "__label__sports_fitness": 0.0005116462707519531, "__label__transportation": 0.0007171630859375, "__label__travel": 0.0002484321594238281}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 47095, 0.03295]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 47095, 0.76034]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 47095, 0.92038]], "google_gemma-3-12b-it_contains_pii": [[0, 1360, false], [1360, 3657, null], [3657, 6514, null], [6514, 7727, null], [7727, 10283, null], [10283, 12907, null], [12907, 15812, null], [15812, 18866, null], [18866, 21595, null], [21595, 22160, null], [22160, 25275, null], [25275, 26819, null], [26819, 29710, null], [29710, 32498, null], [32498, 34279, null], [34279, 37177, null], [37177, 38767, null], [38767, 41806, null], [41806, 44710, null], [44710, 47095, null]], "google_gemma-3-12b-it_is_public_document": [[0, 1360, true], [1360, 3657, null], [3657, 6514, null], [6514, 7727, null], [7727, 10283, null], [10283, 12907, null], [12907, 15812, null], [15812, 18866, null], [18866, 21595, null], [21595, 22160, null], [22160, 25275, null], [25275, 26819, null], [26819, 29710, null], [29710, 32498, null], [32498, 34279, null], [34279, 37177, null], [37177, 38767, null], [38767, 41806, null], [41806, 44710, null], [44710, 47095, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 47095, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 47095, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 47095, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 47095, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 47095, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 47095, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 47095, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 47095, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 47095, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 47095, null]], "pdf_page_numbers": [[0, 1360, 1], [1360, 3657, 2], [3657, 6514, 3], [6514, 7727, 4], [7727, 10283, 5], [10283, 12907, 6], [12907, 15812, 7], [15812, 18866, 8], [18866, 21595, 9], [21595, 22160, 10], [22160, 25275, 11], [25275, 26819, 12], [26819, 29710, 13], [29710, 32498, 14], [32498, 34279, 15], [34279, 37177, 16], [37177, 38767, 17], [38767, 41806, 18], [41806, 44710, 19], [44710, 47095, 20]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 47095, 0.20988]]}
olmocr_science_pdfs
2024-12-07
2024-12-07
d1dc55274bc7aa9658690557f7682ac76a629733
An ontological framework for user-driven system specification de Moor, A.; Weigand, Hans Published in: Proceedings of the 32nd Hawaii International Conference on Systems Science Publication date: 1999 Link to publication Citation for published version (APA): General rights Copyright and moral rights for the publications made accessible in the public portal are retained by the authors and/or other copyright owners and it is a condition of accessing publications that users recognise and abide by the legal requirements associated with these rights. - Users may download and print one copy of any publication from the public portal for the purpose of private study or research - You may not further distribute the material or use it for any profit-making activity or commercial gain - You may freely distribute the URL identifying the publication in the public portal Take down policy If you believe that this document breaches copyright, please contact us providing details, and we will remove access to the work immediately and investigate your claim. Download date: 04. Jan. 2019 Aldo de Moor, Hans Weigand Infolab, Tilburg University P.O.Box 90153, 5000 LE Tilburg, The Netherlands tel.+31-13-4663020, e-mail:ademoor/weigand@kub.nl Abstract User-driven specification of network information systems is required in many virtual professional communities, such as research networks. This paper introduces a method and an accompanying tool being developed to support the legitimate user-driven specification of network information systems. The need for method ontologies, organized in an ontological framework, is motivated. A key part of this framework, the core process ontology, is described. The application of the framework is illustrated with some case study examples. It is shown how ontological and normative knowledge can be combined to model the user-driven specification process. Its formal semantics are described using dynamic deontic logic. 1. Introduction Collaborative work is increasingly being done in a distributed fashion. Collaborating professionals from within and across organizations are more and more expected to set their own goals and ways of working. As such collaboration often entails having people from many different locations working together intensively on complex tasks, distributed computer technologies, such as Internet-based groupware, have the potential to considerably increase productivity. This paper focuses on supporting the creation of information systems for such virtual professional communities, which can be composed out of standard Internet-based information tools. Such tools include mailers, mailing lists and a great variety of Web-applications. Still, from an analytical instead of such a design perspective, a network information system can be regarded as a set of meaningfully configured and combined information and communication processes necessary to support and coordinate the activities of the network participants in their various roles. This implies that the usage context in which the information system operates, needs to be very clearly defined. 1.2. User-Driven System Specification Active participation of members of a virtual professional community in the specification process is essential in order to successfully develop the desired community partnerships and the required supporting information systems. Such user-driven development is based on a paradigm very different from traditional, waterfall-like development methods. First, the network information system is generally implemented as a set of commonly available information tools. This entails a socio-technical approach to system design, as the specified requirements and the roles that the available tools play must co-evolve. Second, network participants themselves take the initiative to system specification. Third, the specification and implementation of the, initially small, system are gradually expanded during system use. Fourth, there is not a single view on the universe of discourse, which an external team of analysts normally develops in traditional information system development. Instead, each user generally is only knowledgeable about and interested in re-specifying the workflows he is actually involved in, although at the same time the need for global specification consistency remains. To foster user participation, a norm-based specification approach is essential. A distinguishing characteristic of many virtual professional communities is that they are egalitarian in nature, because participation is voluntary. Such a community can only thrive if all of its members see the particular interests they represent sufficiently reflected in the communal goals, activities, organizational structures, and supporting information system. Contrary to a hierarchical organization, claims to power cannot be used to control communal specification processes. Instead, permitted, obliged, and forbidden specification behaviour is guided by norms. Unlike explicit rules, norms are often left implicit. Furthermore, norms can occur in very complex, interrelated clusters [7]. Based on these norm groupings, legitimate specifications which are (1) semantically meaningful and (2) acceptable to the network participants concerned need to be produced by participants in a form of rational discourse, i.e. discussion which is open and allows background assumptions on usage context factors to be examined [5]. Several specification approaches have been developed, which aim to increase the acceptability of specifications, such as the REMAP method [8]. However, these approaches focus on optimizing a fair deliberation process with given participants, but do not indicate how these participants are to be selected in the first place. In the RENISYS (REsearch Network Information SYstem Specification) project, a specification method, implemented by a Web-based tool, is being developed that does support such a legitimate user-driven specification process. An initial prototype of the tool has been implemented (Fig. 1, http://infolab.kub.nl/renisys.phtml), which allows for relatively simple specification changes to be formulated and negotiated. We first explain the approach to user-driven specification adopted in RENISYS. 2. The RENISYS Method One way to increase the precision of user participation is to let users themselves trigger and define specification processes. Users in general are not continuously involved, but produce specifications intermittently [9]. Empirical evidence also shows that users often initially only need to have an essential understanding of their (business) processes and information tools in order to achieve concrete results [10]. These natural tendencies can be supported by focusing the support of the specification discourse between users on the resolution of breakdowns. The support provided needs to aid the user in fostering awareness of a breakdown, and the formulation and negotiation of specification changes that can resolve the breakdown. 2.1. Breakdowns According to Winograd and Flores, the ‘breakdown’ has a central role in human understanding, and, more particularly, in design. "A breakdown is not [necessarily] a negative situation to be avoided, but a situation of non-obviousness, in which the recognition that something is missing leads to uncovering some aspect of the network of tools that we are engaged in using (p.165)" [11]. Breakdowns play two fundamental roles in the design process. On the hand hand, they are the things that the designer will try to avoid, by anticipating on what can go wrong. But when they occur, they also trigger a reconsideration of the functionality of the system. It is only when a user fails in accomplishing a certain goal, that he feels the need for an instrument, and can express what the instrument should do. RENISYS aims at supporting user participation in the specification process precisely at the point a breakdown occurs (no sooner, no later). We hypothesize that such a breakdown-focused user-driven specification approach is especially useful for information systems that support creative knowledge processes, which need a lot of subtle fine-tuning before they are acceptable to a user community. This claim we will try to substantiate in future empirical research by applying RENISYS in several case studies. 2.2. Specification Knowledge Representation As an underlying knowledge representation formalism, RENISYS makes use of conceptual graphs [12]. To organize the various kinds of complex specification knowledge, three different categories of specification knowledge are distinguished [5]. Ontological type definitions contain descriptions of the terminology used in the community. Norms describe the accepted behaviour of the various actors in the network. State specifications describe the actual or potential state-of-affairs of network entities. 2.3. A Model of Legitimate User-Driven Specification In individualistic user-driven approaches, user-involvement in system development generally takes place in relative isolation (Fig. 2). For instance, a user facing a breakdown contacts the system administrator, and asks him to implement a desired change in a Web server. Subsequently, the updated tool is used and the process is possibly repeated. However, this relatively simple and straightforward specification and implementation loop does not work in a virtual professional community, as any change in tool implementation may profoundly affect group collaboration. As not only communal work, but also specification behaviour is guided by norms, any specification change to be implemented must be legitimate, that is, meaningful and acceptable (as described in Sect. 1.2.) The process goes as follows (Fig. 3). Again, a user faces a breakdown during work. However, instead of directly requesting an implementor to realize a change, the user formulates his desired specification in terms meaningful to the network. Then, this change is proposed to a relevant group of users (see Sect. 5, for more on how to determine what are relevant actors). This group discusses and decides upon the proposed change, while possibly modifying the proposal and initiating new specification processes. The approved specifications are then assigned to a particular implementor. Upon implementation, the user is notified and asked to evaluate the updated functionality, and, if necessary, start a new loop. Before focusing our attention on the structure and use of these ontologies, we first introduce the case with which we illustrate the theory developed in this paper. 2.4. Case: The Electronic Journal on Comparative Law IWI, a Dutch organization stimulating new ways of distributing scientific information, funded a project to create an Electronic Journal on Comparative Law (EJCL, http://law.kub.nl/ejcl/). The project group included participants from various academic law institutes, university libraries, and computer centres. The goal was to have all publishing activities, ranging from paper submission to editing, peer review, and publication done completely electronically, making use of the Web. The project started in spring 1997 and ended in summer 1998. The initially basic set of requirements defined by the users (e.g. editors or authors) gradually evolved in scope and complexity. Furthermore, the initial basic set of simple information tools over time included more advanced groupware applications. For instance, at first only a relatively simple Web site and mailing list were being used, whereas later also the much more sophisticated BSCW tool [13], supporting advanced group work, was integrated into the network information system. Because of these clear user-driven specification aspects, the EJCL-project was an interesting case to test and refine the theory underlying the RENISYS method. 3. Ontology-Based Support of the Specification Process The user-driven specification approach applied by RENISYS is briefly described. Next, some advantages of using ontologies are listed. Then, the reference framework used to organize specification knowledge from different domains is introduced. Finally, the ontological framework used to model entities to be stored in the reference framework is presented. 3.1. User-Driven Specification in RENISYS Key to a successful application of RENISYS is its smooth integration with the network information system it helps to specify. Two important features facilitate this interaction. First, each tool that is part of the information system must include an option for the users to call RENISYS, passing it on a parameter containing the exact location from where the call is being made. For instance, in the case of a Web server, a link can be included in each page, via which the RENISYS server may be contacted. Second, RENISYS includes an authorization mechanism, which identifies the calling user and checks which actor roles he is allowed to play. Through these roles, RENISYS can simply determine which specification authorizations a particular user has. Furthermore, once the actor roles of a particular user have been determined, the knowledge from (1) these actor roles, and (2) the mappings from domain specifications to the calling page can be combined. RENISYS can then generate a very specific context of entities possibly related to the breakdown the user experiences. This greatly helps the user to - with minimum effort - produce a precise specification proposal to present to the relevant group of users. To determine who are the relevant users and what they should negotiate about, a conceptual graph-based mechanism applying context lattices that can handle such specification knowledge context evolution has been proposed [14]. A language/action theory-based way for such groups of users to discuss and decide upon specifications is described in [15]. However, what has not been described in detail yet, is the structure and evolution of the entities to be specified. To this purpose, ontologies can play an important role. 3.2. Ontologies in RENISYS In [5], a formal conceptual graph-based approach for specification knowledge, including ontologies, was introduced. The approach allows for the simple customization of ontologies by users, when its graph-based queries are mapped to semi-natural language statements. Three kinds of ontology evolution operations were distinguished, allowing for the creation, modification, and termination of ontological definitions. In this paper, the focus is not on these (essential) mechanisms of ontological change, but rather on the development of a set of ontological primitives that are the starting point for the required ontology evolution. These primitives form the basis for the (user-customized) specifications that define a particular network information system. The reasons for our use of an ontology-based approach are similar to some proclaimed advantages of domain ontologies (cf.[16]): 1. Domain ontologies may be used in knowledge acquisition where teams have to work together and an ontology serves as the agreed upon, common understanding of the terms in the domain [17]. This argument is of particular relevance for networks where groups of users and developers with widely varying backgrounds are involved. 2. A second important function of ontologies is that such a common understanding often entails certain commitments for participants playing network roles. These bind users to the implications of the definitions agreed upon. For instance, if an edit process definition says that a set of review guidelines is to be an input into the process, all users implicitly accept that these guidelines need to be available and adhered to. Such commitments, if made explicit, enable more controlled development and maintenance of a knowledge-base system [18]. 3. The most often cited role is in enabling reuse of knowledge for building new applications. In our user-driven network system environment, reuse not only can be fruitful at the very beginning, but each time a new specification needs to be defined (i.e. when a breakdown has occurred). In our view, the ontologies form the language necessary to describe the community-wide defined and accepted properties of network actors, objects, and processes, thus providing a description of required functionality. Normative knowledge, on the other hand, provides a way to precisely denote the acceptable information system usage and specification behaviour. As functionality of an information system generally changes less than the usage aspects, the explicit distinction between ontological and normative knowledge allows for more stable system specification and implementation. We already gave a formal definition of norms in [5], and showed what role they play in user-driven system specification. In this paper, we introduce our ontological framework. 3.3. The Reference Framework All specification knowledge in RENISYS is organized in a reference framework, consisting of three interrelated domains. Five ontologies provide the concepts needed to describe entities from these domains as well as their linkages. The Domains RENISYS specifications belong to, or link entities from, three different domains. A domain is a system of network entities that can be observed by analyzing the universe of discourse from a particular perspective. The problem domain is the UoD seen from the task perspective, the human network (domain) is the UoD observed from the organizational perspective, the information system (domain) is the UoD seen from the functionality perspective. The domain interrelationships are shown in the reference framework (Fig. 4) The problem domain and the human network form the two top domains. The distinction between problem domain and human network is based on Habermas' distinction between work and interaction [19]. In his theory of communicative action these concepts designate respectively a domain of purposive-rational action and a subsuming institutional context. Together the problem domain and the human network are called the usage context, which models the determinants of change in the network information system. In the usage context, the requirements are formulated that determine the high-level design specifications that are generated at the information system level. To understand how the information system evolves, these system determinants need to be described. Finally, in the information system, the actual network information system is represented. 3.4. The Ontological Framework For each of the domains, a domain ontology has been developed, which contains a set of predefined ontological domain axioms or primitives. These primitives can be applied to users either to modify existing definitions or to define new terminology. A somewhat similar approach was used by [8], who extracted primitives from the literature and modified these according to empirical findings. In RENISYS, however, these theory-grounded primitives are meant to be accepted and modified by (authorized) users. To increase the efficiency of this customization process, reference models predefining concepts of particular domains can be useful [20]. To link entities from the various domains, the framework ontology contains a set of mappings. These mappings can be used to represent functionality determinants, which are entities in the usage context that are connected to entities from the information system domain. For example, the edit process (represented in the problem domain) is linked to a set of communication processes in the information system domain, such as those that enable the distribution of documents to the mailers of users playing the editor roles. Space does not permit to describe the domain and framework ontologies in detail. We therefore focus on the fundamental ontology of which the domain ontologies are specializations: the core process ontology. 4. The Core Process Ontology The heart of the ontological framework is the core process ontology, consisting of elementary network process concepts. The concepts in this ontology are derived from language action theories (for an overview of current work see [21]), which are useful for modelling complex goal-oriented communication processes. The core process ontology contains the common vocabulary for three domain ontologies. Such a core process ontology is necessary, because various domain ontologies provide different perspectives on the same reality. The most generic concepts are entities. An entity is an identifiable phenomenon in the universe of discourse. Entities include actors, objects, and processes. Different users can have different views on these entities, but each entity definition has global scope. 4.1. Actors An actor is a context interpreting entity capable of playing transformation control roles. The total set of roles that a specific actor has in turn is played by one or more subjects: sentient physical entities in the universe of discourse. A subject can play the roles of more than one actor. 4.2. Objects An object is defined as an entity that can be acted upon or produced in a transformation. 4.3. Processes Central to RENISYS is its process model (Fig. 5). A process is an abstract entity mediating some kind of change in other entities. This change can, for example, be one of space, time, or quality. However, we constrain ourselves to processes that are relevant for the user-driven specification of network information systems. Three main kinds of processes are distinguished: control processes, delegation processes, and transformations. Transformations are further subdivided into workflow, specification, implementation, and use processes. Delegation, implementation, and use processes are not described here, as they are not essential for the modelling of specification processes. Control Processes In a control process, the status of a controlled process, called a transformation, is changed. A controller is an actor playing transformation control roles. Three such roles are distinguished: initiator, executor, and evaluator. The corresponding control processes are: initiations, executions and evaluations. In an initiation, a transformation is started. In an actor-initiation this happens on the own initiative of the initiator; in an event-initiation a transformation is required to start because of the successful completion of another transformation, resulting in an explicit inter-transformation dependency. It is also possible that both an actor-initiation and an event-initiation apply. In that case the initiator can decide whether to start the transformation he controls on the condition that the event has taken place. In an execution, the intended result of a transformation is realized. In an evaluation, an assessment of the change realized in the execution is made. If this result is accepted by the evaluator, the evaluation completing the transformation may result in an event that triggers the initiation of other transformations. Transformations We call a process affected by control processes a transformation. In a transformation, a single type of output object is produced from a set of input objects under the control of a set of actors playing the control process roles. This restriction of allowing only a single output object type is necessary to simplify transformation change, as it is now clear which (sub)transformation is affected. This would not be the case if two or more output object types are generated in a single transformation. Several kinds of transformations are distinguished, based on the kinds of objects they produce. Two categories of transformations treated in this paper are workflow and specification processes. In workflow processes, the production of domain objects is described: a set of input domain objects is transformed into an output domain object. In specification processes, definitions are handled. A definition is a proposition in which specification knowledge is asserted. Definitions consist of a defined term and a defining set of terms, which include entities from the universe of discourse. Definitions are of either types, norms, or states. A type is a class of entities sharing certain properties. A norm is the accepted (permitted, mandatory, and forbidden) behaviour of an actor. A state is the actual or potential state-of-affairs in the universe of discourse. In specification processes, actors from the universe of discourse (operational level), in which they are involved in workflow processes, play the roles of specifiers, which can be further subdivided into creators, modificators, and terminators. In order to do so, three kinds of specification processes are possible: creations, modifications, and terminations. A creation is a specification process in which a new definition is created. In a modification, the defining set of terms of an existing definition is changed. A termination is a specification process in which an existing definition is removed, and references to the terminated definition are reviewed. Examples of such specification processes for types were given in [5]. Actions and Compositions Control processes combined with transformations form new entities. For each transformation at least one initiation, execution, and evaluation control process must be given, in order for the transformation to be sufficiently defined. A control process plus its controlled workflow process is called an action, in combination with a specification process it is called a composition. Every transformation can only be realized by an ensemble of initiations, executions, and evaluations. Each such action or composition in turn is assigned to actors by means of norms, which, under certain conditions, either permit, require, or forbid them to do these control processes. Norms will be further discussed in the next section. 5. Applying the Ontological Framework We have used the ontological framework in the EJCL-case to model the specification evolution occurring in the setup of an electronic journal. This was done by constructing a set of process diagrams, based on the concepts as defined in the framework. An example of such a diagram is given in Fig. 6. Users playing various key actor roles in the project were asked to fill in the diagrams as much as they could. Using the framework, it was then determined which actors should evaluate, and, if necessary, modify or complement the specifications. In this way, in a very short period of time specifications were generated which were found to be both accurate and complete by the participants and could easily be mapped to the available set of enabling tools. The manual approach used in this particular case is now being incorporated in an automated version in the RENISYS tool. A particular advantage of our approach has proven to be that the framework allows for the simple expression of high-level specifications in which details need to be filled only when the users themselves deem this necessary. In other words, the specification follows the users in their thinking rather than forcing them into some (to them) foggy methodological direction. A related workflow modelling approach based on the same line of thought is described in [22]. An actual case example of an ontological specification was the definition of the main workflow of producing a journal needed to accomplish the network goal: publishing an on-line series of electronic journal issues. At the start of the project, the users identified the main workflow to consist of seven sub-workflows, represented in the following ontological specification (in conceptual graph notation): \[ \begin{align*} \text{TYPE: } & \text{[PRODUCE_JOURNAL:*x]} \to \text{(def)} \to \text{(obj)} \to \text{(agnt)} \to \text{[EDIT]} \to \text{[ASS_EDITOR]} \to \text{[EVAL]} \to \text{[CREATE]} \to \text{(rslt)} \to \text{[REQ_ACT: \text{[CHIEF_EDITOR]} \to \text{(agnt)} \to \text{[CONTROL] \to \text{(obj)} \to \text{[EDIT]}}]}. \end{align*} \] This norm says that the chief editor must start, carry out, and assess the outcome of the editing process, as it is one of his responsibilities. Note that the user is not directly confronted with this abstract representation. Instead, the tool uses it to generate a pseudo-natural language dialogue with the user. In order to also require the assistant editor to at least evaluate the results of the edit process, the additional norm proposed by the participant is the following: \[ \begin{align*} \text{REQ_ACT: } & \text{[ASS_EDITOR]} \to \text{(agnt)} \to \text{[EVAL] \to \text{(obj)} \to \text{[EDIT]}}. \end{align*} \] However, although this change is proposed by the participant having the breakdown, it is not yet clear if it is also acceptable to the community as a whole. To determine which users are to be involved in the change process of the action norm, the tool needs to project the following query on the existing base of composition norms (see [14]): \[ \begin{align*} \text{REQ_COMP: } & \text{[ACTOR:?] \to \text{(agnt)} \to \text{[CONTROL] \to \text{(obj)} \to \text{[CREATE]} \to \text{(rslt)} \to \text{[REQ_ACT: \text{[ASS_EDITOR]} \to \text{(agnt)} \to \text{[EVAL] \to \text{(obj)} \to \text{[EDIT]}}]}}. \end{align*} \] In a further simple projection, the set of returned actors can then be queried to determine the particular subjects playing those roles. These users are subsequently invited to participate, for instance by sending them an e-mail containing the login code for this particular specification process. In sum, our approach allows for evolving specification knowledge to be concisely represented, as well as to precisely identify which users should be involved in particular specification processes. Regarding the implementation of these specifications: the specifications at the information system domain level are ultimately represented in terms of those attributes of information tools that can easily modified, such as the public or private status of a mailing list. In this way, a close match between specification and implementation processes can be guaranteed, thus ensuring that the evolution of the technical information system rapidly follows the changes in requirement definitions. 6. Formal Semantics of the Specification Process The specification process illustrated in the previous section needs to be formally represented in a logical language. This is necessary in order to automate the calculation of which particular users can legitimately be involved in a particular stage of a specification process. In [23], a formal language called \(L_{sc} \) for an integrated semantics for information and communication systems was described. In this modal logic it is possible to specify object types and roles (static part), actions and constraints (dynamic part) as well as communicative actions (illocutionary part). The constraints can be objective (what is possi- able or necessary) and deontic (what is permitted or obligatory). The illocutionary part adds the special action category of “speech acts”. $L_{tl}$ contains also a special (declarative) speech act for granting, as well as for retracting, authorizations. The language $L_{tl}$ can be used for describing the semantics of the specification process in which the ontological framework is used. Using the language we formally describe how users are authorized to be involved in the subsequent specification process stages. The details of the language are discussed in [24], here we will only introduce the ideas most relevant to the discussion. In the RENISYS ontology, a composition was defined as a combination of a control process and a specification process. The ontological definition of a particular specification process $S_\Delta$ (e.g. ‘create some knowledge definition’) includes the knowledge definition being changed (e.g. of the ‘edit process type’). To formally represent this, we introduce a set $C$ of control processes, a set $S$ of specification processes, and a set $D$ of knowledge definitions, and define the set $Comp$ of compositions in $L_{tl}$ as the Cartesian product of $C \times S \times D$. In RENISYS, each particular specification process $S_\Delta$ consists of three subsequent compositions $Comp_i$, which indicate the initiation, execution, and completion process that make up $S_\Delta$. To carry out $S_\Delta$, a conversation for specification needs to be successfully completed, of which the result is an accepted knowledge definition $D_\Delta$. In this conversation, three conversational roles are distinguished: the initiator ($I$), executor ($X$), and evaluator ($E$). A conversational role can be fulfilled by more than one actor. Composition norms determine which actors (and thus which subjects) play the various conversational roles in a particular specification process, by, for example, stating that an editor is permitted to initiate the ‘create edit type definition’ specification process: $$Perm_{Comp}(Editor, I, CreateType, Edit)$$ In this paper, we do not work out how this mapping from composition norms to conversational roles takes place (see [14] for a conceptual-graph based approach to accomplish this). The following stages are distinguished in a successful conversation for specification: - $I$ initiates a specification process by proposing to start $S_\Delta$. - $X$ executes $S_\Delta$ by discussing a $D_\Delta$. - $E$ evaluates $S_\Delta$ by deciding on a $D_\Delta$. We start using $L_{tl}$ by defining a finite set $Subj$ of constants to represent the subjects. We also have a finite set $Act$ of actors. $\Phi$ is a first order logic formula and $\alpha$ some speech act $\in \{PROPPOSE, DISCUSS, DECIDE\}$. The intuitive meaning of $[\alpha]\Phi$ is that after the execution of $\alpha$, $\Phi$ necessarily holds. In $L_{tl}$, different validity claims for speech acts are distinguished. In this context, we use only one, to authorize a conversational role to perform a speech act in a specification process, which is represented by means of the auth predicate. A conversational role in RENISYS is authorized to perform a speech act depending on the (initiation, execution, or evaluation) stage of a particular conversation for specification. To say that some conversational role $x$ is authorized to perform speech act $\alpha$ on specification process $S_\Delta$ resulting in (intermediate) knowledge definition $D_\Delta$, we propose the following axiom (assuming universal quantifications): $$P(DO(x, \alpha, S_\Delta, D_\Delta)) \iff auth(x, \alpha, S_\Delta, D_\Delta)$$ which expresses formally that some role is authorized to perform a speech act, if and only if the role is allowed to do it. The predicate $DO(x, \alpha)$ is used to denote the performance of a particular speech act by a particular role. Instead of $[\alpha]$, we write $[DO(x, \alpha)]$, to represent that $x$ is the role carrying out the speech act $\alpha$. The predicate $P$ is formally defined in terms of the deontic modalities as expressed in deontic logic. These modalities can be represented with the following abbreviations (cf. [24]): $$O(\alpha) \iff \exists \ [Violation (\"\alpha \ is \ obligatory\")] F(\alpha) \iff \exists \ [Violation (\"\alpha \ is \ forbidden\")] P(\alpha) \iff \neg [Violation (\"\alpha \ is \ permitted\")] This can be interpreted as that $\alpha$ is obliged if not doing $\alpha$ leads to a violation state, $\alpha$ is forbidden if doing $\alpha$ leads to a violation state and $\alpha$ is permitted if it is not forbidden to do $\alpha$. Note that the $P$ predicate in the abovementioned axiom is of a higher order than the $Perm$ of permission (norms). In other words, having some $Perm_{Comp}$ apply to an actor is a necessary, but not always a sufficient condition to be authorized to perform speech act $\alpha$. For example, an actor must be permitted by some composition norm to execute a specification process. However, he is only actually authorized to do so after this process has first been initiated as well. We now need to define exactly when actors playing conversational roles are authorized to perform the various speech acts constituting a conversation for specification. Knowing these authorizations is essential in order to give particular users access to the proper specification tool functionality at the right moment in time. As mentioned before, we assume that we already know which actors $\{i, x, e\}$ in the network are allowed to play the conversational roles $\{I, X, E\}$, as determined by the composition norms that apply to $S_\Delta$. First, any initiator $i$ of $S_\Delta$ (as determined by the relevant composition norms) is always authorized to propose that $S_\Delta$ starts. $$auth(i, PROPPOSE, S_\Delta, \emptyset)$$ The result of this speech act is a proposed specification process according to the following rule: $$[PROPPOSE(i, S_\Delta)]prop(S_\Delta)$$ Discussion by the executor $x$ resulting in (tentative) knowledge definition $D_\Delta$ can start after a proposal has been made: $$P(D_{DISCUSS}(x, S_\Delta, D_\Delta)) \leftrightarrow \text{prop}(S_\Delta)$$ Once $D_\Delta$ has been finalized by the executor, the discussion is closed: $$[D_{DISCUSS}(x, S_\Delta, D_\Delta)(\text{disc}(S_\Delta, D_\Delta) \land \neg \text{prop}(S_\Delta))]$$ Note that the specification process is no longer in ‘proposed’ state and that $\text{prop}(S_\Delta)$ therefore needs to be removed. Once this has been done, evaluator $e$ is authorized to make a decision: $$P(D_{DECIDE}(e, S_\Delta, D_\Delta, \text{Execution})) \leftrightarrow \text{disc}(S_\Delta, D_\Delta)$$ The actual decision can be either to accept (+) or reject (⇒) the discussed $D_\Delta$. Since we assume that the specification process was successful, we represent the acceptance of $D_\Delta$ in the following way: $$[D_{DECIDE}(e, S_\Delta, D_\Delta, +)](\text{accept}(D_\Delta) \land \neg \text{disc}(S_\Delta, D_\Delta))$$ which says that a positive (+) decision results in an accepted definition, while its discussed status is retracted. With a negative decision, the proposal is retracted as well, but of course, no accepted status is given. The specification process was only described in a very rudimentary way, as the main objective was to illustrate how the ontological concepts can be used in the authorization of users involved in the dynamic specification process. Some possible directions of extension of the formal framework are outlined next. In current research we are addressing these and related issues. It was assumed that all actors playing conversational roles are assigned by means of permitted composition norms. However, if required and forbidden compositions are also known (as in any realistic case), other authorizations will be additionally needed. Another simplification was that compositions were considered to be atomic, in the sense that no generalization/specialization hierarchy of definitions is supported. However, in real-world specification the latter is extremely useful. In [14] we propose a context-lattice based conceptual graph approach, which we are currently developing further. Furthermore, in RENISYS, two types of specification process (and workflow) initiations are distinguished: the ‘actor initiation’ and ‘event initiation’ (as described in Sect. 4.3.). The initiation process described here referred to actor initiations only. To also represent event initiations, the discussion authorization needs to be extended (note that the retraction of event$_\text{init}$ also needs to be addressed in later speech acts): $$P(D_{DISCUSS}(x, S_\Delta, D_\Delta)) \leftrightarrow \text{prop}(S_\Delta) \lor \text{event}_\text{init}(S_\Delta)$$ Finally, the distinction that is made in $L_{\Delta\iota}$ between permitted and possible actions is worth noting. In RENISYS, this distinction is particularly relevant, since possible is useful in the information system domain (“enabling information tools”), whereas permitted is the modality that prevails in the usage context. Formally dealing with these issues is important to describe the matching process between required and (tool-)enabled functionality. The relationships between these two domains can be of various kinds, for instance: - “everything that is permitted is possible” is a completeness requirement on the implementation functionality. This is a very basic requirement. - “everything that is possible is permitted” means that only permissible behaviour is implemented, a kind of correctness requirement (cf. a speed control system that makes it impossible for drivers to violate the speed limit). Note that this requirement is seldom met completely, which means that users can do things wrong, leading to a violation that has to be repaired or sanctioned later. So although many ‘permit’ constraints at usage context level are translated into functionality of the implementation, and hence lose their deontic status, also in the information system domain there is a need to express norms. 7. Related Work and Conclusion An ontological framework was described as part of the RENISYS specification method for research network information systems. The framework can be used to structure and support the discussions that users have as part of the specification process. An important feature of our approach is that it allows users to consider functionality (re)specification of the network information system in terms of the particular context in which they use it, thus strongly connecting cooperation for work with cooperation for specification. A number of tools have been developed, many of them Web-based like the earlier mentioned BSCW tool [13] that allow users to relatively easily modify often complex functionality characteristics. However, structured support for the specification processes is often not given. This makes it hard to ensure the legitimacy of the specifications, i.e. that they are both meaningful and acceptable to a professional community of users. To increase the strong link between usage and specification, some form of descriptive terminology is needed. End-user modifiable tools such as ‘radically tailorable tools’ [25] do provide a, basic, language for integrating specification and implementation change. However, this tailorability is typically single-user and single-tool focused. On the other hand, socio-technical design methods such as Mumford’s ETHICS [26] strongly focus on making legitimate specifications, which are acceptable to a complete community. A drawback of this method, however, is that it is typically oriented towards large-scale, waterfall-like information systems development projects, and lacks the advantages of knowledge-based specification support. A Web-based RENISYS tool is under development that supports the legitimate user-driven specification process. A first prototype will be tested in a case on group report authoring. References
{"Source-Url": "https://pure.uvt.nl/ws/portalfiles/portal/308622/hicss99.pdf", "len_cl100k_base": 8585, "olmocr-version": "0.1.53", "pdf-total-pages": 11, "total-fallback-pages": 0, "total-input-tokens": 35332, "total-output-tokens": 10780, "length": "2e13", "weborganizer": {"__label__adult": 0.0003616809844970703, "__label__art_design": 0.0010051727294921875, "__label__crime_law": 0.0005559921264648438, "__label__education_jobs": 0.005626678466796875, "__label__entertainment": 0.0001982450485229492, "__label__fashion_beauty": 0.00024580955505371094, "__label__finance_business": 0.0009765625, "__label__food_dining": 0.00045108795166015625, "__label__games": 0.0006890296936035156, "__label__hardware": 0.0008440017700195312, "__label__health": 0.000912189483642578, "__label__history": 0.0005950927734375, "__label__home_hobbies": 0.00016641616821289062, "__label__industrial": 0.0007152557373046875, "__label__literature": 0.0017032623291015625, "__label__politics": 0.0005230903625488281, "__label__religion": 0.0007734298706054688, "__label__science_tech": 0.439453125, "__label__social_life": 0.00032138824462890625, "__label__software": 0.03265380859375, "__label__software_dev": 0.509765625, "__label__sports_fitness": 0.0002384185791015625, "__label__transportation": 0.0007429122924804688, "__label__travel": 0.0002377033233642578}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 48000, 0.02579]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 48000, 0.6717]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 48000, 0.91123]], "google_gemma-3-12b-it_contains_pii": [[0, 1306, false], [1306, 4387, null], [4387, 8861, null], [8861, 12572, null], [12572, 18098, null], [18098, 22502, null], [22502, 27940, null], [27940, 31288, null], [31288, 37284, null], [37284, 43124, null], [43124, 48000, null]], "google_gemma-3-12b-it_is_public_document": [[0, 1306, true], [1306, 4387, null], [4387, 8861, null], [8861, 12572, null], [12572, 18098, null], [18098, 22502, null], [22502, 27940, null], [27940, 31288, null], [31288, 37284, null], [37284, 43124, null], [43124, 48000, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 48000, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 48000, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 48000, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 48000, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 48000, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 48000, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 48000, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 48000, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 48000, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 48000, null]], "pdf_page_numbers": [[0, 1306, 1], [1306, 4387, 2], [4387, 8861, 3], [8861, 12572, 4], [12572, 18098, 5], [18098, 22502, 6], [22502, 27940, 7], [27940, 31288, 8], [31288, 37284, 9], [37284, 43124, 10], [43124, 48000, 11]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 48000, 0.0]]}
olmocr_science_pdfs
2024-12-04
2024-12-04
2c4d8cf64189b54413cb223589c21ef26a84ff8f
Visualizing Ontologies with VOWL Steffen Lohmann\textsuperscript{a,\ast}, Stefan Negru\textsuperscript{b,\ast\ast}, Florian Haag\textsuperscript{a}, Thomas Ertl\textsuperscript{a} \textsuperscript{a} Institute for Visualization and Interactive Systems (VIS), University of Stuttgart, Universitätsstraße 38, 70569 Stuttgart, Germany E-Mail: \{steffen.lohmann, florian.haag, thomas.ertl\}@vis.uni-stuttgart.de \textsuperscript{b} Faculty of Computer Science, Alexandru Ioan Cuza University, Strada General Henri Mathias Berthelot 16, 700483 Iasi, Romania E-Mail: stefan.negru@info.uaic.ro Abstract. Visualizations can be very useful when working with ontologies. The Visual Notation for OWL Ontologies (VOWL) is a comprehensive and well-specified visual language for the user-oriented representation of ontologies. It defines graphical depictions for most elements of the OWL Web Ontology Language that are combined to a force-directed graph layout visualizing the ontology. In contrast to related work, VOWL aims for an intuitive representation that is also understandable to users less familiar with ontologies. This article presents VOWL in detail and describes its implementation in two different tools: ProtégéVOWL and WebVOWL. The first is a plugin for the ontology editor Protégé, the second a standalone application entirely based on open web standards. Both tools demonstrate the applicability of VOWL by means of various ontologies. In addition, the results of three user studies conducted to evaluate the comprehensibility and usability of VOWL are summarized. They are complemented by latest insights gained from an expert interview and from testing the visual scope and completeness of VOWL with a benchmark ontology. The evaluations helped to improve VOWL and confirm that it creates comparatively intuitive and usable ontology visualizations. Keywords: OWL, VOWL, ontology, visualization, user-orientation 1. Introduction Ontologies have received a lot of attention with the rise of the Semantic Web as a way to give information well-defined meaning \cite{12}. They are nowadays used in many different contexts to structure and organize information \cite{60}. As a consequence, an increasing number of people in modern knowledge societies get in contact with ontologies. They are no longer exclusively used by ontology experts but also by non-expert users. However, especially these casual users often have difficulties in understanding ontologies. Visualizations can help in this regard by assisting in the development, exploration, verification, and sense-making of ontologies \cite{29,40,44}. They are particularly useful to casual users, but can also provide a new perspective on ontologies for experts. Although several visualizations for ontologies have been developed in the last couple of years, they either focus on specific aspects of ontologies or are hard to read for casual users. Furthermore, many visualizations are tailored for a specific task or use special types of diagrams that must first be learned to understand the visualization. A review of existing ontology visualizations is given in Section 2 of this article. The Visual Notation for OWL Ontologies (VOWL) aims to fill this gap by defining a comprehensive visual language for the representation of ontologies that can also be understood by non-expert users with only little training. It is designed for the OWL Web Ontology Language \cite{63}, which has become the de facto standard to describe ontologies. VOWL defines graphical depictions for OWL elements that are combined to a graph visualization representing the ontology. It can be \textsuperscript{1}Invited extended version of a paper submitted to EKAW 2014. \textsuperscript{\ast}Corresponding author. \textsuperscript{\ast\ast}Stefan Negru is now with MSD IT Global Innovation Center. used to generate static ontology visualizations, while it also supports the interactive exploration of ontologies and the customization of the visual layout. An early version of VOWL has been presented in [56] and compared to the UML-based visualization of ontologies in [55]. Based on insights from that comparison and further feedback, the notation was completely reworked and VOWL 2 was developed, with significant improvements and more precise mappings to OWL. VOWL 2 will be presented in Section 3, followed by a description of two tools that implement it in Section 4: ProtégéVOWL, a plugin for the ontology editor Protégé [3], and WebVOWL, a responsive web application entirely based on open standards. VOWL and its implementations have been evaluated in user studies that are summarized in Section 5, followed by an expert interview providing additional insights. Finally, an evaluation of the visual scope and completeness of VOWL based on a benchmark ontology is provided. 2. Related Work A number of visualizations for ontologies have been presented in the last couple of years [21,29,40,44] while some of them are implemented as standalone applications, most visualizations are provided as plugins for ontology editors like Protégé [4]. 2.1. Graph Visualizations of Ontologies Many approaches visualize ontologies as graphs, which is a natural way to depict the structure of the concepts and relationships in a domain of knowledge. The graphs are often rendered in force-directed or hierarchical layouts, resulting in appealing visualizations. However, only few visualizations show complete ontologies, but most focus on certain aspects. For instance, OWLViz [37], OntoTrack [45], and KC-Viz [52] depict only the class hierarchy of ontologies. GLOW [36] also depicts the class hierarchy but uses a radial tree layout and hierarchical edge bundles to display additional property relations. OWLPropViz [64], OntoGraf [24], and FlexViz [25] represent different types of property relations, but do not show datatype properties and property characteristics required to fully understand ontologies. A smaller number of works provide more comprehensive graph visualizations that represent all key elements of ontologies. Unfortunately, the different ontology elements are often hard to distinguish in the visualizations. For instance, TGViz [8] and NavigOWL [39] use very simple graph visualizations where all nodes and links look the same except for their color. This is different in GrOWL [43] and SOVA [13], which define more elaborated notations using different symbols, colors, and node shapes. Furthermore, as the notations of both GrOWL and SOVA rely on symbols from Description Logic [9] and abbreviations, they are not perfectly suited for casual users. Furthermore, the visualizations created with GrOWL and SOVA are characterized by a large number of crossing edges which has a negative impact on the readability. There are also 3D graph visualizations for ontologies, such as OntoSphere [15], or tools that use hyperbolic trees to visualize ontologies, such as OntoRama [22] or Ontobroker [26]. However, these works again focus only on specific aspects of ontologies, such as the class hierarchy or the relationships of certain elements. 2.2. Specific Diagram Types While the reported graph visualizations use common node-link diagrams to represent ontologies, there are also a number of works that apply other diagram types. For instance, Jambalaya [61] and OWL-VisMod [28] use treemaps to depict the class hierarchy of ontologies. Jambalaya additionally provides a nested graph visualization called SHRiMP that allows to split up the class hierarchy into different views [61]. CropCircles is a related visualization technique that visualizes the class hierarchy of ontologies with the goal to support the identification of “undermodeled” ontology parts [65]. All these approaches visualize once again mainly the class hierarchy, without considering other property relations. Cluster Maps use a visualization technique that is based on nested circles and has also been successfully applied to ontologies [27]. Instead of showing the class hierarchy, Cluster Maps visualize individuals grouped by the classes they are instances of. Each individual is represented by a small circle that is shown inside a larger circle representing the class. Similar techniques are used in VisCover [46] and OOBIAN Insight [2] that additionally provide a number of interactive filtering capabilities. While offering appealing visualizations, these tools show only a selection of classes along with their instances but do not provide complete visualizations of ontologies. Another related approach is OntoTrix [10], which represents ontologies with the NodeTrix visualization technique, a combination of node-link diagrams and adjacency matrices [34]. While OntoTrix also focuses on the visualization of individuals and their connections within ontologies, it provides a more complete image of the ontology. However, the ontology is converted into the NodeTrix structure for the visualization, making it difficult to get an impression of its global structure and topology. 2.3. UML-like Ontology Visualizations A powerful type of diagram related to OWL and often reused to visualize ontologies is the class diagram of the Unified Modeling Language (UML) [6]. Precise mappings between OWL and UML class diagrams are specified in the Ontology Definition Metamodel (ODM) [1], among others. There are numerous editors for UML diagrams, but as conventional UML editors cannot read and visualize OWL files, special ontology editors or plugins for UML editors have been developed. Examples are the Visual Ontology Modeler (VOM) [42], TopBraid Composer [5], and OWL-GrEd [11]. A major drawback of these attempts is that they require knowledge about UML class diagrams. Although many people with an IT background are familiar with these types of diagrams, people from other domains have difficulties interpreting them correctly, as found in the aforementioned user study [55]. Since UML has been designed for the representation of software rather than knowledge, there are also some conceptual limitations and incompatibilities when using UML class diagrams for the visualization of ontologies. A related type of diagram for ontology visualization is used by OntoViz. It groups classes and datatypes in boxes that can be linked by different properties. However, the resulting diagram quickly grows in size and is not very intuitive. This is different in Graffoo [23] which aims for an easy-to-understand notation for OWL diagrams similar to VOWL. However, it is intended to be used in diagram editors and therefore rather related to the idea of UML-based modeling than to the visualization approach that is followed by VOWL. 2.4. Other Visualization Approaches Since any OWL ontology can be represented as RDF graph, it can also be visualized using the common RDF notation [41]. RDF visualizations are, for instance, provided by the RDF validator of W3C [7] or tools like RDF Gravity [62]. However, the visualizations quickly become large with plenty of nodes and edges, as the OWL constructs are represented by multiple triples in RDF. Such RDF visualizations of OWL are not only hard to read but also fail to adequately reflect the semantics of the OWL constructs. This is similar for Linked Data visualizations that are also RDF-focused and usually do not consider and visualize complete ontologies [19]. One such tool is RelFinder [32] that visualizes relationships between individuals described by ontologies and makes these relationships interactively explorable. Another tool is gFacet [33] where individuals are grouped by their classes and filtered by selecting linked individuals or data values. Both tools provide some insight into the relationships between a limited set of classes and/or individuals, but they do not visualize complete ontologies. This is similar in the tool LodLive [18] that enables the visual exploration of Linked Data using a graph visualization. 2.5. Discussion of Related Work Looking at the related work, some common characteristics stand out: Most visualizations utilize a well-known type of diagram for ontology visualization (graph visualization, treemap, UML), are in 2D, and focus on specific aspects of ontologies. Only few attempts aim for a comprehensive ontology visualization. Even less approaches provide an explicit description of the visual notation, i.e., a specification that precisely defines the semantics and mappings of the graphical elements. Often, there is no clear visual distinction between different property types or between classes, properties, and individuals. Furthermore, many works implement a stepwise approach of ontology exploration, where only a root class is shown at the beginning and the user has to navigate through the visualization (e.g., by expanding or collapsing visual elements). VOWL rather aims for an approach that provides users with an overview of the complete ontology and let them subsequently explore parts of it in depth, following the popular Visual Information Seeking Mantra of “overview first, zoom and filter, then details-on-demand” [58]. This approach was chosen, as it was considered important to give users a visual impression of the size and topology of the ontology before they start to explore it any further. Most importantly, VOWL aims for an intuitive visualization that is also understandable to users less familiar with ontologies, while most of the related work has rather been designed for ontology experts. It uses a graph visualization, as this is considered a natural and intuitive way to represent the structure of ontologies, which is confirmed by many of the related work reported above. 3. Visual Notation for OWL Ontologies (VOWL) So far, two versions of VOWL have been specified at http://purl.org/vowl/spec/. While the first version emerged from the idea of providing an integrated representation of classes and individuals [56], VOWL 2 focuses on the visual representation of classes, properties, and datatypes. This information is known as the Terminological Box (TBox) in Description Logic and distinguished from the individuals and data values making up the Assertional Box (ABox). The TBox is usually most important to understand the conceptualization described in an ontology and therefore considered ‘first-class citizen’ in most ontology visualizations. VOWL 2 addresses primarily the TBox and only optionally integrates some ABox information in the visualization. It recommends to display detailed information about individuals in another part of the user interface (e.g., a sidebar) that is linked with the visualization. This design decision is supported by comments from a user study on VOWL 1 [55], expressing concerns about the scalability of an integrated TBox and ABox visualization. Even with few individuals per class, additional information, such as property values of individuals, would be difficult to include in the visualization without creating lots of clutter. 3.1. Basic Building Blocks of VOWL VOWL 2 is based on the graphical representations specified in VOWL 1 but uses a more systematic and modular approach for the visual language. The basic building blocks of VOWL 2 are a clearly defined set of graphical primitives and a color scheme. Both express specific aspects of the OWL elements (e.g., datatype or object property, different class and property characteristics, etc.), while considering possible combinations thereof. In addition, VOWL 2 provides explicit splitting rules that define which elements are multiplied in the graph visualization in which way. This systematic and modular approach does not only improve the semantics of the visual language but also facilitates its implementation. For instance, the small set of graphical primitives that are consistently varied and combined fit well with object-oriented programming. The same holds for the style information that is specified in a modular way in the stylesheet deployed with the VOWL specification. Finally, the graph structure was refined in a way in VOWL 2 that it can be more easily visualized (e.g., by avoiding edges between property labels), and developers were given more freedom in the parametrization of VOWL (e.g., by defining an abstract color scheme that can be adapted as needed). 3.1.1. Graphical Primitives Table 1 lists the small set of graphical primitives that VOWL is based on, along with the ontology elements they are applied to. Classes are depicted as circles that are connected by lines representing the properties with their domain and range axioms. Property labels and datatypes are displayed in rectangles, and text is used for the labels and for cardinality constraints. Where available and desired, the number of instances that belong to a class can be visually expressed by the circle size. VOWL does not specify a particular scaling method for the circle radius, but proper results will likely be achieved with a logarithmic or square-root scaling in most cases. If instance information is not considered in the visualization, the circles of all classes have the same predefined size. The only exception are the circles of anonymous classes and of classes that represent owl:Thing: They are shown in a smaller size, as they usually do not carry relevant domain information. Even though all individuals in an ontology are instances of owl:Thing according to the OWL specification, this is irrelevant for the visualization so that owl:Thing has always a fixed size. Most connecting lines in VOWL have an arrowhead that points to the class or datatype that is defined as the range of the property the line represents. If no domain and/or range axiom is defined for a property, owl:Thing is used as domain and/or range. An exception are datatype properties without a defined range, where rdfs:Literal is used as range instead. Lines of inverse properties have arrowheads at both ends, while the direction of the respective property can be interactively highlighted by hovering over the label. If the same pair of classes is connected by multiple lines, it is recommended to curve the lines to avoid visual overlapping. Subproperty axioms are also indicated by interactive highlighting instead of explicit connections between the property labels (as in VOWL 1) to reduce the number of edge crossings and to facilitate the implementation and interpretation of VOWL. The rectangles representing property labels have no border to distinguish them from those representing datatypes. The labels depict usually the text for the element given with rdfs:label in the language selected by the user. If no label is given for an element, the last part of the URI is taken, i.e., the string that follows the last slash (/) or hash (#) character. Long labels are abbreviated, but the full text is always available on demand (e.g., displayed in a sidebar or tooltip). ### 3.1.2. Color Scheme In addition, VOWL defines a color scheme for a better distinction of the different elements (see excerpt in Table 2). The colors are defined by their function in an abstract way and relative to the canvas color to leave room for customization. While concrete colors are recommended, developers may choose different colors as long as they comply with the abstract descriptions. The color scheme also defines how the colors should relate to each other in order to encode the VOWL semantics. For example, the external color is defined to be a “dark version of the general color”, and the datatype color is described as a “light color that is clearly different from the other colors”. Where several of the color mappings may apply, priority rules are specified. One example for such a rule is that the deprecated color has always priority over the external color, as this information is considered to be more important in most cases. The recommended color scheme has been designed in accordance with the general guidelines: For instance, and inline with the above example, the recommended external color (dark blue) is similar to the general color (light blue), whereas the color for datatype properties (light green) is clearly different. Some of the other colors were picked based on their global characteristics, such as the signal aspect of the highlighting colors (red and orange). However, colors are not required in order to use the visualization—it is also comprehensible when printed in black and white or viewed by color-blind people. Details that rely on color, such as the subtle distinction of owl:Class and rdfs:Class, may be added as text information in these cases. Other information is by default provided as text so that it remains available in the absence of colors. The text labels also help to make the visualization more self-explanatory, as was found in a user study [51]. Similar to the conflicting colors, the VOWL specification contains guidelines on how to combine conflicting text labels (in most cases, they are displayed as a comma-separated list (e.g., “deprecated, external”). ### 3.2. Visual Elements VOWL provides visual elements for most language constructs of OWL 1 and 2, including those of RDF and RDFS reused in OWL. The representations are based on the graphical primitives and the color schema described above; a selection is shown in Figure 1. As already mentioned, information is redundantly encoded in several cases. One such example is the visual element for external classes, i.e. classes whose base URI differs from that of the visualized ontology. It has both the external color, as defined in the color scheme, and the hint “external” beneath its label. Other examples are the visual elements for class disjointness and logical disjunction that use either a mathematical symbol or text label in combination with an illustration reminiscent of Venn diagrams. These illustrations help to communicate the underlying set operations to users who are not familiar with the mathematical symbols and names of the concepts. Some of the visual elements were inspired by UML class diagrams, such as the notations for subclass relations and cardinality constraints. The representations of these elements were considered intuitive by many participants of the user study that compared VOWL 1 to the UML-based visualization of ontologies [55]. The notations of object and datatype properties dif- <table> <thead> <tr> <th>Table 2: Excerpt of the VOWL color scheme</th> </tr> </thead> <tbody> <tr> <td>Name</td> </tr> <tr> <td>----------------------------</td> </tr> <tr> <td>General</td> </tr> <tr> <td>External</td> </tr> <tr> <td>Deprecated</td> </tr> <tr> <td>Datatype</td> </tr> <tr> <td>Datatype property</td> </tr> <tr> <td>Highlighting</td> </tr> </tbody> </table> fer only in color, which is sufficient, as object properties usually point to classes and datatype properties to datatypes, so that they remain distinguishable even without colors. It is important to note that certain elements are merged in the visualization. Equivalent classes are one example, which is visually indicated by a double circle border in the graphical representation. The idea behind the merging is that equivalent classes share the same properties, among others, and can therefore be represented by only one element in the visualization. The labels of merged elements are shown in brackets so that they are still available to the viewer. The graphical representations for further OWL elements are defined in the VOWL specification. Most of the remaining representations are variations of the ones presented in Figure 1 and visualize specific property characteristics (e.g. functional, transitive) or other set operators (e.g. intersection, complement), among others. 3.3. Graph Visualization The visual elements are combined to a graph representing the entire ontology. By default, VOWL graphs are visualized using a force-directed algorithm. Such an algorithm tends to arrange the nodes in a way that highly connected classes are placed more to the center of the visualization, while less connected ones are rather placed in the periphery. This helps to reflect the relative importance of the classes in the resulting graph layout, as the number of connections of a class is often an indication of its importance in the ontology [57]. Moreover, graph layouts generated with force-directed algorithms are usually perceived as aesthetically pleasant, since all edges have roughly the same length and since they tend to avoid edge crossings, which increases the readability of the visualization. In order to relax the energy of the force-directed layout and reduce the visual importance of generic ontology concepts, certain elements are multiplied so that they may appear more than once in a VOWL graph. Multiplication is realized with the aforementioned splitting rules that determine whether there is no multiplication for elements, multiplication across the entire graph, or multiplication for each connected class. For instance, the generic class owl:Thing is multiplied in a way that it appears once for every class it is connected to, while datatype nodes appear once for every datatype property. Figure 2 shows the visualization that results for a small ontology if the visual elements are rendered and combined according to VOWL. The visualization represents version 1.0 of the Modular Unified Tagging Ontology (MUTO) [47,48]. It has been created with the WebVOWL tool that is presented in the next section. 4. Implementations VOWL has been implemented in two different tools that demonstrate its applicability: ProtégéVOWL has been realized as a Java-based plugin for the ontology editor Protégé [3], whereas WebVOWL is a standalone application based on web technologies. Both tools are released under the MIT license and are publicly available at http://vowl.visualdataweb.org. A demo of ProtégéVOWL has been presented at ESWC 2014 [50]; a demo of WebVOWL will be presented at EKAW 2014 [49]. 4.1. ProtégéVOWL: VOWL Plugin for Protégé Protégé is currently the most widely used ontology editor [3,35]. It is an open source project developed at Stanford University and can be used free of charge. Although a lightweight version of Protégé is available as web application (WebProtégé), the more popular and powerful tool is the Java-based Desktop version of the editor (Protégé Desktop) at the moment. It has an open plugin structure that allows for the integration of special-purpose components, such as ontology visualizations [4]. Like VOWL 2, ProtégéVOWL focuses on the visualization of the ontology schema, i.e., the classes, properties, and datatypes (TBox), while it does not consider individuals and data values (the ABox) for the time being. ProtégéVOWL is deployed as a JAR file that must be copied to the plugins folder of the Protégé installation. Figure 3 shows a screenshot of ProtégéVOWL depicting version 1.35 of the SIOC Core Ontology [14]. The user interface consists of three parts: The VOWL Viewer displaying the ontology visualization, the VOWL Sidebar listing details about the selected element, and the VOWL Controls allowing to adapt the force-directed graph layout. 4.1.1. VOWL Viewer ProtégéVOWL makes use of the visualization toolkit Prefuse [31] to render the visual elements and to arrange them in a force-directed graph layout. It accesses the internal ontology representation provided by the OWL API of Protégé and transforms it into the data model required by Prefuse. The OWL elements are mapped to the graphical representations as specified by VOWL and combined to a graph. Prefuse uses a physics simulation to generate the force-directed graph layout consisting of three different forces: Edges act as springs, while nodes repel each other, and drag forces ensure that nodes settle. The forces are iteratively applied, resulting in an animation that dynamically positions the nodes. Users can smoothly zoom in to explore certain ontology parts in detail or zoom out to analyze the global structure of the ontology. They can pan the background and move elements around via drag and drop, to further optimize the graph visualization and adapt it to their needs. Whenever a node is dragged, the rest of the nodes are repositioned with animated transitions by the force-directed algorithm. 4.1.2. VOWL Sidebar Whenever an element is selected in the visualization, details about it are shown in the sidebar, such as for the selected class “User Account” in Figure 3. The details are provided by the OWL API and include the type and URI of the element as well as ontology comments, among others. URIs are displayed as hyperlinks that can be opened with a Web browser or other tools for further exploration. 4.1.3. VOWL Controls The repelling forces of classes and datatypes are separately adaptable with the two sliders in the VOWL Controls. This allows to fine-tune the force-directed layout in accordance with the size and structure of the visualized ontology. Since datatypes have their own repelling force, they can be positioned in close proximity to the classes they are connected with—to emphasize their radial arrangement and increase the readability of the visualization. In addition, the force-directed algorithm can be paused via the VOWL Controls. This does not only reduce processor load but also allows to rearrange selected elements without an immediate adaptation of the whole layout. 4.2. WebVOWL: Web Implementation of VOWL Implementing visualizations as plugins for ontology editors like Protégé has the advantage that one does not have to deal with ontology processing. The parsing of the OWL files and their transformation into an efficient data structure is performed by the ontology editor, or the library it uses for this purpose, such as the OWL API in case of Protégé. 4.2.1. Ontology Preprocessing This is different in WebVOWL, which is not a plug-in like ProtégéVOWL but a standalone application. It is based on open web standards (HTML, JavaScript, CSS, SVG) and runs completely on the client-side, i.e. does in principle not require any server-side processing. Instead of being tied to a particular OWL parser, WebVOWL defines a JSON schema that ontologies need to be converted into. The JSON schema is optimized with regard to VOWL, i.e., its format differs from typical OWL serializations in order to enable an efficient generation of the interactive graph visualization. Due to this fact, it is also different from other JSON schemas that emerged in the context of the Semantic Web, such as RDF/JSON [20] and JSON-LD [59]. The JSON-VOWL file contains the classes, properties, and datatypes of the ontology along with type information (owl:Class, owl:ObjectProperty, xsd:dateTime, etc.). Additional characteristics (inverse, functional, deprecated, etc.) as well as header information (ontology title, version, etc.) and optional ontology metrics (number of classes, properties, etc.) are separately listed. If no ontology metrics are provided in the JSON file, they are computed in WebVOWL at runtime. Instance information is currently not included in the JSON-VOWL file but planned to be added in the future. Even though WebVOWL is based on JavaScript, the transformation of the OWL ontology into the JSON file can also be done with other programming languages. By default, WebVOWL is deployed with a Java-based OWL2VOWL converter that uses the well-tested OWL API of the University of Manchester [38]. The converter accesses the ontology representation provided by the OWL API and transforms it into the JSON format required by WebVOWL. It already applies the rules for node splitting and node aggregation specified by VOWL to allow for annotated JSON files and a more efficient generation of the graph visualization. 4.2.2. User Interface and Visualization Figure 4 shows a screenshot of WebVOWL (version 0.2.13) visualizing version 1.5 of the Personas Ontology [53,54]. The user interface of WebVOWL is similar to that of ProtégéVOWL, consisting of the ontology visualization in the main view, a sidebar with details about the selected element, and a menu of controls and options. Fig. 4. WebVOWL has a similar user interface as ProtégéVOWL, consisting of the ontology visualization, a sidebar, and a menu with controls. The SVG-based visualization is generated from the JSON file at runtime. WebVOWL renders the graphical elements according to the VOWL specification, i.e., it takes the SVG code and CSS styling information provided by the specification. The force-directed graph layout is created with the JavaScript library D3 [16]. It is based on a physics simulation similar to the one of Prefuse used in ProtégéVOWL. The forces cool down in each iteration and the layout animation stops automatically after some time to remove load from the processor and provide a stable graph visualization. Users can interact with the graph visualization in a similar way as in ProtégéVOWL. They can zoom in and out, pan the background, and move elements around to adapt the force-directed layout. Certain elements (e.g., subproperties) are interactively highlighted according to the VOWL specification. Details about selected elements are once again shown in the sidebar (partly as hyperlinks), such as for the selected class “AffectiveState” in Figure 4. In addition, the sidebar displays metadata about the ontology, such as its title, namespace, author(s), and version, as well as the ontology description and the aforementioned metrics provided by the JSON file or computed at runtime. The information in the sidebar is displayed in an accordion widget to save screen space. Like ProtégéVOWL, WebVOWL provides two gravity sliders that allow to adapt the repelling forces of classes and datatypes, respectively. It also comes with a pause button to suspend the automatic layout in favor of a manual positioning of the nodes. Furthermore, WebVOWL implements some features that complement the ones provided by ProtégéVOWL. One such feature is a special “pick-and-pin” mode inspired by the RelFinder tool [32]: It allows to decouple selected nodes from the automatic layout and pin them at fixed positions on the canvas. Pinned nodes are indicated by a needle symbol (cf. classes “Persona” and “Person-aType” in Figure 4) that can be removed to recouple the nodes with the force-directed layout. Another class of interactive features provided by WebVOWL are filters that help to reduce the size of the VOWL graph and increase its visual scalability. Currently, two filters are implemented, one for datatypes and another for “solitary subclasses”, i.e., subclasses that are only connected to their superclass but no other classes. Finally, WebVOWL allows to export the complete graph visualization or a portion of it as SVG image that can be opened in other programs, scaled without loss of quality, edited, shared, and printed. 4.2.3. Discussion of WebVOWL To the best of our knowledge, WebVOWL is the first tool for comprehensive ontology visualization that is completely based on open web standards. Like ProtégéVOWL, most other ontology visualizations are implemented in Java (see Section 2). Related tools running in web browsers, such as FlexViz [25] or OOBIAN Insight [2], are based on technologies like Adobe Flex or Microsoft Silverlight that require proprietary browser plugins. While the tool LodLive [18] is also based on open web standards and technically related to WebVOWL, it focuses on the visual explo- ration of Linked Data and not on the visualization of ontologies. WebVOWL works in all major browsers, except for the current version of Internet Explorer, which lacks support for several SVG features. However, cross-browser compatibility is an issue of any application based on open web standards and a general drawback compared to Java-based tools like ProtégéVOWL. Moreover, WebVOWL has been designed with different interaction contexts in mind, including settings with touch interfaces. For instance, zooming can either be performed with the mouse wheel, a double click/tap, or a two fingers zooming gesture. As some features may not be available in all situations (e.g., mouseover effects), care has been taken that these features are not crucial for the interaction and for understanding the ontology. 5. Evaluations In order to evaluate the comprehensibility and usability of VOWL, a number of experiments of different types have been conducted. 5.1. Comparisons with Other Ontology Visualizations Previous work has compared VOWL to other approaches of ontology visualization in three qualitative user studies. None of the participants in these studies had extensive prior knowledge about ontologies or other Semantic Web technologies, but they could rather be regarded as lay users. In the studies, participants were first provided with a brief explanation of the visual notations and the underlying ontology concepts. Then, they were presented various ontologies visualized on a screen. Questions about these ontologies were asked, which had to be solved by looking at the visualizations. Among those questions, some referred to the general structure of the visualized ontologies (e.g., “What is the approximate number of classes visible?”), while others focused on particular ontology elements (e.g., “Which property is the inverse of the property P?”). Moreover, participants were asked for comments on the visualizations, with respect to aspects such as general overview, choice of shapes and colors, the level of intuitive comprehensibility or confusion when looking at the visualization, perceived completeness of displayed information and suggestions for improvement. Ontology visualizations aiming at an overview over the entire ontology and at approximating feature-completeness typically follow a node-link diagram approach (cf. Section 2). Hence, all of the alternative visualizations that VOWL was compared to were based on some kind of node-link diagram: The first version of VOWL was compared to an OWL visualization using UML class diagrams [55]. The second comparison [51] focused the WebVOWL implementation of VOWL 2, the GrOWL visualization [43], and the SOVA plugin for Protégé [13]. Finally, the SOVA plugin was also featured in the third evaluation, this time in comparison with the ProtégéVOWL plugin [50]. In the first study, static images of the visualizations were used, while the second and third studies were conducted with implementations and therefore included interactive features. Overall, participants considered all presented visualizations generally comprehensible. The inherent possibility to distinguish basic elements such as properties and classes was stated to be important, and a reduced number of crossing edges was confirmed to support the overview. Users who were already familiar with similar visual notations, as was the case for some users with the UML-based ontology visualization, considered that similarity to be beneficial. This knowledge also helped some users interpret unlabeled subclass arrows in VOWL 1. As subclass arrows are labeled in VOWL 2, they could be correctly understood by all users, though one user remarked that with his prior knowledge of UML class diagrams, the subclass label was redundant. Generally, short descriptive labels on elements, as they were included in VOWL, were seen as helpful. In the case of special property characteristics and modifiers, such as functional or transitive, the unabbreviated textual description was considered indispensable for interpreting the visualizations correctly. The multiplication of nodes, as featured in VOWL, was met with mixed reactions. Remembering the aforementioned explanations on the visual notation, some of the participants quickly understood that generic elements, such as owl:Thing, would appear several times, and that groups of equivalent classes were combined into a single visual node, while others had expected a different behavior—only one representation of the unique class owl:Thing and one separate node per equivalent class—and thus required a moment to adjust to the visualization. Some of the interactive features requested in the evaluation of VOWL 1 had been incorporated into VOWL 2 and its implementations. Participants welcomed the continuous zooming option, but asked for additional highlighting features (e.g., a highlighting of all nodes that are directly related to the selected one) as well as a feature to search and highlight specific elements. In summary, users could solve most tasks well when using VOWL. When a preference for one of the visualizations was stated, it leaned toward VOWL for the majority of participants, based on aspects such as clarity and distinguishability of elements, ease of use with interactive highlighting and layouting features, as well as aesthetics. 5.2. Evaluation by Experienced Ontology Users To get more insight into how users perceive VOWL, and to become more aware of the differences between users experienced with ontologies and lay users, VOWL has been presented to five users who had previously worked with ontology editors and formal OWL syntax. Their expertise varied between being very familiar with the specifics of OWL and able to define custom ontology elements, and knowing the major OWL features from working with existing ontologies. The recruited users could interact with the Web-VOWL implementation themselves, while they were gradually told about the interactive features. A quick presentation of the VOWL 2 specification and the Protégé-VOWL implementation [50] were provided for comparison. However, as opposed to the other user studies, no systematic introduction to the VOWL notation was given. Instead, participants started out without any prior knowledge on the meaning of shapes, colors and symbols found in VOWL and were supposed to familiarize themselves with the visualization while adhering to the “think-aloud” method. Hence, they would state everything they were thinking, feeling, considering, or doing with respect to the exploration of various ontologies (FOAF [17], MUTO [47], PersonasOnto [53], SIOC [14]) displayed with Web-VOWL. When participants could not figure out the meaning of a visual element based on the information provided in the visualization or the sidebar, they could ask for an explanation. Moreover, four of the five participants explored the ontologies in groups of two, meaning that they could discuss their thoughts with each other during the interview. To provide some rough guidance through the features of VOWL and ensure touching upon a wide range of visualization aspects, a number of questions were prepared. Participants were asked these questions to give them an incentive to look at WebVOWL features and aspects of the ontologies they might not notice on their own, and to induce suggestions on missing or desired features. Where appropriate, additional hints were provided during the interview. The results showed that the participants had no problems in distinguishing classes, properties, and datatypes. 5.2.1. Navigation and Layout All study participants spoke favorably about the force-directed layout, as it helped them to recognize clusters and the general inheritance relations between classes defined in the ontology. They stated that central elements could be easily recognized due to the layout, and that the gravity options, which control how closely elements are attracted to each other, were helpful to further understand the ontology. While the pick-and-pin feature was generally thought of as useful, one participant even asked for such a feature on his own. Several participants asked for more automated layouts beside the force-directed algorithm and for the ability to focus single elements that the remaining elements should align around. Irrespective of the particular layout chosen, one participant suggested the addition of a minimap to ease navigation in large graphs. 5.2.2. Multiplication The multiplication of nodes was considered beneficial for the simplicity of the graph structure. In particular, the multiplication of datatypes was seen as desirable by all participants except one, and most participants agreed that they normally would not want to answer questions such as “What datatype properties with range X exist in the ontology?” The one remaining participant did not see the necessity for datatype multiplication, but was not confused by it, either. 5.2.3. Equivalent Classes The meaning of double-ringed classes as groups of equivalent classes was not inherently clear to any of the participants. Once they had been explained their meaning, they viewed the visual representation as appropriate. One participant wondered why one of the equivalent class names is bigger than the others. Also, one participant did not see the necessity for a distinct visual notation, as he would prefer groups of equivalent classes to look the same as a single normal class instead. All participants were content with the combination of all equivalent classes into a single visual element, though one participant remarked that for edit- ing and determining the provenance of property definitions, the equivalent class groups might optionally have to be splittable. 5.2.4. Properties Both object and datatype properties were generally instantly found and recognized for what they were. Three participants asked for options to hide either property labels or property datatypes, as they deemed that information to be relevant only in certain scenarios. Inverse properties were correctly identified by most participants; one of them explicitly praised the way how pairs of inverse properties were displayed on a single graph edge (i.e., as bidirectional links with arrows at both sides). However, users generally had to be pointed to the highlighting feature indicating which property is associated with which direction. Likewise, the highlighting feature of subproperties was not noticed unless explicitly pointed out. With that explanation, however, the visual representation was comprehensible to users who had some experience with the ontology concept of subproperties. In summary, while highlighting features of properties are considered helpful, users would not discover them as flawlessly as the permanently displayed elements of the visualization. 5.2.5. Set Operators Users were not sure they could recognize the visual notation for anonymous classes based upon set operations—union, intersection, and complement—on their own. Three of the users quickly figured out the meaning based on the symbols (∪, ∩, ¬), but did not even notice the Venn diagrams at first. Two users thought the combination of a node border, the Venn diagrams, and the logical symbols was a visual overload that should be tackled, while another one remarked that, were the symbol replaced with a descriptive text, the notation would be more consistent with the rest of VOWL. 5.2.6. Filtering Several users asked for additional ways of filtering elements in the graph. For example, one user wished for advanced filter criteria such as ranges of properties to hide the respective property edges, while two others thought an option for selectively collapsing and expanding subtrees or subgraphs was missing. The possibility to hide datatype properties and weakly connected subclasses were praised as promising steps into this direction. 5.2.7. Colors Most colors were not commented on a lot. Two users stated the color coding was not clear to them, especially with respect to external classes. One of them pointed out that the dark color of external elements emphasizes these elements, but did not see a particular reason why external classes should visually call for attention. Two users would have wished for colors that express the class hierarchy—for example, the specialization level in the inheritance tree—in some way, though they admitted such a color coding would probably only be conceivable for strictly hierarchical class relationships rather than the inheritance graphs supported by OWL. 5.2.8. Completeness When asked whether VOWL lacks any information, three users answered that the amount of information currently displayed is rather almost too much, for which some overlapping labels that occurred during the user study were thought of as proof. Users agreed that disjoint relationship between classes should not be displayed by default, but only for particularly pointing out disjointedness among a given set of classes. One user would have preferred some more explicit information in the sidebar, such as an indication of namespaces along with resource labels. The same user did, however, ask for a way to display other class restrictions that are not currently supported by VOWL, such as restricting the instances of a class to a specific set of resources. Beside these omissions, the visualization was stated to be “quite complete” in terms of OWL 2 features considered relevant by the users. 5.2.9. Possible Use Cases Lastly, participants of the expert interview were asked how they could imagine to use VOWL. All users agreed with the basic idea of finding out about the structure and content of an ontology, and some mentioned techniques such as navigating through an ontology starting with some core elements. One participant could imagine to use VOWL to align several ontologies. Usage for various editing tasks—related to adding, modifying, and removing ontology elements—was suggested by all users, which also includes using VOWL for the debugging of ontologies. One user also proposed to show VOWL in a teaching context such as lectures on the Semantic Web, in order to explain OWL concepts to learners. Another user pondered about navigating through ontologies displayed with VOWL as some form of a “decision graph” to choose a certain result. 5.3. Benchmark of the VOWL Visualization VOWL has additionally been tested with OntoViBe, the Ontology Visualization Benchmark [30], available at http://ontovibe.visualdataweb.org. OntoViBe is an ontology comprising of a comprehensive set of OWL 1 and 2 language constructs and systematic combinations thereof. It has been designed to support the testing of feature-completeness of ontology visualizations. Figure 5 shows the VOWL visualization of version 1.0 of OntoViBe. It has been created with WebVOWL (version 0.2.13), which provided a nearly complete implementation of VOWL 2 in contrast to ProtégéVOWL at the time the benchmark was performed. The visualization has been annotated to point to some of the aspects discussed in the following. By viewing OntoViBe in VOWL, the effects of the force-directed layout are noticeable right away. A strongly connected class, PropertyOwner, appears to be very central on the first glance, based on the large number of other nodes it is connected to (annotation ① in Figure 5). The convenient radial placement of outbound and inbound edges, which mostly avoids any overlapping arrowheads, is immediately visible, as was already noted during the user studies. OntoVibe includes a small class hierarchy, which is sufficiently arranged in VOWL (annotation ②). Further visualization features that are directly visible are the merging of equivalent classes to single nodes (also seen in annotation ③), and the use of human-readable labels, where available. Several kinds of possible conflicts in the definitions are consistently resolved by VOWL. In the case of conflicting colors to express different characteristics of elements, the guidelines from the specification are applied: Deprecated elements appear with light gray background, while the dark blue back- ground color of external elements overrides the gray background in deprecated external elements such as DeprecatedImportedClass (in annotation 2). The color of the deprecated properties, on the other hand, overrides the standard colors of light blue and green for object and datatype properties, respectively. Another kind of avoided conflict concerns the geometry, as multiple properties between the same pair of classes, such as classToClassProperty1 and classToClassProperty2 do not visually obstruct one another, but are rendered as curved multi-edges. The same applies to sets of cyclic properties whose domain and range axioms point to the same class. An example of this can be seen around the class MultiPropertyOwner (annotation 3). As OntoViBe features a few classes that are not directly connected to the rest of the graph, the fact that these tend to drift away from the central ontology part up to a certain distance in VOWL is noticeable. While some measures will have to be found for supporting users to find disconnected ontology parts, especially when viewport size is limited, at the same time, this behavior emphasizes the disjointedness of the respective subgraphs. Beside the lack of support for custom OWL 2 data ranges in VOWL—which is intentionally not included for the time being, as VOWL focuses on classes and properties—, only two omissions in the current VOWL syntax became apparent that might be crucial to the class structure of some ontologies: On the one hand, unions, intersections, and complements of classes have only been defined for anonymous classes in VOWL. So far, no notation for named classes that are defined by these set operations exists. On the other hand, in the case of set operation classes that refer to other set operation classes, the nesting direction is not yet displayed in VOWL: A union of an intersection and an intersection of unions may look the same (annotation 4). Based on these observations, it can be concluded that VOWL supports a large portion of constructs featured in OntoViBe, and hence in OWL 1 and 2. Therefore, the notation can be expected to consistently visualize a wide variety of ontologies. 6. Conclusion and Future Work In an earlier effort to create a uniform visual notation for OWL ontologies, a first version of VOWL has been developed [56]. Based upon that work, related endeavors, as well as findings from a user study [55], large parts of the notation have been redesigned to create VOWL 2, a visual language that can also be understood by casual ontology users. This article described the key considerations, features, and capabilities of VOWL 2, as well as two implementations, a plugin for the widely used ontology editor Protégé and a responsive web application. Both tools demonstrate the applicability and usability of VOWL by means of several ontologies. The comprehensibility of VOWL is confirmed by several user studies conducted with different user groups, while its visual expressiveness and completeness have been tested with a benchmark ontology. The ontologies used in the evaluations were of relatively moderate size. However, there is no upper limit for the size of ontologies, both because a vast number of topics can be covered in one ontology, and because an ontology can be modeled down to an arbitrary level of detail. Graph visualizations are, on the other hand, viable only up to a certain size, at which the overview is lost and the graph is not easily usable any longer. The visualization of large-scale ontologies with VOWL is still an issue that needs to be tackled. First steps have been done by designing interactive features to filter elements and reduce the graph size. Future solutions might consider both automatic and manual methods to detect ontology components that carry context-specific importance, so that parts of the visualization can be hidden or bundled where appropriate. A related issue is that ontology elements have no inherent location information. Therefore, all elements are initially placed in a random manner in the force-directed layout. While this does not influence a single session of work, it prevents users from creating a "mental map" of the visualization that is valid for several sessions, since the elements are at different locations every time the VOWL graph is rendered. Future work will have to develop reasonable guidelines on how to best place ontology elements so their positioning follows a reproducible pattern. Future work will also be concerned with incorporating further OWL elements into VOWL. Although VOWL 2 already considers a large portion of the language constructs of OWL 1 and 2, it is not complete. The ultimate goal is to further extend VOWL in order to make it a visual language that represents OWL ontologies as completely as possible. This would also call for a web service where users can upload ontologies and get them visualized (e.g., with WebVOWL). Other open issues with regard to the VOWL implementations are multi-language support, improved search functionality, and the inclusion of instance data in the JSON schema, converter, and tools. Apart from that, it is hoped that VOWL and its implementations will be useful to others and in related areas, such as ontology alignment or Linked Data exploration, as well as in teaching and training contexts. Acknowledgements The authors would like to thank David Bold, Vincent Link, and Eduard Marbach for their contributions to the implementation of VOWL and their valuable feedback on the notation. Likewise, the authors would like to thank all participants of the user studies, and all experts who took part in the expert interview. References
{"Source-Url": "http://www.semantic-web-journal.net/system/files/swj892.pdf", "len_cl100k_base": 11477, "olmocr-version": "0.1.50", "pdf-total-pages": 16, "total-fallback-pages": 0, "total-input-tokens": 47911, "total-output-tokens": 16040, "length": "2e13", "weborganizer": {"__label__adult": 0.0004892349243164062, "__label__art_design": 0.002777099609375, "__label__crime_law": 0.000644683837890625, "__label__education_jobs": 0.004520416259765625, "__label__entertainment": 0.0004184246063232422, "__label__fashion_beauty": 0.0003056526184082031, "__label__finance_business": 0.0006399154663085938, "__label__food_dining": 0.0003876686096191406, "__label__games": 0.0015125274658203125, "__label__hardware": 0.0008101463317871094, "__label__health": 0.0008134841918945312, "__label__history": 0.0008821487426757812, "__label__home_hobbies": 0.00016939640045166016, "__label__industrial": 0.0005388259887695312, "__label__literature": 0.0023212432861328125, "__label__politics": 0.0005822181701660156, "__label__religion": 0.00112152099609375, "__label__science_tech": 0.30029296875, "__label__social_life": 0.00038743019104003906, "__label__software": 0.128662109375, "__label__software_dev": 0.55029296875, "__label__sports_fitness": 0.0002918243408203125, "__label__transportation": 0.0006871223449707031, "__label__travel": 0.00030875205993652344}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 68520, 0.03676]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 68520, 0.5552]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 68520, 0.90575]], "google_gemma-3-12b-it_contains_pii": [[0, 3843, false], [3843, 8526, null], [8526, 13268, null], [13268, 17734, null], [17734, 23076, null], [23076, 25499, null], [25499, 30008, null], [30008, 32470, null], [32470, 35808, null], [35808, 40544, null], [40544, 45448, null], [45448, 50174, null], [50174, 51981, null], [51981, 57010, null], [57010, 62417, null], [62417, 68520, null]], "google_gemma-3-12b-it_is_public_document": [[0, 3843, true], [3843, 8526, null], [8526, 13268, null], [13268, 17734, null], [17734, 23076, null], [23076, 25499, null], [25499, 30008, null], [30008, 32470, null], [32470, 35808, null], [35808, 40544, null], [40544, 45448, null], [45448, 50174, null], [50174, 51981, null], [51981, 57010, null], [57010, 62417, null], [62417, 68520, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 68520, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 68520, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 68520, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 68520, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 68520, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 68520, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 68520, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 68520, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 68520, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 68520, null]], "pdf_page_numbers": [[0, 3843, 1], [3843, 8526, 2], [8526, 13268, 3], [13268, 17734, 4], [17734, 23076, 5], [23076, 25499, 6], [25499, 30008, 7], [30008, 32470, 8], [32470, 35808, 9], [35808, 40544, 10], [40544, 45448, 11], [45448, 50174, 12], [50174, 51981, 13], [51981, 57010, 14], [57010, 62417, 15], [62417, 68520, 16]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 68520, 0.04386]]}
olmocr_science_pdfs
2024-12-02
2024-12-02
3aa787ca67d821e2e146d8dbb9a4d17eb6d048e5
[REMOVED]
{"Source-Url": "http://homepages.abdn.ac.uk/jeff.z.pan/pages/pub/PPRW*2014.pdf", "len_cl100k_base": 10686, "olmocr-version": "0.1.53", "pdf-total-pages": 16, "total-fallback-pages": 0, "total-input-tokens": 52042, "total-output-tokens": 12239, "length": "2e13", "weborganizer": {"__label__adult": 0.000385284423828125, "__label__art_design": 0.0008015632629394531, "__label__crime_law": 0.0007772445678710938, "__label__education_jobs": 0.0017719268798828125, "__label__entertainment": 0.0002038478851318359, "__label__fashion_beauty": 0.0002484321594238281, "__label__finance_business": 0.0008273124694824219, "__label__food_dining": 0.0004143714904785156, "__label__games": 0.0008931159973144531, "__label__hardware": 0.00093841552734375, "__label__health": 0.0008034706115722656, "__label__history": 0.0006232261657714844, "__label__home_hobbies": 0.0001405477523803711, "__label__industrial": 0.0006098747253417969, "__label__literature": 0.0010051727294921875, "__label__politics": 0.00044417381286621094, "__label__religion": 0.0005521774291992188, "__label__science_tech": 0.41796875, "__label__social_life": 0.00019240379333496096, "__label__software": 0.054962158203125, "__label__software_dev": 0.51416015625, "__label__sports_fitness": 0.0002868175506591797, "__label__transportation": 0.0005555152893066406, "__label__travel": 0.0002548694610595703}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 45518, 0.03197]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 45518, 0.68376]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 45518, 0.87754]], "google_gemma-3-12b-it_contains_pii": [[0, 2820, false], [2820, 5811, null], [5811, 8975, null], [8975, 12668, null], [12668, 14871, null], [14871, 17919, null], [17919, 21202, null], [21202, 23197, null], [23197, 26693, null], [26693, 28414, null], [28414, 31390, null], [31390, 34266, null], [34266, 37359, null], [37359, 40552, null], [40552, 42603, null], [42603, 45518, null]], "google_gemma-3-12b-it_is_public_document": [[0, 2820, true], [2820, 5811, null], [5811, 8975, null], [8975, 12668, null], [12668, 14871, null], [14871, 17919, null], [17919, 21202, null], [21202, 23197, null], [23197, 26693, null], [26693, 28414, null], [28414, 31390, null], [31390, 34266, null], [34266, 37359, null], [37359, 40552, null], [40552, 42603, null], [42603, 45518, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 45518, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 45518, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 45518, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 45518, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 45518, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 45518, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 45518, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 45518, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 45518, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 45518, null]], "pdf_page_numbers": [[0, 2820, 1], [2820, 5811, 2], [5811, 8975, 3], [8975, 12668, 4], [12668, 14871, 5], [14871, 17919, 6], [17919, 21202, 7], [21202, 23197, 8], [23197, 26693, 9], [26693, 28414, 10], [28414, 31390, 11], [31390, 34266, 12], [34266, 37359, 13], [37359, 40552, 14], [40552, 42603, 15], [42603, 45518, 16]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 45518, 0.08155]]}
olmocr_science_pdfs
2024-12-07
2024-12-07
6f13729ad0081e24a28b21b50e7f2ad589cd053d
Towards a Statistical Methodology to Evaluate Program Speedups and their Optimisation Techniques Sid Touati To cite this version: Sid Touati. Towards a Statistical Methodology to Evaluate Program Speedups and their Optimisation Techniques. 2009. hal-00356529v8 HAL Id: hal-00356529 https://hal.archives-ouvertes.fr/hal-00356529v8 Submitted on 6 Jul 2009 Towards a Statistical Methodology to Evaluate Program Speedups and their Optimisation Techniques Sid-Ahmed-Ali TOUATI Sid.Touati@uvsq.fr University of Versailles Saint-Quentin en Yvelines, France April 2009 Abstract The community of program optimisation and analysis, code performance evaluation, parallelisation and optimising compilation has published since many decades hundreds of research and engineering articles in major conferences and journals. These articles study efficient algorithms, strategies and techniques to accelerate programs execution times, or optimise other performance metrics (MIPS, code size, energy/power, MFLOPS, etc.). Many speedups are published, but nobody is able to reproduce them exactly. The non-reproducibility of our research results is a dark point of the art, and we cannot be qualified as computer scientists if we do not provide rigorous experimental methodology. This article provides a first effort towards a correct statistical protocol for analysing and measuring speedups. As we will see, some common mistakes are done by the community inside published articles, explaining part of the non-reproducibility of the results. Our current article is not sufficient by its own to deliver a complete experimental methodology, further efforts must be done by the community to decide about a common protocol for our future experiences. Anyway, our community should take care about the aspect of reproducibility of the results in the future. Keywords: Program optimisation, Statistical Performance Evaluation 1 Introduction The community of program optimisation and analysis, code performance evaluation, parallelisation and optimising compilation has published since many decades hundreds of research and engineering articles in major conferences and journals. These articles study efficient algorithms, strategies and techniques to accelerate programs execution times, or optimise other performance metrics (MIPS, code size, energy/power, MFLOPS, etc.). The efficiency of a code optimisation technique is generally published according to two principles, non necessarily disjoint. The first principle is to provide a mathematical proof given a theoretical model that the published research result is correct or/and efficient: this is the hard part of research in computer science, since if the model is too simple, it would not represent real world, and if the model is too close to real world, mathematics become too complex to digest. A second principle is to propose and implement a code optimisation technique and to practice it on a set of chosen benchmarks in order to evaluate its efficiency. This article concerns this last point: how can we convince the community by rigorous statistics that the experimental study publishes correct and fair results? 1.1 Non-Reproducible Experimental Results Hard natural sciences such as physics, chemistry and biology impose strict experimental methodologies and rigorous statistical measures in order to guarantee the reproducibility of the results. The reproducibility of the experimental results in our community is, namely, our dark point. Given a research article, it is in practice impossible or too difficult to reproduce the published performance. If our results are not reproducible, we cannot say that we are doing science! Some aspects make a research article non-reproducible: - Non using precise scientific languages such as mathematics. Ideally, mathematics must always be preferred to describe ideas, if possible, with an accessible difficulty. - Non available software, non released software, non communicated precise data. - Not providing formal algorithms or protocols make impossible to reproduce exactly the ideas. For instance, the authors in (PMT04) spent large efforts to re-implement some branch predictor algorithms based on the published research articles, but they fail to reproduce the initial results of the authors. Simply because the initial articles describing the branch predictors are not formal, so they can be interpreted differently. - Hide many experimental details. As demonstrated by (MDSH09), bringing small modification on the execution environment brings contradictory experimental results. For instance, just changing the size of the linux shell variables or the order of linking an application alter the conclusions. As pointed by the authors in (MDSH09), a lot of published articles in major conferences hide these details, meaning that their experimental results are meaningless. - Usage of deprecated machines, deprecated OS, exotic environment, etc. If we take a research article published five years after the experiences for instance, there is a high chance that the workstations that served the experiences have already died or already changed their behaviour (usury of hardware, software patches, etc.). With the huge amount of published articles in the code optimisation community, with the impressive published speedups, an external reviewer of our community has the right to ask the following naive question: *If we combine all the published speedups (accelerations) on the well known public benchmarks since four decades, why don’t we observe execution times approaching to zero?* This question is justified, and brings a reforming malaise to us. Now, we are asked to be clear about our statistics, some initiatives start to collect published performance data in order to compare them (FuTe09). The malaise raised by the above question is not a suspicion of a general cheating in research. We believe that our community is honest in publishing data, but the published observed speedups are sometimes rare events far from what we could observe if we redo the experiences multiple times. Even if we take an ideal situation where we use exactly the original experimental machines and software, it is too difficult to reproduce exactly the same performance numbers again and again, experience after experience. Usually, published speedups are computed with bias describing pretty rare events. Frankly, if a computer scientist succeeds in reproducing the performance numbers of his colleagues (with a reasonable error ratio), it would be equivalent to what rigorous probabilists and statisticians call a surprise. 1.2 Why Program Execution Times Vary What makes a binary program execution time to vary, even if we use the same data input, the same binary, the same execution environment? • Background tasks, concurrent jobs, OS process scheduling; • Interrupts; • Input/output; • Starting louder address; • Branch predictor initial state; • Cache effects; • Non deterministic dynamic instruction scheduler; • Temperature of the room (dynamic voltage/frequency scaling service) One of the reasons of the non-reproducibility of the results is the variation of execution times of the same program given the same input and the same experimental environment. With the massive introduction of multicore architectures, we believe that the variations of executions times will become exacerbated because of the complex dynamic features influencing the execution: threads scheduling policy, synchronisation barriers, resource sharing between threads, hardware mechanisms for speculative execution, etc. Consequently, if you execute a program (with a fixed input and environment) $k$ times, it is possible to obtain $k$ distinct execution times. The mistake here is to assume that these variations are minor, and are stable in general. The variation of execution times is something that we observe everyday, we cannot neglect it. An usual error in the community is to replace all the $k$ execution times by one value, such that the minimum, the mean or the maximum. Doing that would produce sexier speedups to publish, but does not reflect the reality with fair numbers. 1.3 Why Don’t we Consider the Minimum Execution Time? Considering the minimum value of the $k$ observed execution times is unfair because: • nothing guarantees that this minimum execution time is an ideal execution of the program. • nothing guarantees that this minimum execution time is a consequence of the optimisation technique under study. Maybe this minimum execution time is an accident, or a consequence of dynamic voltage scaling, or anything else. • if this minimal execution time is a rare event, all your statistics describe rare speedups. So, they become non-reproducible easily. 1.4 What is Inside this Article, What are its Limitations We base our reasoning here on common well known results in statistics, especially on some results explained in the book of Raj Jain [Jain91]. We propose a first step towards a rigorous statistical methodology to evaluate program optimisation techniques. This article recalls some common mistakes in performance evaluation, explains which statistics should be used in a particular situation, and provide practical examples. Furthermore, we show how to use the free software called R to compute these statistics [CGH+08; RD08]. Our article is organised to help computer scientists (and of course PhD students) willing to make correct and rigorous statistical study of their code optimisation method. The question is how to convince real experts by statistics, provided a confidence level $\alpha \in [0\%, 100\%]$, that your code optimisation technique is really efficient in practice. Section 2 explains when we can decide about a speedup of a program and how we can measure it using $k$ observations of execution times. Having a set of $n$ distinct independent programs (considered as a set of benchmarks), Section 3 explains how to compute an average speedup (while it is a bad idea to synthesise a set of speedups in by a unique average). Getting a speedup (acceleration) inside a sample of $n$ benchmarks does not guarantee you that you can get a speedup on another program. Consequently, Section 4 shows how we can estimate the chance that the code optimisation would provide a speedup on a program non belonging to the initial sample of benchmarks used for experiences. The limitations of this article are: we do not study the variation of execution times due to changing the program input. We consider real executions, not emulation/simulation nor executions on virtual machines. We also consider a fixed (universal?) experimental environment. ## 2 Computing a Speedup Factor for a Single Program with a Single Data Input Let $P$ be an initial program, let $P'$ be a transformed version after applying the code optimisation technique under study. If you execute the program $P$ $k$ times, it is possible to obtain $k$ distinct execution times (especially if the program is short): $t_1, \ldots, t_k$. The transformed program $P'$ can be executed $m$ times producing $m$ execution times too $t'_1, \ldots, t'_m$. The unit of measure here is the milisecond in general, so we can consider a timing precision in seconds with three digits after the coma. Below is a list of elementary recommendations before starting statistics: 1. $P$ and $P'$ must be executed with the same data input in similar experimental environment. The community of code optimisation has not decided yet on the exact semantics of similar, since many unknown/hidden factors may influence the experiences. 2. Statistically, it is not necessary that $k = m$. However, it is strongly recommended that $k \geq 30$ and $m \geq 30$. 30 runs may seem quite prohibitive, but this is the practical limits of the number of observations used in statistics if you want to have a precise Student test that we will explain later. If the number of observations is below 30, computing the confidence intervals of the mean time becomes more complex: we should first check the normality of the distribution (using the normality test of Shapiro-Wilk for instance). If the normality check succeeds, then the test of Student can be applied. Otherwise, the confidence intervals of the mean execution times must be computed using complex bootstrap methods (DaHi97) instead of the test of Student. We highly recommend 30 runs per program to ensure the validity of the Student test. If the program execution time is too large to consider 30 executions, you can do less executions but you should follow the method we just described (either a normality check followed by a Student test, or by using bootstrap methods). 3. It is important that the repetitive executions of the same program should be independent. For instance, it is not fair to use a single loop around a code kernel that repeat the execution $k$ times. This is because repeating a program $P$ inside a loop makes them to execute inside the same application. Consequently, the operating system does not behave as if you execute the program $k$ times from the shell. Furthermore, the caches are warmed by the repetitive executions of the code kernels if they belong to the same application. 4. Anyway, even if we execute a program $k$ times from the shell, the executions are not necessarily independent, especially if they are executed back-to-back: the seek time of the disk is altered by repetitive executions, some data are cached on the disk by applications and benefit from repetitive executions. Recently, we have been told that branch predictors are also influenced by separate applications: this seems strange, but we should stay careful with hardware mechanisms. As you can see, it is not easy to guarantee $k$ independent executions! We have remarked a common mistake in computing speedups in presence of program execution time variance: assuming that the variations in execution times are not really a problem, because caused by external factors, these variations may be neglected and smoothed. Consequently, we may be asked to compute the speedup resulted from transforming $P$ into $P'$ by using one of the following fractions: $$\frac{\min_{i=1}^{k} t_i}{\max_{i=1}^{k} t_i}, \quad \text{or} \quad \frac{\mu(P)}{\mu(P')},$$ Here, $\mu$ is the usual notation of the sample arithmetic mean: $\mu(P) = \frac{\sum_{i=1}^{k} t_i}{k}$. If one of the previous speedups is higher than 1, than people conclude victory. The mistake here is to assume that $k$ observed execution times represent any future execution time of the program, even with the same data input. Statistically, we are wrong if we do not consider confidence intervals. To be rigorous, we can follow the four major steps described below to assert a high confidence in the computed speedup. The whole detailed protocol is illustrated in Figure 1. --- **Figure 1: Statistical Protocol for Asserting and Computing a Speedup with Confidence Level $\alpha$** 2.1 Step 1: If the Number of Runs is Below 30, Check the Normality As said before, if the number of runs is at least 30, you can skip this step. If the number of runs of a program is below 30, we should check if the values \((t_1, \cdots, t_k)\) and \((t'_1, \cdots, t'_m)\) follow a normal distribution. In practice, we can use the Shapiro-Wilk normality test providing a confidence level. The user should fix a confidence level (say \(\alpha = 95\%\)), and the Shapiro-Wilk test can determine (with \(1 - \alpha = 5\%\) chance of error) that the values follow a normal distribution. A later example will show how to practice this using the R software. If the normality check fails, you can either run more executions till 30, or use complex bootstrap method (that we will not explain here). 2.2 Step 2: Perform a Student Test to Decide if a Speedup Occurs The Student test allows to statistically check if all the future executions of the program \(P'\) are faster than the executions of \(P\) with a fixed confidence level \(\alpha (0 < \alpha < 100)\). The Student test allows to say that we have \(\alpha\%\) of chance that the mean execution time of \(P'\) is faster than the mean execution time of \(P\) by just analysing the \(n + m\) observations. This test estimates the confidence interval of the difference between the mean execution times of \(P\) and \(P'\). If the value zero is inside the confidence interval, then the Student test does not guarantee with a confidence level \(\alpha\) that the program \(P'\) is faster in average than the program \(P\). That is, if 0 belongs to confidence interval of the Student test, no speedup can be concluded for the program \(P\). Let \([a, b]\) be the confidence interval computed by the Student test. If \(0 < a\) then we can say that \(P'\) would be faster in average than \(P\) in \(\alpha\%\) of the future executions (considering the same data input and experimental environment). An example is illustrated later. 2.3 Step 3: If the Student Test Concedes a Speedup, We then Can Measure it The speedup factor for the program \(P'\) can be defined as the fraction between the sample mean times, as follows: \(s(P') = \frac{\mu(P')}{{\overline{m}}(P')}\). Here, \(\mu\) is the usual notation of the sample arithmetic mean: \(\mu(P) = \frac{\sum_{i=1}^{k} t_i}{k}\), \(\mu(P') = \frac{\sum_{i=1}^{m} t'_i}{m}\). The problem with this definition of speedup is that it is sensitive to outliers. Indeed, the distributions of the values of \((t_1, \cdots, t_k)\) and \((t'_1, \cdots, t'_m)\) may be biased. For the above reasons, we prefer using the median as suggested by (Jain91) instead of the sample mean of the execution times\(^1\). Consequently, the speedup becomes \[ s(P') = \frac{\text{median}_{i=1}^{k} t_i}{\text{median}_{j=1}^{m} t'_j} \] Remember that this speedup has no sense if the Student test fails to determine if 0 is outside the confidence interval. For the remaining part of the article, we note by \(m(P)\) and \(m(P')\) the observed median of the execution times of the program \(P\) and \(P'\) resp. Example 2.1 Let \(P\) be a initial program with its "representative" data input. We are willing to statistically demonstrate with a confidence level \(\alpha = 95\%\) that an optimisation technique transforms it into \(P'\) and produces benefit in terms of execution speed. For doing this, I should execute \(P\) and \(P'\) at least 30 times. For the sake of the example, I consider here only 5 executions for \(P\) and \(P'\). Using the software R, I introduce the values of execution times (in seconds) of \(P\) and \(P'\) as two vectors \(T_1\) and \(T_2\) resp. \(^1\)Keeping the median execution time is currently used by the SPEC benchmarks for instance We must not hurry to conclude and to publish the following result: the resulted speedup for this program is equal to \( \min(T1) / \min(T2) = 4.86 \). Publishing such performance gain (acceleration of factor equal to 4.86) is a statistical mistake. Since we have only 5 observations instead of 30, we should check the normality of the values of \( T_1 \) and \( T_2 \) resp. using the test of Shapiro-Wilk. ```r > shapiro.test(T1) Shapiro-Wilk normality test data: T1 W = 0.9862, p-value = 0.9647 ``` The test of Shapiro-Wilk on the data \( T_1 \) computes here a value \( W = 0.9862 \). In order to say that the test succeeds with confidence level \( \alpha \), the value \( W \) must be greater or equal to the \( W \) value of the Shapiro-Wilk table (this table can be found on Internet for instance). I use here a confidence level \( \alpha = 95\% \). The Shapiro-Wilk table for \( n = 5 \) (number of values) and \( \alpha = 0.95 \) indicates the value of 0.986. Consequently, the normality test succeeds for \( T_1 \). Idem for \( T_2 \). ```r > shapiro.test(T2) Shapiro-Wilk normality test data: T2 W = 0.9862, p-value = 0.9647 ``` Since \( W = 0.9862 \geq 0.986 \), the values of \( T_2 \) follows a normal distribution with a confidence level of \( \alpha = 0.95 \). It is important to notice here that if the normality test fails for a program (\( T_1 \) or \( T_2 \)), we must run it at least 30 times. I can now continue with the Student test to check if \( P' \) is faster than \( P \) with a very high confidence level \( \alpha = 99\% \). ```r > t.test(T1,T2, alternative="greater", conf.level=0.99) Welch Two Sample t-test 99 percent confidence interval: -0.02574667 Inf The obtained confidence interval for the difference between the mean execution times is \([-0.02, +\infty] \). This interval includes 0. Consequently, we cannot assert with 99\% confidence level that \( P' \) is faster in average than \( P \). I have the choice by either rejecting the obtained speedup (too hard), or reduce my confidence level. I check with \( \alpha = 95\% \) instead of 99\%. ```r > t.test(T1,T2, alternative="greater", conf.level=0.95) 95 percent confidence interval: 0.3414632 Inf The confidence interval is \([0.34, +\infty]\), it does not include 0. Consequently, we can assert with 95\% confidence level that we obtained a speedup. In other words, the risk (of error) of not obtaining an acceleration for the future executions is equal to 5\%. The obtained speedup is \( s(P) = \frac{m(P)}{m(P')} = \frac{2.046}{1.046} = 1.95 \). Remark: Speedup with Low Confidence Level If the confidence level used for the Student test is too low, it is not impossible that we reach a situation where the Student test detects a speedup while the computed speedup is $< 1$. The following example shows that low confidence levels may bring incoherent speedup measure. **Example 2.2** Let take the same previous example with $T_1$ and $T_2$. We apply a Student Test with a confidence level equal to 1% to ensure that $P'$ is slower than $P$. In the previous example, we showed the contrary with a confidence level equal to 95%. ```r > t.test(T2, T1, alternative="greater", conf.level=0.01) ... 1 percent confidence interval: 0.02574667 Inf ... ``` As you can see, the test of Student succeeds, so we have 1% of chance that $P'$ is slower than $P$. The computed speedup (either by considering the sample mean of the median) is as follows: ```r > mean(T2)/mean(T1) [1] 0.5110024 > median(T2)/median(T1) [1] 0.5112414 ``` As you can see, the speedup here is below 1. Is this a contradiction? No of course, remember that the confidence level of this speedup is only 1%. This section explained how to check with a confidence level $\alpha$ that a code optimisation technique produces a faster transformed program (for a fixed data input and experimental environment). We also provided a formula for quantifying the speedup. The following section explains how to compute an overall average of speedups of a set of benchmarks. ### 3 Computing the Overall Speedup of a Set of Benchmarks When we implement a code optimisation technique, we are generally asked to test it on a set of benchmarks, not on a unique one. Let $n$ be the number of considered benchmarks. Ideally, the code optimisation technique should produce speedups on the $n$ programs (at least no slowdown) with the same confidence level $\alpha$. Unfortunately, this situation is rare nowadays. Usually, only a fraction of $p$ programs among $n$ would benefit from an acceleration. Let $s(P_j)$ be the obtained speedup for the program $P_j$. While this is not correct in statistics, some reviewers ask an average speedup of all the benchmarks. In statistics, we cannot provide a fair average because the programs are different, and their weights are different too. So, asking for an overall speedup for a set of benchmarks will highly bring unfair value. Neither an arithmetic mean, nor a geometric or harmonic mean can be used to synthesise in a unique speedup of the whole set of benchmarks. The arithmetic mean does not distinguish between short and long programs: for instance, having a speedup of 105% on a program which lasts 3 days must not have the same impact as a speedup of 300% obtained on a program which lasts 3 seconds. In the former, we save 5% of 3 days (=216 minutes), while in the latter we save 200% of 3 seconds (=2 seconds). If we use the arithmetic mean, we would obtain an overall speedup equal to $(105+300)/2=202\%$, this does not reflect the reality with a fair number. The geometric mean cannot be applied here because we are not faced to a succession of accelerations on the same program, but to accelerations to distinct programs. The harmonic mean in our case is not meaningful too because the quantity $\frac{1}{n}$ represents also a sort of speedup, so we can provide the same criticism as the arithmetic mean. In order to compute $G$, an overall performance gain factor (not an overall speedup) that represents the weights of the different programs, we can use the following method. The confidence level of this performance gain factor is equal to the minimal value of confidence levels used in the Student tests to validate individual speedups. First, an interesting question is to decide if we should neglect the $n - p$ programs where no speedup has been validated by the Student test. That is, the performance gain factor is computed for a subset $p$ of programs, not on all the $n$ benchmarks. We believe we neglect the $n - p$ programs that fail in the Student test if we study afterwards (in the next section) the confidence interval of the proportion $\frac{W}{n}$; studying this proportion helps us to decide if the reported overall gain is meaningful. If we decide to include all the $n$ programs for computing the overall performance gain factor, this is also fair, but the reported gain may be negative since it includes the slowdowns. Second, we associate a weight $W(P_j)$ to each program $P_j$. The general characteristics of a weight function is $\sum_{j} W(P_j) = 1$. If not, we should normalise the weights so that they sum to 1. The weight of each benchmark can be chosen by the community, by the benchmark organisation, by the user, or we can simply decide to associate the same weight to all benchmarks. Also, it is legitimate to choose the weight as the fraction between the observed execution time and the sum of all observed execution times: $W(P_j) = \frac{\text{ExecutionTime}(P_j)}{\sum_{i=1,p} \text{ExecutionTime}(P_i)}$. Here we choose to put $\text{ExecutionTime}(P_j) = m(P_j)$, i.e., the median of all the observed execution times of the program $P_j$. Someone would argue that this would give more weight on long running time programs: the answer is yes, because what we want to optimise at the end is the absolute execution time, not the relative one. Third, transforming a program $P_j$ into $P'_j$ allows to reduce the execution time by $\text{ExecutionTime}(P_j) - \text{ExecutionTime}(P'_j)$. This absolute gain should not be considered as it is, but should be multiplied by the weight of the program as follows: $g(P_j) = W(P_j) \times (\text{ExecutionTime}(P_j) - \text{ExecutionTime}(P'_j))$. Fourth and last, the overall performance gain factor is defined as the fraction between weighted gains and the sum of weighted initial execution times: $G = \frac{\sum_{j=1,p} g(P_j)}{\sum_{j=1,p} W(P_j) \times \text{ExecutionTime}(P_j)}$. By simplification, we obtain: $$G = 1 - \frac{\sum_{j=1,p} W(P_j) \text{ExecutionTime}(P'_j)}{\sum_{j=1,p} W(P_j) \text{ExecutionTime}(P_j)}$$ By definition, the overall gain $G < 1$, since the execution times of the optimised programs are hopefully non zero values ($\text{ExecutionTime}(P'_j) \neq 0$). **Example 3.1** Let a program $P_1$ that initially lasts 3 seconds. Assume we succeed to accelerate it with a factor of 300% with a confidence level $\alpha_1 = 95\%$. Thus, its new median execution time becomes 1 second. Let $P_2$ be a program that initially lasts 1 hour and has been accelerated with a factor of 105% with a confidence level $\alpha_2 = 80\%$. Thus, its new median execution time becomes 3428 seconds. The arithmetic mean of these two speedups is 202.5%, the geometric mean is 177.48% and the harmonic mean is 155.56%. None of these means is suggested for publications as explained before. The weights of the programs $P_1$ and $P_2$ are resp. $W(P_1) = 3/(3600 + 3) = 0.0008$ and $W(P_2) = 3600/(3600 + 3) = 0.9991$. The obtained weighted gain for each program is: $g(P_1) = 0.001$ and $g(P_2) = 171.85$. The overall performance gain factor is then $G = 1 - \frac{0.0008 \times 1 + 0.9991 \times 3428}{0.0008 \times 3 + 0.9991 \times 3600} = 4.77\%$ and the confidence level is equal to $\alpha = \min(\alpha_1, \alpha_2) = 80\%$. If we consider that the weights are unit, $W(P_1) = W(P_2) = 1$, then the overall performance gain factor is then $G = 1 - \frac{1+3428}{3+3600} = 4.82\%$ and the confidence level is still equal to $\alpha = \min(\alpha_1, \alpha_2) = 80\%$. As can be remarked, there is not a direct comparison between the overall gain and the individual speedups. The following section gives a method to evaluate the quality of a code optimisation method. Precisely, we want to evaluate the chance that a code optimisation technique produces a speedup on a program that does not belong to the initial set of experimented benchmarks. 4 A Qualitative Evaluation of a Code Optimisation Method Computing the overall performance gain for a sample of $n$ programs does not allow to estimate the quality nor the efficiency of the code optimisation technique. In fact, within the $n$ programs, only a fraction of $p$ benchmarks have got a speedup, and $n - p$ programs got a slowdown. If we take this sample of $n$ program as a basis, we can measure the chance of getting the fraction of accelerated programs as $\frac{p}{n}$. The higher is this proportion, better would be the quality of the code optimisation. In fact, we want to estimate if the code optimisation technique is beneficial for a large fraction of programs. The proportion $C = \frac{p}{n}$ has been observed on a sample of $n$ programs. The confidence interval for this proportion (with a confidence level $\alpha$) is given by the equation $C \pm r$, where $r = \frac{z(1+\alpha)/2}{\sqrt{\frac{C(1-C)}{n}}}$. In other words, the confidence interval of the proportion is equal to $I = [C - r, C + r]$. Here, $z(1+\alpha)/2$ represents the value of the $(1 + \alpha)/2$ quartile of the unit normal form. This value is available in a known table (table A.2 in [Jain91]). The confidence level $\alpha$ is equal to the minimal value of confidence levels used in the Student tests to validate individual speedups. We should notice that the previous formula of the confidence interval of the proportion $C$ is valid only if $n.C \geq 10$. If $n.C < 10$, computing the confidence interval becomes too complex according to [Jain91]. Example 4.1 Having $n = 30$ benchmarks, we obtained a speedup on only $p = 17$ cases. We want to compute the confidence interval for the proportion $C=17/30=0.5666$ with a confidence level $\alpha = 0.9 = 90\%$. The quantity $n.C = 17 \geq 10$, I can then easily estimate the confidence interval of $C$ using the R software as follows. > prop.test(17, 30, conf.level=0.90) ... 90 percent confidence interval: 0.4027157 0.7184049... The above test allows us to say that we have 90\% of chance that the proportion of accelerated programs is between 40.27\% and 71.87\%. If this interval is too wide for the purpose of the study, we can reduce the confidence level as a first straightforward solution. For instance, if I consider $\alpha = 50\%$, the confidence interval of the proportion becomes [49.84\%, 64.23\%]. Or, if we do not want to reduce the confidence level, we need to do more experiences on more benchmarks. The next formula gives the minimal number $n$ of benchmarks requested if we want to estimate the confidence interval with a precision equal to $r\%$ with a confidence level $\alpha$: $$ n \geq (z(1+\alpha)/2)^2 \times \frac{C(1-C)}{r^2} $$ Example 4.2 In the previous example, we have got an initial proportion equal to $C = \frac{17}{30} = 0.5666$. If I want to estimate the confidence interval with a precision equal to 5% with a confidence level of 95%, I put $r = 0.05$ and I read in the quartiles tables $z(1+0.05)/2 = z_{0.975} = 1.960$. The minimal number of benchmarks to observe is then equal to: $n \geq 1.960^2 \times \frac{0.566 \times (1 - 0.566)}{0.05^2} = 377.46$. We need to experiment 378 benchmarks in order to assert that we have 95% of chances that the proportions of accelerated programs are in the interval $0.566 \pm 5\%$. The discussion that we can have here is on the quality or on the representativeness of the sample of $n$ benchmarks. This is outside the scope of the paper! Until now, we do not know what does a set of representative programs means. 5 Conclusion Program performance evaluation and their optimisation techniques suffer from the disparity of the published results. It is of course very difficult to reproduce exactly the experimental environment since we do not always know all the details or factors influencing it. This article treats a part of the problem by recalling some principles in statistics allowing to consider the variance of program execution times. The variance of program execution times is not a chaotic phenomena to neglect or to smooth; we should keep it under control and incorporate it inside the statistics we publish. This would allow us to assert with a certain confidence level that the results we publish are reproducible under similar experimental environment. Using simulators instead of real executions provide reproducible results, since simulators are deterministic: usually, simulating a program multiple times should always produce the same performance numbers. This article assumes that the observations have been done on the physical machine not by simulation. If the physical machine does not exist, the observations based on simulation cannot be studied exactly with the methods described in this article. The study should more be concentrated on the statistical quality of the simulator. As far as we know, it does not exist yet a simulator that has been rigorously validated by statistics as described in [Jain91]. Usual error ratios reported by simulators are not sufficient alone to judge about their quality. This article does not treat performance evaluation with multiple data inputs of a program. In fact, the speedups defined in this article are computed for a unique set of data input. Experimenting multiple sets of data input to measure a speedup is let for a future work. We conclude with a short discussion about the confidence level we should use in this sort of statistical study. Indeed, there is not a unique answer to this crucial question. In each context of code optimisation we may be asked to be more or less confident in our statistics. In the case of hard real time applications, the confidence level should be high enough (more than 95% for instance), requiring more experiments and benchmarks. In the case of soft real time applications (multimedia, mobile phone, GPS, etc.), the confidence level can be more than 80%. In the case of desktop applications, the confidence level should not be necessarily high. In any case, the used confidence level for statistics must be declared for publication. References [CGH+08] Pierre-André Cornillon, Arnaud Guyader, François Husson, Nicolas Jégou, Julie Josse, Maella Acknowledgement We would like to thank Sebastien BRIAIS from the University of Versailles Saint-Quentin en Yvelines for his helpful remarks to improve this document.
{"Source-Url": "https://hal.archives-ouvertes.fr/hal-00356529v8/document", "len_cl100k_base": 8315, "olmocr-version": "0.1.49", "pdf-total-pages": 13, "total-fallback-pages": 0, "total-input-tokens": 37196, "total-output-tokens": 9304, "length": "2e13", "weborganizer": {"__label__adult": 0.00041103363037109375, "__label__art_design": 0.00034618377685546875, "__label__crime_law": 0.00042176246643066406, "__label__education_jobs": 0.0007767677307128906, "__label__entertainment": 8.171796798706055e-05, "__label__fashion_beauty": 0.00017917156219482422, "__label__finance_business": 0.00032830238342285156, "__label__food_dining": 0.0004177093505859375, "__label__games": 0.0006556510925292969, "__label__hardware": 0.0017032623291015625, "__label__health": 0.0007510185241699219, "__label__history": 0.00032711029052734375, "__label__home_hobbies": 0.00013303756713867188, "__label__industrial": 0.000598907470703125, "__label__literature": 0.0003235340118408203, "__label__politics": 0.00028705596923828125, "__label__religion": 0.00047516822814941406, "__label__science_tech": 0.0933837890625, "__label__social_life": 0.00011092424392700197, "__label__software": 0.007633209228515625, "__label__software_dev": 0.88916015625, "__label__sports_fitness": 0.0004496574401855469, "__label__transportation": 0.0007886886596679688, "__label__travel": 0.0002353191375732422}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 35769, 0.05318]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 35769, 0.64911]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 35769, 0.90206]], "google_gemma-3-12b-it_contains_pii": [[0, 359, false], [359, 3163, null], [3163, 6798, null], [6798, 9563, null], [9563, 13450, null], [13450, 14981, null], [14981, 18734, null], [18734, 21293, null], [21293, 24310, null], [24310, 28660, null], [28660, 31926, null], [31926, 35603, null], [35603, 35769, null]], "google_gemma-3-12b-it_is_public_document": [[0, 359, true], [359, 3163, null], [3163, 6798, null], [6798, 9563, null], [9563, 13450, null], [13450, 14981, null], [14981, 18734, null], [18734, 21293, null], [21293, 24310, null], [24310, 28660, null], [28660, 31926, null], [31926, 35603, null], [35603, 35769, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 35769, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 35769, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 35769, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 35769, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 35769, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 35769, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 35769, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 35769, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 35769, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 35769, null]], "pdf_page_numbers": [[0, 359, 1], [359, 3163, 2], [3163, 6798, 3], [6798, 9563, 4], [9563, 13450, 5], [13450, 14981, 6], [14981, 18734, 7], [18734, 21293, 8], [21293, 24310, 9], [24310, 28660, 10], [28660, 31926, 11], [31926, 35603, 12], [35603, 35769, 13]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 35769, 0.0]]}
olmocr_science_pdfs
2024-11-27
2024-11-27
f7632722844f4a64081a68dd08077e99317fe73f
Concurrent Programming Constructs in Multi-Engine Prolog Parallelism just for the cores (and not more!) Paul Tarau Department of Computer Science and Engineering University of North Texas tarau@cs.unt.edu Abstract We discuss the impact of the separation of logic engines (independent logic processing units) and multi-threading on the design of parallel programming constructs aware of the fundamental invariant of today’s typical computer architectures: the presence of a few independent cores. We advocate a combination of coroutining constructs with focus on expressiveness and a simplified, multi-threading API that ensures optimal use of a desired number of cores. In this context, native multi-threading is made available to the application programmer as a set of high-level primitives with a declarative flavor. Keywords: multi-engine Prolog, corouting and multi-threading, high-level multi-threading, coordination in multi-engine Prolog, Java-based Prolog implementation Categories and Subject Descriptors D.3.3 [PROGRAMMING LANGUAGES]: Language Constructs and Features—Concurrent programming structures, Coroutines General Terms Languages, Performance, Algorithms, Design 1. Introduction Multi-threading has been adopted in today’s Prolog implementations as it became widely available in implementation languages like C or Java. An advantage of multi-threading over more declarative concurrency models like various AND-parallel and OR-parallel execution schemes, is that it maps to the underlying hardware directly: on typical multi-core machines threads and processes are mapped to distinct “CPUs”. Another advantage is that a procedural multi-threading API can tightly control thread creation and thread reuse. On the other hand, the explicit use of a procedural multi-threading API breaks the declarative simplicity of the execution model of logic based languages. At the same time it opens a Pandora’s box of timing and execution order dependencies, resulting in performance overheads for various runtime structures that need to be synchronized. It also elevates risks of software failure due to programmer errors given the mismatch between assumptions about behavior expected to follow the declarative semantics of the core language and the requirements of a procedural multi-threading API. In this paper we will describe a design emphasizing the decoupling of the multi-threading API and the logic engine operations and encapsulation of multi-threading in a set of high-level primitives with a declarative flavor. We advocate using threads when there are performance benefits and resorting to determinacy through lightweight, cooperative sequential constructs, when the main reason is programming language expressiveness. We have implemented the API in the context of an experimental, Java-based Prolog implementation. It is called Lean-Prolog as we have consistently tried to keep implementation complexity under control and follow minimalist choices in the design of built-ins, external language interfaces and a layered, modular extension mechanism. Lean-Prolog is a new Java-based reimplementation of BinProlog’s virtual machine, the BinWAM. It succeeds our Jinni Prolog implementation that has been used in various applications [13, 14, 16, 18] as an intelligent agent infrastructure, by taking advantage of Prolog’s knowledge processing capabilities in combination with a simple and easily extensible runtime kernel supporting a flexible reflexion mechanism [23]. Naturally, this has suggested to investigate whether some basic agent-oriented language design ideas can be used for a refactoring of Prolog’s interaction with the external world, including interaction with other instances of the Prolog processor itself. Agent programming constructs have influenced design patterns at “macro level”, ranging from interactive Web services to mixed initiative computer human interaction. Performatives in Agent communication languages [4] have made these constructs reflect explicitly the intentionality, as well as the negotiation process involved in agent interactions. At the same time, it has been a long tradition of logic programming languages [6, 9] to use multiple logic engines for supporting concurrent execution. In this context we have centered our implementation around logic engine constructs providing an API that supports reentrant instances of the language processor. This has naturally led to a view of logic engines as instances of a generalized family of iterators called Fluents [17], that have allowed the separation of the first- --- 1 In the presence of features like “hyper-threading” CPUs have a somewhat virtual flavor by sharing a core, but typically the OS recognizes them as distinct and allocates threads and processes to them independently. An upper estimate on the maximum amount of parallelism available through multi-threading or multiple processes is then given by the number of CPUs seen by the OS. 2 Used here to mean “results independent of execution order or timing assumptions”. Not to be confused with determinism which in logic programming parlance means returning unique solutions. order language interpreters from the multi-threading mechanism, while providing a very concise source-level reconstruction of Prolog’s built-ins. Later we have extended the original Fluents with a few new operations [22] supporting bi-directional, mixed-initiative exchanges between engines. The resulting language constructs, that we have called Interactors, express control, metaprogramming and cooperation with stateful objects and external services. They complement Horn Clause Prolog with a significant boost in expressiveness, to the point where they allow emulating at source level virtually all Prolog built-ins, including dynamic database operations. On the other hand, our multi-threading layer has been designed to be independent of the interactor API. This allows assumptions of determinacy when working with multiple engines (and other sequential interactors) within a thread. Such assumptions would be complex to emulate in combination with unrestricted multi-threading and would require adding inefficient and error prone synchronization constructs. The multi-threading API integrates thread-constructs with interactors called Hubs that provide synchronization between multiple consumers and producers. It supports high-level performance-centered concurrency patterns while removing the possibility of programming errors involving explicit synchronization. The general architectural principle advocated in the paper can be stated concisely as follows: separate concurrency for performance from concurrency for expressiveness. Arguably, it is a good fit with the general idea behind declarative programming languages – delegate as much low level detail to underlying implementation as possible rather than burdening the programmer with complex control constructs. The paper is organized as follows. Section 2 overviews logic engines and describes their basic operations and the interactor API that extends the same view to various other built-in predicates. Section 3 introduces Hubs – flexible synchronization devices that allow cooperation and coordination between threads. Section 4 describes a set of high-level multi-threading operations that ensure concurrent execution seen as a means to accelerate computations while keeping the semantics as close as possible to a declarative interpretation. An evaluation of practical performance gains is given in section 5. Section 6 introduces inner servers - a programming abstraction providing a simple client-server style communication between threads. A similar model described in section 7 provides a “dialog” mechanism between processes for atomic remote predicate calls on a network. Section 8 shows that fairly complex “concurrency for expressiveness” patterns like Linda blackboards can be implemented cooperatively in terms of sequential operations on logic engines. Finally, section 9 discusses related work and section 10 concludes the paper. 2. Logic engines as answer generators Out Interactor API has evolved progressively into a practical Prolog implementation framework starting with [17] and continued with [19] and [22]. We summarize it here and refer to [22] for the details of a semantic description in terms of Horn Clause Logic of various engine operations. An logic engine is simply a language processor reflected through an API that allows its computations to be controlled interactively from another Engine very much the same way a programmer controls Prolog’s interactive toplevel loop: launch a new goal, ask for a new answer, interpret it, react to it. A logic engine can be seen as an instance of the Prolog runtime system implementing LD-resolution [20] on a given clause database, together with a set of built-in operations. The command new_engine(AnswerPattern, Goal, Interactor) creates a new logic engine, uniquely identified by Interactor, which shares code with the currently running program and is initialized with Goal as its starting point. AnswerPattern is a term, usually a list of variables occurring in Goal, of which answers returned by the engine will be instances. Note however that new_engine/3 acts like a typical constructor, no computations are performed at this point, except for initial allocation of data areas. In our Lean-Prolog implementation, with all data areas dynamic, engines are lightweight and engine creation is fast and memory efficient to the point where using them as building blocks for a significant number of built-ins and various language constructs is not prohibitive in terms of performance. 2.1 Iterating over computed answers Note that our logic engines are seen, in an object oriented-style, as implementing the interface Interactor. This supports a uniform interaction mechanism with a variety of objects ranging from logic engines to file/socket streams and iterators over external data structures. The ask_interactor/2 operation is used to retrieve successive answers generated by an Interactor, on demand. It is also responsible for actually triggering computations in the engine. The query \[ \text{ask_interactor(Interactor, AnswerInstance)} \] tries to harvest the answer computed from Goal, as an instance of AnswerPattern. If an answer is found, it is returned as the(AnswerInstance), otherwise the atom no is returned. As in the case of the Maybe Monad in Haskell, returning distinct constructor in the case of success and failure, allows further case analysis in a pure Horn Clause style, without needing Prolog’s CUT or if-then-else operation. Note that bindings are not propagated to the original Goal or AnswerPattern when ask_interactor/2 retrieves an answer, i.e. AnswerInstance is obtained by first standardizing apart (re-naming) the variables in Goal and AnswerPattern, and then backtracking over its alternative answers in a separate Prolog interpreter. Therefore, backtracking in the caller interpreter does not interfere with Interactor’s iteration over answers. Backtracking over Interactor’s creation point, as such, makes it unreachable and therefore subject to garbage collection. An interactor is stopped with the stop_interactor(Interactor) operation, that, in the case of logic engines, allows reclaiming resources held by the engine. In our latest implementation Lean Prolog, we are using a fully automated memory management mechanism where unreachable engines are automatically garbage collected. While this API clearly refers to operations going beyond Horn Clause logic, it can be shown that a fairly high-level pure Prolog semantics can be given to them in a style somewhat similar to what one would do when writing a Prolog interpreter in Haskell, as shown in section 4 of [22]. So far, these operations provide a minimal API, powerful enough to switch tasks cooperatively between an engine and its client and emulate key Prolog built-ins like if-then-else and findall [17], as well as typical higher order operations like fold and best_of [22]. \[ \text{The additional operation load_engine(Interactor, AnswerPattern, Goal)} \] that clears data areas and initializes an engine with AnswerPattern, Goal has also been available as a further optimization, by providing a mechanism to reuse an existing engine. A yield/return operation The following operations provide a “mixed-initiative” interaction mechanism, allowing more general data exchanges between an engine and its client. First, like the yield return construct of C# and the yield operation of Ruby and Python, our return/1 operation \[ \text{return}(\text{Term}) \] will save the state of the engine and transfer control and a result Term to its client. The client will receive a copy of Term simply by using its return/2 operation. Note that an interactor returns control to its client either by calling return/1 or when a computed answer becomes available. By using a sequence of return/ask_interactor operations, an engine can provide a stream of intermediate/final results to its client, without having to backtrack. This mechanism is powerful enough to implement a complete exception handling mechanism simply by defining \[ \text{throw}(E) :- \text{return}(\text{exception}(E)). \] When combined with a catch(Goal, Exception, OnException), on the client side, the client can decide, upon reading the exception with ask_interactor/2, if it wants to handle it or to throw it to the next level. Coroutining logic engines Coroutining has been in use in Prolog systems mostly to implement constraint programming extensions. The typical mechanism involves attributed variables holding suspended goals that may be triggered by changes in the instantiation state of the variables. We discuss here a different form of coroutining, induced by the ability to switch back and forth between engines. The operations described so far allow an engine to return answers from any point in its computation sequence. The next step is to enable an engine’s client to inject new goals (executable data) to an arbitrary inner context of an engine. Two new primitives are needed: \[ \text{to_engine}(\text{Engine}, \text{Data}) \] that is called by the client to send data to an Engine, and \[ \text{from_engine}(\text{Data}) \] that is called by the engine to receive a client’s Data. A typical use case for the Interactor API looks as follows: 1. the client creates and initializes a new engine 2. the client triggers a new computation in the engine, parameterized as follows: (a) the client passes some data and a new goal to the engine and issues an ask_interactor/2 operation that passes control to it (b) the engine starts a computation from its initial goal or the point where it has been suspended and runs (a copy of) the new goal received from its client (c) the engine returns (a copy of) the answer, then suspends and returns control to its client 3. the client interprets the answer and proceeds with its next computation step 4. the process is fully reentrant and the client may repeat it from an arbitrary point in its computation For instance, using to_engine and from_engine, one can implement a close equivalent of Ruby’s yield statement as follows: \[ \text{ask_engine}(\text{Engine}, (\text{Answer:-Goal})), \text{Result}) :- \text{to_engine}(\text{Engine}, (\text{Answer:-Goal})), \text{ask_interactor}(\text{Engine}, \text{Result}). \] \[ \text{engine_yield}(\text{Answer}) :- \text{from_engine}((\text{Answer:-Goal})), \text{call}(\text{Goal}), \text{return}(\text{Answer}). \] The predicate ask_engine/3 sends a query (possibly built at runtime) to an engine, which in turn, executes it and returns a result with an engine_yield operation. The query is typically a goal or a pattern of the form AnswerPattern:-Goal in which case the engine interprets it as a request to instantiate AnswerPattern by executing Goal before returning the answer instance. As the following example shows, this allows the client to use, from outside, the (infinite) recursive loop of an engine as a form of updatable persistent state. \[ \text{sum_loop}(\text{S1}) :- \text{engine_yield}(\text{S1} =\Rightarrow \text{S2}), \text{sum_loop}(\text{S2}). \] \[ \text{inc_test}(\text{R1}, \text{R2}) :- \text{new_engine}(\_, \text{sum_loop}(0), \text{E}), \text{ask_engine}(\text{E}, (\text{S1} =\Rightarrow \text{S2} :- \text{S2} is \text{S1}+2), \text{R1}), \text{ask_engine}(\text{E}, (\text{S1} =\Rightarrow \text{S2} :- \text{S2} is \text{S1}+5), \text{R2}). \] \[ 7 =\Rightarrow \text{inc_test}(\text{R1}, \text{R2}), \text{R1}=\text{the}(0 =\Rightarrow 2), \text{R2}=\text{the}(2 =\Rightarrow 7) \] Note also that after parameters (the increments 2 and 5) are passed to the engine, results dependent on its state (the sums so far 2 and 7) are received back. Moreover, note that an arbitrary goal is injected in the local context of the engine where it is executed. The goal can then access the engine’s state variables S1 and S2. As engines have separate garbage collectors (or in simple cases as a result of tail recursion), their infinite loops run in constant space, provided that no unbounded size objects are created. Hubs and threads As a key difference with typical multi-threaded Prolog implementations like Ciao-Prolog [1] and SWI-Prolog [25], our Interactor API is designed up front with a clear separation between engines and threads as we prefer to see them as orthogonal language constructs. To ensure that communication between logic engines running concurrently is is safe and synchronized, we hide the engine handle and provide a producer/consumer data exchanger object, called a Hub, when multi-threading. A Hub can be seen as an interactor used to synchronize threads. On the Prolog side it is introduced with a constructor hub/1 and works with the standard interactor API: \[ \text{hub}(\text{Hub}) \] \[ \text{ask_interactor}(\text{Hub}, \text{Term}) \] \[ \text{tell_interactor}(\text{Hub}, \text{Term}) \] \[ \text{stop_interactor}(\text{Hub}) \] On the Java side, each instance of the Hub class provides a synchronizer between M producers and N consumers. A Hub supports data exchanges through a private object port and it implements the Interactor interface: \[ \text{private Object port}; \] synchronized public Object ask_interactor() { while(null==port) { try { wait(); } catch(InterruptedException e) { if(stopped) break; } } Object result=port; port=null; notifyAll(); return result; } synchronized public Object tell_interactor(Object T) { while(null!=port) { try { wait(); } catch(InterruptedException e) { if(stopped) break; } } port=T; notifyAll(); return stopped?null:T; } synchronized public void stop_interactor() { this.stopped=true; } Consumers issue ask_interactor/2 operations that correspond to tell_interactor/2 operations issued by producers. A group of related threads are created around a Hub that provides both basic synchronization and data exchange services. The built-in new_logic_thread(Hub, X, G, Clone, Source) creates a new thread by either "cloning" the current Prolog code and symbol spaces or by loading new Prolog code in a separate name space from a Source (typically a precompiled file or a stream). Usually a default constructor new_logic_thread(Hub, X, G) is used. It shares the code but it duplicates the symbol table to allow independent symbol creation and symbol garbage collection to occur safely in multiple threads without the need to synchronize or suspend thread execution. 4. High-level concurrency with higher-order constructs Encapsulating concurrent execution patterns in high-level abstractions, when performance gains are the main reason for using multiple threads, avoids forcing a programmer to suddenly deal with complex procedural issues when in the middle of working with declarative constructs in a (mostly) declarative language like Prolog. It is also our experience that in an untyped language this reduces software risks significantly. The predicate multi_all(XGs, Xs) runs list of goals XGs of the form X:-G (on a new thread each) and collects all answers to a list Xs. multi_all(XGs, Xs):- hub(Hub), length(XGs, ThreadCount), launch_logic_threads(XGs, Hub), collect_thread_results(ThreadCount, Hub, Xs), stop_interactor(Hub). When launching the threads we ensure that they share the same Hub for communication and synchronization. launch_logic_threads([], Hub). launch_logic_threads([[X:-G]|Gs], Hub):- new_logic_thread(Hub, X, G), launch_logic_threads(Gs, Hub). Collecting the bag of results computed by all the threads involves consuming them as soon as they arrive to the Hub. collect_thread_results(0, _Hub, []). collect_thread_results(ThreadCount, Hub, MoreXs):- ThreadCount>0, ask_interactor(Hub, Answer), count_thread_answer(Answer, ThreadCount, ThreadsLeft, Xs, MoreXs), collect_thread_results(ThreadsLeft, Hub, Xs). Note also that termination is detected by counting the "no" answers indicating that a given thread has nothing new to produce. count_thread_answer(no, ThreadCount, ThreadsLeft, Xs, Xs):- ThreadsLeft is ThreadCount-1. count_thread_answer(the(X), ThreadCount, ThreadsLeft, Xs, Xs). One can try out the code as follows: ?-multi_all([[I:-for(I, 1, 10)], (J:-member(J, [a, b, c]))], Rs). Rs = [1, 2, 3, a, 4, b, 5, 6, 7, 8, 9, 10, c]. A typical use (reminding of the map-reduce design pattern) is to call multi_all with a list of goals of length larger or equal to the number of available CPUs that can work independently in producing answers to the same problem. The next stage consists of filtering these answers (a reduce step) followed by another call to multi_all. However, when one wants to be able to tell apart the answers produced by different goals a variation of the same pattern, that we have called multi_findall can be used. The predicate multi_findall(XGs, Xss) works as follows: for each (X:-G) on the list XGs it starts a new thread and then aggregates solutions as if findall(X, G, Xss) were called. It collects all the answers Xs to a list of lists Xss in the order defined by the list of goals XGs. It adopts a well-known technique from TCP/IP networking - answer patterns are marked with the number of the goal producing them, such that the results of out-of-order multi-threaded execution can be sorted and grouped using these consecutive integer markers. multi_findall(XGs, Xss):- mark_answer_patterns(XGs, MarkedXGs, 0), multi_all(MarkedXGs, Xss), collect_marked_answers(克斯, Xss). mark_answer_patterns([], [], _). mark_answer_patterns([[X:-G]|Gs], ([N-X:-G][MarkedXGs], N):- W is N+1, mark_answer_patterns(XGs, MarkedXGs, W).- collect_marked_answers(克斯, Xss):- findall(Xs, keygroup(克斯, _, Xs), Xss). ?-multi_findall([[I:-for(I, 1, 10)], (J:-member(J, [a, b, c]))], Rs). Rs = [[1, 2, 3, 4, 5, 6, 7, 8, 9, 10], [a, b, c]]. Note the use of the keygroup/3 LeanProlog built-in that backtracks over key-list of answers pairs. The list of results collected at the end is the same as if a sequence of findall/3 operations were used – a pattern familiar to the Prolog programmer - except that the results are produced by parallel threads. Note also that the only thing the programmer needs to know is that grouping together at least as many goals as the number of CPUs available will speed up execution accordingly. One of deficiencies of these multi-threaded findall-like operations is that they might build large lists of answers unnecessarily. With inspiration from combinators in functional languages one can implement a more flexible multi-threaded fold operation. The predicate multi_fold(F, XGs, Xs) runs a list of goals XGs of the form Xs:-G and combines with F their answers to accumulate them into a single final result without building intermediate lists. multi_fold(F, XGs, Final):- hub(Hub), length(XGs,ThreadCount), launch_logic_threads(XGs, Hub), ask_interactor(Hub, Answer), (Answer = the(Init) -> fold_thread_results(ThreadCount, Hub, F, Init, Final) ; true ), stop_interactor(Hub), Answer=the( ). Like the predicate multi_all, multi_fold relies on the predicate launch_logic_threads to run threads initiated by the goal list XGs. It relies on fold_thread_results to collect results computed by various threads from Hub and to combine them into a single result, while keeping track of the number of threads that have finished their work. fold_thread_results(0, _Hub, _F, Best, Best). fold_thread_results(ThreadCount, Hub, F, SoFar, Best):- ThreadCount > 0, ask_interactor(Hub, Answer), count_thread_answer(Answer, ThreadCount, ThreadsLeft, F, SoFar, Better), fold_thread_results(ThreadsLeft, Hub, F, Better, Best). count_thread_answer(no, ThreadCount, ThreadsLeft, _F, SoFar, SoFar):- ThreadsLeft is ThreadCount-1. count_thread_answer(Yes(X), ThreadCount, ThreadCount, F, SoFar, Better):- call(F, X, SoFar, Better). A typical application is the predicate multi_best(F, XGs, M), which runs a list of goals XGs of the form Xs:-G where N is instantiated to a numeric value. By using max/3 to combine the current best answers with a candidate one it extracts at the the maximum of all answers computed (in an arbitrary order) by all threads. multi_best(XGs, M):=multi_fold(max, XGs, M). Note that, as in the case of its fold cousins in functional languages, fold can be used to emulate various other higher order predicates. For instance the findall-like predicate multi_all is emulated by the predicate multi_all(XGs, Xs) which runs a list of goals XGs of the form Xs:-G and combines all answers to a list using list_cons. multi_all(XGs, Rs):- multi_fold(list_cons, [[ ];true ]|XGs],Rs). list_cons(X, Xs, [X|Xs]). A different pattern arises from combinatorial search algorithms where one wants to stop multiple threads as soon as a first solution is found. Things like restarts in SAT solvers and various Monte Carlo algorithms fit in this category. The predicate multi_first(K, XGs, Xs) runs list of goals XGs of the form Xs:-G until the first K answers Xs are found (or fewer if less then K) answers exist. It uses a very simple mechanism built into Lean Prolog’s multi-threading API: when a Hub interactor is stopped, all threads associated to it are notified to terminate. multi_first(K, XGs, Xs):- hub(Hub), length(XGs, ThreadCount), launch_logic_threads(XGs, Hub), collect_first_results(K, ThreadCount, Hub, Xs), stop_interactor(Hub). collect_first_results(_, 0, _Hub, []). collect_first_results(0, _Hub, []). collect_first_results(K, ThreadCount, Hub, MoreXs):- K > 0, ThreadCount > 0, ask_interactor(Hub, Answer), count_thread_answer(Answer, ThreadCount, ThreadsLeft, Xs, MoreXs), (ThreadCount=:=ThreadsLeft->K1 is K-1 ; K1 is K ), collect_first_results(K1, ThreadsLeft, Hub, Xs). In particular, searching for at most one solution is possible: multi_first(XGs, X):=multi_first(1, XGs, [X]). The multi_first/3 and multi_first/2 predicates provide an alternative to using CUT in Prolog as a means to limit search while supporting a scalable mechanism for concurrent execution. Note also that it is more flexible than CUT as it can be used to limit the search to a window of K solutions. However, in contrast with CUT, the order in which these first solutions are found is arbitrary. 5. Measuring the practical performance gains The main focus of the high level multi-threading predicates described so far is to provide performance gains without major changes in existing Prolog code. To evaluate the maximum amount of parallelism provided by multi_all with a number of independent goals related to the actual number of hardware threads and virtual-threads provided by Intel’s hyper-threading, we have run the naive reverse benchmark on a MacPro with two 2.66GHz Quad-Core Intel Xeon processor giving a total of 8 cores with 2 virtual threads each (provided by hyper-threading) and 16GB of memory (Figure 1). The benchmark indicates that performance increases almost linearly with the number of cores (up to 8) as they provide genuine hardware threads, but it will not benefit from hyper-threading which shares the same arithmetic-logic units among virtual threads. Rather than working on other artificial examples where performance can use the maximum parallelism available, we have reorganized the the Lean Prolog parser and compiler to speed-up the self-compilation test. To better evaluate the practical performance improvements we have tried it on 3 computers (Figure 2) featuring a blend or real and virtual threads (hyper-threading). Note that hyper-threading provides 2 virtual CPUs sharing one core and typically a less than 1.5 performance increase from multithreading. The maximum performance increase of only about 2.3 times despite of the large number of available threads on the 8 core MacPro is explained by the fact that there are big variations in the files sizes of LeanProlog’s modules and by the fact that the time taken by the largest file dominates the benchmark. To a smaller extent, the final concatenation of the resulting binaries has added a constant sequential cost reducing the overall speed-up ratio as well. The relatively good performance on the 4 GB 2.13 GHz ### Figure 1. Lean Prolog on naive reverse on an 8-core MacPro <table> <thead> <tr> <th>Threads</th> <th>Execution time (ms)</th> <th>Thousands of LIPS</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>1599</td> <td>9664</td> </tr> <tr> <td>2</td> <td>548</td> <td>28181</td> </tr> <tr> <td>3</td> <td>424</td> <td>36445</td> </tr> <tr> <td>4</td> <td>355</td> <td>43405</td> </tr> <tr> <td>5</td> <td>297</td> <td>52001</td> </tr> <tr> <td>6</td> <td>256</td> <td>60262</td> </tr> <tr> <td>7</td> <td>227</td> <td>67925</td> </tr> <tr> <td>8</td> <td>232</td> <td>66559</td> </tr> <tr> <td>9</td> <td>222</td> <td>69583</td> </tr> <tr> <td>10</td> <td>224</td> <td>68898</td> </tr> <tr> <td>11</td> <td>218</td> <td>70581</td> </tr> </tbody> </table> MacAir with a CoreDuo CPU which does not have hyper-threading and provides a maximum of 2 hardware threads, is partly due to its fast SSD drive and partly to its comparably fast (in terms of GHz) CPU. The results on the Sony Linux NetBook with a single hyper-threading enabled 1.66 GHz Intel N450 CPU match the performance increase one can expect from the 2 virtual threads provided by hyper-threading. ### 6. Inner servers A simple “inner server” API, similar to a socket based client/server connection can be used to delegate tasks to a set of threads for concurrent processing. The predicate `new_inner_server(IServer)` creates an inner server consisting of a thread and 2 hubs. ```prolog new_inner_server(IServer):- IServer = hubs(In, Out), hub(In), hub(Out), new_logic_thread(In, _, inner_server_loop(In, Out)). ``` The predicate `inner_server_loop(In, Out)` loops consuming data from hub In and returning answers to hub Out. ```prolog inner_server_loop(In, Out):- ask_interactor(In, (X:-Goal)), ( Goal == stop, !, tell_interactor(Out, done), fail ; Goal = = R=the(X) ; R=no ), tell_interactor(Out, R), inner_server_loop(In, Out). ``` ### Figure 2. Lean Prolog bootstrapping time (in seconds) <table> <thead> <tr> <th>System/Program</th> <th>Sequential</th> <th>Multithreaded</th> </tr> </thead> <tbody> <tr> <td>8 core MacPro slowest</td> <td>11.46</td> <td>4.89</td> </tr> <tr> <td>8 core MacPro fastest</td> <td>10.16</td> <td>4.49</td> </tr> <tr> <td>2 core MacAir slowest</td> <td>14.29</td> <td>8.53</td> </tr> <tr> <td>2 core MacAir fastest</td> <td>12.56</td> <td>7.55</td> </tr> <tr> <td>1 core NetBook slowest</td> <td>84.39</td> <td>62.21</td> </tr> <tr> <td>1 core NetBook fastest</td> <td>79.04</td> <td>56.27</td> </tr> </tbody> </table> ### 7. Sequentializing remote predicate calls It is typical in various programming languages to associate client-server connections and multi-threading: when a new client connects, the server launches a new thread to service it. On the other hand, one can use client-server connections to ensure sequential – one transaction at a time – cooperation between clients connected to a server. The predicate `seq_server(Port)` uses the built-in `new_seq_server(Port,Server)` that creates a server listening on a port and then handles client requests sequentially. ```prolog seq_server(Port):- new_seq_server(Port, Server), repeat, new_seq_service(Server, ServiceSocket), seq_server_step(ServiceSocket), fail. ``` ```prolog seq_server_step(Service):- recv_canonical(Service, (X:-Goal)), ( Goal == stop, !, R=stopped ; call(Goal) = = R=the(X) ; R=no ), send_canonical(Service, R), R=\=stopped, seq_server_step(Service). ``` On the client side, an atomic operation called a “dialog” is initiated with the built-in ```prolog open_socket_dialog(Host, Port, Client) ``` that waits for the server to be available. After exchanging a sequence of remote predicate calls with the server over the open socket using ```prolog ask_over_socket(S, Query, Answer):- send canonical(S, Query), recv canonical(S, Answer). ``` the client terminates the “dialog” with ```prolog close_socket_dialog(Socket). ``` Note the use of `send canonical` and `recv canonical` built-in predicates that send and receive Prolog terms (translated to a canonical form as byte sequences) on both the client and server side. While it is possible to have several such servers running in parallel... and executing tasks concurrently on a given machine, one should be aware that performance benefits will only be as good as the total number of available hardware threads. Note also that having atomicity of remote predicate call transactions with the “dialog” mechanism ensures simple and safe coordination between multiple clients connecting to the same server on networked computers. 8. Integrating cooperative multi-tasking constructs The message passing style interaction shown in the previous sections between engines and their clients, can be easily generalized to associative communication through a unification based blackboard interface [3]. Exploring this concept in depth promises more flexible interaction patterns, as out of order operations would become possible, matched by association patterns. An interesting question arises at this point. Can blackboard-based coordination be expressed directly in terms of engines, and as such, can it be seen as independent of a multi-threading API? We have shown so far that when focusing on performance on multi-core architectures, multi-threading can be encapsulated in high-level constructs that provide its benefits without the need of a complex procedural API. To support our claim that “concurrency for expressiveness” works quite naturally with coroutining logic engines we will describe here a cooperative implementation of Linda blackboards. In contrast to multi-threaded or multi-process implementations, it ensures atomicity “by design” for various operations. It is an example of concurrency for expressiveness that can be used orthogonally from concurrency for performance to coordinate cooperatively multiple logic engines within a single thread. The predicate new_coordinator(Db) uses a database parameter Db (a synthetic name, if given as a variable, provided by \( \text{db\_ensure\_bound} \)) to store the state of the Linda blackboard. The state of the blackboard is described by the dynamic predicates available/1 that keeps track of terms posted by operations, waiting/2 that collects pending in operations waiting for matching terms, and running/1 that helps passing control from one engine to the next. \[ \text{new\_coordinator(Db)} \\ \quad \text{db\_ensure\_bound(Db),} \\ \quad \text{db\_dynamic(Db, available/1),} \\ \quad \text{db\_dynamic(Db, waiting/2),} \\ \quad \text{db\_dynamic(Db, running/1).} \] The predicate new_task initializes a new coroutining engine, driven by goal G. We shall call such an engine “an agent” in the next paragraphs. \[ \text{new\_task(Db, G)} \\ \quad \text{new\_engine(nothing, (G, fail), E),} \\ \quad \text{db\_assertz(Db, running(E)).} \] Three cooperative Linda operations are available to an agent. They are all expressed by returning a specific pattern to the Coordinator. \[ \text{coop\_in(T)}:\text{return(in(T)), from\_engine(X), T=X.} \\ \text{coop\_out(T)}:\text{return(out(T)).} \\ \text{coop\_all(T, Ts)}:\text{return(all(T, Ts)), from\_engine(Ts).} \] The Coordinator implements a handler for the patterns returned by the agents as follows: \[ \text{handle\_in(Db, T, E)}: \\ \quad \text{db\_retract1(Db, available(T)), !,} \] \[ \text{to\_engine(E, T),} \\ \quad \text{db\_assertz(Db, running(E)).} \\ \text{handle\_out(Db, T)}: \\ \quad \text{db\_retract(Db, waiting(T, E)).} \] \[ \text{The Coordinator’s dispatch loop coordinate/1 (failure driven here to run without requiring garbage collection) works as follows:} \\ \text{coordinate(Db)}: \\ \quad \text{repeat,} \\ \quad \text{foreach(db\_clause(C, waiting(_, E), true), stop(E)).} \\ \quad \text{foreach(db\_clause(C, running(E), true), stop(E)),} \\ \quad \text{dispatch(A, Db, E),} \\ \quad \text{ask\_interactor(E, the(A)),} \\ \quad \text{dispatch(A, Db, E).} \] Its dispatch/3 predicate calls the handlers as appropriate. \[ \text{dispatch(in}(X), Db, E):\text{-handle\_in(Db, X, E).} \\ \text{dispatch(out}(X), Db, E):\text{-handle\_out(Db, X),} \\ \quad \text{db\_assertz(Db, running(E)).} \\ \text{dispatch(all}(T, Ts), Db, E):\text{-handle\_all(Db, T, Ts, E).} \\ \text{dispatch(exception(Ex)), _, _}:\text{-throw(Ex).} \] Note also that the dispatch/3 predicate propagates exceptions - in accordance with a "fail fast" design principle. \[ \text{Stop\_coordinator(C)}: \\ \quad \text{foreach(db\_clause(C, running(E), true), stop(E)),} \\ \quad \text{foreach(db\_clause(C, waiting(_, E), true), stop(E)).} \] When the coordinator is stopped using stop_coordinator the database is cleaned of possible records of unfinished tasks in either running or waiting state. The code uses a few Lean Prolog extensions - like multiple dynamic databases (with operations like \( \text{db\_assertz} \) similar to \( \text{assertz/1} \) except for the extra first argument that names the database on which they act). Another extension, foreach makes failure-driven loops more readable - it is defined as follows: \[ \text{foreach(When,Then):- When,once(Then),fail.} \\ \text{foreach(_,_).} \] The following test predicate shows that out-of-order in and out operations are exchanged as expected between engines providing a simple transactional implementation of Linda coordination. \[ \text{test\_coordinator:-} \\ \text{new\_coordinator(C),} \\ \text{new\_task(C),} \\ \quad \text{foreach(} \\ \quad \quad \text{member(I, [0, 2]),} \\ \quad \quad \text{( coop\_in(a(I, X)),} \\ \quad \quad \quad \text{println(coop\_in=X)} \\ \quad \quad \text{)} \\ \quad \text{)} \\ \quad \text{new\_task(C),} \\ \quad \text{foreach(} \\ \quad \quad \text{member(I, [3, 2, 0, 1]),} \] When running the code, one can observe that explicit coroutining control exchanges between engines have been replaced by operations of the higher level Linda coordination protocol. ?- test_coordinator. coop_out = f(3) coop_out = f(2) coop_out = f(0) coop_in = f(0) coop_out = f(1) coop_in = f(2) coop_out = f(1) coop_in = f(3) true. This shows that “concurrency for expressiveness” in terms of the logic-engines-as-interactors API provides flexible building blocks for the encapsulation of non-trivial high-level concurrency patterns. A final detail, important for optimizing engine-based coroutining models is engine reuse. Thread pools have been in use either at kernel level or user level in various operating system and language implementations [10] to avoid costly allocation and deallocation of resources required by threads. Likewise, for first-class logic engine implementations that cannot avoid high creation/initialization costs, it makes sense to build interactor pools. For this, an additional operation is provided by our API, allowing the reuse of an existing logic engine (load_engine/3). An interactor pool can be maintained by a dedicated logic engine that keeps track of the state of various interactors and provides recently freed handles, when available, to new engine requests. 9. Related work Multiple logic engines have been present in one form or another in various parallel implementation of logic programming languages [5, 11, 12, 24]. Among the earliest examples of parallel execution mechanisms for Prolog, AND-parallel [6] and OR-parallel [9] execution models are worth mentioning. However, with the exception of the author’s papers on this topic [15–17, 19, 21, 22] there are relatively few examples of using first-class logic engines as a mechanism to enhance language expressiveness, independently of their use for parallel programming. A notable exception is [2] where such an API is discussed for parallel symbolic languages in general. In combination with multithreading, our own engine-based API bears similarities with various other Prolog systems, notably [1, 25]. Coroutining has also been present in logic languages to support constraint programming extensions requiring suspending and resuming execution based on changes of the binding state of variables. In contrast to these mechanisms that focus on transparent, fine-grained coroutining, our engine-based mechanisms are coarse-grained and programmer controlled. Our coroutining constructs can be seen, in this context, as focussed on expressing cooperative design patterns that typically involve the use of a procedural multi-threading API. Finally, our multi_findall and multi_fold predicates have similarities with design patterns like ForkJoin [8] or MapReduce [7] coming from sharing a common inspiration source: higher-order constructs like and map fold in functional programming. 10. Conclusion We have shown that by decoupling logic engines and threads, programming language constructs can be kept simple when their purpose is clear – multi-threading for performance is separated from concurrency for expressiveness. This is achieved via communication between independent language interpreters independent of the multi-threading API. Our language constructs are particularly well-suited to take advantage of today’s multi-core architectures where keeping busy a relatively small number of parallel execution units is all it takes to get predictable performance gains, while reducing the software risks coming from more complex concurrent execution mechanisms designed with massively parallel execution in mind. The current version of LeanProlog containing the implementation of the constructs discussed in this paper, as well as a number of draft papers describing other aspects of the system are available at http://logic.cse.umn.edu/research/LeanProlog. Acknowledgment We thank NSF (research grant 1018172) for support. References
{"Source-Url": "http://www.cse.unt.edu/~tarau/research/LeanProlog/draft_damp11.pdf", "len_cl100k_base": 10011, "olmocr-version": "0.1.53", "pdf-total-pages": 9, "total-fallback-pages": 0, "total-input-tokens": 32343, "total-output-tokens": 12692, "length": "2e13", "weborganizer": {"__label__adult": 0.0003082752227783203, "__label__art_design": 0.0003108978271484375, "__label__crime_law": 0.00032258033752441406, "__label__education_jobs": 0.0007448196411132812, "__label__entertainment": 6.61611557006836e-05, "__label__fashion_beauty": 0.00012105703353881836, "__label__finance_business": 0.00015592575073242188, "__label__food_dining": 0.0003008842468261719, "__label__games": 0.0004863739013671875, "__label__hardware": 0.0008859634399414062, "__label__health": 0.0004115104675292969, "__label__history": 0.00023281574249267575, "__label__home_hobbies": 8.744001388549805e-05, "__label__industrial": 0.00044846534729003906, "__label__literature": 0.00023353099822998047, "__label__politics": 0.0002677440643310547, "__label__religion": 0.0005512237548828125, "__label__science_tech": 0.0247802734375, "__label__social_life": 7.867813110351562e-05, "__label__software": 0.005245208740234375, "__label__software_dev": 0.962890625, "__label__sports_fitness": 0.00027489662170410156, "__label__transportation": 0.0005769729614257812, "__label__travel": 0.00018966197967529297}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 48642, 0.01976]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 48642, 0.40106]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 48642, 0.87465]], "google_gemma-3-12b-it_contains_pii": [[0, 5160, false], [5160, 12362, null], [12362, 18358, null], [18358, 23399, null], [23399, 29622, null], [29622, 33733, null], [33733, 39308, null], [39308, 45305, null], [45305, 48642, null]], "google_gemma-3-12b-it_is_public_document": [[0, 5160, true], [5160, 12362, null], [12362, 18358, null], [18358, 23399, null], [23399, 29622, null], [29622, 33733, null], [33733, 39308, null], [39308, 45305, null], [45305, 48642, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 48642, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 48642, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 48642, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 48642, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 48642, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 48642, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 48642, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 48642, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 48642, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 48642, null]], "pdf_page_numbers": [[0, 5160, 1], [5160, 12362, 2], [12362, 18358, 3], [18358, 23399, 4], [23399, 29622, 5], [29622, 33733, 6], [33733, 39308, 7], [39308, 45305, 8], [45305, 48642, 9]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 48642, 0.04828]]}
olmocr_science_pdfs
2024-12-06
2024-12-06
143466d8045c34da2f9f1ce5446f7a72d3ba3508
A scalable infrastructure for teaching concepts of programming languages in Scala with WebLab An experience report van der Lippe, Tim; Smith, Thomas; Pelsmaeker, Daniël; Visser, Eelco DOI 10.1145/2998392.2998402 Publication date 2016 Document Version Accepted author manuscript Published in SCALA 2016 - Proceedings of the 2016 7th ACM SIGPLAN Symposium on Scala Citation (APA) Important note To cite this publication, please use the final published version (if applicable). Please check the document version above. A Scalable Infrastructure for Teaching Concepts of Programming Languages in Scala with WebLab An Experience Report Tim van der Lippe Thomas Smith Daniël Pelsmaeker Eelco Visser Delft University of Technology T.J.vanderLippe@student.tudelft.nl, T.N.Smith@student.tudelft.nl, D.A.A.Pelsmaeker@student.tudelft.nl, E.Visser@tudelft.nl Abstract In this paper, we report on our experience in teaching a course on concepts of programming languages at TU Delft based on Krishnamurthi’s PAPL book with the definitional interpreter approach using Scala as meta-language and using the WebLab learning management system. In particular, we discuss our experience with encoding of definitional interpreters in Scala using case classes, pattern matching, and recursive functions; offering this material in the web-based learning management system WebLab; automated grading and feedback of interpreter submissions using unit tests; testing tests to force students to formulate tests, instead of just implementing interpreters; generation of tests based on a reference implementation to reduce the effort of producing unit tests; and the construction of a product line of interpreters in order to maximize reuse and consistency between reference implementations. Categories and Subject Descriptors K.3.2 [Computers and Education]: Computer science education; D.3.4 [Programming Languages]: Processors—Interpreters; D.2.5 [Software Engineering]: Testing and Debugging—Test generation Keywords Teaching, Concepts of Programming Languages, Definitional Interpreters, Testing, Scala, WebLab 1. Introduction There are essentially three approaches to the study of concepts of programming languages. A popular approach is to study several real world programming languages as representative examples of (collections of) concepts [13, 17]. The study activity consists of reading typical example programs and perhaps writing some programs in each language to conduct comparative experiments. This approach requires no other tools than existing programming languages and has the useful side effect of teaching these languages. However, the approach lacks depth and precision; students only get an understanding of concepts through their observable behavior in experiments. An approach that addresses this concern is to study the formal semantics of programming languages. For example, Nielson and Nielson [7] present the formal specification of languages using denotational, operational, and axiomatic semantics. This provides a precise description of the meaning of a language and supports formal reasoning about applications such as program analysis. The recent work of Pierce et al. [10] transforms this approach from paper formalization to mechanized formalization with proof assistants. The downside of this approach is that it requires the introduction of a fair amount of heavyweight theoretical machinery. The third approach provides a middle ground between these approaches by using definitional interpreters as its main vehicle. A definitional interpreter, as introduced by Reynolds [11, 12], is a program that interprets an abstract syntax tree representation of a program and computes its value. This makes explicit the mechanisms behind language constructs, or at least abstractions of such mechanisms. It allows to directly study the operational behavior of language constructs and to study the effect of alternative semantics by means of experiments. This approach combines the experimental style of the first approach with the precision of the second without introducing more machinery than that of a basic functional language. The approach was introduced as a tool for teaching programming languages by Kamin in his book “Programming languages — an interpreter-based approach” [2]. Krishnamurthi has adopted the approach, first using Scheme as meta-language and object language [4], more recently using the Pyret teaching language as meta-language and a Scheme-like language as object language [5]. In this paper, we report on our experience applying the definitional interpreter approach in a course on concepts of programming languages at TU Delft using Scala as meta- language and using the WebLab learning management system [3, 15]. The course is based on Krishnamurthi’s PAPL book [5]. In our course we chose to adopt Scala instead of Pyret as the implementation language. Scala provides similar features for algebraic data type definition, pattern matching, and immutable data types that simplify programming language parsing and interpretation. Using Scala introduces our students to functional programming on a platform they are familiar with. And it also helps that there are more Scala resources for the students to consult. (The existing support for Scala in WebLab also contributed to the choice of language.) The main study activity in the course is writing interpreters. However, just submitting the code of interpreters makes grading a significant effort (especially considering the increasing enrolment into the curriculum) and does not encourage students to put additional effort in developing examples and test cases for the languages they implement. To address these concerns we have developed infrastructure for automatically assessing student submissions and providing feedback at scale and such that the effort of developing assignments and their automated grading is manageable. In particular, we discuss our experience with • encoding of definitional interpreters in Scala using case classes, pattern matching, and recursive functions (Section 2); • offering this material in the web-based learning management system WebLab (Section 3); • automated grading and feedback of interpreter submissions using unit tests (Section 4); • generation of tests based on a reference implementation to reduce the effort of producing unit tests (Section 5); • testing tests to encourage students to formulate tests, instead of just implementing interpreters (Section 6); and • the construction of a product line of interpreters in order to maximize reuse and consistency between reference implementations (Section 7). We expect that this report will be helpful for instructors considering to apply the approach in their courses. 2. Definitional Interpreters in Scala The course revolves around developing interpreters for a range of small languages with representative language constructs. In this section we illustrate the approach by means of an interpreter for a small language with arithmetic and functions as first-class citizens, which we will use as the running example in the rest of the paper. Abstract Syntax Rather than putting much emphasis on syntax and parsing, PAPL makes the abstract syntax the central representation in terms of which semantics is studied. sealed abstract class Ext // Numbers case class NumExt(num: Int) extends Ext // Binary and unary operators. E.g.: (+ 1 3) case class BinOpExt(s: String, l: Ext, r: Ext) extends Ext // Application of a function with one argument case class AppExt(f: Ext, a: Ext) extends Ext // Definition of a function with one argument case class FdExt(arg: String, body: Ext) extends Ext // Variables case class IdExt(c: String) extends Ext Figure 1. Abstract syntax of extended (sugared) language. sealed abstract class Core case class NumC(num: Int) extends Core // Numerical addition and multiplication case class PlusC(l: Core, r: Core) extends Core case class MulC(l: Core, r: Core) extends Core // Function application, definition and variables case class AppC(f: Core, a: Core) extends Core case class FdC(arg: String, body: Core) extends Core case class IdC(c: String) extends Core Figure 2. Abstract syntax of core language. sealed abstract class Value case class NumV(n: Int) extends Value // Closures to support first-class functions case class CloV(f: FdC, e: List[Bind]) extends Value // For binding a value to a variable case class Bind(name: String, value: Value) Figure 3. Representation of values and bindings. Abstract syntax trees are represented using algebraic data types, which are conveniently defined using case classes in Scala. PAPL explicitly introduces the distinction between a feature rich (sugared) source language and a minimal core language that includes the essential constructs to achieve a certain level of expressiveness. The extended version of our example language is defined in Figure 1. It features number literals, generic binary and unary operators, unary function literals (lambdas), function application, and variables. Rather than taking the core language to be a subset of the extended source language, PAPL defines it as a separate data type. The core for our example language is defined in Figure 2. It is mostly the same as the extended language, but instead of a generic representation for operators, it has explicit representations for an addition and multiplication operator only. Parsing Since writing object programs as abstract syntax trees is tedious, a little concrete syntax is useful. To avoid the overhead of implementing full blown parsers, PAPL uses S-expressions as a concrete syntax substrate. For example, here is an expression in our example language: object Parser { def parse(sexpr: SExpr): Ext = sexpr match { case SNum(n) => NumExt(n) case SLList(List(SSym("lambda"), SLList(List(SSym(arg))))) => FdExt(arg, parse(body)) case SLList(List(SSym(sym), l, r)) if Set("*", ",", ") contains(sym) => BinOpExt(sym, parse(l), parse(r)) case SLList(List(SSym(sym), e)) if Set("-", ",", ") contains(sym) => UnOpExt(sym, parse(e)) case SLList(head :: arg :: Nil) => AppExt(parse(head), parse(arg)) case SSym(s) => IdExt(s) } def parse(str: String): Ext = parse(Reader.read(str)) } --- Figure 4. Parser object Desugarer { def desugar(e: Ext): Core = e match { case NumExt(n) => NumV(n) case BinOpExt(op, l, r) => interp(l, env), interp(r, env)) case UnOpExt(sym, e) => interp(e, env) case AppExt(f, a) => interp(f, env), interp(a, env) :: env_clos) case FdExt(arg, body) => ClosV(fdc, env) } } --- Figure 5. Desugarer ```(lambda (x) (* 2 (+ x (- 2 1))))``` This divides the task of parsing into application of a generic read function that parses a string representation of a concrete syntax S-expressions into an object of the SExpr data type, and a language-specific parse function that translates an SExpr object into an AST object. We provide the read function and SExpr data type to our students who only have to write the parse function. (And in later assignments we even give them the parse function.) With this approach parsing is reduced to matching S-expression patterns corresponding to constructs of the language as illustrated in Figure 4. For example, the pattern ``` SLList(List(SSym("lambda"), SLList(List(SSym(arg))), body)) ``` matches the S-expression ``` (lambda (<arg> <body>) ``` --- object Interpreter { def interp(e: Core, env: List[Bind]): Value = e match { case NumV(n) => NumV(n) case PlusC(l, r) => interp(l, env), interp(r, env)) case MultC(l, r) => interp(l, env), interp(r, env)) case AppC(f, a) => interp(f, env), interp(a, env) :: env_clos) case FdExt(arg, body) => ClosV(fdc, env) } } --- Figure 6. Interpreter where <arg> is the name of the function argument and <body> should be an expression. **Desugaring** A core language expresses the key computational ideas. However, programming languages often provide constructs that make programming more convenient, but can be expressed in terms of the core language. Rather than just ignoring such syntactic sugar, PAAPL introduces an explicit desugaring step in the semantic pipeline. The desugar function mostly copies constructs in the extended language to their counterparts in the core language, and in the process translates sugar patterns to combinations of the constructs in the core language. Figure 5 illustrates this for our example language, transforming Ext objects into Core objects. The function translates generic binary operators to the specific operators of the core language. The addition and multiplication operators are translated directly, but the binary and unary minus operators are desugared in terms of the former. **Interpreter** The key component of the semantic pipeline is the interpreter. The interp function computes the value of an expression in the core language, i.e. it is a function from objects of type Core to objects of type Value. Just like abstract syntax trees, we use case classes for the representation of value objects. Figure 3 defines as values for our example language numbers (NumV), the values of arithmetic operations, and closures (ClosV), the values of function expressions. To interpret our example language, the interpreter also requires an environment to keep track of the binding of values to variables. The Bind class in Figure 3 represents... such bindings, and an environment consists of a list of such bindings. A function value should keep track of the bindings at the point of its definition. Therefore, a closure has an environment as argument in addition to the abstract syntax tree of the function. A syntax-directed interpreter is defined by induction on the structure of the abstract syntax tree, defining a match case for each language constructor, recursively invoking the interpreter on sub-trees. Figure 6 defines the interpreter for our example language. The interesting case for this language is the evaluation of function expressions, function application, and variables. A variable is evaluated by looking up its binding in the current environment. A function expression returns a closure with the definition-time environment. A function application evaluates the body of a function value in an environment, extended with a binding of the value of the actual parameter to the formal parameter. The crucial point of this definition is the treatment of environments in function application. In order to realize static scoping semantics, the actual parameter should be evaluated in the call-time environment, but the function body should be evaluated in the definition-time environment from the closure. Having an executable definition of this semantics allows direct experimentation with alternatives. Typical mistakes made by students are evaluating the body in the call-time environment, giving dynamic scoping, or evaluating the actual parameter in the closure environment. More intricate errors emerge when extending the language to functions with multiple parameters. 2.1 Course Organization In the course we extend and modify this language to study more concepts of programming languages. Over the span of the course, students write a parser, desugarer, and interpreter for a new language each week. The lab covers the following weekly topics: 1. Scala introduction: basic functional programming and test driven development in Scala 2. Arithmetic and Booleans: architecture of the parse-desugar-interpret approach 3. First-class functions: names, environments, function values, closures, function application 4. Records: extensible, immutable records 5. Type checking: type checking for a language with lists, type soundness 6. Mutation: boxes, mutable variables, stores 7. Mini Java: small object-oriented programming language 8. Type inference: type expressions, unification Figure 7 shows the dependency graph that illustrates which interpreters were used in which week of the 2015–2016 edition of the course. For example, in week 5 (w5), students extend the basic language (created as assignment in week 3 (w3)) with type-checking and lists. 3. WebLab The enrollment into the curriculum has been steadily increasing. In the 2015–2016 edition, 180 students enrolled... into the second year course, and this number is expected to further increase in the coming years. While not near MOOC scale, these numbers already create a significant grading and administration effort. Furthermore, the 10 week quarter in Delft requires weekly deadlines for assignments and a very short turnaround time for grading and feedback. To scale our education without involving large numbers of teaching assistants we have been developing WebLab\textsuperscript{2}, a web-based learning management system especially geared to programming education [3, 15], including support for Scala. The system integrates the development of assignments by instructors, writing submissions by students, and the administration of results for an entire course. \textbf{Interface} Figure 8 shows the user interface for developing a submission to a programming assignment, with the following components: An editor (under the ‘Solution’ tab) for developing the solution to the assignment. An additional editor (under the ‘Test’ tab) for developing unit tests to test the solution. The ‘Your Test’ button for invoking the tests written in the ‘Test’ tab. The ‘Spec Test’ button for invoking the secret specification tests. A console for displaying feedback from test invocation. A revision history for keeping track of all edits to the program and tests. A discussion tab for asking questions to the teaching assistants. The execution of a solution against a test set is done on the server and may include compilation for compiled languages. We strive to give immediate feedback on execution, which requires execution within seconds of invocation. To that purpose, the LabBack back-end provides a pool of running JVMs to execute test jobs [15]. LabBack currently supports Scala, Java, Python (via JPython), JavaScript, and C (via clang produced JavaScript). A benefit of this set-up is that we do not need to worry about deployment of programming environments on student machines. \textbf{Automated Grading} The key benefit of WebLab is that it integrates course administration with submission, persistent storage, and grading of student solutions. WebLab organizes all assignments of a course in a tree structure with configurable grading schemes at each node of the tree. Grades for individual assignments are aggregated into grades for composite assignments according to a configurable weighted grading scheme. Programmed assignment submissions can be graded using two mechanisms. First, a submission is tested against a set of secret specification tests. Students do not see these tests, nor their output on failure. However, students do see the ratio of successful versus all scores of each specification test run (e.g. 22/30). Automated grading is useful for instructors as it considerably lowers to effort of grading programming submissions. It is an advantage to students as well, since the testing ratio feedback, even if minimal, provides very early feedback on progress. Second, a submission can be scored against a rubric that states Boolean criteria that it should satisfy. Where needed, rubric grading can address grading issues that cannot be covered by unit testing. While this requires teaching assistant intervention, the WebLab workflow reduces the grading effort since basic testing (does it compile? is it functionally correct?) is taken care of by the specification test. The weight of each grading mechanisms can be configured for each assignment. \textbf{Related Work} With the rise of MOOCs the issue of scalable courses has been addressed by others as well. For example, Miller et al. [6] describe the set-up for a course on functional programming principles in Scala, using cloud-based computing to grade the style and implementation of student submissions. However, they require that students install Scala, the Scala build tool sbt, and an IDE to get started. WebLab instead provides an online code editor, which not only eases the requirements on the students and their systems, but also ensures that all students work in the same environment with the same software. \textbf{Course Development Effort} WebLab reduces grading effort and speeds up feedback to students. This frees up teaching assistants to help students during assisted labs, rather than spending time on grading. However, this requires a careful upfront design and development of the assignments, including high quality test sets. In the remainder of this paper we elaborate on the Scala infrastructure we developed for also reducing this upfront design and development cost. 4. Testing Interpreters The default interface of WebLab for automated grading is based on unit testing, taking the ratio of successful tests to the size of the test suite as measure for a grade. For Scala, WebLab provides a binding to the ScalaTest unit testing framework [14]. Thus, to check correctness of student submissions of parsers, desugarers, and interpreters we developed specification test suites using ScalaTest. Figure 9 shows an example test suite with integration tests that exercise the whole chain of parsing, desugaring, and interpretation. The result is either a value in the case of a positive test or an exception in the case of a negative test. However, this basic approach is too simplistic, and needs to be refined, in order to test that all components of the chain are implemented correctly. This also provides us with better diagnostics to determine the errors made by a student. Thus, for a single input program, we write separate assertions for each component. Figure 10 shows how the first, positive, test of Figure 9 is rendered. The first assertion tests that the parser produces the expected AST in the extended language. The third assertion tests the interpretation of the corresponding core language AST. The second assertion tests desugaring. Since there are many possible equivalent desugarings for each sugared expression, testing the AST produced by desugaring requires \textsuperscript{2}https://weblab.tudelft.nl students to guess the desugaring our tests checks for. Therefore, we check the result of interpreting the result of desugaring. Figure 11 shows the rendering of the second, negative, test of Figure 9. In order to check that an exception is thrown at the correct stage, we verify that the preceding stages execute successfully. **Clustering Tests** The specification tests are used to provide feedback to students about the quality of their solution and is used to calculate a grade. A student can continuously run the specification tests on their solution to get the number of successful tests versus the total number of tests. This serves as a useful indicator of the completeness of their solution. WebLab uses the ratio of success versus failed specification tests to determine the student’s grade. A disadvantage of this approach is that all tests contribute equally to the grade, while not all tests are equally important. For example, we include tests that check that the solution for aspects corresponding to the previous assignment still works, but we do not want these tests to count very much towards the final grade. A related issue is that tests may be dependent. For example, negative tests for the corner cases of the addition operator should not succeed when the positive test for the addition operator does not succeed. To have more control over the test dependencies and the contribution of tests to the grade, we group tests into *clusters*. A cluster of tests is counted as a single test in Scala, and all tests in a cluster must succeed for the cluster to succeed. By varying the number of clusters, we can influence the test success ratio, and therefore the grade. A cluster of only negative tests will succeed even when the feature in question has not been implemented. To prevent this, each cluster must have at least one positive test for that feature. To get even better control of the grade, clusters have percentual weights. The example in Figure 12 shows two clusters with tests for the Week 2 assignment as used in the specification tests of Week 3. The total weight the previous week is 30%. This week has 2 clusters, one has weight 1, the other weight 2. As a result, the first cluster increases the test score by $1 \cdot \frac{30}{3} = 10$, the second by $2 \cdot \frac{30}{3} = 20$. At the start of a test, the totalScore is increased with the corresponding total attribution value. The achievedScore is increased with the same attribution value if and only if all asserts in the tests have succeeded. The student does not receive any credit if only a portion of the tests succeed. ### 5. Test Generation Writing test suites following the approach of Section 4 is extremely tedious. To avoid this tedium we have developed an internal test definition DSL. The DSL reduces the specification of a test case to the input program to be evaluated. For example, Figure 13 defines a small test suite consisting of two groups, each consisting of clusters of positive and negative tests. A test is represented as an instance of a case class ```scala class TestSpec extends FunSuite { test("POS: (+ 5)") { assertResult(NumV(9)) { Interp.interp( Desugar.desugar( Parser.parse("**(+ 5)**") ) ) } } test("NEG: ((lambda () 13) (+ 4 5))") { Interp.interpException { Interp.interp( Desugar.desugar( Parser.parse("**((lambda () 13) (+ 4 5))**") ) ) } } } ``` **Figure 9.** Example test suite. ```scala test("POS: (+ 4 5)") { assertResult(BinOpExt("+", NumExt(4), NumExt(5))){ Parser.parse("**(+ 4 5)**") } assertResult(NumV(9)) { Interp.interp( Desugar.desugar( BinOpExt("+", NumExt(4), NumExt(5)) ) ) } assertResult(NumV(9)) { Interp.interp(PlusC(NumC(4), NumC(5))) } } ``` **Figure 10.** An expanded positive test. ```scala test("NEG: ((lambda () 13) (+ 4 5))") { assertResult(AppExt(FdExt(List(), NumExt(13)), List(BinOpExt("+", NumExt(4), NumExt(5))))){ Parser.parse("**((lambda () 13) (+ 4 5))**") } Desugar.desugar(AppExt(FdExt(List(), NumExt(13)), List(BinOpExt("+", NumExt(4), NumExt(5)))){ intercept[InterpException] { Interp.interp(AppC(FdC(List()), NumC(13)), List(PlusC(NumC(4), NumC(5)))) } } } ``` **Figure 11.** An expanded negative test. object Week3 extends TestSpecBase { def getTests = List( Group("Test 2", scoreTotal = 30, + CoreLanguageTests.parserTests + CoreLanguageTests.clusters), Group("Arithmetic", scoreTotal = 70, List( Cluster("Binary operators arity", List( Neg("(+ 4 5 6)"), Neg("(+ 4)"), Pos("(+ 4 5)") )), Cluster("Arithmetic tests", List( Pos("(+ 248 80)"), Pos("(+ (+ 12 55) 89)") ))) ) } Figure 13. Example test suite in our internal test DSL. into it. The positive and negative test cases for the generator are represented as case classes. By default the TestSpec class defines and handles two case classes Pos and Neg for positive and negative respectively that test the parser, desugarer and interpreter. If a particular chapter requires more case classes than the default, we can add them in the subclass and override the generateTestCases() method to handle those case classes too. The test case classes usually specify only the syntax and any environment in which the test must be run. The test case’s syntax is then fed through our own parser, desugarer and interpreter to find what kind of AST or result it produces. Then Scala tests are generated that check that the student solution produces the same results. For a negative test it is asserted that the test fails with a particular exception. 6. Testing Tests Writing a correct interpreter for a language is only half of the job of studying semantics. It is important to understand how an interpreter can go wrong. That is, to understand what is not correct behavior. This requires developing test cases for corner cases by thinking through feature interactions. For example, when all test cases in a test suite use distinct variables, it will not discover interpreters with variable capture (dynamic scoping) errors. In a previous edition of the course, students were not always inclined to write tests. The instantaneous feedback of the automatic specification tests did not help in this respect. This effect has also been observed by earlier research [1]. In the 2015–2016 edition we introduced separate assignments to write tests for a language. To support this, automatically testing and grading for these tests was required. Meta-Test Procedure We developed the meta-test suite outlined in Figure 17. It runs a student test suite against a collection of faulty interpreters, applying the good test criterion: A good test is a test that fails if and only if a flaw abstract class TestSpecBase extends FunSuite { def getTests: List[Group] def generate(): String = { val groups = this.getTests.map(groupToString).mkString s"\"classify $testName extends FunSuite with BeforeAndAfterAll { $groups }\".stripMargin } def groupToString(group: Group): String = group match { case Group(_, _, clusters) => clusters.map(clusterToString(group, sumOfClusterWeights, _)).mkString case _ => "\" } def clusterToString(group: Group, sumOfClusterWeights: Double, cluster: Cluster): String = ensureNotAllNegative(group, cluster) \n cluster.tests.map(test => generateTestCase(group, cluster, test)).mkString("\n") def generateTestCase(group: Group, cluster: Cluster, test: Test): String = case Pos(input, env) => val either = Either[Either[Throwable, List[Product]]] = for { p <- tryParse(input).right d <- tryDesugar(p).right i <- tryInterp(d).right } yield List(p, d, i) either match { case Left(ex) => throw new PosTestFailedException() case Right(pp :: dp :: ip :: Nil) => this.emitParseAssert(input, pp) + this.emitDesugar(pp) + this.emitInterpAssert(dp, ip) case Neg(input, env) => /* ... */ } } Figure 14. Test generator. is introduced in the system under test. That is, testing a test boils down to supplying the test an implementation with a flaw and verifying that the test fails. Conversely, the test should not fail when the provided implementation does not contain any flaws. Students write one full test suite which means that the full test suite must be evaluated to verify that even a single error in the implementation is caught. The injectInterp(_: Interp): FunSuite method finds the student test suite on the class path and then replaces its default interpreter field for the (faulty) interpreter provided. The modified student suite is then returned so the tests can be run with our custom runner. // this will succeed if the x in the outer application // is evaluated in the environment of the closure Neg(((let ((x 1)) (lambda () x)) x)). Figure 15. Specification of complex test case in embedded test DSL. // RES: ((let ((x 1)) (lambda () x)) x) assertResult(AppExt(LetExt(List(LetBindExt("x", NumExt(1))), FdExt(List(), IdExt("x"))), List(IdExt("x"))) Parser.parse("""((let ((x 1)) (lambda () x)) x)""") ) Desugar.desugar(AppExt(LetExt(List(LetBindExt("x", NumExt(1))), FdExt(List()), IdExt("x"))), List(IdExt("x"))) } intercept[InterpException] { Interp.interp(AppC(AppC(FdC(List("x"), FdC(List(), IdC("x")))))), List(List)(List(NumC(1))), List(List(NumC(1)))) } Figure 16. Code generated from test case in Figure 15. Defining Faulty Interpreters Following the definition of a good test, we need a set of faulty interpreters that each introduce exactly one fault. To avoid a maintenance nightmare, the introduction of a fault should not require duplicating all code of an interpreter. To achieve this goal, we use inheritance with method overriding to efficiently inject faults in a reference solution. For example, a correct reference solution for an interpreter contains a lookup method. This method takes the current variable scope, and finds the value for a bound variable. The method should return an UnboundIdException when the variable is not in scope as defined in Figure 18. To introduce a flaw in this interpreter, we override the lookup method and return NumV(-1) whenever an identifier is not in scope as defined in Figure 19. We then inject the extended BasicInterp into the student test suite. In order to allow this style of fault injection, we refactored the reference implementations of interpreters in order to expose bodies of cases in the interpretation function with calls to separate semantic functions. Preventing Test Tampering The algorithm has several ways to detect test suites that are created to cheat the system. First of all a test suite with just one test which always fails would score all points. Therefore before the actual MetaTest is run, in the beforeAll function of the MetaTest suite it is verified that the student test suite passes on a correct implementation. While this does solve the issue for always-failing tests, a simple test suite that only succeeds once and then always fails would still be awarded the full score. The last cheat prevention mechanism employs running the test suite a random number of times to prevent students from hardcoding test based on the number of test invocations. trait AbsMetaTest extends FunSuite /* Prevent students from checking certain counts and succeed/fail based on the count */ var max = Math.abs(new Random().nextInt() % 10) for (a <- 1 to max) testInterp(createInterp(), expectFail = false) override def beforeAll() = testInterp(createInterp(), expectFail = false) def testInterp(i: Interp, expectFail: Boolean=true) = testSuite(injectInterp(i), expectFail) protected def testSuite(suite: FunSuite, expectFail: Boolean) = var failed = false // Reporter used to verify at least one test failed val reporter: Reporter = new Reporter override def apply(event: Event) = { event match { case _: TestFailed => failed = true case e: TestSucceeded => reportSuccess(e) case _ => // Do nothing } } suite.run(Nothing, reporter, new Stopper, new Filter(Nothing, Set()), Map[String, Any](), Nothing, new Tracker) // Assert that the suite correctly failed or passed // on the given implementation. assert(failed == expectFail) Figure 17. Meta-test procedure for testing test suites. 7. Product Line During the course, students are tasked with building an interpreter each week for a language with specific features. For each week in the course one reference interpreter is used to automatically generate output for specification tests. In the first version of the course these interpreters were all completely stand-alone Scala classes. Each interpreter was isolated from the others by a package structure. The interpreters had a high amount of overlap in functionality, because many language features were reused in multiple weeks of the course. This approach quickly proved to be hard to maintain as any change in the basic functionality had to be applied to each interpreter. Therefore we developed a solution to re-use code shared between interpreters. Towards reuse The assignments for each week build on solutions of previous weeks. Sometimes, an assignment requires partial solutions of multiple previous assignments. The goal was to ease the burden of maintaining separate interpreters while allowing instructors to easily reconfigure assignments. An instructor determining the course schedule must be able to combine language features into assignments according to the desired schedule. More technically speaking, the goal was to have one stand-alone interpreter for each desired language feature as opposed to one interpreter for each week in the course. Ideally, the reference solution for each week should be a simple composition of the required language features. Traits and multiple inheritance After several iterations, multiple inheritance using traits proved to be the best solution. The solution makes composing interpreters as simple as creating a trait mixin: class BasicInterp { // ... other implementation details omitted def lookup(name: String, nv: List[Bind]): Value = nv.find(x => x.name == name) .getOrElse(throw UnboundIdException(name)).value } test("Lookup does not throw exception") { testInterp(new BasicInterp { override def lookup(name: String, env: List[Bind]) = env.find(x => x.name == name) .getOrElse(NumV(-1)).value }) } Figure 18. Part of basic interpreter. class ParserWeek5 extends BaseParser with TypedParser with ListParser with ParserWeek3 The above statement defines the reference parser used in week 5. This same construct is used for composing desugaring and interpreter-traits. Each trait defines a method that parses an s-expression into a high-level AST (that includes sugar) of the target language: parse(expr: SExpr): ExprExt. Standard pattern matching in Scala is used to unmarshall the SExpr case class into an AST. When a trait fails to match a pattern, the fallback case will delegate parsing to its parent in the inheritance linearization: case _ => super.parse(sexpr). By making the call to super, the next trait in the inheritance linearization will be called [8]. When no trait can match the given expression, the fall through case will call BaseParser which throws an exception. Moreover, when a pattern matches and a recursive step is required, this.parse(...) is called. This call will be dispatched to the first trait in the linearization. Conclusion This approach provides easy composition of language features. It allows instructors to structure a weekly assignment with a high amount of freedom. Since interpreters are separated by features rather than by course sched- ule, the maintainability of multiple interpreters is greatly improved. One disadvantage of this approach is the verbosity of the trait mixin classes for each week. However, the impact of this verbosity on the overall maintainability is very low. Another disadvantage is that language features can only be composed if the types of their ASTs, parsers and interpreters are compatible. For example, due to the introduction of mutation, the method signature of the interpreter changes. This mismatch in method signatures makes it impossible to create a trait mixin with other interpreters. The overall problem of extensibility is also known as the expression problem [9, 16]. Solutions to this problem involve trait extensions of a base class which processes one expression at a time. Our solution differs in the sense that one processor can handle multiple expressions. There is no guarantee that a certain expression is processed by a composition of traits of sub-processors. This type safety is not a problem for us since we have a known set of expressions to be processed. We make use of super calls to delegate processors while we manually make sure every expression is processed by at least one mixed in trait. 8. Conclusion In this paper we have discussed how, through leveraging the Scala programming language and the WebLab online learning management system to automatically run specification tests on the students submissions, we have developed a scalable solution for running a course on concepts of programming languages using definitional interpreters. Scala has proven to be a convenient language for this purpose. It supports a functional style of programming with algebraic data types and pattern matching, which is suitable for implementation of big-step interpreters. At the same time it provides a well developed programming language and ecosystem allowing us to develop the course as a collection of reusable components. This includes a malleable unit testing framework that could be used to test student tests suites, express an internal DSL for test generation, and develop a product line of interpreters. As part of future work, we are planning to investigate techniques to provide feedback to students on other aspects than functional correctness. This feedback will involve static analysis of the code written by a student. For example check that the solution of the student has methods no longer than a number of lines. References
{"Source-Url": "https://pure.tudelft.nl/portal/files/10179585/scala16main_main24_p_4a5fcc5_29103_preprint.pdf", "len_cl100k_base": 8676, "olmocr-version": "0.1.53", "pdf-total-pages": 11, "total-fallback-pages": 0, "total-input-tokens": 37999, "total-output-tokens": 10555, "length": "2e13", "weborganizer": {"__label__adult": 0.0007028579711914062, "__label__art_design": 0.0007419586181640625, "__label__crime_law": 0.0005006790161132812, "__label__education_jobs": 0.02911376953125, "__label__entertainment": 0.0001722574234008789, "__label__fashion_beauty": 0.0003139972686767578, "__label__finance_business": 0.0003559589385986328, "__label__food_dining": 0.0008335113525390625, "__label__games": 0.0010356903076171875, "__label__hardware": 0.0008344650268554688, "__label__health": 0.0006966590881347656, "__label__history": 0.0004549026489257813, "__label__home_hobbies": 0.00020062923431396484, "__label__industrial": 0.0006871223449707031, "__label__literature": 0.0009527206420898438, "__label__politics": 0.0005478858947753906, "__label__religion": 0.0009484291076660156, "__label__science_tech": 0.01155853271484375, "__label__social_life": 0.0003371238708496094, "__label__software": 0.005279541015625, "__label__software_dev": 0.94140625, "__label__sports_fitness": 0.0005555152893066406, "__label__transportation": 0.001125335693359375, "__label__travel": 0.00043654441833496094}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 44313, 0.0189]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 44313, 0.70005]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 44313, 0.84853]], "google_gemma-3-12b-it_contains_pii": [[0, 873, false], [873, 5044, null], [5044, 10173, null], [10173, 14139, null], [14139, 16996, null], [16996, 23020, null], [23020, 27633, null], [27633, 30144, null], [30144, 34708, null], [34708, 39253, null], [39253, 44313, null]], "google_gemma-3-12b-it_is_public_document": [[0, 873, true], [873, 5044, null], [5044, 10173, null], [10173, 14139, null], [14139, 16996, null], [16996, 23020, null], [23020, 27633, null], [27633, 30144, null], [30144, 34708, null], [34708, 39253, null], [39253, 44313, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 44313, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 44313, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 44313, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 44313, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 44313, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 44313, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 44313, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 44313, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 44313, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 44313, null]], "pdf_page_numbers": [[0, 873, 1], [873, 5044, 2], [5044, 10173, 3], [10173, 14139, 4], [14139, 16996, 5], [16996, 23020, 6], [23020, 27633, 7], [27633, 30144, 8], [30144, 34708, 9], [34708, 39253, 10], [39253, 44313, 11]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 44313, 0.0]]}
olmocr_science_pdfs
2024-12-06
2024-12-06
ab671109c281491281630fce220f29bdd8b2ede3
Mitigating Risk with the CSA 12 Critical Risks for Serverless Applications GIAC (GCED) Gold Certification Author: Mishka McCowan, mmcocwan@eagna.net Advisor: Jonathan Risto Accepted: August 22, 2020 Abstract Since its introduction in 2014, serverless technology has seen significant adoption in businesses of all sizes. This paper will examine a subset of the 12 Most Critical Risks for Serverless Applications from the Cloud Security Alliance and the efficacy of their recommendations in stopping attacks. It will demonstrate practical attacks, measure the effectiveness of the Cloud Security Alliance recommendations in preventing them, and discuss how the recommendations can be applied more broadly. 1. Introduction Since their introduction in 2014 (Amazon Web Services, n.d.), the use of Lambdas, the AWS serverless technology, has become incredibly widespread. In 2018, Gartner predicted that more than 20 percent of global enterprises would deploy serverless technologies by the end of the decade (Gartner, 2018). The monitoring and analytics company Datadog reported in early 2020 that half of their AWS customers had adopted Lambda (Datadog, 2020). They concluded that "serverless functions are now in widespread use across a variety of companies with an infrastructure footprint in AWS." (Datadog, 2020) The security community's efforts to create best practices for securing serverless technologies has trailed the explosive growth in its adoption. In the latter part of 2018, OWASP released a serverless interpretation of their OWASP Top Ten (Open Web Application Security Project, 2018). A list of the top 12 security risks for serverless created by the Cloud Security Alliance (Cloud Security Alliance, 2019) was released shortly after that. The security portion of the Lambda documentation on the AWS site references neither document (Amazon Web Services, n.d.). Even as the security community struggles to define how to best secure serverless, we are using them for security automation. According to the 2019 Cloud Security Survey from SANS, 46.4% of respondents used serverless for automation and orchestration (Shackleford, 2019). This begs the question as to how well the security is securing its own infrastructure. This paper will examine the CSA Top 12 Critical Risks for Serverless Applications as a viable framework for securing serverless applications. A sample of the risks will be tested using practical attacks against a vulnerable application in the AWS cloud. After remediating the vulnerabilities, the application will be retested to measure the efficacy of the CSA recommendations. 2. CSA Top 12 Critical Risks for Serverless Applications A serverless architecture is a model for organizations to run applications without having to manage the underlying infrastructure. In this model, the cloud provider is responsible for dynamically allocating computing resources for code when it executes. Typically, the code takes the form of a function and is running inside stateless containers. Hence, this model is also referred to as Function-as-a-Service or FaaS. The serverless model is attractive to both developers and enterprises. It allows developers to focus on building and maintaining their applications without having to worry about managing the infrastructure because that is the responsibility of the cloud provider. Enterprises are attracted to the serverless model because of the potential for cost savings. Instead of paying an hourly fee for each server supporting the application, serverless functions typically incur a cost when they execute. This eliminates the need to pay for idle servers. However, this model is not without its drawbacks. For example, an attacker may invoke a serverless application many times over a long period with the intent of inflating the target organization's monthly bill and inflicting financial loss. The Top 12 Critical Risks for Serverless Applications is an effort to define security best practices for serverless applications. Developed by the Cloud Security Alliance (CSA), the Critical Risks came out of a recognition that this new paradigm introduces a different set of security issues. The size and complexity of the attack surface for these types of applications are more extensive than they are for "traditional" applications. At the same time, the current crop of automated scanning tools has not adapted to examining serverless applications (Cloud Security Alliance, 2019). The CSA Critical Risks were released in 2019 to aid and educate "organizations seeking to adopt the serverless architecture model" (Cloud Security Alliance, 2019). They are patterned after work done by the Open Web Application Security Project (OWASP) with their Top Ten Web Application Security Risks. In 2017, OWASP released an "Interpretation for Serverless" of their Top Ten to serve as a "first glance to the serverless security world and will serve as a baseline to the official OWASP Top 10 in Serverless project" (OWASP, 2018). The CSA Critical Risks references the OWASP Top Ten and has a mapping to it. Mishka McCowan, mmccowan@eagna.net The CSA Critical Risks was chosen as the reference for this paper over the OWASP interpretation for two reasons. First, it is more recent. The serverless world is evolving quickly, so the CSA Critical Risks represent the most current thinking by the security community. Second, the language used to convey the risks is very specific to serverless. This specificity is useful in illustrating both the vulnerabilities and the associated remediation. There are many cloud providers with serverless or Function-as-a-Service offerings. Amazon, Microsoft, Google, IBM, Oracle, and others include serverless as part of their portfolio. This paper will focus on the serverless offering from Amazon Web Services (AWS) because they are a market leader and a pioneer of serverless with their release of Lambda functions in 2014. While the examples will be specific to AWS, the concepts are applicable, regardless of vendor. To examine the efficacy of the Critical Risks in stopping attacks, this paper will demonstrate practical attacks, measure the effectiveness of the CSA recommendations in preventing them, and discuss how they can be applied more broadly. The demonstrations will use a tool called Serverless Goat, a serverless application maintained by OWASP for demonstrating common serverless security flaws (Open Web Application Security Project 2019). After each demonstration, a technique will be put in place to address the flaw. Rerunning the attack will gauge the effectiveness of the mitigation. There will then be a discussion of other types of mitigations for each class of vulnerability. Three of the Critical Risks will be tested as a representative sample of the entire list. 3. Mitigating the Risks The CSA has marked each of the Critical Risks with a unique identifier in the form of SAS-[NUMBER]. For ease of reference, the number will be used for each of the risks in this section. 3.1 SAS-1: Function Event-Data Injection Injection attacks are a staple of application security. OWASP has highlighted this type of attack as one of its top 10 application security risks since its initial release in 2003. Mishka McCowan, mmccowan@eagna.net (Heinrich, n.d.). It appears on the Top 10 Secure Coding Practices from Carnegie Mellon University's Software Engineering Institute's CERT Division (Carnegie Mellon University Software Engineering Institute). The CWE Top 25 Most Dangerous Software Errors published by MITRE lists three different variants (MITRE, 2019). However, despite all of this, injection errors still make up 6% of the public vulnerabilities published on MITRE's Common Vulnerabilities and Exposures list (MITRE, n.d.). Like web applications, serverless applications are vulnerable to injection attacks. Unlike web applications, the surface area for attacks against serverless applications is much larger. They can be triggered by events from user input, message queues, cloud storage, databases, and other serverless functions. Defenders must consider not only direct attacks, but also more complicated ones in which data placed into a queue or data store may contain a malicious payload to be consumed by the serverless application. To add to the degree of difficulty, the input provided by these events can be provided in different formats, depending on their source. 3.1.1 Example: Command Injection The Serverless Goat is a simple application that takes a Microsoft Word document as an input, parses it, and displays the text of the document for the user. There is a default value for a Word document hosted by one of the project supporters that can be used for testing. Pressing the "Submit" button with the default value will return the text of a William Blake poem. The first step for any attacker is to start probing for vulnerabilities. In the case of the Serverless Goat, testing for injection vulnerabilities begins by adding different special characters to the end of the url for the Word document. When a semi-colon is added, the following error message is displayed: ``` Error: Command failed: ./bin/curl --silent -L https://www.puresec.io/hubfs/document.doc; | /lib64/ld-linux-x86-64.so.2 ./bin/catdoc - /bin/sh: -c: line 0: syntax error near unexpected token `|' /bin/sh: -c: line 0: `./bin/curl --silent -L https://www.puresec.io/hubfs/document.doc; | /lib64/ld-linux-x86-64.so.2 ./bin/catdoc -' ``` at checkExecSyncError (child_process.js:630:11) at Object.execSync (child_process.js:666:15) Mishka McCowan, mmccowan@eagna.net The bolded portion of the error message reveals two critical pieces of information. First, the application uses curl to download the Word document. Second, the error message "syntax error near unexpected token `|" indicates that the output is piped from the curl utility into something else. These two things indicate that the application is passing commands to the operating system for execution. The next step is to try to exploit the possible command injection vulnerability by changing parameters in the URL. A simple test is to add an operating system command to the end of the URL. Updating the URL to "https://www.puresec.io/hubfs/document.doc; ls;#" results in random characters surrounding the text of the poem. At the very bottom of the output is a list of files. Changing the URL to refer to a non-existent document will ensure that the listing is not part of the document's metadata: "http://not-a-domain/bad.doc; ls;#". The new URL returned the same list of files (line breaks added for clarity), as follows: ``` bin index.js lib node_modules package.json package-lock.json ``` The listing shows directories and files on the filesystem for the application's deployment directory. Another change to the URL displays the source code for the Lambda function that is processing the files: "http://not-a-domain/bad.doc; cat index.js;#". For the full text of the Lambda, please refer to Appendix A. The source code reveals how the application is constructed. It is written in NodeJS, stores the URL in a DynamoDB table each time it is called, and an S3 bucket with public-read permissions stores the results. The source code also reveals the root cause for the vulnerability: untrusted user input. The URL is used without sanitizing it first. Mishka McCowan, mmccowan@eagna.net 3.1.2 Remediation: Command Injection There are multiple methods for correcting command injection vulnerabilities, including input validation, whitelisting, escaping OS commands, parameterization, and removing direct calls to OS commands. The OWASP Command Injection Defense Cheat Sheet recommends using multiple methods to provide for a layered defense (Open Web Application Security Project, n.d.). For this demonstration, whitelisting will be used as a simple method to address this vulnerability. The whitelist will consist of the letters A through Z, numbers, and the special characters required to make a valid URL – the colon, period, and forward slash. Removing the ability to use special characters such as a semi-colon or pound sign severely restricts how a would-be attacker can manipulate the OS command to fetch the document. The first line below is the original assignment of the URL entered by the end-user to a variable for processing. The second line uses the replace function to restrict the characters in the URL to the list described above. Any other characters are removed. ```javascript let documentUrl = event.queryStringParameters.document_url; let documentUrl = (event.queryStringParameters.document_url) .replace(/[^0-9a-zA-Z.:/\]/g,""); ``` Once the change has been made, and the code is deployed, the original commands were rerun. The section below shows each command, the original result, and the result after inserting the whitelisting. - **https://www.puresec.io/hubfs/document.doc** - Original Result – The William Blake poem is displayed - Whitelisted Result – The William Blake poem is displayed - Notes – A valid request continues to return the parsed text - **https://www.puresec.io/hubfs/document.doc;** - Original Result – An error message from the operating system - Whitelisted Result – The William Blake poem is displayed - Notes – The semi-colon is removed because the character is not in the whitelist. The result is that the URL for the document is valid and is processed without error • https://www.puresec.io/hubfs/document.doc; ls;# o Original Result – The William Black poem is display surrounded by random characters and a file system listing o Whitelisted Result – A 404 error o Notes – The semi-colon, pound sign, and spaces are removed, resulting in an invalid URL, https://www.puresec.io/hubfs/document.docls. When called, this URL will return the 404 message provided the server • http://not-a-domain/bad.doc; ls;# o Original Result – A file system listing o Whitelisted Result – A zero (0) is displayed o Notes – There was no server to return a 404 error. The –silent parameter in the curl statement suppresses curl's return code, so no information is passed to into catdoc. The zero is the return code from catdoc, indicating the operation completed. The results show that whitelisting was effective in stopping the command injection. The attempts were either ignored by the system or returned a 404 Page Not Found error. The junk characters in the last test case are the result of curl's inability to resolve the domain with the –silent parameter, so it can be considered an implicit 404 error. Note that the code changes, while effective for this demonstration, are not production-ready. It blocks characters that could legitimately be a part of a URL such as question marks and ampersands. It also does not take into account character encodings such as Unicode or HTML encodings, both of which could potentially circumvent the whitelist's protection. To address this issue, OWASP has a repository of regular expressions for validation on their site at https://owasp.org/www-community/OWASP_Validation_Regex_Repository. The repository includes a regular expression for URL validation. Organizations can use this regular expression as a starting point for creating a validation that meets their requirements. The OWASP regular expression will require customization because it is written to accept URLs for a variety of protocols such as gopher, telnet, and nntp. Good security practice dictates removing any unnecessary protocols. This demonstration highlights a common misconception with serverless, which is that the cloud provider manages the underlying infrastructure and operating system, so attacks against them are the cloud provider's responsibility. Conversely, the customer must harden both the application and the infrastructure configuration. The other danger shown in this demonstration is how untrusted input can come to reside on the trusted network. The Serverless Goat application parses the text of a Word document and saves it into an S3 bucket. It also stores the URL submitted by the user into a DynamoDB table. Neither piece of data was subject to any security checks. While the current incarnation of the application makes use of this data, nothing is preventing a future version from adding additional lambdas that do. Those lambdas need to check and sanitize the input even though it is not directly from the user, but from another source within the application. 3.2 SAS-3: Insecure Serverless Deployment Configuration Cloud services offer a plethora of configuration settings that allow their customers to tailor their environments to their specific needs. Some of those settings have profound security implications for applications deployed in those environments. In the 2020 Verizon Data Breach Report, misconfiguration was cited as the fourth most common error leading to breaches, up four spots from 2015 (Verizon, 2020). According to the report, errors such as misconfigurations "are now equally as common as Social breaches and more common than Malware, and are truly ubiquitous across all industries (Verizon, 2020)" 3.2.1 Example: Insecure Configuration One of the most common areas for misconfiguration errors is cloud storage. One high profile example was the 2019 Capital One data breach that compromised the personal data of 100 million credit card customers and applicants (SC Media, 2019). In that case, the root cause was a misconfigured Web Application Firewall, manipulated into giving access to information stored in S3 buckets stored within Capital One's AWS Mishka McCowan, mmccowan@eagna.net infrastructure. The Serverless Goat also has flaws that allow access to information stored in an S3 bucket. When the Serverless Goat finishes extracting the text from a Word document, it stores the result in an S3 bucket. That bucket is configured to host web content, and the objects it contains have been given read permissions for all users. As a result, the contents of any of the files are available to anyone with the URL. At first glance, accessing the URL for each file would seem to be a tall order. An attacker would need to know both the bucket name and the name of the file. While the bucket name would be simple to discover, the files' names are random UUIDs generated by the application. They are not predictable and would take a considerable amount of time to brute force. A list of all of the files in the bucket would be required for the attack to be practical. The Serverless Goat's configuration allows even a minimally-skilled attacker to generate a list of files for the bucket. The Access Control List for the bucket grants the List Objects permission to the Everyone group, allowing anyone to list the bucket's contents. The steps for doing so require no skills beyond being able to copy and paste the text. It takes just three steps for an attacker to view the bucket's contents. 1. Log any the AWS Console. It does not matter what account is used so long as the user is authenticated. 2. Append the bucket name to the end of the following URL: 3. Paste the new URL into a different tab in the same browser. A list of the files will be displayed. The attacker could then view the contents of individual files or download them in bulk. Logging is disabled on that bucket, so there would be no evidence of data being viewed or exfiltrated. ### 3.2.2 Remediation: Insecure Configuration Two simple changes can be made to the application to secure the S3 bucket used to store the extracted text. The first is by far the simplest – remove the List Objects permission from the Everyone group in the Permission section. Once that permission has been removed, viewing the bucket from another account results in an Access Denied error. However, viewing the contents of an individual file is still possible. Appending a forward slash and a file name to the end of the URL will display the file. Removing the List permission only stops others from listing the contents of the bucket. It does not block access to viewing or downloading them if the names of the bucket and file are known. The next step is to disable public access to the bucket by disabling web hosting. On the bucket properties page, click on the "Static website hosting" setting, click the "Disable website hosting" option, and click Save. Additionally, the AWS "Block public access" setting should also be enabled to help ensure that public access is not enabled accidentally through a bucket policy or ACL. The setting is on the permissions page. Click the Edit button, put a check next to "Block all public access," and click the Save button. A prompt appears to confirm this choice. Once completed, public access will be disabled. The application, however, will be broken after blocking public access. Attempting to submit a file for processing will result in an Access Denied error. The Lambda function explicitly sets the permissions on the file to public, read-only access. To set the correct permission, change line 41 from "ACL: 'public-read'" to "ACL: 'private'." After updating the Lambda and submitting a file for processing, a new error is displayed. The existing code relies on the bucket to host the content as a web server. When it tries to redirect the user to the bucket, it fails because web hosting has been disabled. To share content securely from an S3 bucket, AWS has a feature called a pre-signed URL that will grant time-limited permission to download an object. The bucket does not have to be public, nor does it have to be configured to serve static web content. Instead, the URL is signed using the credentials the Lambda function uses to access the S3 bucket. During the creation process, the length of time for which the URL is valid is specified. Anyone who receives the pre-signed URL can then access the object. When the URL expires, it will no longer retrieve the content, and a new one must be generated to reaccess the object. Modifying the Lambda function to create a pre-signed URL requires three changes to the code – adding a module, a block of code to generate the URL, and Mishka McCowan, mmccowan@eagna.net modifying the return statement to redirect the user to the pre-signed URL. Adding the module requires a single line of code. ```javascript const s3 = new AWS.S3({signatureVersion: 'v4'}); The following code is added after the s3.putObject block in the exports.handler method. In this example, the expiration for the URL has been set to 30 seconds to facilitate testing. In a real application, the timeout would be a value that strikes a balance between security and business needs. ```javascript const url = s3.getSignedUrl('getObject', { Bucket: process.env.BUCKET_NAME, Key: key, Expires: 30 }); ``` The final change is to update the existing redirect to use the variable that holds the pre-signed URL. ``` "Location": `${url}` ``` Once these changes are made to the Lambda, the application functions normally again. Submitting the test Word document returns the poem. While anyone with the URL can still access the file, its lifetime is limited to a short window of time. 3.2.3 Final Thoughts: Insecure Configuration Insecure configurations for data stores is a severe and widespread security problem. Cloud infrastructure providers such as AWS provide many tools for addressing these issues. Additional steps could also be taken to secure the data in the S3 bucket. For instance, adding authentication using Cognito would ensure that the intended recipient could only use the URL. Other examples of additional security controls include configuring the S3 data lifecycle to enforce data retention policies and moving the data to DynamoDB, where it could be encrypted. Insecure configuration vulnerabilities are not restricted to data stores. It encompasses any of the infrastructure used by the application. For instance, the network is another area where misconfigurations are common. Overly permissive security groups, public IP addresses assigned to resources that should be private, and a lack of network segregation are common mistakes. Mishka McCowan, mmccowan@eagna.net © 2020 The SANS Institute Author retains full rights. 3.3 SAS-4: Over-Privileged Function Permissions and Roles The description of this vulnerability in the official CSA documentation is a single sentence: "A serverless function should have only the privileges essential to performing its intended logic - a principle known as 'least privilege'" (Cloud Security Alliance, 2019). This vulnerability exists because, in the infrastructure-as-code world, permissions are simple for developers to assign but can be difficult to monitor at scale. 3.3.1 Example: Over-Privileged Function Permissions and Roles Once again, the Serverless Goat will be used to demonstrate the vulnerability and its remediation. The source code for the processing Lambda retrieved via command injection in Section 3.1.1 showed the request's information is logged to a DynamoDB table. The name of that table is not hard-coded into the source code. Command injection can be used to retrieve the table name using the env command. http://not-a-domain/bad.doc; env|grep TABLE_NAME;# TABLE_NAME=serverlessrepo-serverless-goat-Table-Q21W29UK6B7N With the table name revealed, the application can be probed with different commands to see what permissions it has with the database. NodeJS code will be appended to the document request. The first command will try to read data from the table and display it as part of the results. https://; node -e 'const AWS = require("aws-sdk"); (async () => { console.log(await new AWS.DynamoDB.DocumentClient().scan({TableName: "serverlessrepo-serverless-goat-Table-Q21W29UK6B7N"}).promise());})();' The above command uses the node command to execute the NodeJS code. The code creates a DocumentDB client and tries to read the data in the serverlessrepo-serverless-goat-Table-Q21W29UK6B7N table. If successful, the data will be outputted to the console and displayed on the web page. Here is an excerpt of what is returned: ```json { id: '2b41b5a0-654c-49fd-a88c-c298d017568e', ip: '108.18.232.37' }, { document_url: 'https://; env | grep table;', id: '2445c30c-8f78-46a4-8a14-03c0c499c47d', ip: '108.18.232.37' } ``` Mishka McCowan, mmccowan@eagna.net The command was successful. All of the records in the DynamoDB table were displayed on-screen. The application has permissions to read as well as write to DynamoDB. The next command will test if arbitrary data can be written to the table. ```javascript https://; node -e 'const AWS = require("aws-sdk"); (async () => {console.log(await new AWS.DynamoDB.DocumentClient().put({TableName: "serverlessrepo-serverless-goat-Table- Q21W29UK6B7N",Item:{"id":"this","document_url":"is","ip":"bad"}}).promise()));})(); ``` When the string above is entered into the Serverless Goat, only two brackets are returned: `{ }`. To see if the insert was successful, the command from the previous example must be rerun. The following now appears in the output: ``` { id: 'this', document_url: 'is', ip: 'bad' } ``` The record was successfully inserted into the DynamoDB table. It is expected that the application has permission to write to the database because it is part of the design. The vulnerability is that users are able to add separate records containing arbitrary values. The final step is to see if data can be deleted from the table as well. This example will delete the record created in the previous example. The command is as follows: ```javascript https://; node -e 'const AWS = require("aws-sdk"); (async () => {console.log(await new AWS.DynamoDB.DocumentClient().delete({TableName: "serverlessrepo-serverless-goat-Table- Q21W29UK6B7N",Key:{"id":"this"}}).promise());})(); ``` This command also returns two empty brackets. The success of this command can be verified by running the code from the first example in this section. ``` https://; node -e 'const AWS = require("aws-sdk"); (async () => {console.log(await new AWS.DynamoDB.DocumentClient().scan({TableName: "serverlessrepo-serverless-goat-Table-Q21W29UK6B7N"}).promise());})(); ``` No records are returned. The delete command was successful. The application is vulnerable to unauthorized reads, writes, and deletes. There may be additional vulnerabilities, but this list is sufficient to demonstrate how it works. ### 3.3.2 Remediation: Over-Privileged Function Permissions and Roles The root cause of this vulnerability is the permissions assigned to the role used by the Lambda function. If the developer granted the permissions according to the concept of least privilege, only the dynamodb:PutItem permission would be assigned. However, the Serverless Goat developers chose to grant the following, more expansive set of permissions. ``` { "Statement": [ { "Action": [ "dynamodb:GetItem", "dynamodb:DeleteItem", "dynamodb:PutItem", "dynamodb:Scan", "dynamodb:Query", "dynamodb:UpdateItem", "dynamodb:BatchWriteItem", "dynamodb:BatchGetItem", "dynamodb:DescribeTable", "dynamodb:ConditionCheckItem" ], "Resource": [ "arn:aws:dynamodb:us-west-2:112033489311:table/serverlessrepo-serverless-goat-Table-Q21W29UK6B7N", "arn:aws:dynamodb:us-west-2:112033489311:table/serverlessrepo-serverless-goat-Table-Q21W29UK6B7N/index/*" ], "Effect": "Allow" } ] } ``` These permissions allow the role to create, update, delete, and query information in the table. The least privileged version of this policy that still allows the application to function as designed would contain only the PutItem permission. ``` { "Statement": [ { "Action": [ "dynamodb:PutItem" ], "Resource": [ "arn:aws:dynamodb:us-west-2:112033489311:table/serverlessrepo-serverless-goat-Table-Q21W29UK6B7N", "arn:aws:dynamodb:us-west-2:112033489311:table/serverlessrepo-serverless-goat-Table-Q21W29UK6B7N/index/*" ], "Effect": "Allow" } ] } ``` Mishka McCowan, mmccowan@eagna.net Updating the policy and running the tests from the previous section yielded the following results: <table> <thead> <tr> <th>Test</th> <th>Result</th> <th>Notes</th> </tr> </thead> <tbody> <tr> <td>Default Word document.</td> <td>Succeeded</td> <td>The poem was displayed. Application functions normally</td> </tr> <tr> <td>Display records</td> <td>Failed</td> <td>No information returned. CloudWatch logs show access was denied.</td> </tr> <tr> <td>Create record</td> <td>Succeeded</td> <td>User can still create records with arbitrary values</td> </tr> <tr> <td>Delete record</td> <td>Failed</td> <td>The record was not deleted. CloudWatch logs show access was denied.</td> </tr> </tbody> </table> After the update, the application continued to function normally. Attempts to gain unauthorized read access and delete access both failed. However, the unauthorized creation of a new record succeeded. The fault lies not with the assigned permissions, but with other vulnerabilities in the application. When the OS command injection remediation from Section 3.1.2 is applied, attempts to create unauthorized records fail as well. 4. Testing Summary The results from the tests can be summarized as follows: 1. **Injection Flaws** – Implementing a whitelist cut stopped command injection attempts. The change will affect users whose documents have forbidden characters in their names. The change also made exploiting the insecure configuration and over-privileged function flaws significantly more difficult. 2. **Insecure Configuration** – Eliminating public access to the S3 bucket and implementing signed URLs restricts access to the data. Minor code changes were required. The expiring URLs would impact end-users who seek to bookmark the data to view it later. 3. **Over-Privileged Functions** – Removing unneeded permissions prevents attackers from exfiltrating or manipulating data stored in DynamoDB. No coding changes were required, and the application continued to function as designed. 5. Remaining Risks This paper addressed only a quarter of the twelve vulnerabilities on the CSA list. Based on the results of the three vulnerabilities tested in this paper, it is possible to make conclusions about the rest of the list. The first conclusion is that the existing best practices also apply to serverless architectures. The three vulnerabilities examined here map directly to three entries on the OWASP Top Ten list – Injection, Broken Access Control, and Security Misconfiguration. Most of the remaining nine vulnerabilities also map to the OWASP Top Ten list. The two that do not have a direct OWASP analog are SAS-11: Obsolete Functions, Cloud Resources, and Event Triggers, and SAS-12: Cross-Execution Data Persistency. Addressing OWASP Top Ten vulnerabilities has been shown to be an effective method of reducing security risk in a web application. Organizations and individuals with expertise in addressing the OWASP vulnerabilities can apply that knowledge to serverless architectures. It would make an excellent starting point while ramping up on vulnerabilities that are specific to serverless. The second conclusion is that a foundational element of serverless security is a detailed understanding of the vendor's services and tools. In two of the three vulnerabilities examined in this paper, knowledge of the AWS IAM roles and permissions was pivotal in remediating them. The same is true for the remaining nine. For example, SAS-7: Insecure Application Secrets Storage relies on the proper configuration of AWS Key Management Service, Secrets Manager, or other similar services for managing secrets within the infrastructure. An understanding of the lifecycle of cloud resources is key to addressing SAS-11: Obsolete Functions, Cloud Resources, and Event Triggers. The last conclusion is that the learning curve for serverless security will vary depending on an organization's experience with the other types of architectures. For instance, an organization moving from a monolithic architecture will likely face more of Mishka McCowan, mmccowan@eagna.net a learning curve than one using microservices. Microservices have a great deal in common with serverless architectures, so the security problem space is similar. Monolithic applications require a much higher learning curve because they are so dissimilar to serverless and microservices. 6. Conclusion The CSA recommendations for remediating the Top 12 critical vulnerabilities proved effective in testing. In all three test cases, the vulnerability was either eliminated or significantly reduced. This demonstrated that the CSA recommendations are a practical framework for locating and remediating common vulnerabilities in serverless architectures. The fully remediated Lambda function can be found in Appendix B. The CSA recommendations have their roots in the OWASP Top Ten vulnerabilities. Organizations can leverage their familiarity with the OWASP material to flatten the learning curve for using the CSA recommendations. Security professionals should become familiar with the services offered by the cloud vendor, as well as the CSA vulnerabilities that are specific to the cloud. Organizations that are embracing serverless architectures should embrace the CSA Top 12 Critical Vulnerabilities in the same way they embraced the OWASP Top Ten. References Mishka McCowan, mmccowan@eagna.net Mishka McCowan, mmccowan@eagna.net Appendix A: Serverless Goat Lambda Source Code ```javascript const child_process = require('child_process'); const AWS = require('aws-sdk'); const uuid = require('node-uuid'); async function log(event) { const docClient = new AWS.DynamoDB.DocumentClient(); let requestid = event.requestContext.requestId; let ip = event.requestContext.identity.sourceIp; let documentUrl = event.queryStringParameters.document_url; await docClient.put({ TableName: process.env.TABLE_NAME, Item: { 'id': requestid, 'ip': ip, 'document_url': documentUrl } }).promise(); } exports.handler = async (event) => { try { await log(event); let documentUrl = event.queryStringParameters.document_url; let txt = child_process.execSync(`./bin/curl --silent -L ${documentUrl} | /lib64/ld-linux-x86-64.so.2 ./bin/catdoc -`).toString(); // Lambda response max size is 6MB. The workaround is to upload result to S3 and redirect user to the file. let key = uuid.v4(); let s3 = new AWS.S3(); await s3.putObject({ Bucket: process.env.BUCKET_NAME, Key: key, Body: txt, ContentType: 'text/html', ACL: 'public-read' }).promise(); return { statusCode: 302, headers: { "Location": `${process.env.BUCKET_URL}/${key}` } }; } catch (err) { return { statusCode: 500, body: err.stack }; } }; ``` Mishka McCowan, mmccowan@eagna.net Appendix B: Updated Serverless Goat Lambda Source Code ```javascript const child_process = require('child_process'); const AWS = require('aws-sdk'); const uuid = require('node-uuid'); const s3 = new AWS.S3({signatureVersion: 'v4'}); async function log(event) { const docClient = new AWS.DynamoDB.DocumentClient(); let requestid = event.requestContext.requestId; let ip = event.requestContext.identity.sourceIp; let documentUrl = (event.queryStringParameters.document_url).replace(/[^0-9a-zA-Z.:/\]/g, ""); await docClient.put({ TableName: process.env.TABLE_NAME, Item: { 'id': requestid, 'ip': ip, 'document_url': documentUrl } }).promise(); } exports.handler = async (event) => { try { await log(event); let documentUrl = (event.queryStringParameters.document_url).replace(/[^0-9a-zA-Z.:/\]/g, "); let txt = child_process.execSync(`./bin/curl --silent -L ${documentUrl} | /lib64/ld-linux-x86-64.so.2 ./bin/catdoc -`).toString(); // Lambda response max size is 6MB. The workaround is to upload result to S3 and redirect user to the file. let key = uuid.v4(); let s3 = new AWS.S3(); await s3.putObject({ Bucket: process.env.BUCKET_NAME, Key: key, Body: txt, ContentType: 'text/html', ACL: 'private' }).promise(); //creates signed url that is returned to client side const url = s3.getSignedUrl('getObject', { Bucket: process.env.BUCKET_NAME, Key: key }); } catch (err) { // handle errors } } ``` Mishka McCowan, mmccowan@eagna.net Key: key, Expires: 30 }); return { statusCode: 302, headers: { "Location": `${url}` } }; try { } catch (err) { return { statusCode: 500, body: err.stack } } };
{"Source-Url": "https://www.sans.org/reading-room/whitepapers/cloud/mitigating-risk-csa-12-critical-risks-serverless-applications-39845", "len_cl100k_base": 8487, "olmocr-version": "0.1.48", "pdf-total-pages": 24, "total-fallback-pages": 0, "total-input-tokens": 49076, "total-output-tokens": 10792, "length": "2e13", "weborganizer": {"__label__adult": 0.0004978179931640625, "__label__art_design": 0.0005726814270019531, "__label__crime_law": 0.0032253265380859375, "__label__education_jobs": 0.00104522705078125, "__label__entertainment": 0.0001885890960693359, "__label__fashion_beauty": 0.00021708011627197263, "__label__finance_business": 0.001739501953125, "__label__food_dining": 0.00035071372985839844, "__label__games": 0.0009560585021972656, "__label__hardware": 0.003879547119140625, "__label__health": 0.0006837844848632812, "__label__history": 0.00033664703369140625, "__label__home_hobbies": 0.0001589059829711914, "__label__industrial": 0.0009360313415527344, "__label__literature": 0.0003383159637451172, "__label__politics": 0.0005230903625488281, "__label__religion": 0.00040793418884277344, "__label__science_tech": 0.2900390625, "__label__social_life": 0.0001558065414428711, "__label__software": 0.07391357421875, "__label__software_dev": 0.61865234375, "__label__sports_fitness": 0.0002593994140625, "__label__transportation": 0.0005860328674316406, "__label__travel": 0.00018334388732910156}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 42556, 0.02062]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 42556, 0.35945]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 42556, 0.86426]], "google_gemma-3-12b-it_contains_pii": [[0, 0, null], [0, 710, false], [710, 2623, null], [2623, 5123, null], [5123, 7246, null], [7246, 9607, null], [9607, 11398, null], [11398, 13447, null], [13447, 15408, null], [15408, 17635, null], [17635, 19755, null], [19755, 22228, null], [22228, 24279, null], [24279, 26475, null], [26475, 28882, null], [28882, 30490, null], [30490, 32385, null], [32385, 34558, null], [34558, 35813, null], [35813, 37535, null], [37535, 39185, null], [39185, 40801, null], [40801, 42373, null], [42373, 42556, null]], "google_gemma-3-12b-it_is_public_document": [[0, 0, null], [0, 710, true], [710, 2623, null], [2623, 5123, null], [5123, 7246, null], [7246, 9607, null], [9607, 11398, null], [11398, 13447, null], [13447, 15408, null], [15408, 17635, null], [17635, 19755, null], [19755, 22228, null], [22228, 24279, null], [24279, 26475, null], [26475, 28882, null], [28882, 30490, null], [30490, 32385, null], [32385, 34558, null], [34558, 35813, null], [35813, 37535, null], [37535, 39185, null], [39185, 40801, null], [40801, 42373, null], [42373, 42556, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 42556, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 42556, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 42556, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 42556, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 42556, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 42556, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 42556, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 42556, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 42556, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 42556, null]], "pdf_page_numbers": [[0, 0, 1], [0, 710, 2], [710, 2623, 3], [2623, 5123, 4], [5123, 7246, 5], [7246, 9607, 6], [9607, 11398, 7], [11398, 13447, 8], [13447, 15408, 9], [15408, 17635, 10], [17635, 19755, 11], [19755, 22228, 12], [22228, 24279, 13], [24279, 26475, 14], [26475, 28882, 15], [28882, 30490, 16], [30490, 32385, 17], [32385, 34558, 18], [34558, 35813, 19], [35813, 37535, 20], [37535, 39185, 21], [39185, 40801, 22], [40801, 42373, 23], [42373, 42556, 24]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 42556, 0.01579]]}
olmocr_science_pdfs
2024-11-25
2024-11-25
43774eebdc983ec2a8840951b37b70923b542490
Almost all software testing is futile! Mike Holcombe and Florentin Ipate. Formal Methods and Software Engineering Research Group (FORMSOFT), Department of Computer Science, University of Sheffield, Regent Court, 211, Portobello Street, Sheffield, S1 4DP, UK. Abstract. All software systems are subject to testing - for some of them testing is the major activity in the project. Testing, however, rarely gets the attention it deserves from researchers and developers, partly because its foundations are very weak and ill-understood. The principal purpose of testing is to detect (and then remove) faults in a software system. A number of techniques for carrying out testing, and in particular, for the generation of test sets exist. Many sophisticated (and expensive) tools are available on the market and many look to these to provide a solution to the problems of building fault-free systems. We consider the problem of fault detection and note that few, if any, of the existing methods really address the real issues. In particular no methods allow us to make any statement about the type or precise number of faults that remain undetected after testing is completed. Thus we cannot really measure the effectiveness of our testing activities in any rigorous way. However, by considering testing from a straightforward, theoretical point of view we demonstrate that a new method for generating test cases can provide a more convincing approach to the problem of detecting ALL faults and allows us to make sensible claims about the level and type of faults remaining after the testing process is complete. Key words: Testing, faults, testability, test coverage, finite state machine testing, X-machines. Introduction. The purposes of software testing have been discussed in a number of places and we will consider a few of the interesting statements and claims that have been made about testing. Myers [1] states that the purpose of testing is to detect faults and the definition of a good test is one that uncovers faults. The implication clearly being that a test that fails to uncover any existing faults is inadequate in some sense. This emphasis on the finding of faults could lead one to assume that the more faults detected the better the test. However, one could argue that a test that uncovers a single serious fault might well be more successful than a test that uncovered a number of trivial faults. This immediately leads us into the vexed question of what is a “serious fault” and how these might be defined and identified! Dijkstra [2] pours scorn on the whole concept of testing and insists that all a test can tell us is that the system has failed - it cannot tell us that the system is correct. This is true of most of the testing methods currently in use and is clearly a major drawback. Dijkstra’s belief, shared by many in the formal methods community is that formal verification, that is mathematical proofs that the system meets all the conditions required of it, is the only solution.\footnote{One could imagine a similar paper entitled “Almost all formal verification is futile” exploring some of the fallacies and illusions pertaining to that activity!} However, formal verification has not been able to demonstrate that it is “scalable” and practical in the context of the massive complexity of today’s applications. Furthermore, some example systems which have supposedly been formally verified have been shown to have faults as a result of testing! (See [6]) There is a case for hoping that building systems from dependable components will overcome some of these problems and it may be possible that current testing or formal verification methods can be used \textit{together} to provide the foundation for a scientifically based engineering approach to software development. At present, however, there is little sign of this happening. The software engineering industry is spending more and more time on testing in the hope of ensuring quality and yet real scientific evidence that they are being successful is minimal. Object-oriented methods are often held to be a great advance in the pursuit of quality software because of their foundation on the principle of reusability. However, it is pointed out in Binder [3] that, far from obviating the need for so much testing, the object-oriented methods require very substantial amounts of effort devoted to the task. Inheritance and dynamic binding provide many opportunities for introducing faults, the large numbers of interfaces between objects and the loose state control environment also compound the problem. Binder states “\textit{the hoped for reduction in object-oriented testing due to reuse is illusory}”. In fact many new testing issues are raised by this paradigm. As a result the need for testing will undoubtedly grow and the industry will become more and more dependent on the successful pursuit this activity. One could argue that our current testing methods are not based on a firm scientific approach or theory, they tend to be methods that have evolved, informal \textit{ad hoc} approaches that have been rationalised after the event rather than carefully constructed engineering methods based on a defensible well-founded strategy. We test because we need to but we do not demand from testing the sort of rigour that the product demands. Testing must be made more to do with reassuring \textit{clients} and \textit{users} than with reassuring \textit{testers}, \textit{designers} and their \textit{managers}! One of the claims made here and elsewhere, is that this will not be possible unless there is a more integrated approach to the design process; and until the testing methods used satisfy some fundamental requirements dictated by a careful investigation of the nature of software systems. Although it might appear that we are belittling the achievements of software testing as a process this is not the intention. Clearly the application of existing testing methods has resulted in the identification and subsequent removal of many important faults in software systems, however the question remains about what faults are left undetected until the system is in service. It is to try to address this issue that we now turn. \section*{2. Fundamental issues of correct software design.} One of the most successful approaches to scientific understanding is the \textit{reductionist} philosophy. This entails the reduction of one problem to the solution of simpler ones or to the understanding of a lower level, perhaps more microscopic situation. Since the current popular design methods in software engineering tend to emphasise the construction of systems from modules, objects and other simpler components one might hope that a similar reductionist approach to testing might be possible. This is not addressed by the different techniques of unit test and system/integration test or the test management process, it is much more fundamental than that. In such a reductionist approach we would consider a system and produce a testing regime that resulted in the complete reduction of the test problem for the system to one of looking at the test problem for the components or reduced parts. However few testing methods support this view since we would have to be able to make the following statement: “the system $S$ is composed of the parts $P_1, ..., P_n$; as a result of carrying out a testing process on $S$ we can deduce that $S$ is fault-free if each of $P_1, ..., P_n$ are fault free. Here we define fault-free in the natural sense - that is the system completely satisfies the behavioural requirements as detailed in the specification. A prerequisite is that the specification should be available as some formal, mathematical description to ensure that we can actually establish what the requirements are in an unambiguous sense. The exercising of tests on the system $S$ involves the testing of the complete system, its internal and external interfaces as well as the the components $P_i$. A corollary is that the approach could be applied to each component $P_i$ thus enabling the reductionist method to be continued downwards for as far is appropriate and feasible. Ultimately we might end up at a point where the components in question are tried and trusted, having been extensively analysed and used over a number of years and thus to have survived through a process of “natural selection”. 2.1. Fault detection. For this approach to work we need to find some mechanism whereby we can establish that if all the components are free from fault then so is the complete system. This is something that is quite beyond most current testing methods. The claim “the system/component is fault-free” is quite beyond current testing methods. In practise all we can usually say is that we have uncovered a number of faults over a period of testing effort and the graph of the number of faults against the period or amount of testing, measured suitably, indicates that the growth rate is reducing. ![Fig.1 The relationship between fault detection and test time](image-url) The trouble is we do not know that no further faults are in the system at any particular time. Also, in general we cannot assert that the only faults remaining are located in a specific module. or component. A general formula for this curve is not known, if one existed it would probably depend on the type of system, on the type of test methods and perhaps on the people doing and managing the testing as well as wider issues relating to the management of the design project, the attitudes of the clients, the implementation vehicle, the design methods and so on. High quality empirical results obtained over a very long period would be needed to make proper use of this approach even then it is less than ideal. The work of Littlewood and others [17], provides some statistical approaches to the question of software reliability but in some senses it is used as substitute because of the failure of software testing to deliver methods able to provide precise answers to the question “what faults are left?”. 2.2 Test effectiveness. Other approaches to the problem of measuring the effectiveness of an individual testing project usually depend on estimating the coverage of the tests, [1]. For example, if the tests are structurally based, using program charts, say, then popular methods include establishing that every path has been exercised or every decision node has been visited. This does not tell us anything about fault detection, it merely measures effort rather than reward! The current accepted definition of fault coverage is misleading since it is not the case that a precise measure can be placed on the number of faults that remain after the test process has been applied. In most cases the definition of fault coverage is based on assumptions of the type described above, that we are questioning. In much of the literature the estimates of the fault coverage are obtained by running experiments with simple examples involving implementations that have faults seeded in them and counting the numbers of known faults detected by the methods. These empirical results are of curiosity value only. Miller & Paul, [19] provide a theoretical method for establishing fault coverage of a test strategy, however, they assume that the implementation machine has the same number of states as the specification machine. As mentioned before, these approaches tend to provide an assurance for the tester rather than a meaningful indication of the success of the tests. Before we look, briefly, at what progress there has been in addressing some of the theoretical issues of testing we will consider a popular method for the analysis and comparison of the effectiveness of different testing methods. 2.3 Test method effectiveness. A number of authors have sought to compare the effectiveness of, for example, random testing methods with formally based functional testing, e.g., [4]. Here the method was to take a small system and to insert known faults into it, then to apply the two techniques to establish which was most successful at detecting these faults. Further analysis could be done on the type of faults each method was good or poor at detecting. Faults were classified for this purpose in a number of categories. Results from this type of survey can be useful in establishing the relative strengths and weakness of different, specific methods of test set generation. However, the situation is essentially artificial and it is not clear what can be said in general. The method is unable to prove, for example, that either approach is better at detecting naturally occurring or unseeded faults (the seeded ones may not be typical of real faults), or to identify conditions under which a method detects all faults. A number of attempts at developing a theory of testing or to analyse the testing situation have been made. We will briefly consider two of them. 2.4 Probable correctness. Hamlet [5] introduced the idea of “probable correctness”. Essentially, he considered the question of what we can say once a system has “passed” all the tests applied to it. He argued from a simple probabilistic point of view about the way in which a value could be placed on the likelihood of faults remaining in the system. This is an attractive idea that deserves more research. Hamlet’s discussion was based on a number of very restrictive assumptions about the distribution of faults in the system and there is no discussion of the type and seriousness of faults. After all, if the likelihood of any faults remaining was quite small, say $1.0 \times 10^{-5}$, then we may or may not be satisfied but it would be so much more reassuring if we could say that the likelihood of a serious fault was $1.0 \times 10^{-10}$, however we define serious - perhaps we might identify certain safety considerations that must be met and orient our tests towards uncovering faults that cause these to be violated. We may not mind too much if a screen display omitted a full-stop in some text - on the other hand if the display was giving instructions on medical dosage to paramedics a full-stop (decimal point) missing could be disastrous. So the importance of a fault depends on the application and the working environment. Treating all faults as of equal import is an unsatisfactory basis for this type of argument. 2.5. A simple theory of testing. Goodenough and Gerhard [6] introduce an outline theory for testing. They treat a software system as a (partial) function from an input set to an output set and the testing process consists of constructing “revealing domains” that expose faults in this function - in other words they are looking for values for which the specified function and the implemented function differ. This is a very general and abstract approach which provides a useful set of simple concepts and terminology for the discussion of some aspects of testing without giving too many clues as how to construct effective testing strategies. We claim, therefore, that few of the existing testing methods measure up to our demands and the main theoretical attempts are inadequate for the purpose that we explained above - the philosophy of reductionist testing. 3. Testing based on an algebraic approach to computational modelling. The process of software design, including within that activity all phases of requirements capture, specification, design, prototyping, analysis, implementation, validation, verification and maintenance is one that is oriented, or should be, around the construction of computational solutions to specific problems. When we are constructing a software system (this also applies to hardware) we are attempting to construct something that will, when operating, carry out some computable function. Consequently it is worth considering what this means. Essentially, computable functions have been identified as the functions computed by Turing machines. The method will not be applicable to implementations that behave like a Turing machine that does not halt. In other words we will not try to deal with those systems that regress into an infinite loop from which no output emanates, for our purposes these systems will be deemed to be unacceptable anyway. A way to establish that a system is not of this form is to identify a period of time which is the maximum that the system can run for without producing any detectable output. We will also assume that the specification of the system is also of this form, namely a Turing machine that halts under its intended operating conditions. Real-time systems are covered by this definition since we require that the specified system does have detectable behaviour under all conditions. This is a kind of design for test condition that we will see more of later. We then have two algebraic objects, the Turing machine representing the specification of the desired system and the Turing machine representing the complete implementation. A testing method would then try to ascertain if these two machines computed the same function. This is a basic strategy that we will develop, however, not in the context of a Turing machine which is too low level and unwieldy, but in the context of a more useful, elegant and equivalent model. In so doing we will quote some important theoretical results that justify what we are doing. It is important to stress that the method of finite state machine testing proposed by Chow [7], and developed by a number of other authors since, e.g., [8], is based on a similar sort of philosophy, the difference being that they have to make very strong assumptions about the nature of the implementation machine. However, their work did act as an important inspiration for our own. (The IEEE specify finite state machine testing as an important aspect of protocol testing, [18].) 3.1. X-machines. The model we have chosen, both as a basis for theoretical work in the theory of computability and the theory of testing and as a basis for a formal specification language, is the X-machine. Introduced by Eilenberg in 1974, [9], they have received little further study. Holcombe, [10], proposed the model as a possible specification language and since then a number of further investigations have demonstrated that this idea is of great potential value to software engineers. In its essence an X-machine is like a finite state machine but with one important difference. A basic data set, $X$, is identified together with a set of basic processing functions, $\Phi$, which operate on $X$. Each arrow in the finite state machine diagram is then labelled by a function from $\Phi$, the sequences of state transitions in the machine determine the processing of the data set and thus the function computed. The data set $X$ can contain information about the internal memory of a system as well as different sorts of output behaviour so it is possible to model very general systems in a transparent way. It is best to separate the control state of the system from the data state since this allows much more scope for organising the model to ensure a small and manageable state space. This is done easily with this method, the set $X$ is often an array consisting of fields that define internal structures such as registers, stacks, database filestores, input information from various devices, models of screen displays and other output mechanisms. The functions will read inputs, datafiles, internal memory, write to all of these, refresh displays etc.. Consider a simple, abstract example: We haven’t specified $X$ or the functions $f_i$ but this is sufficient to provide a basic idea of the machine. It starts in a given, initial state (control state) and a given state of the system's underlying data type $X$, (the data state), there are a number of paths that can be traced out from that initial state, these paths are labelled by functions $f_1, f_2$ etc. Sequences of functions from this space are thus derived from paths in the state space and these may be composed to produce a function that may be defined on the data state. This is then applied to the value \( x \), providing that the composed function is defined on \( x \). This then gives a new value, \( x' \in X \) for the data state and a new control state. It is best if the machine is deterministic so that at any moment there is only one possible function defined (that is the domains of the functions emerging from a given state are mutually disjoint). From the diagram we note that there is a possible sequence of functions from state 1 to state 6, here a specified terminal state, labelled by the functions \( f_1, f_1, f_2, f_1 \). Assuming that each value is defined this path then transforms an initial value \( x \in X \) into the value \( f_1(f_2(f_1(f_1(x)))) \in X \). So we are assuming that \( x \in \text{domain } f_1; \) \[ f_1(x) \in \text{domain } f_1; \] \[ f_1(f_1(x)) \in \text{domain } f_2; \] and \( f_2(f_1(f_1(x))) \in \text{domain } f_1 \). The computation carried out by this path is thus a transformation of the data space as well as a transformation of the control space. This is a very general model of computing and a Turing machine can easily be represented in this way, see [9]. In fact it is slightly too general and we now consider a natural subclass of these machines. ### 3.2. Stream X-machines and the fundamental theorem of testing. Those X-machines in which the input and the output sets behave as orderly streams of symbols are called stream X-machines and are defined formally in the appendix. The basic idea is that the machine has some internal memory, \( M \), and the stream of inputs determine, depending on the current state of control and the current state of the memory, the next control state, the next memory state and any output value. So if \( \Sigma \) is the set of possible inputs and \( \Gamma \) represents the set of possible outputs we put \[ X = \Gamma^* \times M \times \Sigma^* \] Each processing function \( \phi : \Gamma^* \times M \times \Sigma^* \rightarrow \Gamma^* \times M \times \Sigma^* \) is of the form whereby, given a value of the memory and an input value, \( \phi \) can change the memory value and produce an output value, the input value is then discarded. There is an initial state and all states are terminals. The results that we will discuss are based on this class of machines. They represent a very wide class of systems that can describe all feasible computing systems. We proceed now with some general strategic remarks. The theory of finite state machines includes a result that describes how to test whether two finite state machines are isomorphic. Isomorphism means that they are algebraically similar and if we wish we can convert from one to another by using a “renaming” which respects the algebraic structure of the machines. Under these conditions their behaviour is the same. We can convert an X-machine into a finite state machine by treating the elements of \( \Phi \) as abstract input symbols. We note that in the automaton all states are terminals. We are, in effect, “forgetting” the memory structure and the semantics of the elements of \( \Phi \). If we call this the associated automata of the X-machine we have the following result: Let \( M \) and \( M' \) be two deterministic stream X-machines, \( f \) and \( f' \) the functions computed by them and \( A \) and \( A' \) their associated automata. If \( A \) and \( A' \) accept the same language then \( f = f' \). Proof. See [13]. Now proving that the two functions computed by the two stream $X$-machines, one the specification and the other the implementation, are equal is precisely what we want. If we can do this with a finite test set we will have a very powerful method indeed. This is our aim. To achieve this we need to consider how to prove that the associated automata of two stream $X$-machines accept the same language. Drawing on the techniques used in state machine testing will enable us to progress with this aim. We need some further terminology for stream $X$-machines. A type $\Phi$ is called output-distinguishable if: $$\forall \phi_1, \phi_2 \in \Phi, \exists m \in M, \sigma \in \Sigma \text{ such that } \phi_1(m, \sigma) = (\gamma, m_1) \text{ and } \phi_1(m, \sigma) = (\gamma, m_2) \text{ with } m_1', m_2' \in M, \gamma \in \Gamma, \text{ then } \phi_1 = \phi_2.$$ What this is saying is that we must be able to distinguish between any two different processing functions by examining outputs. If we cannot then we will not be able to tell them apart. So we need to be able to distinguish between any two of the processing functions (the $\phi$’s) for all memory values. A type $\Phi$, is called complete if $\forall \phi \in \Phi$ and $\forall m \in M, \exists \sigma \in \Sigma$ such that $(m, \sigma) \in \text{dom } \phi$. This condition prohibits “dead-ends” in the machine. These two conditions are required of our specification machine, we shall refer to them as design for test conditions. They are quite easily introduced into a specification by simply extending the definitions of suitable $\Phi$ functions and introducing extra output symbols. These will only be used in testing. Now we consider how test sets can be constructed that will show that the two associated automata are isomorphic. Let $V \subseteq \Phi^*$ be a set of input sequences and let $q$ and $q'$ two states in $A$ and $A'$ respectively. Then, $q$ and $q'$ are said to be $V$-equivalent if $\forall v \in V$ then $Aq$ accepts $v$ iff $A'q$ accepts $v$, where $Aq = (\Phi, Q, F, q)$ and $A'q = (\Phi', Q', F', q')$ are the finite state machines obtained from $A$ and $A'$ respectively by considering $q$ and $q'$ as initial states. Thus $q$ and $q'$ are said to be $V$-equivalent if we can always find defined paths labelled by elements from $V$ from both $q$ and $q'$. Two states $q$ and $q'$ are said to be $V$-distinguishable if they are not $V$-equivalent. Thus some $v$ exists in $V$ such that either: - a path labelled $v$ exists from $q$ and no path labelled $v$ exists from $q'$; - or a path labelled $v$ exists from $q'$ and no path labelled $v$ exists from $q$. The following definitions are derived from the work of Chow [7]. Let $A = (\Phi, Q, F, q_o)$ be a minimal finite state machine. Then a set of input sequences $W \subseteq \Phi^*$ is called a characterisation set of $A$ if $W$ can distinguish between any two pairs of states of $A$. Let $A = (\Phi, Q, F, q_o)$ be a finite state machine. Then a set of input sequences $T \subseteq \Phi^*$ is called a transition cover if, for any state $q \in Q$, there is an input sequence $t \in \Phi^*$ which forces the machine $A$ into $q$ from the initial state $q_o$ such that $t \in T$ and $t\phi \in T, \forall \phi \in \Phi$. We can thus construct a set of sequences of elements from $\Phi^*$ that will be the basis for our testing process, a set that will establish whether the two stream $X$-machines compute the same function. However, this is not really very convenient, we really want a set of input sequences from $\Sigma^*$. We thus need to convert sequences from $\Phi^*$ into sequences from $\Sigma^*$. We do this by using a fundamental test function, $t: \Phi^* \rightarrow \Sigma^*$, defined recursively with reference to the specification machine. This is defined in the appendix. Note that the test function is not uniquely determined, many different possible test functions exist and it is up to the designer to construct it. There is an issue of choosing one which is of maximal efficiency which we have yet to investigate. We can now assemble our fundamental result which is the basis for the testing method. The fundamental theorem of testing: Let $M$ and $M'$ be two deterministic stream $X$-machines with $\Phi$ output-distinguishable and complete which compute $f$ and $f'$ respectively and $t: \Phi^* \rightarrow \Sigma^*$ be a fundamental test function of $M$. Let $T$ and $W$ be a transition cover and a characterisation set, respectively, of the associated automaton $A$ of $M$ and put $Z = \Phi^k W \cup \Phi^{k-1} W \cup ... \cup W$. If $A$ and $A'$ are minimal, $\text{card}(Q') - \text{card}(Q) \leq k$ and $f(s) = f'(s) \forall s \in t(TZ)$, then the associated automata $A$ and $A'$ are isomorphic. If the automata are not both minimal we can still establish that the functions the two machines compute are equal. Once all of this mechanism is in place we can apply the fundamental theorem to generate a test set mechanically. Thus we construct explicitly $Z = \Phi^k W \cup \Phi^{k-1} W \cup ... \cup W$ and form the set of input strings $t(TZ)$. This is the test set we are seeking. The value of $k$ is chosen to represent the difference between the known state size of the specification and the (unknown) state size of the implementation. In practice this is not usually large, for especially sensitive applications one can make very pessimistic assumptions about $k$ at the cost of a large test set. We must make the following further assumptions: 1. The specification is a deterministic stream $X$-machine; 2. The set of basic functions $\Phi$ is output-distinguishable and complete; 3. The associated automata of the specification machine is minimal; 4. The implementation is a deterministic stream $X$-machine with the same set of basic functions $\Phi$. Of these assumptions the first three lie within the capability of the designer. An algorithm for ensuring that a stream $X$-machine satisfies condition 2 is given in Ipat& Holcombe [13]. Any stream $X$-machine can be replaced by a machine satisfying condition 2. We refer to these conditions as “design for test” conditions, without them it is going to be difficult to test a system properly, there may be hidden behavioural faults in the implementation which cannot be exposed. The procedures are quite straightforward and intuitive. Condition 3 requires some comment. It is clear that the designer can arrange for the associated automata of the specification $X$-machine to be minimal, standard techniques from finite state machine theory are available. The problem remains with the requirement that the implementation’s associated automata is minimal. Since we do not have an explicit description of the implementation as an $X$-machine we cannot analyse its associated automata to see if it is minimal. We do know, however, that there is a minimal automata with the same behaviour as the automata of the implementation. It is this that will feature in the application of the fundamental theorem. Thus we have a test set that determines whether the behaviour, that is the function computed, by the specification equals the function computed by the implementation - providing that both implementation $X$-machine and the specification $X$-machine have the same basic function set $\Phi$. The The final condition is the most problematical. Establishing that the set of basic functions, Φ, for the implementation is the same as the specification machine’s has to be resolved, however. In practice this will be done with a separate testing process, either an application of the method explained above since the basic processing functions are computable and thus expressible as the computations of other, presumably much simpler, X-machines or by using some other testing method for testing simple functions - perhaps the category-partition method [14] or a variant. If the basic processing functions are **tried and tested** with a long history of successful use - perhaps they are standard procedures, modules or objects from a library - then their individual testing could perhaps be assumed done. If we assume that the Φs are implemented correctly this carries with it the consequence that the implementation is a stream X-machine since these functions are the processing functions of a stream X-machine by construction. What sort of restriction is this? It is quite legitimate to assume that the implementation is a deterministic stream X-machine because of the computational generality of this class of machines. This does not mean that all Turing machines can be represented as a stream X-machine, but that there exists a hierarchy of stream X-machines with progressively more complex basic functions which will approach the generality of the Turing model. In likely applications of the method we will successively apply the test method to the hierarchy of stream X-machines that are created when we consider the basic functions Φ at each level. Thus, testing a specific function φ, will involve considering it as the computation defined by a simpler stream X-machine and so on. Diagram illustrating how the basic functions can themselves be specified using simpler stream X-machines in a natural hierarchical manner. Ultimately, at the bottom level we need to test the basic functions in some suitable way - or assume that they are implemented correctly. In many of the case studies that we have looked at the basic functions that need to be used... are typically very straightforward ones that carry out simple tasks on simple data structures, inserting and removing items from registers, stacks etc., carrying out simple arithmetic operations on simple types and processing character strings in well understood ways. There is probably little point in devoting a great deal of testing effort to this aspect of the problem, it may seem to be slightly dangerous to say so but we know how to implement such simple operations correctly. The benefits that accrue if the method is applied are that the entire control structure of the system is tested and all faults detected modulo the correct implementation of the basic functions. 4. Discussion. Let us examine these results in the context of the issues raised in the earlier part of the paper. In particular, does this new method really deliver a principled method of testing? We now can say something about any faults remaining after the successful application of the full test set generated by the method (assuming that the specification X-machine satisfies all of the requirements). Any such faults are restricted to the basic processing functions. This approach does satisfy the reductive requirement that we expressed at the start. We no longer need to consider test coverage issues since we have full coverage with respect to faults - outside of the set of basic functions Φ. Recall that the reductionist philosophy means that we can replace the problem of testing for all faults in a stream X-machine to one of detecting faults in something simpler - namely the processing functions Φ. These, themselves, can be represented as the computations of even simpler stream X-machines if desired and the reduction continued further. Alternatively these may be functions obtained from a library of dependable objects that the designers are confident are essentially fault-free. The main point from all of this is that if this testing method is used and the implementation passes all of the tests in the test set then it is known to be free of faults, providing the Φ’s have been implemented in a fault-free fashion. The final question that needs to be addressed is concerned with the practicality of the method. For example, how complex is the test generation algorithm? A detailed complexity analysis of the algorithm has yet to be carried out and so we cannot provide a theoretical answer to this question yet. However, we can make out the following observations. Let A , the associated automaton of the stream X-machine specification, be a minimal finite state machine with n states and card(Φ) = r and let n’ be the maximum number of states in the implementation. Then, the method involves generating the values of n test functions t₀, ..., tₙ₋₁ for domains included in Z ∪ ΦZ. In the worst case, W contains at most n² sequences of length n-1 each. Hence, the maximum number of sequences in Z ∪ ΦZ is of the order of n²(r+1)n⁻r, each one is of length no more than n’. Therefore, the maximum size of the set test will be of the order of n³(r+1)n⁻r, and the maximum length of a test sequence will be n’ n. The actual size could be significantly lower, since the domains of the test functions we generate are subsets of Z ∪ ΦZ and also since these test functions might not be injective. If the number of the inputs is large (i.e. card(Σ) >> card(Φ)) the size of the test set is considerable lower compared to Chow’s method. Thus test sets generated by the method appear to be manageable as is the test application process. Clearly it has to be supported by automated systems and suitable tools which do not yet exist. The X-machine specification method also needs further research and evaluation although all those that we know of who have used it have found it to be very intuitive and simple to use. It is also powerful and has been used to construct a detailed specification of a time dependent system [15]. There will clearly be a need to develop the method to deal with large scale systems and a refinement process which allows the development of components and their linking together will be needed. Some of the theoretical work for this has been done [16]. In [11] we propose the use of X-machines as the foundation of a completely integrated design, verification and test methodology. Because the approach lends itself to a rigorous refinement based development process it is possible to construct test sets for intermediate versions of the implementation, providing that they satisfy all the design for test conditions. At subsequent stages, after the model has been refined, perhaps by expanding some of the processing functions and reducing the abstraction in a coherent way, the refined machine may be tested in a way that utilises test information from the earlier version together with tests generated from the components used to carry out the refinement succinctly. Conclusions. We have described a new approach to the testing of software systems which is reductionist in the sense that the approach provides a method for generating a finite test set which will detect all faults in the system providing that the basic processing functions are implemented correctly. The complexity of the test sets is better than that of a number of existing methods. The precondition for the application of the method is a formal specification of the system as a stream X-machine, a method that we and colleagues have introduced recently and evaluated with case studies drawn from a wide variety of different applications. The scope of the method is quite general and is relevant for real-time applications as well as traditional information system applications. It is independent of the nature of an implementation also. The recent interest in object-oriented systems and the urgent need to develop effective testing methods for them, provides a new and exciting opportunity. The claim is made in [3], that “a state model can provide a conceptual basis for object-oriented testing”. References. [7]. T.S. Chow, “Testing software design modeled by finite state machines.” IEEE Transactions Appendix. Let Σ and Γ two finite alphabets (called the input and output alphabet respectively). Then, an X-machine $M = (Σ, Γ, Q, M, Φ, F, I, T, m₀)$ is called a stream X-machine if 1. $X = Γ^* × M × Σ^*$, where $M$ is a (possibly infinite) set called the (internal) memory. 2. The type is $Φ = \{ φ: X \leftrightarrow X \}$, where each relation $φ$ is defined by: $φ(g, m, s) = \begin{cases} (g \ ρ(m, head(s)), \ μ(m, head(s)), tail(s)), & \text{if } s \neq λ \\ ∅, & \text{otherwise} \end{cases}$ where $μ: M × Σ \leftrightarrow M$, $ρ: M × Σ \leftrightarrow Γ$ are relations. 3. $Q$ is the finite set of (control) states, $I$ is the set of initial states, $T$ is the set of terminal states. In this paper we will always take $T = Q$. 4. $F: Q × Φ \rightarrow P (Q)$, where $P (Q)$ denotes the set of subsets of $Q$, (the power set), defines the next state function. Note: $λ \in Σ^*$ is the empty string. For two strings $s, t ∈ Σ^*$, $s::t$ represents the string obtained by concatenation. Also $head: Σ^* \rightarrow Σ^*$ and $tail: Σ^* \rightarrow Σ^*$ are partial functions defined by: $head(σ::s) = σ, \forall σ ∈ Σ, s ∈ Σ^*$; $head(λ)$ is undefined; $tail(σ::s) = s, \forall σ ∈ Σ, s ∈ Σ^*$; $tail(λ)$ is undefined. Each transition function removes the head of the input stream and adds an element to the rear of the output stream, and, furthermore, no transition is allowed to use information from the tail of the input or any of the output. $m₀$ is the initial state of the memory. It is clear that each relation $φ$ is well determined by $ρ$ and $μ$. For the sake of simplicity, in what follows we shall be referring to $\phi$ as a pair $\phi = (\rho, \mu)$. Then, the type, $\Phi$, will be written as $$\Phi = \{ \phi : M \times \Sigma \leftrightarrow \Gamma \times M, \phi = (\rho, \mu) \}.$$ For a a stream $X$-machine to be deterministic, then $I$ must be a single state and $T = Q$, $\Phi$ must be a set of partial functions and $\forall \phi, \phi' \in \Phi, \exists q \in Q, m \in M, \sigma \in \Sigma$ such that $(q, \phi) \in \text{dom } F$, $(m, \sigma) \in \text{dom } \phi$ and $(m, \sigma) \in \text{dom } \phi'$, then $\phi = \phi'$. (Here $\text{dom } f$ refers to the domain of a partial function $f$.) So each computation from the initial state to any other state is completely determined by the input sequence and the initial memory value. A deterministic stream $X$-machine will compute a partial function $f : \Sigma^* \rightarrow \Gamma^*$. A. 2. The test functions. Let $M = (\Sigma, \Gamma, Q, M, \Phi, F, q_o, m_o)$ be a deterministic stream $X$-machine with $\Phi$ complete and let $q \in Q$, $m \in M$. We define recursively a function $t_{q,m} : \Phi^* \rightarrow \Sigma^*$ as follows: 1. $t_{q,m}(\lambda) = \lambda$, where $\lambda \in \Phi^*$ and $\lambda \in \Sigma^*$ are the empty strings. 2. The recursion step depends on the following two cases: a. if $\exists \ a \ path$ $$q \xrightarrow{\phi_1} q_2 \xrightarrow{\phi_2} \ldots q_n \xrightarrow{\phi_n} q_{n+1}$$ in $M$ starting from $q$, then $t_{q,m}(\phi_1 \ldots \phi_{n+1}) = t_{q,m}(\phi_1 \ldots \phi_n) \sigma_{n+1}$, where $\sigma_{n+1}$ is chosen such that $(w(q, m, t_{q,m}(\phi_1 \ldots \phi_n)), \sigma_{n+1}) \in \text{dom } \phi_{n+1}$ and where $w(q, m, t_{q,m}(\phi_1 \ldots \phi_n))$ is the value of the next memory state given the current control state, $q$, the initial memory value $m$, and the input string $t_{q,m}(\phi_1 \ldots \phi_n)$. [Note: Since we only apply this construction in the case where $\Phi$ is complete, there exists such a $\sigma_{n+1}$.] b. otherwise, $t_{q,m}(\phi_1 \ldots \phi_{n+1}) = t_{q,m}(\phi_1 \ldots \phi_n)$. Then $t_{q,m}$ is called a test function of $M$ w.r.t. $q$ and $m$. If $q = q_o$ and $m = m_o$, $t_{q,m}$ is denoted by $t$ and is called a fundamental test function of $M$. If $$q \xrightarrow{\phi_1} q_2 \xrightarrow{\phi_2} \ldots q_n \xrightarrow{\phi_n} q_{n+1}$$ is a path in $M$, then $s = t_{q,m}(\phi_1 \ldots \phi_n)$ will be an input string which, when applied in $q$ and $m$, will cause the computation of the machine to follow this path. If there is no arc labelled $\phi_{n+1}$ from $q_{n+1}$, then $t_{q,m}(\phi_1 \ldots \phi_n \phi_{n+1}) = s: \sigma$, where $\sigma$ is an input which would have caused the machine to exercise such an arc if it had existed (i.e. therefore making sure that it does not exists). Also, for all $\phi_{n+2} \ldots, \phi_{n+k} \in \Phi$, $t_{q,m}(\phi_1 \ldots \phi_n \phi_{n+1} \ldots \phi_{n+k}) = t_{q,m}(\phi_1 \ldots \phi_n \phi_{n+1})$ (i.e. therefore only the first non-existing arc in the path is exercised by the value of the test function). We can say that a test function tests whether a certain path exists or not in $M$ (hence the name). A. 3. The fundamental theorem of X-machine testing: Let $M = (\Sigma, \Gamma, Q, M, \Phi, F, q_o, m_o)$ and $M' = (\Sigma, \Gamma', Q', M, \Phi, F', q_o', m_o)$ be two deterministic stream $X$-machines with $\Phi$ output-distinguishable and complete which compute $f$ and $f'$ respectively and $t : \Phi^* \rightarrow \Sigma^*$ be a fundamental test function of $M$. . Let $T$ and $W$ be a transition cover and a characterisation set, respectively, of the associated automaton $A$ of $M$ and put $Z = \Phi^k W \cup \Phi^{k-1} W \cup \ldots \cup W$. If $A$ and $A'$ are minimal, $\text{card}(Q') - \text{card}(Q) \leq k$ and $f(s) = f'(s) \forall s \in t(TZ)$, then the associated automata $A$ and $A'$ are isomorphic. Proof. [13]. A. 4. Example. A simple example of a deterministic stream $X$-machine satisfying the design for test conditions is: 1. $\Sigma = \{x, y\}$ is the input set, 2. $\Gamma = \{a, b\}$ is the output set, 3. $Q = \{q_0, q_1, q_2\}$ is the set of states; $q_0$ is the initial state and all the states are terminal (i.e. $T = Q$). 4. $M = \{0, 1\}$. The initial memory value is $m_0 = 0$. 5. $\Phi = \{\phi_1, \phi_2, \phi_3, \phi_4\}$, where $\phi_1: M \times \{y\} \rightarrow \Gamma \times M$ is defined by: $\phi_1(m, y) = (a, 1), m \in M$ $\phi_2: M \times \{x\} \rightarrow \Gamma \times M$ is defined by: $\phi_2(m, x) = (a, 0), m \in M$ $\phi_3: M \times \{y\} \rightarrow \Gamma \times M$ is defined by: $\phi_3(m, y) = (b, 1), m \in M$ $\phi_4: M \times \{x\} \rightarrow \Gamma \times M$ is defined by: $\phi_4(m, x) = (b, 0), m \in M$ 6. $F$ is represented in the diagram below: For example, the function, $f$ computed by this machine will, for example, transform the input sequence $yxyy$ into $f(yxyy) = aabb$ and for $xy$, $f(xy)$ will be undefined etc. The sequence of state transitions when the input sequence $yxyy$ is applied is: $$(q_0, 0) \phi_1 \rightarrow (q_1, 1) \phi_2 \rightarrow (q_1, 0) \phi_3 \rightarrow (q_2, 1) \phi_3 \rightarrow (q_2, 1)$$ where $$(q_0, 0) \phi_1 \rightarrow (q_1, 1)$$ means that in state $q_0$ with memory contents 0 the function $\phi_1$ can be applied giving a next state $q_1$ and new memory value 1. We see that, for example, $\phi_1$ distinguishes between $q_0$ and $q_1$. A characterisation set for this machine is $W = \{\phi_1, \phi_2\}$. A transition cover is: $$T = \{\Lambda, \phi_1, \phi_2, \phi_3, \phi_4, \phi_1 \phi_1, \phi_1 \phi_2, \phi_1 \phi_3, \phi_1 \phi_4, \phi_1 \phi_3 \phi_3, \phi_1 \phi_3 \phi_4, \phi_1 \phi_3 \phi_1, \phi_1 \phi_3 \phi_2\}$$ but this can be broken down into more manageable pieces so that for this stream $X$-machine a transition cover $T = T_0$ can be written as follows: \[ T_0 = \{1\} \cup \{\phi_1\} \cup \{\phi_2, \phi_3, \phi_4\} \cup \{\phi_1\} T_1, \] where \[ T_1 = \{1\} \cup \{\phi_2, \phi_3\} \cup \{\phi_1, \phi_4\} \cup \{\phi_3\} T_2 \] and \[ T_2 = \{1\} \cup \{\phi_3, \phi_4\} \cup \{\phi_1, \phi_2\} \] If \( m_0 = 0 \) is the initial memory value and \( m_1 = m_2 = 1 \), then: - \( t_0 \) is a test function w.r.t. \( q_0 \) and \( m_0 \) with \( t_0(\phi_1) = y \); - \( t_1 \) is a test function w.r.t. \( q_1 \) and \( m_1 \) with \( t_1(\phi_3) = y \); - \( t_2 \) is a test function w.r.t. \( q_2 \) and \( m_2 \). Then, a test set \( Y_0 = t_0(X_0), X_0 = T_0 Z \), can be written as: \[ t_0(X_0) = t_0(Z) \cup t_0(\{\phi_1\} Z) \cup t_0(\{\phi_2, \phi_3, \phi_4\}) \cup \{t_0(\phi_1)\} t_1(X_1), \] where \[ t_1(X_1) = t_1(Z) \cup t_1(\{\phi_2, \phi_3\} Z) \cup t_1(\{\phi_1, \phi_4\}) \cup \{t_1(\phi_3)\} t_2(X_2) \] and \[ t_2(X_2) = t_2(Z) \cup t_2(\{\phi_3, \phi_4\} Z) \cup t_2(\{\phi_1, \phi_2\}). \] For \( W = \{\phi_1, \phi_2\} \) and \( m = n \), we have \( Z = \{\phi_1, \phi_2\} \). Hence, by choosing appropriate values for the test functions, the test set \( Y_0 \) is: \[ Y_0 = \{y, x\} \cup \{yy, yx\} \cup \{x, y, x\} \cup \{y\} Y_1, \] where \[ Y_1 = \{y, x\} \cup \{xy, xx, yy, yy\} \cup \{y, x\} \cup \{y\} Y_2 \] and \[ Y_2 = \{y, x\} \cup \{yy, yx, xy, xx\} \cup \{y, x\} \] The full set of test inputs is thus: \[ Y_0 = \{y, x, yy, yx, xy, xx, yyyy, yyy, yyyy, yyyx, yyyxy, yyxx\}. \] Alternatively we can construct a fundamental test function, \( t \), directly, which satisfies the following values \( t(\phi_1) = y, t(\phi_1 \phi_2) = yx, t(\phi_1 \phi_2 \phi_4) = yxx, t(\phi_1 \phi_2 \phi_4 \phi_1) = yxx \) etc. and proceed from there.
{"Source-Url": "http://www.dcs.shef.ac.uk/~wmlh/paper/futile.pdf", "len_cl100k_base": 11798, "olmocr-version": "0.1.53", "pdf-total-pages": 16, "total-fallback-pages": 0, "total-input-tokens": 54465, "total-output-tokens": 13545, "length": "2e13", "weborganizer": {"__label__adult": 0.0003612041473388672, "__label__art_design": 0.00039076805114746094, "__label__crime_law": 0.0003466606140136719, "__label__education_jobs": 0.0009312629699707032, "__label__entertainment": 5.8650970458984375e-05, "__label__fashion_beauty": 0.00017070770263671875, "__label__finance_business": 0.00015878677368164062, "__label__food_dining": 0.0003981590270996094, "__label__games": 0.0007114410400390625, "__label__hardware": 0.0008826255798339844, "__label__health": 0.000568389892578125, "__label__history": 0.00023162364959716797, "__label__home_hobbies": 9.65595245361328e-05, "__label__industrial": 0.0003368854522705078, "__label__literature": 0.00039458274841308594, "__label__politics": 0.00023055076599121096, "__label__religion": 0.0005087852478027344, "__label__science_tech": 0.018280029296875, "__label__social_life": 8.821487426757812e-05, "__label__software": 0.004703521728515625, "__label__software_dev": 0.96923828125, "__label__sports_fitness": 0.00030303001403808594, "__label__transportation": 0.0004563331604003906, "__label__travel": 0.00018358230590820312}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 50885, 0.02645]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 50885, 0.72675]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 50885, 0.90796]], "google_gemma-3-12b-it_contains_pii": [[0, 2929, false], [2929, 6594, null], [6594, 9289, null], [9289, 13088, null], [13088, 16847, null], [16847, 19999, null], [19999, 23581, null], [23581, 26961, null], [26961, 30932, null], [30932, 33097, null], [33097, 36526, null], [36526, 39798, null], [39798, 43236, null], [43236, 46792, null], [46792, 49160, null], [49160, 50885, null]], "google_gemma-3-12b-it_is_public_document": [[0, 2929, true], [2929, 6594, null], [6594, 9289, null], [9289, 13088, null], [13088, 16847, null], [16847, 19999, null], [19999, 23581, null], [23581, 26961, null], [26961, 30932, null], [30932, 33097, null], [33097, 36526, null], [36526, 39798, null], [39798, 43236, null], [43236, 46792, null], [46792, 49160, null], [49160, 50885, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 50885, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 50885, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 50885, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 50885, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 50885, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 50885, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 50885, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 50885, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 50885, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 50885, null]], "pdf_page_numbers": [[0, 2929, 1], [2929, 6594, 2], [6594, 9289, 3], [9289, 13088, 4], [13088, 16847, 5], [16847, 19999, 6], [19999, 23581, 7], [23581, 26961, 8], [26961, 30932, 9], [30932, 33097, 10], [33097, 36526, 11], [36526, 39798, 12], [39798, 43236, 13], [43236, 46792, 14], [46792, 49160, 15], [49160, 50885, 16]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 50885, 0.0]]}
olmocr_science_pdfs
2024-12-06
2024-12-06
b90639114b277cd63f00192cca2880c531807595
Finding Compiler Bugs via Live Code Mutation Chengnian Sun Vu Le Zhendong Su Department of Computer Science, University of California, Davis, USA {cnsun, vmle, su}@ucdavis.edu Abstract Validating optimizing compilers is challenging because it is hard to generate valid test programs (i.e., those that do not expose any undefined behavior). Equivalence Modulo Inputs (EMI) is an effective, promising methodology to tackle this problem. Given a test program with some inputs, EMI mutates the program to derive variants that are semantically equivalent w.r.t. these inputs. The state-of-the-art instantiations of EMI are Orion and Athena, both of which rely on deleting code from or inserting code into code regions that are not executed under the inputs. Although both have demonstrated their ability in finding many bugs in GCC and LLVM, they are still limited due to their mutation strategies that operate only on dead code regions. This paper presents a novel EMI technique that allows mutation in the entire program (i.e., both live and dead regions). By removing the restriction of mutating only the dead regions, our technique significantly increases the EMI variant space. It also helps to more thoroughly stress test compilers as compilers must optimize mutated live code, whereas mutated dead code might be eliminated. Finally, our technique also makes compiler bugs more noticeable as miscompilations on mutated dead code may not be observable. We have realized the proposed technique in Hermes. The evaluation demonstrates Hermes’s effectiveness. In 13 months, Hermes found 168 confirmed, valid bugs in GCC and LLVM, of which 132 have already been fixed. Categories and Subject Descriptors D.2.5 [Software Engineering]: Testing and Debugging—testing tools; D.3.2 [Programming Languages]: Language Classifications—C; H.3.4 [Programming Languages]: Processors—compilers General Terms Algorithms, Languages, Reliability, Verification Keywords Compiler testing, miscompilation, equivalent program variants, automated testing 1. Introduction Compilers are among the most important, widely-used system software, on which all programs depend for compilation. A bug in a compiler can have profound impact: it may lead to catastrophic consequences in safety-critical domains. Generally, compiler bugs can be categorized into two classes: crashes and miscompilations. The first class causes the compiler to crash during compilation due to either memory errors or internal assertion failures, which hinders the software development process. The second class causes the compiler to silently compile the program into wrong code. The compiler bug manifests itself indirectly as an application failure. Compared to crashes, this class is more harmful, because (1) compiler bugs are usually rare and application developers usually do not attribute the failure to the compiler, incurring extra debugging effort, and (2) such bugs can escape from in-house software testing and result in field failures. It is critical to make compilers dependable. In the past decade, compiler verification has been an important, active area for the verification grant challenge in computing research [8]. The main compiler validation techniques include formal verification [12, 13], translation validation [22, 24], and random testing [4, 9–11, 35]. The first two categories try to produce certified compilers or optimization passes. Although promising and encouraging progress has been made (e.g., CompCert [13]), it is still challenging to apply formal techniques to fully verify a production compiler, such as GCC and LLVM. Therefore, random testing remains the dominant approach in compiler validation. A notable example is Csmith [35], which generates random valid programs and relies on multiple compilers as testing oracles to detect possible discrepancies. Recently, Le et al. introduced Equivalence Modulo Inputs (EMI) [9] to extend the capability of existing testing approaches. EMI is a general methodology to derive semantically equivalent valid variants from existing test programs. Since the variants and the original test program are expected to behave the same w.r.t. some inputs, EMI only needs a single compiler to discover compiler inconsistencies. **Dead-Code EMI Mutation** The state-of-the-art EMI instantiations are Orion [9] and Athena [11]. Both mutate test programs by manipulating statements in dead code regions. In particular, given an existing program $P$ and some inputs $I$, they profile the execution of $P$ under the inputs $I$. While Orion only randomly prunes the unexecuted statements, Athena also inserts extra code into the dead code regions. Because the mutated code is never executed, the semantics of the variants is equivalent to the original program w.r.t. the inputs. Although Orion and Athena have been proved to be effective at finding bugs in mature production compilers such as GCC and LLVM, they are still technically limited by their mutation strategies. First, the search space of their variant generation is limited by the size of dead code regions. Orion can only output a limited number of variants. Although Athena is able to insert extra dead code to extend the search space, the mutation is still confined within the dead code regions. Second, compilers can identify dead code regions and eliminate them during compilation. If this happens, all mutations in these regions become futile. Third, a miscompilation bug manifesting only in dead code regions is not observable as the wrong code is not executed (note that miscompilations manifest as application failures). For example, if a function with a large body is never called, then any miscompilation bug in the function body cannot be noticed. This happens for test programs that have large chunks of dead code under some inputs. **Live-Code EMI Mutation** In this paper, we propose a set of novel EMI mutation strategies that address the aforementioned limitations. Our mutation strategies apply to the live code regions, while still preserving the original semantics w.r.t. the inputs. Our approach has the following two steps: **Profiling Stage** Instead of profiling which statements are not executed as Orion and Athena do, we record more information during profiling. Given a program point $l$ and a set of live variables $V$ at $l$, we also record all the valuations of $v \in V$, i.e., all the values that each $v$ ever has during execution. **Mutation Stage** Based on the valuations of $V$, we synthesize a code snippet $c$ at $l$, such that at the exit of $c$ the program state remains identical to the one prior to the entry of $c$. A simple example would be a code snippet consisting of only `nop` statements which have no side effects on the runtime. However, in order to stress test compilers, we require that the snippet make changes to the program state, and ensure the semantics preservation at the exit of $c$ by construction. In this paper, we synthesize the following three types of code snippets to insert into the live code regions: 1) an if/while statement with a non-empty randomly generated body and a contradiction predicate, 2) an if statement with a tautology predicate to enclose an existing statement in the live code regions, and 3) a chunk of live code mutating existing variables, which restores these values at the exit of the code snippet. We will detail them in Section 4.2. Compared to the simple mutation strategies of Orion and Athena, the main challenge in this work is how to ensure that the statements synthesized for execution have no undefined behavior. Our key idea is to leverage the valuation of $V$ to ensure the validity of the synthesized code. We propose a bottom-up approach to constructing valid expressions progressively (Section 4.3.2). We have implemented the proposed technique for validating C compilers in a tool called Hermes. Our evaluation on validating two widely-used mature production compilers GCC and LLVM has strongly positive results. Within only 13 months, Hermes found 168 confirmed, valid bugs in the development trunk of GCC and LLVM. Of these bugs, 29 also affect stable releases, and 132 have already been fixed by compiler developers. Note that 29 of the reported bugs have been latent (bugs found in stable releases of production compilers), thus having slipped through traditional testing and previous compiler testing techniques (i.e., Athena and Orion). **Contributions** This paper makes the following main contributions: - We propose a set of novel EMI mutation strategies, which manipulate both live and dead code regions, to overcome the limitations of existing techniques, such as Orion and Athena. - We present a bottom-up approach to synthesizing valid (i.e., undefined behavior-free) expressions by leveraging the program states of the original test program w.r.t. a set of inputs. - We realize our approach as the Hermes tool for validating C compilers. Hermes is remarkably effective: it has found 12.9 bugs per month on average during our continuous 13-month evaluation as of the submission date. **Paper Organization** The remainder of the paper is structured as follows. Section 2 illustrates our approach via two of our reported bugs. Section 3 briefly introduces the concept of EMI. Section 4 presents the details of our approach. Section 5 describes our extensive evaluation on GCC and LLVM. Section 6 surveys related work and Section 7 concludes. ## 2. Illustrative Examples We illustrate Hermes’s bug finding process via two concrete bugs: one for GCC and one for LLVM. Both examples show how we use the profiled variable valuations to synthesize code snippets and insert them into live code regions, while still preserving the EMI property. We use Csmith [35] to generate the initial testing programs, from which we derive EMI variants to stress test compilers. The Csmith-generated programs are referred to as seed programs in the remainder of this paper. Because the original seeds and their bug-triggering variants are large (a few thousands lines of code), in this paper, we only show their reduced versions.\(^1\) ### 2.1 GCC Miscompilation Bug 66186 Figure 1 shows the reduced variant which triggers a GCC miscompilation bug. The executable compiled with GCC 4.9, 5.1, or development trunk 6.0.0 at optimization levels -O2 or -O3 throws a segmentation fault. However, this does not conform to the semantics of this program. The if statement on line 10 is not executed because \(a\) is 0. Therefore, the program should terminate normally. ```c int a; int main () { int b = -1, d, e = 0, f[2] = { 0 }; unsigned short c = b; for (; e < 3; e++) for (d = 0; d < 2; d++) if (a < 0) // Inserted code highlighted in gray. for (d = 0; d < 2; d++) if (!c) break; return 0; } ``` Figure 1: GCC 4.9, 5.1, and development trunk (6.0.0 rev 223265) miscompile the variant at -O3. (https://gcc.gnu.org/bugzilla/show_bug.cgi?id=66186). The compiled binary throws segmentation fault instead of terminating normally. The code snippet inserted by Hermes is highlighted in gray between lines 10 and 13. It is synthesized as follows: 1. Hermes profiles the execution of the seed program (i.e., the program in Figure 1 excluding the highlighted code) to determine the possible values of in-scope variables at all execution points. For instance, line 9 shows the observed values of all variables in scope at this location. 2. Hermes synthesizes a statement that does not have any side effect to the program (in this case it is an if statement where the guard is false\(^2\)), and inserts the statement into the location. The bug occurs because GCC incorrectly assumes that accesses to stack variables (in this case, access to \(f[c]\) on line 12) are non-trapping, and therefore hoists \(f[c]\) out of the if statement on line 10, making it unconditionally executed. However, this array access is out-of-bounds as \(c\) is 65535, and should not be executed as it is in the dead code region. GCC developers have confirmed and fixed this bug. Note that existing tools such as Orion [9] and Athena [11] cannot reveal this bug because the mutation happens in the live region of the program. ### 2.2 LLVM Miscompilation Bug 26266 ```c extern void abort(); char a; int b, c = 9, d, e; void fn1() { unsigned f = 1; int g = 8, h = 5; for (; ; a != 6; a--){ int i = 6, *j; for (; j <= 0;) if (k) l = f; f = -(~(c && b) | -~(e * ~l)); if (c < f) abort(); g = k; f = 1; if (d <= 8) break; *i = 0; ; } if (main()) fn1(); return 0; } ``` Figure 2: LLVM development trunk (3.9.0 rev 258508) miscompile the variant at -O1 and above. (https://llvm.org/bugs/show_bug.cgi?id=25154). The compiled binary aborts instead of terminating normally. Figure 2 shows a reduced variant that triggers a miscompilation bug of Clang. Initially, Clang compiles the seed program correctly at all optimization levels — all compiled executables terminate normally. However, after Hermes inserts the live code snippet (between lines 11 and 21 highlighted in gray) on line 11, Clang trunk 3.9 miscompiles the variant: the compiled binary aborts on line 18, a program point which should not be reachable. Different from the GCC example above where Hermes only generates an if statement whose guard is false, in this example, Hermes synthesizes a chunk of code which is --- \(^1\) A reduced version is derived from the bug-triggering test program by removing bug-irrelevant code fragments in order to help developers understand and diagnose the bug. \(^2\) The global variable \(a\) is not explicitly initialized, and according to the C language standard it is implicitly set to 0 by default. Thus the conditional is always false. executed at runtime. By instrumenting the program, Hermes knows that the values of $g$ and $h$ on line 10 are 8 and 5 respectively. Then it synthesizes a block of live code to mutate $f$. Specifically, we use $g$ and $h$ to construct a true if statement on line 13. In the body, we first save the value of $f$ on line 15, later change its value and use the new value (lines 17). This live code snippet is generated by our mutation strategy Always True Conditional Block which will be detailed in Subsection 4.2. This bug is in the demanded-bits analysis in Clang. When computing the demanded bits for the comparison $c < f$ on line 17, Clang should consider both operands $c$ and $f$. However, in the buggy version of this analysis, the first operand is accidentally ignored, leading the compiler to conclude that this comparison $c < f$ is always true (actually it should be always false), and consequently making the abort() unconditionally executed. Again, this bug cannot be triggered by Orion and Athena because the insertion happens in the live region. 3. Equivalence Modulo Inputs This section briefly introduces the formal definition of Equivalence Modulo Inputs (EMI) [9]. Let $\mathcal{L}$ denote a generic programming language $\mathcal{L}$ with deterministic semantics $\left\lceil \cdot \right\rceil$. Repeated executions of a program $P \in \mathcal{L}$ on the same input $i$ always yield the same output $\left\lceil P \right\rceil(i)$. Given two programs $P, Q \in \mathcal{L}$ and a set of common inputs $I$ (i.e., $I \subseteq \text{dom}(P) \cap \text{dom}(Q)$), $P$ and $Q$ are equivalent modulo inputs w.r.t. $I$ (denoted as $\left\lceil P \right\rceil =_I \left\lceil Q \right\rceil$) iff $$\forall i \in I \ \left\lceil P \right\rceil(i) = \left\lceil Q \right\rceil(i).$$ Given a program $P \in \mathcal{L}$, any input set $I \subseteq \text{dom}(P)$ naturally induces a collection of programs $\mathcal{P} \subseteq \mathcal{L}$ such that $\left\lceil P \right\rceil =_I \{Q\}$. We refer to this collection as $P$’s EMI variants. EMI relaxes the notion of program equivalence, and provides a practical way to generate test programs from existing code for compiler testing. The state-of-the-art instantiations of EMI are Orion and Athena. Both operate on unexecuted code regions. Given a program $P$ and its inputs $I$, Orion and Athena first profile the execution of $P$ and identify the dead code regions. Then they delete statements from or insert additional statements into the dead code regions. As these modified regions remain unexecuted under the same inputs $I$, the mutated programs are EMI variants of $P$. The main benefit of EMI is the preservation of the validity of $P$ w.r.t. $I$ after mutation. Another attractive property of EMI is that it does not need a reference compiler for differential testing, because EMI provides an explicit testing oracle, that is, all EMI variants are expected to output the same result w.r.t. the same input. In contrast, other approaches such as Csmith [35] relies on an extra reference compiler to cross-check the consistency of the compiled code, as the semantics of the randomly generated test programs is unknown. Without loss of generality, we assume that the input set $I$ has only one element in order to facilitate the presentation. Thus in the remainder of this paper, we use $I$ to represent a single input, rather than a set of inputs. 4. Approach Algorithm 1 shows the general process of using EMI. Given a compiler under test, we first compute the testing oracle $O$ on line 2 by caching the output of compiling and running the test program $P$. In each of the main iterations on line 4, we generate an EMI variant $P'$, and compare the output of compiling and running $P'$ (i.e., $O'$) with the oracle $O$. Algorithm 1: Hermes’s process for testing compilers ``` 1 procedure Test(Compiler $C$, Program $P$, Input $I$): 2 \hspace{1em} $O \leftarrow C.\text{Compile}(P).\text{Execute}(I)$ \hspace{1em} // oracle 3 \hspace{1em} $P' \leftarrow P$ \hspace{1em} // initialization 4 \hspace{1em} for $i \leftarrow 1$ to MAX_ITER do 5 \hspace{2em} // create a random EMI variant 6 \hspace{2em} $P' \leftarrow EMI(P', I)$ 7 \hspace{2em} $O' \leftarrow C.\text{Compile}(P').\text{Execute}(I)$ 8 \hspace{2em} if $O' \neq O$ then \hspace{1em} // inconsistent outputs 9 \hspace{3em} ReportBug($C, P'$) 10\end{algorithm} ``` 4.1 Program Profiling Our EMI variant generation (the function EMI on line 8 in Algorithm 1) starts on line 9 with profiling the test program to record necessary program states. Our profiling schema is more sophisticated than the one used in both Orion and Athena. While Orion and Athena only need the coverage information to identify dead code regions, our approach, in addition to the coverage information valuation of variables --- 3 For a closed program (e.g., a Csmith-generated program), we assume that it only has one type of inputs, i.e., $\emptyset$. 4 $\text{dom}(f)$ denotes the domain the function $f$. at certain program points so that we can mutate the live code safely without introducing any undefined behavior. We formally define the execution profile as follows: **Definition 4.1 (Execution Profile).** Given a program $P$ and an input $I$, the execution profile of running $P$ with input $I$ records all the values observed at runtime for each variable at each program point. Let $\text{Var}$ denote all the in-scope variables (including fields of structures and elements of arrays), $\mathbb{Z}$ be the integers, and $\text{Loc}$ denote the program points in $P$. The profile $\text{Profile}$ is defined as a mapping from a program point $l \in \text{Loc}$ to an environment $e \in \text{Env}$, which maps a variable $v \in \text{Var}$ to the set of its observed values. \[ \text{Profile} = \text{Loc} \rightarrow \text{Env} \quad \text{(Profile)} \] \[ \text{Env} = \text{Var} \rightarrow \mathcal{P}(\mathbb{Z}) \quad \text{(Environment)} \] Take Figure 1 as an example. After running the program, we collect a profile, which associates line 10 with the following environment: \[ \text{profile}(10) = \left\{ \begin{array}{ll} \ a & \rightarrow \{0\} \\ \ b & \rightarrow \{-1\} \\ \ c & \rightarrow \{65535\} \\ \ d & \rightarrow \{0, 1\} \\ \ e & \rightarrow \{0, 1, 2\} \\ \ f[0] & \rightarrow \{0\} \end{array} \right. \] Figure 3: The environment on line 10 in Figure 1 For a program point $l$ in dead code regions, the profile has an empty environment, namely, $\text{profile}(l) = \emptyset$. Note that in this paper, we only use integer values (i.e., $\mathbb{Z}$) in execution profiles. This is mainly due to the inherent inaccuracy of floating-point number arithmetics, which makes differential testing of compilers intractable [9, 11, 35]. In other words, it is difficult to predict the results of comparisons on close floating point values. We leave this as future work. ### 4.2 Live Code EMI Mutation Our approach relies on mutating live code regions in a test program. Given a test program $P$, its inputs $I$, and a statement $s$ executed by running $P$ with $I$, we formally define the mutation as a program synthesis problem as follows. **Definition 4.2 (Live Code EMI Mutation).** Let $C$ be a code snippet to be inserted right before $s$, resulting in a variant program $P'$. $C$ is an EMI mutation in $P'$ if when $P'$ is executed with $I$ the program state before the entry of $C$ and the program state after the exit of $C$ are the same. To stress test compilers, the code snippet $C$ should have side effects, otherwise a compiler may be smart enough to safely remove $C$ from $P'$. The extra side effects complicate data- and control-dependencies so that compilers may optimize $P'$ differently from $P$. After obtaining a profile, we randomly insert a code snippet into a live code region. Specifically, on line 16 in Algorithm 1, if the statement $s$ is executed (by checking whether its associated environment is not empty, i.e., $\text{dom}(\text{env}) \neq \emptyset$) and $\text{FlipCoin}$ returns true, we then randomly synthesize a code snippet via calling $\text{SynCode}()$ and insert the snippet into the program right before $s$ on line 17. This procedure is repeatedly applied to the child statements of $s$ on line 20. We have designed the following strategies in $\text{SynCode}()$ to synthesize live code EMI snippets. In each invocation to $\text{SynCode}()$, the following strategies are randomly selected with the same probability, i.e., 1/3 each. **Always False Conditional Block (FCB)** We generate an if/while statement, of which the body is not empty and the conditional predicate of this statement is always evaluated to false under the program input $I$. We synthesize the false predicate based on the variable valuations in the environment at the program point. The body is randomly generated by unrolling the C grammar. Concretely, during code generation, we randomly pick a production rule from the grammar, and instantiate it by recursively instantiating its sub-production rules with the in-scope variables available at the program point. We try to reuse the existing variables as much as possible in order to maximize the data dependencies between the code in the seed program and the synthesized code snippet. To limit the size of the generated code, we set an upper bound of the depth for derivation of production rules. For example, the above code snippet (extracted from lines 10–13 of Figure 1) is synthesized based on the environment in Figure 3. As $a$ is 0 at runtime, the predicate $(a < 0)$ is false, and the body will not be executed. The body is synthesized by instantiating the production rule of the for loop, which requires instantiations of four more production rules (e.g., the loop body, initializer, condition) and uses three existing variables $d$, $f$, and $c$. Note that since the body is not executed, we do not need to ensure the validity of the code during program generation. **Always True Guard (TG)** For an existing executed statement $s$ in the original program, we introduce an if statement to guard $s$, of which the predicate $p$ is always true, i.e., 1 if $(p)$ 5). This strategy alters the control flow but still preserves the original semantics. **Always True Conditional Block (TCB)** We synthesize an if statement with a non-empty body with side effects, where the guard is always true based on the environment. This is the opposite of FCB because the body of this statement will be executed. Therefore, we need to ensure that the body does not exhibit any undefined behavior (i.e., well-defined w.r.t. $\text{FlipCoin}$ returns true with a tuned probability. In a different context, the probability can be different.) 1 int backup_v = (synthesized valid expression); 2 if ((synthesized true predicate)) { 3 backup_v = v; 4 v = (synthesized valid expression); 5 if/while ((synthesized false predicate)) { 6 print v; 7 } 8 } 9 v = backup_v; Figure 4: Skeleton to synthesize TCB with one variable $v$. The highlighted text will be replaced by synthesized expressions and predicates. 4.3 Predicate, Expression and TCB Synthesis This subsection describes the building blocks of realizing our three mutation strategies: synthesizing a predicate with a given truth value, and synthesizing an expression without undefined behavior for TCB. We also discuss how we generate a TCB block via speculative execution. 4.3.1 Predicate Synthesis Algorithm 2 presents the process to generate a predicate with a given truth value. The parameter $depth$ is used to limit the size of the generated predicate. A predicate is built top-down. At the top we first randomly choose a logical operator (i.e., conjunction, disjunction, and negation), then carefully randomize and compute the target truth values of the children so that the whole predicate evaluates to the expected truth value. We then proceed to build the children. Specifically in Algorithm 2, the function $SynPred$ synthesizes a negation predicate, $SynCon$ generates a conjunction, and $SynDis$ generates a disjunction. An atomic predicate (one with depth 0) checks the relation between a variable and a constant, or between two variables. It is constructed with a set of rules (i.e., the function $SynAtom$). Specifically, as we know all values of each variable, we can create tautologies or contradictions by construction by selecting the right constants or relational operators. For example, in Figure 1, because $a$ is 0 on line 10, we can create a contradiction $a < 0$, $a > 0$, $a < d$ and many others. 4.3.2 Bottom-Up Valid Expression Synthesis In order to realize the TCB mutation strategy, we need to synthesize valid expressions without undefined behavior, a challenging synthesis problem in compiler testing for decades. In this paper, we leverage the fact that we know the values of all variables at runtime w.r.t. the program inputs $I$, and propose a bottom-up expression building algorithm that safely avoids undefined behaviors. Figure 5 shows the grammar of expressions we support in this work. Figure 5: BNF Grammar of Synthesized Expressions Algorithm 3: Synthesize valid expressions ``` function SynExpr (Env env): worklist ← Sample(env, Random(|dom(env)|)) while |worklist| > 1 do if FlipCoin() then // unary expression v ← Sample(worklist, 1) uop_list ← a shuffled list of unary operators foreach uop ∈ uop_list do if IsUndefined(env, v, uop) then continue worklist ← (worklist \ {v}) worklist ← worklist ∪ {Expr(uop, v)} break else // binary expression {u, v} ← Sample(worklist, 2) bop_list ← a shuffled list binary operators foreach bop ∈ bop_list do if IsUndefined(env, u, v, bop) then continue worklist ← (worklist \ {u, v}) worklist ← worklist ∪ {Expr(bop, u, v)} break return the only expression in worklist ``` Algorithm 3 shows the process to build valid expressions with unary and binary operators. The variable worklist stores a set of valid expressions, which are gradually merged together with various operators and form a valid single compound expression. The function Sample samples elements from a set without replacement. Initially, we sample a random number of variables from env on line 2 and use them as the leaves of the expression to build. We then make a random choice to generate either a unary or a binary expression on line 4. **Building Binary Expression** If we choose to construct a binary expression, we first sample two elements \{u, v\} from worklist as child expressions on line 14, then iterate through all the available binary operators in a randomized order until we find an operator bop that does not introduce undefined behaviors according to the valuations of u and v. Note that some operators are always well defined independently of their arguments according to the C language standard (e.g., negation (!), bit and/or/xor, and relational operators), so this step will always succeed. The algorithm removes u and v from worklist and adds the new binary expression Expr(bop, u, v) to worklist. **Building Unary Expression** This process is similar to constructing binary expressions. However, because building unary expressions does not shrink worklist, our algorithm may not terminate. To deal with this problem, a counter records the number of consecutive unary constructions (This counter is not shown in Algorithm 3 for clear presentation of the algorithm). If a threshold is reached, we force the algorithm to build binary expressions in the next iteration. **Checking Undefined Behavior** To evaluate the validity of an expression e, we need all the possible values of its child expression(s). We perform a speculative execution Spex(env, e) over e with the given environment env to compute an over-approximation of the environment as follows: - \( v \in Var \): If e is a variable expression v, its values can be obtained from env, i.e., \[ Spex(env, e) = env(v) \] - \( Expr(uop, e') \): If e is a unary expression, its values are computed by applying uop to each value of its child expression e', i.e., \[ Spex(env, e) = \{ uop \, x | x \in Spex(env, e_1) \} \] - \( Expr(bop, e_1, e_2) \): If e is a binary expression, its values are the application of bop to the elements of the Cartesian product of Spex(env, e_1) and Spex(env, e_2), namely, \[ \{ x_1 \, bop \, x_2 | (x_1, x_2) \in Spex(env, e_1) \times Spex(env, e_2) \} \] To check for undefined behaviors, we emulate the semantics of unary and binary operators defined in the C language standard over all the possible values of child expressions. If no values trigger undefined behaviors, the function IsUndefined returns false. ### 4.4 TCB Synthesis with Speculative Execution Hermes generates TCB code snippets by instantiating the template in Figure 4. Specifically, it replaces the highlighted text in Figure 4 with synthesized expressions and predicates by calling SynExpr and SynPred, as shown in Figure 6. Both functions SynExpr and SynPred require the environment of the insertion point (i.e., the program point at which the synthesized code will be inserted). However, because the whole TCB code snippet is statically synthesized (not executed yet), the environment of each program point in the template except the entry is \( \varnothing \). The environment of the entry \texttt{env} is the one associated to the insertion point of the whole TCB code in the original test program, which is accessible from the execution profile. Similar to checking undefined behaviors, we perform speculative execution to over-approximate environments for each program point of a TCB code block. Figure 6 shows how we instantiate the TCB template. The template is interpreted line by line from top to bottom. For each line, the plain text will be output directly as a part of the final code snippet. The highlighted text within \texttt{if} will be executed first and its result will be a part of the final code snippet. The environment \texttt{env} is updated along the live path of the template. After each assignment to a variable, we update \texttt{env} with the new valuation. For example, after creating a new variable \texttt{backup\_v} and initializing it with a random expression on line 2, we update \texttt{env} by incorporating \texttt{backup\_v} and its valuation on line 3. The updated \texttt{env} is used later to synthesize other predicates and expressions. ``` 1 // env is obtained from the execution profile 2 int backup_v = (SynExpr(env)) 3 (add backup_v and its valuation to env) 4 if ((SynPred(env, true, depth))) { 5 backup.v = v; 6 (update backup_v in env with v’s valuation) 7 v = (SynExpr(env)); 8 (update v in env with its new valuation) 9 if/while((SynPred(env, false, depth))) { 10 print v; 11 } 12 } 13 v = backup_v; ``` Figure 6: Synthesizing TCB with speculative execution 4.5 Implementation We have implemented the proposed technique in Hermes for testing C compilers. Hermes uses Clang’s LibTooling library [30] to instrument profiling code into the program to obtain the execution profile, and to mutate the program based on the obtained profile. In addition to the algorithmic complexity, we also face the challenge of handling the intricate type conversions defined in the C language when performing speculative execution. This is crucial as any inconsistency with the C standard will lead the synthesized code to deviate from our expectation, which breaks the mutated program’s EMI property. For example, given two variables ‘\texttt{int a=0}’ and ‘\texttt{short b=-1}’, the sum ‘\texttt{a+b}’ will be -1. However if the type of \texttt{a} is unsigned, then ‘\texttt{a+b}’ will be the maximum value of unsigned type (4294967295 if unsigned has 32 bits) as \texttt{b} is converted to unsigned first. Therefore, although our speculative execution operates on concrete values in execution profiles, we also need to take their types into consideration when performing unary and binary operations. Hermes carefully implements these conversions including integer promotion, usual arithmetic conversion and implicit conversion in C. Note that an alternative to implement \texttt{Spex} is creating tiny C programs with the desired fragments of code and running them. However, the code fragments may contain undefined behavior. And currently we do not have a reliable way to detect and control the undefined behavior in the executable code. Moreover, this approach may incur additional overhead as it involves compilation, execution, and process-level communication, compared to our current implementation by simulating the semantics of the C language. 4.5.1 Sparse Profiling Profiling all program points to collect the valuations of all in-scope variables is usually not feasible or practical, as it can consume much time and huge storage space. In the following, we describe an optimization technique to reduce the profiling overhead. The optimization is based on an insight that not all collected environments in the profile are used for EMI mutation. Note line 16 in Algorithm 1. For each program point with non-empty environment (checked by \texttt{dom(env) \neq \emptyset}), Hermes makes a random decision to mutate this program point (determined by \texttt{FlipCoin()}). If Hermes decides to skip this point (i.e., \texttt{FlipCoin()} returns \texttt{false}), then the effort to collect the environment for this point is wasted. Based on this observation, we propose a sparse profiling schema by moving the non-determinism of code synthesis at the mutation stage to the profiling stage. Let \texttt{s} denote all the eligible program points for profiling. Instead of instrumenting profiling code into each point in \texttt{s}, we introduce a profiling probability \( P_{\text{profile}} \), and sample a subset \( s' \subseteq s \) with \( P_{\text{profile}} \) for profiling. Concretely, when we visit each point in \( s \), we randomly select the point and instrument the profiling code with the probability \( P_{\text{profile}} \). Next on line 16 in Algorithm 1, we remove the call to \texttt{FlipCoin()}, and deterministically synthesize a code fragment for the program point \( l \) if \( l \) has a non-empty environment. 5. Evaluation This section discusses our testing efforts over 13 months, from middle May 2015 to middle March 2016. We focus on testing two open-source compilers GCC and LLVM because of their openness in tracking and fixing bugs. Some highlights of this process follows: - **Many detected bugs**: In 13 months, we have reported 168 new and valid bugs. Developers have confirmed all these bugs and fixed 132 of them. - **Many long-latent bugs**: We have found 29 latent bugs in stable releases of GCC and LLVM. These bugs have slipped through traditional testing and previous compiler testing techniques, e.g., Athena. Developers are generally responsive in confirming and fixing our bugs, which is a strong indication that they take our bugs seriously. To quote one developer: “Wow, this was a *horrible* failure. Thanks for the testcase! We were invalidating a cached reference under our own feet.” 5.1 Testing Setup We ran Hermes on two machines (one has 18 cores and the other 6 cores) running Ubuntu 14.04 (x86_64). Compiler Versions We built the development trunks of GCC and LLVM daily and tested them on their five standard options, ".O0", ".O1", ".Os", ".O2" and ".O3". The reason for testing development trunks is mainly that developers fix bugs primarily in truck revisions rather than stable releases. Fixes for bugs in stable releases are only available much later in subsequence stable releases. This long gap between when a bug is found and when the fix is released makes it difficult to identify whether a newly found bug is a duplicate to an existing unfixed bug. We also lose the opportunity of finding bugs in the trunk as early as possible if we only focus on stable releases. Seed Programs In this paper, we use Csmith [35] as the seed program generator, because Csmith-generated programs can be effectively reduced using existing reduction tools such as Berkeley’s Delta [19] and CReduce [25]. Note that Hermes is orthogonal to and independent of the seed programs. We can use the vastly available open-source code as seeds. However, the major obstacle of doing this is that those programs are usually large and consist of multiple files, and thus cannot be effectively reduced by the state-of-the-art reduction tools. Testing Process Our testing process is fully automated and runs continuously. In each iteration, we first use Csmith to generate a seed program. We then apply Hermes to derive 10 variants from the seed, and use then to test GCC and LLVM. This process involves little human intervention. In addition to test program generation, we have also automated the test case reduction (using Delta and CReduce). The only manual effort is to confirm that the reduced test programs are indeed valid and report them. Concretely, if the compiler bug is miscompilation, we ensure that the test program does not contain undefined behavior. Moreover, we check whether the new bug is a duplicate to any existing bugs in compilers’ Bugzilla databases. Profiling and Synthesis Parameters We set the profiling probability \( P_{\text{profile}} \) to 0.1 to perform sparse profiling (cf. Section 4.5.1). The CSmith-generated programs usually have around 1000 ~ 2000 lines of code, so the profiler will select around 100 ~ 200 program points to instrument. Note that some of these instrumented points might be in dead code regions, hence the final number of executed profiling points can be fewer, not zero according to our experiences. When synthesizing a predicate, we set its maximum depth to 2. In detail, before each call to SynPred in Algorithm 2, we randomize a number \( d \in [0, 2] \) and pass \( d \) as the argument depth. 5.2 Quantitative Results We next present some statistics on our reported bugs. Bug Count Table 1 summarizes our bug results. In 13 months, we reported in total 217 bugs (124 in GCC and 93 in LLVM). Developers confirmed 168 valid bugs and fixed 132 of them; 49 have yet to be confirmed as they were reported very recently. Not-Yet-Fixed Bugs All these bugs were reported recently. Developers have confirmed these bugs, and are discussing how to fix them. Duplicate Bugs Although we only considered bugs that have different symptoms from that of the not-yet-fixed bugs, we reported 48 duplicated bugs (all are GCC bugs) during this testing period. These bugs turned out to have the same root cause. Invalid Bugs We reported one invalid bug in GCC, in which the variant has an undefined behavior, in particular, sequence point violation [34]. This was caused by a bug in our Hermes tool, which we later fixed. Bug Type Compiler bugs can be generally classified into the following three categories. Miscompilation The compiler silently miscompiles the program by producing a wrong executable that alters the semantics of the source program. Crashing The compiler crashes when compiling the program, due to either runtime errors (e.g., segmentation fault, floating-point exceptions) or assertion failures. Performance The compiler hangs or takes a very long time to compile the program. Miscompilation bugs are run-time bugs because they manifest when the compiled binaries are executed. Crashing and performance bugs are compile-time bugs because they manifest during compilation. Table 2 partitions our 168 confirmed and valid bugs into the above three categories. The category performance represents bugs that cause the compiler to not terminate within a <table> <thead> <tr> <th>Bug Type</th> <th>GCC</th> <th>LLVM</th> <th>TOTAL</th> </tr> </thead> <tbody> <tr> <td>Fixed</td> <td>85</td> <td>47</td> <td>132</td> </tr> <tr> <td>Not-Yet-Fixed</td> <td>10</td> <td>26</td> <td>36</td> </tr> <tr> <td>Duplicate</td> <td>28</td> <td>20</td> <td>48</td> </tr> <tr> <td>Invalid</td> <td>1</td> <td>0</td> <td>1</td> </tr> <tr> <td>TOTAL</td> <td>124</td> <td>93</td> <td>217</td> </tr> </tbody> </table> Table 1: Reported bugs. certain amount of time when compiling a program (five minutes in our experiments). As the table shows, nearly half of our bugs are miscompilation, the most serious kind. <table> <thead> <tr> <th></th> <th>GCC</th> <th>LLVM</th> <th>TOTAL</th> </tr> </thead> <tbody> <tr> <td>Miscompilation</td> <td>42</td> <td>34</td> <td>76</td> </tr> <tr> <td>Crash</td> <td>52</td> <td>38</td> <td>90</td> </tr> <tr> <td>Performance</td> <td>1</td> <td>1</td> <td>2</td> </tr> </tbody> </table> Table 2: Bug classification. **Mutation Cost and Throughput** Given a seed program, the time cost of Hermes to derive an EMI variant is low. Thanks to the sparse profiling and efficient implementation of the code synthesizer, the time is negligible. On average, it took Hermes only 1.7 seconds to complete both the profiling and code synthesis. Table 3 shows the statistics of the time cost. In the setting of a single run (a single thread on a single CPU core), our testing process can test around 400 programs per hour. Most of the CPU time is taken up by the compilation by GCC and LLVM at different optimization levels. The throughputs of Hermes and Athena are similar, as the mutation overhead of Hermes is quite small although Hermes has an extra step of profiling. <table> <thead> <tr> <th>Min</th> <th>Mean</th> <th>Median</th> <th>Max</th> <th>StdDev</th> </tr> </thead> <tbody> <tr> <td>0</td> <td>1.7</td> <td>1</td> <td>6</td> <td>1.2</td> </tr> </tbody> </table> Table 3: Time of Generating an EMI variant (seconds). 5.3 Comparison with Athena This section presents our in-depth comparison evaluation of Hermes and Athena. In general, we performed the comparison in three different ways: 1) running Athena concurrently with Hermes, 2) running Athena with the same seeds to re-trigger the bugs found by Hermes in Table 4, and 3) measuring the covered lines of compiler code. These three evaluations complement each other, and together offer a comprehensive comparison between Athena and Hermes. Since Le et al. has shown in [11] that Athena outperforms Orion at finding bugs in GCC and LLVM, we exclude Orion from this study. 5.3.1 Effectiveness Based on the data reported in [11], Athena took 19 months to find 72 confirmed bugs, whereas Hermes has already found 168 confirmed bugs within only 13 months. Moreover, since last May, we have launched a parallel run of Athena along with Hermes. During the same period, Athena has found only a few bugs. We have also conducted an evaluation to compare Hermes and Athena directly. In particular, we selected all the confirmed bugs (28 bugs in total) that were found by Hermes and reported in November and December 2015, and tried to re-trigger them using Athena with the same seed programs used by Hermes. For each bug, we used Athena to derive a sequence of variants from the same seed program. Considering the stochastic characteristics of Athena, we set the number of variants per seed to 200 (in comparison to 10 variants per seed of Hermes), and repeated the generation process 100 times. Table 4 lists the results. Only three bugs (GCC-68327, GCC-68870, and LLVM-25538) can be re-triggered by Athena. Table 4: The results of running Athena to re-trigger the confirmed bugs that were reported in November 2015. The first column shows the bug ID. The second column is the type of the bug, either miscompilation or crash. The third column lists the optimization levels to trigger the bug, and the forth shows the reproduction result. <table> <thead> <tr> <th>BUG ID</th> <th>Type</th> <th>Optimization</th> <th>Athena</th> </tr> </thead> <tbody> <tr> <td>GCC-68194</td> <td>Mis.</td> <td>-O3, -O2, -O3</td> <td></td> </tr> <tr> <td>GCC-68240</td> <td>Crash</td> <td>-O2, -O3</td> <td></td> </tr> <tr> <td>GCC-68248</td> <td>Crash</td> <td>-O2, -O3</td> <td></td> </tr> <tr> <td>GCC-68285</td> <td>Mis.</td> <td>-O3</td> <td></td> </tr> <tr> <td>GCC-68305</td> <td>Crash</td> <td>-O1, -O3, -O2, -O3</td> <td></td> </tr> <tr> <td>GCC-68327</td> <td>Crash</td> <td>-O3</td> <td>✓</td> </tr> <tr> <td>GCC-68376</td> <td>Mis.</td> <td>-O1, -O3, -O2, -O3</td> <td></td> </tr> <tr> <td>GCC-68506</td> <td>Mis.</td> <td>-O3</td> <td></td> </tr> <tr> <td>GCC-68520</td> <td>Crash</td> <td>-O3</td> <td></td> </tr> <tr> <td>GCC-68570</td> <td>Crash</td> <td>-O1, -O3, -O2, -O3</td> <td></td> </tr> <tr> <td>GCC-68624</td> <td>Mis.</td> <td>-O2, -O3</td> <td></td> </tr> <tr> <td>GCC-68691</td> <td>Crash</td> <td>-O3</td> <td></td> </tr> <tr> <td>GCC-68721</td> <td>Mis.</td> <td>-O3, -O2, -O3</td> <td></td> </tr> <tr> <td>GCC-68730</td> <td>Mis.</td> <td>-O3</td> <td></td> </tr> <tr> <td>GCC-68906</td> <td>Crash</td> <td>-O3</td> <td></td> </tr> <tr> <td>GCC-68909</td> <td>Crash</td> <td>-O3</td> <td></td> </tr> <tr> <td>GCC-68911</td> <td>Mis.</td> <td>-O3</td> <td></td> </tr> <tr> <td>GCC-68951</td> <td>Mis.</td> <td>-O3</td> <td></td> </tr> <tr> <td>GCC-68955</td> <td>Mis.</td> <td>-O3</td> <td></td> </tr> <tr> <td>GCC-69030</td> <td>Crash</td> <td>-O2, -O3</td> <td></td> </tr> <tr> <td>GCC-69083</td> <td>Crash</td> <td>-O3</td> <td></td> </tr> <tr> <td>GCC-69097</td> <td>Wrong</td> <td>-O1, -O3, -O2, -O3</td> <td></td> </tr> <tr> <td>LLVM-25372</td> <td>Crash</td> <td>-O1, -O2</td> <td>✓</td> </tr> <tr> <td>LLVM-25538</td> <td>Crash</td> <td>-O1, -O2</td> <td>✓</td> </tr> <tr> <td>LLVM-25629</td> <td>Mis.</td> <td>-O1, -O3, -O2, -O3</td> <td></td> </tr> <tr> <td>LLVM-25754</td> <td>Crash</td> <td>-O1, -O3, -O2, -O3</td> <td></td> </tr> <tr> <td>LLVM-25900</td> <td>Wrong</td> <td>-O1, -O3, -O2, -O3</td> <td></td> </tr> <tr> <td>LLVM-25988</td> <td>Wrong</td> <td>-O2, -O3</td> <td></td> </tr> </tbody> </table> The various comparisons above demonstrate that the mutation strategy of Hermes is more effective at finding bugs than that of Athena. 5.3.2 Line Coverage We now evaluate the line coverage improvement of Hermes on GCC and LLVM compared to Athena. The baseline is the coverage of compiling 100 Csmith-randomly-generated The number of generated variants per seed program — the coverage ratio of GCC is 34% and that of LLVM is 21.1%. We then use Athena and Hermes to derive EMI variants from these 100 test programs, compile the variants with GCC and LLVM, and lastly measure the coverage of compilers. We vary the number of variants to generate from each seed program, and obtain the coverage data shown in Figure 7. The x-axis is the number of generated variants per seed program, and the y-axis is the absolute coverage ratio improvement over the baseline. Figure 7 demonstrates that Hermes significantly improves line coverage of both GCC and LLVM over Athena. Take the second group of vertical bars at x=10 as an example. Hermes improved the coverage over the baseline by 4.8% (24,612 lines) for GCC and 1.8% (12,672 lines) for LLVM, while Athena did by 0.6% (3,111 lines) for GCC and 0.2% (1,753 lines) for LLVM. The additionally covered code is mainly in the middle-end and the back-end of each compiler. ### 5.4 Comparison of Mutation Strategies This section presents the comparison of the three mutation strategies (i.e., FCB, TG, TCB) in terms of numbers of bugs detected. We use the 28 bugs in Table 4 as samples for this analysis. Each bug-revealing test program P′ is derived from the seed program P by injecting a set S of code snippets, of which each is synthesized by a strategy of Hermes. Then we iteratively remove elements from S until we obtain a minimal S′ ⊆ S such that P + S′ (i.e., an EMI variant by inserting the mutation code S′ into P) still trigger the same bug. Figure 8: Distribution of bugs found by different mutation strategies. Intersection represents the number of bugs found by the combination of strategies. For example, the intersection of the three circles means that four bugs are found by a set of code snippets synthesized by FCB, TG and TCB together. Then we classify S′ based on the mutation strategies that synthesize the elements in S′. The result is shown in Figure 8 as a Venn diagram. Each single strategy can find bugs alone. But there are two bugs found by the combination of FCB and TCB, one bug by the combination of TG and TCB, and four bugs by the three strategies together. ### 5.5 Sample Bugs This section illustrates the diversity of our bugs via six bug samples. Note that all these bugs are reduced from (much) larger mutated programs. **Figure 9a** The expected behavior of this program is to print 0 (the value of d assigned inside the loop). Note that because the conditional statement at line 13 is not executed (b is 0), none of its printf statements are executed. However, the program compiled with GCC trunk prints 1. The reason is that GCC decides to perform loop unswitching [33] to move the conditional at line 15 outside the loop. This optimization is incorrect because the now-used local variable j was not initialized: the optimized program contains undefined behavior. Note that the original program is valid (no undefined behavior) because j is not evaluated. **Figure 9b** The expected behavior of this program is to terminate normally. Because the value of a after exiting the loop at line 5 is 1, the program does not abort at line 21. However, the program compiled with GCC trunk aborts. The ifcombine optimization mistakenly moves the uninitialized variable k at line 9 before the guard at line 8, introducing undefined behavior (k is now evaluated). **Figure 9c** The expected behavior of this program is to terminate normally. In the function fn2, the for loop executes twice, each time decreasing the value of g by 1. While calling \texttt{fn1} at line 20, the argument is \texttt{0} because \texttt{g} is \texttt{-2}. This function assigns \texttt{b} to \texttt{a[0]}, which is \texttt{1}. Therefore, the \texttt{if} statement at line 21 is not executed, and the program does not abort. However, the program compiled by Clang trunk aborts because of a bug in calculating liveness. \textbf{Figure 9d} Clang 3.6.3.7, and trunk crashes while compiling this program at -Os and above because of an issue in global value numbering \cite{32}. \textbf{Figure 9e} Clang trunk crashes while compiling this program at -02. The bug happened because the developer (a) GCC development trunk (6.0.0 rev 228389) miscompiles the variant at -03. The compiled binary prints \texttt{1} instead of \texttt{0}. (b) GCC development trunk (6.0.0 rev 229251) miscompiles the variant at -03. The compiled binary aborts instead of terminating normally. (c) LLVM development trunk (3.8.0 rev 248820) miscompiles the variant at -02 and -03. The compiled binary aborts instead of terminating normally. (d) LLVM 3.6.3.7, and development trunk (3.8.0 rev 250927) crash while compiling the variant at -05s and above. (e) LLVM development trunk (3.8.0 rev 253143) crashes while compiling the variant at -02. (f) GCC 4.9.2.5.1, and development trunk (6.0.0 rev 223630) miscompiles the variant at -03. The compiled binary aborts instead of terminating normally. https://llvm.org/bugs/show_bug.cgi?id=25291 https://llvm.org/bugs/show_bug.cgi?id=25538 https://llvm.org/bugs/show_bug.cgi?id=228389 https://gcc.gnu.org/bugzilla/show_bug.cgi?id=24991 https://gcc.gnu.org/bugzilla/show_bug.cgi?id=67828 https://gcc.gnu.org/bugzilla/show_bug.cgi?id=68083 https://gcc.gnu.org/bugzilla/show_bug.cgi?id=66272 https://llvm.org/bugs/show_bug.cgi?id=255538 https://llvm.org/bugs/show_bug.cgi?id=255538 Figure 9: Some sample variants that trigger a variety of GCC and LLVM bugs. did not handle a special case while avoiding recomputing the expensive loop-closed SSA form [15]. **Figure 9f** The expected behavior of this program is to terminate normally. After the first iteration of the loop at line 9, \( a[8] \) has the same value as \( d \). After the second iteration, \( a[1] \) also has the same value as \( d \). The program does not abort at line 14 because \( d \cdot f1 \) is 1. However, the program compiled with GCC 4.9.2, 5.1, and trunk aborts. The predictive commoning pass [7] mistakenly hoisted the store \( d \cdot f1 = a[8] \cdot f1; \) at line 11 out of the loop because it incorrectly assumes that the store is independent of the previous store to \( a[b] \). 6. Related Work Our work is closely related to research on compiler testing and verification. In this section, we survey the three most related lines of work: compiler testing, compiler verification and translation validation. 6.1 Compiler Testing Due to its practicability, compiler testing is still the dominant technique to assure compiler quality. For example, mature production compilers (e.g., GCC and LLVM) have their own regression test suites. Commercial test suites are also available such as PlumHall [23] and SuperTest [1] for language conformance and correctness checking. Most of these test suites are written manually. An alternative to manually written test suites is random testing, which can further stress test compilers by providing extra testing coverage. Zhao et al. proposed a tool JTT to test the EC++ embedded compiler [36]. Nagai et al. [20, 21] proposed a technique to generate random arithmetic expressions to find bugs in the arithmetic optimizers of GCC and LLVM. CCG is another random C program generator that targets compiler crashing bugs [2]. Sun et al. proposed an automated approach to finding bugs in compiler warning diagnostics [27]. Chen et al. proposed a guided approach to detecting discrepancies between different implementations of Java Virtual Machine [3]. Sun et al. proposed a simple but effective program fuzzer to find crashing bugs in GCC and LLVM based on an observation that most of bug revealing test programs are small [28]. **Csmith** Csmith [35] is one of the most successful random program generator for testing C compilers. It targets crashing and miscompilation bugs. Over the last several years, Csmith has made significant contribution to improve the quality of GCC and LLVM. Csmith is well-known for its careful control to avoid generating test programs with undefined behaviors and the large set of C language features it supports. In addition to compiler testing, Csmith has also been applied to test static analyzers such as Frama-C [5], and CPU emulators [18]. Csmith [35] and all these efforts [2, 20, 21, 36] generate test programs from scratch. We propose a technique to derive EMI variants from existing tests. [2, 20, 21, 36] only found several bugs. Csmith found hundreds of bugs before, but the current production compilers (e.g., GCC and LLVM) are already resilient to it. We also used Csmith to generate seed programs, but rarely found bugs triggered directly by the seeds. **EMI** Recently, Le et al. introduce equivalence modulo inputs (EMI), a technique that allows creation of many variants from a single program that are semantically equivalent under some inputs to stress test compilers [9]. They have developed a series of tools to instantiate EMI. Orion [9] deletes unexecuted statements randomly. Proteus [10] stress tests the link-time optimizers of GCC and LLVM by splitting a translation unit into multiple ones and randomizing optimization levels. Athena [11] randomly inserts code into and removes statements from dead code regions, and uses the Markov Chain Monte Carlo (MCMC) method to guide EMI variant generation. Hermes complements all the three tools above, as our mutation strategies operate on live code regions, which overcome the limitations of mutating dead code regions as mentioned in Section 1. Moreover, our approach is also orthogonal to Athena because it can be easily integrated into the MCMC process of Athena to propose EMI variants. **CLsmith** CLsmith is a testing system built on top of Csmith to validate OpenCL compilers [4] by leveraging differential testing [9, 35] (i.e., using a reference compiler to serve as the test oracle) and EMI. As stated in [4], the dynamically-dead code regions are scarce in practical kernels, and therefore they injected dead-by-construction code into kernels. Specifically, they construct an always false conditional block, and the condition compares two global literals (e.g. a literal can be an integral constant, or a global variable whose value is known at compile time and does not change at run time) which is known to be dead by construction but unknown to compilers. Later in [6], Donaldson and Lascu discussed a broader way to generate EMI variants by mutating existing expressions with identity functions. For example, an identity function can be defined as \[ \text{id}(e) = e + e_0, \] where \( e \) is an existing expression in the seed program, \( e_0 \) is a synthesized expression whose value is always zero w.r.t. the same input, and the result expression \( e + e_0 \) is equivalent to \( e \) but in a different syntactical form. Hermes differs from CLsmith as our mutation strategies interact with the local context more as CLsmith’s false predicate relies on the comparison between two global literals, whereas ours are randomly synthesized over all in-scope variables. Moreover, we also generate live code blocks (TCB) which is not supported by CLsmith. All our mutation strategies are ready to be incorporated into CLsmith, which we believe can improve the diversity of its test programs. 6.2 Verified Compilers A verified compiler ensures that the compilation from source code is semantics preserving, i.e., the compiled code is semantically equivalent to the source code. This goal is achieved by accompanying a correctness proof with the compiler that guarantees semantic preservation. The most notable verified compiler is CompCert [13, 14], a certified optimizing compiler for a subset of C language. The compiler with its proof has been developed using Coq proof assistant. Zhao et al. proposed a new technique to verify SSA-based optimizations in LLVM with the Coq proof assistant [37]. Malecha et al. applied the idea of verified compilers to the database domain and built a verified relational database management system [17]. Lopes et al. proposed a domain-specific language to automatically prove and generate peephole optimizers [16]. The benefit of verified compilers is clearly their guarantee of compilation correctness. For example, years of testing with Csmith, Orion and Athena have not revealed a single bug in the optimizer component of CompCert. This correctness guarantee is crucial to safety-critical domains. However, for general application domains, verified compilers have not been widely accepted due to their limited types of optimizations compared to the production compilers, e.g., GCC and LLVM. 6.3 Translation Validation Translation validation aims to verify that the compiled code is equivalent to its source code and find any compilation errors on the fly. The motivation originates from the fact that it is usually easier to prove the correctness of a specific compilation than to prove the correctness of compiling every input program. Hanan Samet first introduced the concept of translation validation in [26]. Pnueli et al.’s work [24] proposed to use translation validation to validate the non-optimizing compilation from SIGNAL to C. Later, Necula [22] extended the concept to directly validate compiler optimizations and successfully validated four optimizers in GCC 2.7. Tate et al. introduced a translation validation framework for JVM based on equality saturation [29]. Later, Tristan et al. validated intraprocedural optimizations in LLVM [31] by adapting the work on equality saturation [29]. 7. Conclusion We have presented a class of novel EMI mutation strategies for compiler testing. Rather than mutating dead code regions like the state-of-the-art tools Orion and Athena, our technique directly manipulates live code regions, which significantly increases the space of EMI variants and testing efficiency. Within only 13 months, our realization Hermes has found 168 confirmed bugs in GCC and LLVM, of which 132 have already been fixed. We keep actively testing GCC and LLVM with Hermes, and have still been able to find around 10 bugs per month even after many months of testing. For future work, we plan to design more live code EMI mutation strategies by leveraging the insights of this paper — investigating observed program states by running programs with a set of inputs in order to fabricate EMI mutation code. 8. Acknowledgments We are grateful to the anonymous reviewers for their insightful comments. This research was supported in part by the United States National Science Foundation (NSF) Grants 1117603, 1319187, 1349528 and 1528133, and a Google Faculty Research Award. The information presented here does not necessarily reflect the position or the policy of the Government and no official endorsement should be inferred. References
{"Source-Url": "http://web.cs.ucdavis.edu/~su/publications/oopsla16.pdf", "len_cl100k_base": 15125, "olmocr-version": "0.1.53", "pdf-total-pages": 15, "total-fallback-pages": 0, "total-input-tokens": 60264, "total-output-tokens": 17247, "length": "2e13", "weborganizer": {"__label__adult": 0.00040650367736816406, "__label__art_design": 0.00028824806213378906, "__label__crime_law": 0.00028014183044433594, "__label__education_jobs": 0.0006127357482910156, "__label__entertainment": 5.394220352172851e-05, "__label__fashion_beauty": 0.00018036365509033203, "__label__finance_business": 0.00020325183868408203, "__label__food_dining": 0.000362396240234375, "__label__games": 0.0006885528564453125, "__label__hardware": 0.00104522705078125, "__label__health": 0.0005216598510742188, "__label__history": 0.0002114772796630859, "__label__home_hobbies": 9.08970832824707e-05, "__label__industrial": 0.0003504753112792969, "__label__literature": 0.00026607513427734375, "__label__politics": 0.00027179718017578125, "__label__religion": 0.0005636215209960938, "__label__science_tech": 0.00984954833984375, "__label__social_life": 7.385015487670898e-05, "__label__software": 0.003276824951171875, "__label__software_dev": 0.9794921875, "__label__sports_fitness": 0.0003437995910644531, "__label__transportation": 0.0005674362182617188, "__label__travel": 0.0002065896987915039}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 66581, 0.04441]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 66581, 0.35173]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 66581, 0.86216]], "google_gemma-3-12b-it_contains_pii": [[0, 4257, false], [4257, 9895, null], [9895, 14021, null], [14021, 19051, null], [19051, 24789, null], [24789, 27160, null], [27160, 31623, null], [31623, 37171, null], [37171, 42278, null], [42278, 47284, null], [47284, 50875, null], [50875, 52805, null], [52805, 58581, null], [58581, 64007, null], [64007, 66581, null]], "google_gemma-3-12b-it_is_public_document": [[0, 4257, true], [4257, 9895, null], [9895, 14021, null], [14021, 19051, null], [19051, 24789, null], [24789, 27160, null], [27160, 31623, null], [31623, 37171, null], [37171, 42278, null], [42278, 47284, null], [47284, 50875, null], [50875, 52805, null], [52805, 58581, null], [58581, 64007, null], [64007, 66581, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 66581, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 66581, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 66581, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 66581, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 66581, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 66581, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 66581, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 66581, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 66581, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 66581, null]], "pdf_page_numbers": [[0, 4257, 1], [4257, 9895, 2], [9895, 14021, 3], [14021, 19051, 4], [19051, 24789, 5], [24789, 27160, 6], [27160, 31623, 7], [31623, 37171, 8], [37171, 42278, 9], [42278, 47284, 10], [47284, 50875, 11], [50875, 52805, 12], [52805, 58581, 13], [58581, 64007, 14], [64007, 66581, 15]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 66581, 0.11002]]}
olmocr_science_pdfs
2024-12-09
2024-12-09
9362515f70ed2fdfa892ffcad2f1a26e29fcf31b
On plan recognition and parsing John Maraist SIFT, LLC∗ jmaraist@sift.info Christopher W. Geib University of Edinburgh† cgeib@inf.ed.ac.uk Robert P. Goldman SIFT, LLC rpgoldman@sift.info Probabilistic plan recognition systems based on weighted model counting all work roughly the same way: first they compute the exclusive and exhaustive set of models that explain a given set of observations; next they assign a probability to each model; finally they compute the likelihood of a particular goal by summing the probability of the explanatory models in which that goal occurs. In this paper we discuss an optimization for the model-building first step: rather than retain the full tree-like structure of goals which have been partially observed, we can keep only the frontier of as-yet unobserved actions and unachieved subgoals. The system Yappr which we present here uses techniques familiar from parsing algorithms. We give an informal introduction to Yappr in Section 1, a more formal presentation in Section 2, and an analysis of Yappr’s complexity in Section 3. In Section 4 we present experimental result showing the improvement realized from this technique, and then conclude with discussions of the algorithm’s limitations, and future work. 1 Introduction The starting point for our work is Geib and Goldman’s system PHATT [2003; 2009]. PHATT models contain collections of partially expanded hierarchical plans [Ghallab et al., 2004] for specific goals that account for the observed actions. PHATT builds these plans incrementally, from left to right, by adjoining leftmost, depth-first plan tree fragments to the existing plans. To extend an existing plan these leftmost trees are attached at the plan’s frontier, in the position of unachieved subgoals at trees’ leaves. There may be multiple ways to incorporate a single observation into an explanatory model: different ways of incorporating the observation yield multiple trees that could be adjoined into the model. In such cases, PHATT makes multiple copies of the original model, and each tree is inserted into its own copy of the plan structure expanding the set of explanations. Here we make two observations about PHATT’s operational behavior. First, this approach to plan recognition is reminiscent of recursive descent parsing algorithms [Steedsman, 2000]; PHATT builds its trees in the same way a parser might label a tree root with the grammar’s starting symbol, expand the tree with nodes corresponding to further nonterminals, finally producing a parse tree with nonterminals labelling branches and terminals labelling leaves. However, traditional parsing methods alone cannot address plan recognition. The most pressing reason for this is our commitment to allowing for the execution and recognition of multiple, concurrent, interleaved plans. Standard parsing algorithms like CKY [Younger, 1967] are designed for a single sentence at a time and usually assume that they will observe a complete sentence. Human language speakers do not interleave multiple sentences in the same way they interleave execution of plans. People regularly engage in such multitasking; our plan recognition algorithms should be capable of recognizing these situations and their component plans. Of course it is not surprising that existing parsing algorithms make such assumptions, but their reliance on these assumptions does make them inappropriate for our task. The second observation about PHATT’s operational behavior is that during explanation construction, the part of the plan’s tree structure above the frontier is not used; only the frontier is required. Any approach which copies that structure will incur significant computational costs. It is the frontier (in combination with observed actions) that determines the new trees which can be added to the model; all additions to the explanation’s structure are made at the frontier. Moreover, with a straightforward transformation of the plan library we will not need the tree structures even to extract the plan’s root-level goals. Since all interactions with the explanation take place at the frontier, we can dispense with the tree structure, maintain only the tree frontier, and avoid unnecessarily creating and copying interior tree structure in the model’s plans. We will show that the frontier of the trees in an explanatory model can be represented as a string of nonterminals and ordering constraints from a grammar that defines the original plan library to be recognized. By careful precomputation, we can build a plan grammar that explicitly models only the frontiers and ordering constraints of the leftmost depth-first trees from the original plan library. We will then show how to use the new grammar to build explanatory models that maintain just the frontiers of the plans in the model. This will allow us to build and maintain equivalent but significantly smaller model structures. Intuitively, the approach we will argue for with Yappr has three high level steps: 1. Offline, precompile the plan library into a plan frontier fragment grammar (PFFG). 2. Use the resulting PFFG to build explanations for the observed actions. This process will look very much like a string rewriting or graph editing process. 3. Maintain the PFFG productions and the order in which they are used in building each of the explanations. This information will allow us to build more complete explanations in the case of queries for information beyond the root goals being followed. Strictly speaking, this approach corresponds to goal recognition rather than plan recognition [Blaylock, 2005]: the latter calculates the complete plan structure being followed by the agent, as opposed to identifying only the top-level goals. We see Yappr as a middle road: the root goals being pursued are the most common probabilistic query for such systems. Therefore, we argue for an algorithm that builds restricted models that allow us to quickly answer this question while still allowing the system to reconstruct complete plan models if a probabilistic query is made about details not available in our restricted models. 2 The Yappr system Plan libraries The foundation of any plan recognition system is a collection of plans to be recognized. These plans must be specified in a formal language. Definition 1 We define a plan library as a tuple \( \langle \Sigma, NT, R, P \rangle \) where, \( \Sigma \) is a finite set of basic actions or terminal symbols, \( NT \) is a finite set of methods or nonterminal symbols, \( R \subseteq NT \) is a distinguished set of intendable or root nonterminal symbols, and \( P \) is a set of production rules of the form \( A \rightarrow \alpha : \phi \) where: - \( A \in NT \). - \( \alpha \) is a finite multiset of symbols from \( \Sigma \cup NT \). - \( \phi \) gives a partial order on indices into \( \alpha \). The similarity between this definition and the usual formalism for context-free grammars (CFGs) is obvious. We have extended the traditional notion with multiple starting symbols and the explicit ordering constraint relation \( \phi \). These ordering constraints indicate when actions must be performed in a specific order. Traditional CFGs productions take \( \alpha \) to be a string instead of a multiset, with \( \phi \) given by the total order of the symbols in the string. Here we assume that the actions in \( \alpha \) are unordered unless that \( \phi \) states otherwise. In a traditional CFG partial ordering is handled by replicating those rules that contain partial ordering, one production rule for each of the possible orderings for the actions. Since a system of the kind we are describing would be forced to consider all of the possible orderings for the actions, using a traditional CFG could result in a catastrophic increase in the computational cost of the algorithm. This formulation is also subtly different than in traditional hierarchical task networks (HTNs) [Ghallab et al., 2004]. Some formulations of HTNs allow arbitrary applicability conditions that must be true before a production can be used. The plan library defined here is strictly less expressive than these formulations of HTNs, but equivalent to HTN formulations without these additional conditions. Definition 2 Given a rule \( \rho = A \rightarrow \beta : \phi \) We say \( \beta[i] \) is a leftmost child of \( A \) given \( \rho \) if \( \exists j \) such that \( (j, i) \in \phi \). We write \( \mathcal{L}(\rho) \) for the set of all leftmost children given \( \rho \); this set describe exactly those symbols that are required to be first in any expansion of the parent nonterminal by \( \rho \). Note that this definition does not require that there be a unique leftmost symbol of a rule. We use \( \mathcal{R}(\rho) \) to denote the set of all symbols that are not leftmost of \( \rho \). Definition 3 Given a plan library \( \langle \Sigma, NT, R, P \rangle \) we define a leftmost tree \( T \) deriving \( \alpha \) as a tree such that: - Every node in \( T \) is labeled with a symbol from \( \Sigma \cup NT \). - Every interior node in \( T \) is labeled with a symbol from \( NT \). - If an interior node \( n \) labeled \( A \) in \( T \) has children with labels \( \beta_1, \ldots, \beta_k \), then: - \( \exists \rho \in P \) such that \( \rho = A \rightarrow \beta_1 \ldots \beta_k : \phi \). - Node \( n \) is additionally annotated with \( \rho \). - No children of \( n \) labeled with symbols in \( \mathcal{R}(\rho) \) have children of their own. - At most one child of \( n \) labeled with a symbol in \( \mathcal{L}(\rho) \) has children of its own. - There is a distinguished node in the frontier of \( T \) labeled with the terminal symbol \( \alpha \) that is leftmost for its parent. We call this the foot of the tree \( T \). Leftmost trees correspond very closely to minimal, leftmost, depth-first, derivation trees for a specific terminal in traditional CFGs. In this case, the ordering relation defined for the plan library is used to determine which nonterminals are leftmost. We will use leftmost trees to build PFFGs. To do this, we first define a generating set of trees: Definition 4 A set of leftmost trees is said to be generating for a plan library \( PL = \langle \Sigma, NT, R, P \rangle \) if it contains all of the leftmost trees that derive some basic action in \( \Sigma \) rooted at a method in \( NT \). We denote the generating set \( \mathcal{G}(PL) \) and refer to its members as generating trees. Finally, on the basis of these generating trees we can define the PFFG for the specific plan library. Definition 5 We define the plan frontier fragment grammar (PFFG) for the plan library \( PL = \langle \Sigma, NT, R, P \rangle \) and its generating trees \( \mathcal{G}(PL) \) as a tuple \( \text{PFFG}_PL = \langle \Sigma, NT', R, P' \rangle \) where: - \( NT' \subseteq NT \). - \( P' \) is the set of all production rules of the form: \[ \text{pid} : (a, B) \rightarrow \alpha : \phi \] for a tree \( T \in \mathcal{G}(PL) \): - \( \text{pid} \) is a unique identifier for the production rule, - \( a \in \Sigma \); we say that \( a \) is the foot of \( T \), - \( B \in NT' \); we say that \( B \) is the root of \( T \). \[ \text{Definition 6} \] We define a (possibly partial) explanation for a sequence of observations \( \sigma_1 \cdots \sigma_n \), given a plan library \((\Sigma, NT, R, P)\), as a tuple \((\sigma_{m+1} \cdots \sigma_n, \alpha, \phi, PS)\) where: - \( 0 \leq m \leq n \), and \( \sigma_{m+1} \cdots \sigma_n \) are those observations that have not yet been explained. - \( \alpha \) is the explanation frontier, a finite multiset of symbols from \( \Sigma \cup NT \) representing the frontiers of the plans in the explanation. - \( \phi \) gives a partial order on indices into \( \alpha \). - \( PS = \langle pid_1, \alpha[i_1], \ldots, pid_m, \alpha[i_m] \rangle \) is a sequence of pairs of production identifiers and elements of \( \alpha \). \( PS \) records the specific productions that were applied to produce \( \alpha \). \[ \text{Definition 7} \] We define the pending attachment points for an explanation \( e = \langle \sigma_1 \cdots \sigma_n, \alpha, \phi, PS \rangle \) as \( \{ \alpha_k : \alpha_k \in \alpha \wedge \mathcal{A}(j, k) \in \phi \} \) and we denote this set as \( AP(e) \). \[ \text{Main algorithm} \] The main YappR algorithm takes a PFFG and a sequence \( \sigma_1 \cdots \sigma_n \) of observations as inputs, and generates the complete set of explanations for a given set of observations. We define the initial explanation for every problem as the tuple \( \langle \sigma_1 \cdots \sigma_n, \{} , \{} , \{} \rangle \). Starting from this base case, we maintain the set of explanations as we process each observation in turn. There are three possibilities at each observation: 1) the observation removes a single terminal symbol from the explanation, 2) the observation adds nonterminals to the frontier of the explanation, and 3) the observation is the first action of a previously unobserved plan. The algorithm below produces the complete set of explanations for a given a set of observations and a PFFG. Each case is commented in the code. \[ \text{PROCEDURE} \] \( \text{Explain}((\sigma_1 \cdots \sigma_n, PFFG_{PL} = (\Sigma, NT, R, P)) \) \[ \text{DO} = \{} \); \( E = \text{Emptyqueue}(); \) \[ \text{Enqueue}((\sigma_1 \cdots \sigma_n, \{} , \{} , \{} , E); \] \[ \text{Process each observation in turn.} \] \[ \text{FOR } i = 1 \text{ to } n \text{ DO} \] \[ \text{Loop over all explanations.} \] \[ \text{WHILE} \text{ Nonempty}(E) \text{ DO} \] \[ E' = \text{Emptyqueue}() \] \[ e = \langle \sigma_1 \cdots \sigma_n, \alpha, \phi, PS \rangle = \text{Dequeue}(E); \] \[ \text{Extend existing plans.} \] \[ \text{FOR EACH } B \in AP(e); \] \[ \text{Remove terminals from the frontier.} \] \[ \text{IF } B = \sigma_i, \text{ THEN} \] \[ \alpha' = \alpha - B; \] \[ \phi' = \text{UpdateRemoving}(\phi, B); \] \[ \text{Enqueue}((\sigma_1 \cdots \sigma_n, \alpha', \phi', PS), E'); \] \[ \text{END IF; \ Expand the frontier.} \] \[ \text{FOR EACH } pid : \langle \sigma_i, B \rangle \rightarrow \gamma : \psi \in P \] \[ \alpha' = (\alpha - B) + \gamma; \] \[ \phi' = \text{UpdateAdding}(\phi, \psi); \] \[ PS' = PS + \langle pid, B \rangle; \] \[ \text{Enqueue}((\sigma_1 \cdots \sigma_n, \alpha', \phi', PS'), E'); \] \[ \text{END FOR LOOP; \ Introduce new plans.} \] \[ \text{FOR EACH } pid : \langle \sigma_i, C \in R \rangle \rightarrow \gamma : \psi \in P \] \[ \alpha' = \alpha + \gamma; \] \[ \phi' = \text{UpdateAdding}(\phi, \psi); \] \[ PS' = PS + \langle pid, C \rangle; \] \[ \text{Enqueue}((\sigma_1 \cdots \sigma_n, \alpha', \phi', PS'), E'); \] \[ \text{END FOR LOOP; \ Prepare for the next iteration.} \] \[ E = E' \] \[ \text{IF } E \text{ is empty THEN fail;} \] \[ \text{END FOR LOOP; \ Return } E; \] A small amount of further bookkeeping in each case ensures that the ordering constraints are kept consistent, and that constraints referring to a removed actions are either deleted or appropriately redirected to existing actions in the explanation. This is the task of the UpdateRemoving and UpdateAdding functions. Note that if none of these cases apply, the current explanation is inconsistent with the current observation and is pruned from the search. Note the addition of \( \langle pid, B \rangle \) to \( PS \) in the second and third cases. If required, we can use \( PS \) with the ordered list of observations to recreate the entire tree structure. Walking the list of \( pid \), nonterminal pairs and adjoining a copy of the tree structures from the plan library indicated by the \( pid \) at the specified nonterminal, will allow us to reconstruct the full plan structure underlying the explanatory model. Of course, implementations which do not require the full generality of queries which this log allows may simplify the representation of explanations appropriately, possibly further improving performance. It is the fact that \( B \) is removed or replaced in \( \alpha \) by \( \gamma \), or that \( \gamma \) is added to \( \alpha \) that makes this algorithm very much in the spirit of a string rewriting algorithm. The string of symbols, \( \alpha \), representing the explanation frontier are rewritten by the PFFG rules. Keep in mind that each enqueue operation in the above code creates a duplicate of the explanation structure to allow the different rules to be applied separately. It is this copying of the explanation structures that is less time consuming with Yappr’s structures than with the forest of trees that PHATT uses. We will return to discuss this in detail later. **Model counting and probabilities** To complete the Yappr system, we must provide a mechanism for computing the probabilities of the explanations we generate, and of individual goals driving some subsequence of the observed actions. An explanation \( e \) for a sequence of observations \( obs = \sigma_1 \ldots \sigma_n \) is a set of plans each built to achieve some multiset \( G_0, \ldots, G_t \) of the known goals \( R \). There may be multiple such explanations for fixed \( obs \) that differ in the goals, plans being pursued, or assignment of observations to plans. Leaving the observations implicit, we denote the complete and covering set of such explanations for a given set of observations as \( Exp \), and the subset of \( Exp \) that make use of a particular goal \( G \) as \( Exp_G \). We take a Bayesian approach to plan recognition, and so compute the conditional probability of a particular goal given the set of observations \( Pr(G|obs) \). By Bayes’ rule we have \[ Pr(G|obs) = \frac{Pr(G \land obs)}{Pr(obs)} \] or equivalently \[ Pr(G|obs) = \frac{Pr(G \land obs)}{\sum_{G' \land obs} Pr(G' \land obs)} \] where the denominator is the sum of the probability mass for all goals. However given our definition, we know that the plans in an explanation determine the goals in that explanation. Given that \( Exp \) is complete and covering, we can rewrite the previous equation as: \[ Pr(G|obs) = \frac{\sum_{e \in Exp} Pr(e \land obs)}{\sum_{e \in Exp} Pr(e \land obs)} \] (1) where the denominator sums the probability of all explanations for the observations, and the numerator sums the probability of the explanations in which the goal \( G \) occurs. Thus, if we can compute the probability of individual explanations for the observations, we can perform plan recognition by weighted model counting. We build a mutually exclusive and exhaustive set of possible explanations for the observations, compute the probability for each, and then sum the probability mass of explanations that contain a particular goal and divide by the probability mass of all of the explanations of the observations. To use Equation 1 to compute the conditional probability for any particular root goal, we need to be able to compute the probability of each explanation and the observations. We use the following formula, which is very similar to the one used in PHATT: **Definition 8** \[ Pr(exp \land obs) = \prod_{i=0}^{l} Pr(G_i) \cdot \prod_{i=1}^{n} Pr(rule_i) \cdot \frac{Pr(exy(AP(exp_i)))}{\sum_{exp} Pr(AP(exp))} \] where: - \( obs = \sigma_1 \ldots \sigma_n \). - \( Pr(G_i) \) is the prior probability of the goals \( G_i \) being pursued; the set of pursued goals is easily extracted from the productions \( PS \) of the explanations. - \( Pr(rule_i) \) is the probabilistic contribution of any plan choices that are captured within the rule, precompiled with the PFFG. Recall that any any particular PFFG rule may actually encode the choice of multiple productions from the original plan library; the likelihood of the agent making each of these choices must be captured in the model’s probability. - \( ext(AP(exp_i)) \) is the set of rules applicable to an explanation immediately prior to observation \( t \); it is just the set of all production rules that could be applied given the pending attachment points. The size of this set in the formula expresses the likelihood of choosing one such expansion. This definition assumes that \( Pr(rule_i) \) is precomputed, and that the choice from \( ext(AP(exp_i)) \) is made uner uniform probability. In fact, modeling these decision making processes is a very complex problem, and nothing in our approach rules out more complex probability models for them. However, for simplicity and low computational cost in our comparisons, we have assumed that each of these choices is captured by a uniform distribution. In the former case, the probability for each PFFG rule is computed offline when the PFFG is created and associated with its respective rule, and so the corresponding calculation is just the multiplication of these precalculated constants. In the latter case, the bookkeeping for counting the possible productions is a simple extension of procedure \texttt{Explain}, whose details we elide. This allows the second term in the above equation to be computed by taking the product of the probabilities associated with each production used in the explanation. One subtle point about the calculation of \( ext(AP(exp_i)) \) is worth mentioning. When a new goal is introduced it is necessary to modify this number for each preceding time point. Since our model is based on the assumption that the set of goals is determined before the actions are started, when a new goal is first observed it is possible that any of the lead actions for the new plan could have been done earlier. This means that when we add a new goal to an explanation we need to account for the possibility that it could have been performed earlier, and this requires modifying the recorded sizes of the pending attachment point sets. Note however, this is a \( O(n) \) operation where \( n \) is the number of observed actions, and as we will see, it is dominated by the cost of explanation construction. 3 Complexity analysis Having given the Yappr algorithm, we still need to show that it will be more efficient than model construction based on tree adjunction. We will show this by considering the complexity of the model construction algorithm. In Yappr, the complexity for generating a single explanation is $O(n \log(m))$ where $n$ is the number of observations to be explained, and $m$ is the length of the longest plan possible in the plan library. We argue for this in the following way. For a single explanation, for each of the $n$ observations, a single PFFG rule is instantiated, the nonterminal is removed from the explanation, and the right hand side of the instantiated PFFG rules is inserted. With efficient data structures the removal of the nonterminal and the insertion of the right hands side of the PFFG rule can be done in constant time, however the instantiating of the PFFG rule requires creating a copy of the rule. This process is dominated by the copying of the right hand side of a PFFG rules. The length of the right hand side of the any PFFG rule, corresponds to the depth of the original plan tree, and so costs $O(\log(m))$ to copy and instantiate. Note the $O(\log(m))$ length of the rules holds even if there are multiple nonterminals at each level of the leftmost trees that generated the PFFG. To see this, let $K$ to be the maximum length of any of the production rules in the initial library. This means that any individual level of one of the leftmost trees can have no more than $K$ nonterminals and by extension the length of any rule in the PFFG can be no longer than $K \log(m)$. $K \leq m$ and for most domains $K \ll m$. This only expands the PFFG right hand by a constant and the depth of the original plan tree dominates this feature for all domains where $K \ll m$. Given that the PHATT algorithm is adjoining leftmost trees, its complexity is not significantly different for this portion of the problem. To see this, consider that the significant difference between a single leftmost trees and a PFFG production rule is the addition of a $O(\log(m))$ number of nonterminals that act as a spine for the attachment of the frontier symbols. We do note that the constant for the Yappr algorithm should be significantly smaller. As we argued in the introduction, the significant savings for Yappr is in the smaller size of the data structure it uses to represent the plans in an explanation. In Yappr, as is in PHATT, the creation of each explanation requires copying the explanation structure. Since in the worst case there can be an exponential number of explanations to consider [Geib, 2004] the size of the data structures to be copied is critical. In PHATT each explanation is a forest of tree structures, in the worst case a single a single tree of $O(2^n - 1)$ nodes has to be copied for each of the explanations. Bounding the size of the Yappr data structure is a little more challenging. In order to copy an explanation in Yappr, we must copy both the model’s frontier and the ordering constraints. First, we consider the ordering constraints. If we let the size of the explanation frontier be $m$, then in the worst case there is an ordering constraint between each pair of actions in $m$, resulting in $m^2$ constraints that need to be copied. Given the absence of epsilon productions in the initial grammar, the size of the explanation frontier must be less than or equal to the number of observations. Therefore in the worst case, copying the ordering constraints would take $O(n^2)$. Note that given the absence of epsilon productions the frontier itself can never exceed $n$ elements in length making the copying of the frontier $O(n)$, and dominated by the constraint copying process. Therefore the worst case $O(n^2)$ sized copy operations for our algorithm represents a significant savings over the tree copying algorithm. For less densely connected graphs the effective complexity of the Yappr data structure will be less that $O(n^2)$ and the resulting savings will be greater. Most promising for the Yappr algorithm, the greatest number of explanation copy operations occurs precisely when the actions in the plan are least ordered. Plans with completely unordered actions result in a very large number of possible explanations. However, in precisely these cases, the Yappr explanation copying operation reduces to $O(n)$ since only the frontier needs to be copied and there are no ordering constraints. Thus the greatest computational savings from the smaller size of the copy operations for Yappr occurs exactly in the most computationally expensive cases. Our experiments confirm this. We also consider the cost of computing the probability of an explanation in the Yappr data structure. Inspection of Definition 8 shows that we have to perform operations on each of the rules used. These multiplications can be done in a single pass as can the computing the probability of the root goals. Thus, the cost of computing the probability for a single explanation in Yappr is $O(n)$, and is dominated by the construction of the explanations. 4 Experimental results To strengthen and verify the complexity results of the previous section, we implemented Yappr in Allegro Common Lisp (ACL) and ran empirical studies to directly compare the runtime of the PHATT and Yappr systems on the same input data. Our experiments were conducted on a single machine, a dual AMD 2000+ (1666.780) running Kubuntu Linux 7.04. We used ACL’s timing facilities to measure the CPU time of the algorithms alone, excluding garbage collection and system background process activity. All of our experiments began by generating a plan library to be recognized. These libraries were represented as partially ordered and/or trees that are similar to HTNs [Ghallab et al., 2004]. In this case and-nodes in the tree correspond to HTN methods and or-nodes correspond to the presence of multiple methods for a single goal in the plan. For all plans the root node was defined to be an or-node, and the plan alternated layers of or-nodes and and-nodes. There are a number of features that define a plan library: - **Root goals**: The number of top-level root goals. - **Plan depth**: The depth of each plan tree in the library. Our plan libraries are made up of alternating layers of and-nodes and or-nodes, we define a depth of one to mean each plan has one layer of or-nodes followed by one layer of and-nodes. A depth of two means there are two such two- ply layers. - **And-node branching factor.** The number of children for each and-node. Note this factor when combined with the plan depth determines the length of each plan in the library. For example, a plan with depth two and and-node branching factor of three has nine (\(3^2\)) observable actions. - **Or-node branching factor.** The number of children for each or-node. Since or-nodes represent alternatives in the plan, this factor has no effect on the length of plan instances but along with the plan depth and and-node branching factor determines the number of possible plans for each root goal in the library. - **Order.** Within each and-node the order factor determines if and how the siblings are related via causal ordering links. We will examine four possible ordering conditions. - **Total.** Children of an and-node are totally ordered. Each child action has a single ordering constraint with the child action that precedes it. - **First.** The children of each and-node have a designated first action. All other sibling actions are ordered after it but are unordered with respect to each other. - **Last.** The children of each and-node have a designated last action. All other sibling actions are ordered before it, but are unordered with respect to each other. - **Unord.** The children of each and-node are completely unordered with respect to each other. It is this last feature, order, that we treat as an experimental factor here. We hold the rest of these features constant with the following values: <table> <thead> <tr> <th>Root goals</th> <th>100</th> </tr> </thead> <tbody> <tr> <td>Plan depth</td> <td>2</td> </tr> <tr> <td>And-node branching factor</td> <td>3</td> </tr> <tr> <td>Or-node branching factor</td> <td>2</td> </tr> </tbody> </table> For each of the different values of the order factor, we generated 100 data points by randomly selecting one root goal from the plan library and generating a plan for that root goal that obeyed the rules and ordering constraints in the plan library. Thus, each data point was nine observations long and contained no noise. Each such list of observations was then presented in turn to both Yappr and PHATT to compute the conditional probabilities for the goals. To provide the most equivalent runtime environments possible for each invocation of each algorithm, we triggered a full garbage collection beforehand. For each run we imposed a thirty second timeout on the problem. The runtimes for each test case are presented in Figure 1, and summarized in Table 1. ACL’s timing facility cannot resolve times of less than ten msec. This resulted in the system reporting a runtime of zero milliseconds for several cases in the Total and First orderings. In cases of a zero reported runtime, we have instead depicted a runtime of five milliseconds. This was done to more accurately reflect the reality of the process taking some non-zero amount of time. Across all tests Yappr outperformed PHATT (in some cases by almost an order of magnitude). These results clearly demonstrate the gains available by using the Yappr approach. We discuss the results for the individual tests in turn. As we described in the previous section, Yappr saves the most on its copy operations when the frontier has the fewest ordering constraints. This can be seen clearly in Figure 1(a) which graphs the runtimes for plans with the Order factor = Unord. In these cases, even though PHATT and Yappr must compute the same number of explanations, the savings from the smaller models allows Yappr to solve problems PHATT is simply incapable of. In none of these cases was PHATT able to solve the problem within the thirty second timeout bound, or indeed within larger bounds of several minutes, while Yappr was able to solve all of them in under seventeen seconds. While this difference is not as profound in more ordered cases, it is present across all of the values of Order. Consider the Order = Last case in Figure 1(b). Here Yappr outperforms PHATT by almost an order of magnitude. For clarity, in all of these figures we have added a line representing the average runtime for each system. Note that Yappr has a lower variance than PHATT. The relatively high variance of both systems is caused by considering models with multiple instances of the root goals that are discarded when the final action is seen. Next, consider the Order = first case in Figure 1(c). While we see a drop in runtime below one second for both systems, Yappr’s runtime still is less than half that of PHATT, and displays a smaller variance than PHATT. Finally, in totally ordered libraries shown in Figure 1(d) we see the same trends. Note that in this final case the runtimes on the y-axis is plotted on a log scale to accommodate the large standard deviation of the PHATT runtimes. Yappr again outperforms PHATT and has a smaller variance. All of these experiments provide confirmation of our claims for the Yappr approach. Across the tested ordering constraints the experiments show the Yappr approach yields faster results and lower variance. ### 5 Limitations Yappr’s algorithm is optimized to be able to answer queries about the root goals being pursued in a set of plans. The model building process only returns the current explanation Figure 1: Runtimes comparing Yappr and PHATT. All graphs plot time in milliseconds on the vertical axis. Each Yappr and PHATT runtime is plotted as a plus-sign or X respectively. Solid lines show mean runtime with dotted lines show one standard deviation from the mean. Note in Graph (a) only Yappr’s performance is shown. PHATT did not terminate on examples from this library, even allowing timeouts of several minutes. For example, suppose we want to know the probability that a particular method was used to achieve a goal. With PHATT’s complete plan tree representations it would be relatively easy to select those explanations that had this structure by walking the plan trees of each of the explanations. In order to do the same thing with Yappr, the full plan structures must be reconstructed from the set of observations and the list of applied rules. Given access to the generating trees for the original grammar, reconstructing a single explanation with \( n \) observations and \( m \) being the length of the largest plan will take \( O(n \log(m)) \) time. This follows from our previous argument about the complexity of explanation building. Of course, again the critical question is how many explanations need to be reconstituted. We can imagine domains where there is very little copying of the explanations and very few explanations are pruned as being inconsistent with the observations. In such domains, if these more complex queries are required, it remains to be seen if Yappr would still outperform PHATT. Yappr is only able to recognize the set of plans that are encoded in the plan library that is initially provided. However, this does not mean Yappr is unable to generate an explanation for observation streams that contain such “unknown” plans. To do this, we include productions in the plan library that allow each action to be done as a root goal. This allows Yappr to build explanations in these cases, while still treating these more complex explanations as less likely than explanations with fewer root goals for known plans. 6 Related work We have discussed the relationship of Yappr to PHATT in detail, but there is a large amount of other related work. Huber et al. [1994] give an early approach to compiling plans into HTN-like structures for plan recognition. Geib and Goldman [2009] give a more complete survey of plan recognition algorithms and their complexity. We are not the first to suggest that plan recognition can be done by a process similar to probabilistic parsing. Pynadath and Wellman [2000] proposed the use of probabilistic context-free grammars for plan recognition. Yappr addresses a number of issues that are not addressed by Pynadath and Wellman, including cases of partially ordered plans and multiple interleaved plans. The idea of maintaining only a subset of parse trees has also been used before in parsing. Most common parsing algorithms for context free grammars, including CKY [Younger, 1967], do not maintain an entire parse tree but instead only maintain the derived nonterminals of the grammar. However, to the best of our knowledge, this approach has never been in plan recognition to reduce the overhead of maintaining explanatory models. Our deployment of Yappr to the SPDR security system [Haigh et al., 2009] provided insight into Yappr’s usability and limitations. Our top-down use of PFFGs restricts the form of plan library rules in a manner similar to that placed on grammars in top-down parsing. We also found that some transformation of plan libraries was required for acceptable system performance: when several decompositions of goals or sub-goals all begin with a common prefix of actions, the space of explanations can grow quickly as all of these explanations must be separately maintained until a distinguishing action comes several relevant observations later. When this effect applies to several goals being executed concurrently, Yappr’s performance degrades. In SPDR we addressed these difficulties by transforming the rules to factor common prefixes above disjunctions, but this introduction of internal symbols can make intermediate states difficult for the human monitor to understand. Parsing techniques may again be applicable: Leermakers et al. [1992] have considered compact storage of parse tree forests in their treatment of recursive ascent parsers; we hope to adapt their techniques both to relaxing the allowable forms of grammars, and avoiding obscuring transforms via more compact explanation storage. Geib [2009] has developed a new algorithm exploring some of these ideas. 7 Conclusion In this paper, we have argued that explicitly representing tree-based explanation in plan recognition is needlessly costly. Instead of using tree fragments and adjunction to construct models for plan recognition, we have formalized the idea of plan frontier fragment grammars and shown how they can be used to build models in a manner similar to string rewriting. We have then provided a complexity argument for this approach and shown its improved performance over the PHATT system. Acknowledgments This material is based on work supported by (DARPA/U.S. Air Force) under Contract FA8650-06-C-7606 and the EU Cognitive Systems project PACO-PLUS (FP6-2004-IST-4-027657) funded by the European Commission. References
{"Source-Url": "http://maraist.org/static/work/pair09.pdf", "len_cl100k_base": 8916, "olmocr-version": "0.1.50", "pdf-total-pages": 8, "total-fallback-pages": 0, "total-input-tokens": 30262, "total-output-tokens": 10247, "length": "2e13", "weborganizer": {"__label__adult": 0.000457763671875, "__label__art_design": 0.0006389617919921875, "__label__crime_law": 0.0005497932434082031, "__label__education_jobs": 0.0011577606201171875, "__label__entertainment": 0.00019609928131103516, "__label__fashion_beauty": 0.0002663135528564453, "__label__finance_business": 0.0003273487091064453, "__label__food_dining": 0.0005335807800292969, "__label__games": 0.0009741783142089844, "__label__hardware": 0.0012826919555664062, "__label__health": 0.0009326934814453124, "__label__history": 0.00046753883361816406, "__label__home_hobbies": 0.00015115737915039062, "__label__industrial": 0.0007100105285644531, "__label__literature": 0.0011301040649414062, "__label__politics": 0.000457763671875, "__label__religion": 0.0007810592651367188, "__label__science_tech": 0.276611328125, "__label__social_life": 0.00017082691192626953, "__label__software": 0.0122528076171875, "__label__software_dev": 0.6982421875, "__label__sports_fitness": 0.00043129920959472656, "__label__transportation": 0.0008769035339355469, "__label__travel": 0.00024890899658203125}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 41025, 0.01448]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 41025, 0.67561]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 41025, 0.90436]], "google_gemma-3-12b-it_contains_pii": [[0, 4902, false], [4902, 11264, null], [11264, 15637, null], [15637, 21967, null], [21967, 28468, null], [28468, 33712, null], [33712, 35674, null], [35674, 41025, null]], "google_gemma-3-12b-it_is_public_document": [[0, 4902, true], [4902, 11264, null], [11264, 15637, null], [15637, 21967, null], [21967, 28468, null], [28468, 33712, null], [33712, 35674, null], [35674, 41025, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 41025, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 41025, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 41025, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 41025, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 41025, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 41025, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 41025, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 41025, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 41025, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 41025, null]], "pdf_page_numbers": [[0, 4902, 1], [4902, 11264, 2], [11264, 15637, 3], [15637, 21967, 4], [21967, 28468, 5], [28468, 33712, 6], [33712, 35674, 7], [35674, 41025, 8]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 41025, 0.02513]]}
olmocr_science_pdfs
2024-11-28
2024-11-28
6956a3d26c7a9c4b42e865a7e4777a3fe8bee56b
Collaborative Hashing Xianglong Liu† Junfeng He† Cheng Deng‡ Bo Lang† †State Key Lab of Software Development Environment, Beihang University, Beijing, China ‡Facebook, 1601 Willow Rd, Menlo Park, CA, USA ‡Xidian University, Xi’an, China {xlliu, langbo}@nlsde.buaa.edu.cn jfh@fb.com chdeng.xd@gmail.com Abstract Hashing technique has become a promising approach for fast similarity search. Most of existing hashing research pursue the binary codes for the same type of entities by preserving their similarities. In practice, there are many scenarios involving nearest neighbor search on the data given in matrix form, where two different types of, yet naturally associated entities respectively correspond to its two dimensions or views. To fully explore the duality between the two views, we propose a collaborative hashing scheme for the data in matrix form to enable fast search in various applications such as image search using bag of words and recommendation using user-item ratings. By simultaneously preserving both the entity similarities in each view and the interrelationship between views, our collaborative hashing effectively learns the compact binary codes and the explicit hash functions for out-of-sample extension in an alternating optimization way. Extensive evaluations are conducted on three well-known datasets for search inside a single view and search across different views, demonstrating that our proposed method outperforms state-of-the-art baselines, with significant accuracy gains ranging from 7.67% to 45.87% relatively. 1. Introduction Recently hashing technique has attracted great attentions in fast similarity search [3, 5, 12–15, 18]. Based on the concept of locality sensitivity [7], it represents data points using the binary codes that preserve the original similarities among data. The retrieval of similar data points can then be completed in a sublinear or even constant time, by Hamming distance ranking based on fast binary operation or hash table lookup within a certain Hamming distance. Moreover, the binary compression of original data can largely reduce the storage consumption. Existing hashing approaches usually find the compact binary codes by exploiting the data correlations among the data entities (e.g., the cosine similarities between feature vectors). In practice, there are many scenarios involving nearest neighbor search on the data matrix with two dimensions corresponding to two different coupled views or entities. For instance, the classic textual retrieval usually works based on the term-document matrix with each element representing the correlations between two views: words and documents. Recently, such bag-of-words (BoW) model has also been widely used in computer vision and multimedia retrieval, which mainly captures the correlations between local features (even the dictionaries using sparse coding) and visual objects [16, 17]. Besides the search applications, the rapidly developed recommendation studies based on collaborative filtering, analyzing relationships between users and interdependencies among items to identify new user-item associations, also impose strong requirements on the nearest neighbor search with a collected rating matrix between users and items [2, 10, 20]. In the literature, rare works have been reported to regard the hashing problem with the matrix-form data, considering the duality between different types of entities or views. It is difficult to directly apply the traditional hashing methods to simultaneously hashing two types of entities and meanwhile preserving their correlations. Recently, [19] and [20] attempted to address the problem by concentrating on the duality between views under different scenarios. [19] viewed both documents and terms as the same type of entities in a bipartite graph, and pursued the binary codes for them following the idea of spectral hashing [18]. To handle the unobserved/missing ratings in collaborative filtering, [20] directly learned the binary codes that can recover the observed item preferences of all users. Both methods mainly explore the correlations between two views in order to preserve the occurrences or preferences in the training matrix. However, they neglected the fact that the entities’ neighbor structures inside each view play rather important roles in compact binary codes pursuit in nearest neighbor search [4, 6] or collective patterns discovery in In this paper we propose a collaborative hashing (CH) scheme for nearest neighbor search with data in matrix form. By simultaneously preserving both the inner similarities in each view (intra-view) and the interrelationships across views (inter-view), it learns the compact hash codes and the hash functions for entities in two views. As Figure 1 demonstrates, the proposed collaborative scheme fundamentally works as follows: On the one hand, fusing the semantic correlations between the coupled views will enhance the discriminative power of the features in each view, and subsequently helps obtain more compact and meaningful hash codes for each view. On the other hand, by retaining the duality between two correlated views based on the collective patterns discovered through hash grouping in each view, the collaborative hashing embeds different types of entities into a joint semantic Hamming space, which enables fast and accurate search across views. Therefore, the proposed collaborative hashing can serve as a unified framework for applications including: (1) search inside a single view: the most typical example is the visual search using local descriptors [16,17]; (2) search across different views: Recommendation using user-item ratings falls in this direction [2,10,20]. In many successful recommendation algorithms, matrix factorization serves as a core technique for collaborative filtering [10]. It turns the item suggestions into the search based on their similarities in a low dimensional Euclidean space. Instead of the Euclidean space, our collaborative hashing aims to find binary codes in Hamming space, guaranteeing efficient storage and fast similarity search across users and items. We essentially summarize our contributions as follows: 1. We propose a collaborative hashing scheme general for nearest neighbor search with data in matrix form. By simultaneously considering both the intra-view (in each view) and the inter-view (across views) relationships in one framework, it enables fast similarity search widely involved in many applications such as image search using bag of words and recommendation using user-item ratings. 2. We formulate it as an optimization problem with a loss function, which incorporates the binary quantization loss for the neighbor relations in each view, and the divergence between the training data and the predictions based on the binary codes for the interrelationships across views. 3. We adopt the projection-based linear hash functions, and present an alternating optimization way to effectively learn both the binary codes and the explicit hash functions for out-of-sample extension. Our extensive empirical study on several large-scale benchmarks highlights the benefits of our method for visual search and item recommendation, with significant performance gains over state-of-the-art hashing methods. 2. Collaborative Hashing 2.1. Notation Suppose we have the data matrix \( U = (u_{ij}) \in \mathbb{R}^{n \times m} \), consisting of \( n \) entities (images, users, etc.) of type I in one dimension and \( m \) entities (visual words, items, etc.) of type II in another dimension. Therefore, the matrix actually characterizes the associations between the two types of entities in terms of observations like word counts or user-item ratings: Each entry \( u_{ij} \) in the matrix indicates the presence of entity \( j \) of type II in entity \( i \) of type I, and its value reflects the strength of their association. Existing hashing algorithms either independently treat the two views of the data matrix \([2,4]\), or mainly concentrate on the correlation information between the two views \([19,20]\). In our collaborative hashing, we will simultaneously learn the discriminative hash functions for both views, which not only preserve the locality in each view, but also capture the correlations between views. Specifically, the problem of collaborative hashing can be formally defined as respectively learning \( b \) hash functions \( h_i(\cdot), i = 1, \ldots, b \) and \( g_j(\cdot), j = 1, \ldots, b \) for different types of entities, and generating the corresponding compact binary codes \( H = [h_1 \ldots h_n] \in \{-1,+1\}^{b \times n} \) and \( G = [g_1 \ldots g_m] \in \{-1,+1\}^{b \times m} \) that well preserve the semantic relationships conveyed by the matrix \( U \). For simplicity, we apply the linear-form hash functions. \[ h_i(x) = \text{sign}(W^T x) \text{ and } g_i(x) = \text{sign}(V^T x) \text{ where } W = [w_1, \ldots, w_6] \text{ and } V = [v_1, \ldots, v_6] \text{ are the projection parameters for both types of hash functions.} \] 2.2. Formulation Our basic idea is trying to exploit the intrinsic relations in the matrix data: both the neighbor structures in each view and the semantic correlations between views. Correspondingly, two types of losses will be employed to guide the hash function learning in our formulation: the binary quantization loss of hash functions and the correlation prediction loss using the binary codes. Firstly, we respectively treat each row and column of \( U \) as the features of the corresponding entities of type I and type II, and hash them into binary codes. Note that the hashing process, grouping similar entities for the collective patterns discovery, serves as an important characteristic of the collaborative scheme. Since the binary quantization in hashing behaves like the clustering algorithms [4, 6, 15], minimizing such quantization loss faithfully preserves the similarity structure of the data in each view: \[ E_{\text{quan}} = \frac{1}{n} \sum_{i=1}^{n} \| h_i - R_h \hat{u}_i \|^2 + \frac{1}{m} \sum_{j=1}^{m} \| g_j - R_g \hat{u}_j \|^2. \tag{1} \] Here \( U_h = [\hat{u}_1, \ldots, \hat{u}_n] \in \mathbb{R}^{b \times n} \) and \( U_g = [\hat{u}_1, \ldots, \hat{u}_m] \in \mathbb{R}^{b \times m} \) are the compressed feature representations for the involved two types of entities (see the initialization details in Section 2.3.4). \( R_h \in \mathbb{R}^{b \times b} \) and \( R_g \in \mathbb{R}^{b \times b} \) are orthogonal rotation matrices for better quantization: \[ R_h^T R_h = I \text{ and } R_g^T R_g = I. \tag{2} \] Besides the quantization error along each view, we should also explore the duality between the two views. Intuitively, the learned binary codes for two views should also preserve their correlations (the word counts in BoW features, the ratings in recommendation, etc.) in the Hamming space, rather than the latent Euclidean space in traditional collaborative filtering. Consequently, the correlation between entity \( i \) of type I and entity \( j \) of type II can be predicted efficiently in Hamming space [12, 20]: \[ c(h_i, g_j) = \frac{1}{2} + \frac{1}{2b} h_i^T g_j. \tag{3} \] with the prediction scaling variable \( \sigma \), the correlation prediction error on all the training samples can be given by: \[ E_{\text{rate}} = \frac{1}{nm} \sum_{i=1}^{n} \sum_{j=1}^{m} (\sigma c(h_i, g_j) - u_{ij})^2. \tag{4} \] Here, we first consider the basic case that all elements in \( U \) are observed. A well-known example is the bag-of-words feature, of which each element is regarded to be observed occurrence. For the sparse observation, we will give a simple, yet efficient solution in Section 2.5.2. Putting the quantization error and prediction error together, we can minimize the following objective function \[ E = E_{\text{quan}} + \lambda E_{\text{rate}}, \tag{5} \] where \( \lambda \) is a fixed weight, balancing the importance of similarities in a single view and across views. By rewriting the objective in matrix form with an \( n \times m \) matrix of ones \( J \), we can get \[ \begin{align*} \min_{H,G,R_h,R_g,\sigma} \quad & \frac{1}{n} \| H - R_h U_h \|_F^2 + \frac{1}{m} \| G - R_g U_g \|_F^2 \\ & + \frac{\lambda}{nm} \| \sigma \left( \frac{1}{2} - \frac{1}{2b} H^T G \right) - U \|_F^2 \\ \text{s.t.} \quad & H \in \{-1, +1\}^{b \times n}, \ G \in \{-1, +1\}^{b \times m} \\ & R_h^T R_h = I, \ R_g^T R_g = I. \tag{6} \end{align*} \] To further reduce the redundancies within the binary codes \( H \) and \( G \), we introduce the uncorrelated constraints: \[ HH^T = nI \text{ and } GG^T = mI. \tag{7} \] Note that the above formulation reveals an interesting connection between learning binary codes and factorizing the matrix in collaborative filtering. In particular, both methods approximate the correlations in low-dimensional space: when \( \sigma \) is already known, the last term in (6) is quite similar to the factorization loss in collaborative filtering. But our collaborative hashing here mainly focuses on the Hamming space for efficient storage and similarity search. Next we will give an alternating optimization solution to (6), which can efficiently learn both the binary codes and the explicit hash functions for out-of-sample extension. 2.3. Optimization The optimization problem can be solved by alternating among variables. We sequentially describe the updating steps for each variable, assuming the others are fixed. 2.3.1 The Binary Codes Fixing other variables and using the fact that the binary codes \( H \) are constrained to be uncorrelated in (7), we can rewrite the objective function in (6) as \[ \begin{align*} \max_{H} \quad & \text{trace} \left( H^T D_h \right) \\ \text{s.t.} \quad & HH^T = nI, \ H \in \{-1, +1\}^{b \times n} \tag{8} \end{align*} \] where \( D_h = \frac{1}{n} R_h U_h + \frac{\lambda \sigma}{2b} G \left( U^T - \frac{\sigma}{2} J^T \right) \). By relaxing the discrete constraint on \( H \), the problem can be solved efficiently by the singular value decomposition (SVD): $H = \text{sign}(S_h S_h^T)$ with the SVD $D_h = S_h \Pi S_h^T$. Likewise, we can update hash codes $G$ by solving $$\max_G \quad \text{trace} \left( G^T D_g \right)$$ $$\text{s.t.} \quad GG^T = mI, \ G \in \{ -1, +1 \}^{b \times m} \tag{9}$$ with $D_g = \frac{1}{m} T_g U_g + \frac{\lambda \sigma}{2bm} H \left( U - \frac{\sigma}{2} J \right)$. The near-optimal solution $G = \text{sign}(S_g S_g^T)$, given $D_g = S_g \Lambda S_g^T$. 2.3.2 The Rotation Matrices With the learned hash codes for both views, we can rewrite the objective function with respect to $R_h$ as $$\min_{R_h} \quad \| H - R_h U_h \|_F^2$$ $$\text{s.t.} \quad R_h^T R_h = I \tag{10}$$ The optimal $R_h$ in the above problem can be obtained by solving SVD of matrix $H U_h^T$: Decomposing $H U_h^T$ as $\hat{T}_h \Delta T_h^T$, then $R_{eh} = \hat{T}_h T_h^T$. For the rotation matrix $R_g$ in another view, we efficiently solve a similar optimization problem as follows: $$\min_{R_g} \quad \| G - R_g U_g \|_F^2$$ $$\text{s.t.} \quad R_g^T R_g = I \tag{11}$$ Based on the decomposition of $G U_g^T = \hat{T}_g \Omega T_g^T$, we obtain the optimal rotation $R_g = \hat{T}_g T_g^T$. 2.3.3 The Prediction Scalar The range of the observations in training data varies in different scenarios (e.g., $[0, +\infty)$ in BoW features, and 1-5 in recommendation), while our correlation prediction $c(\cdot, \cdot) \in [0, 1]$. Therefore, a scalar variable should be introduced to match the scales between the predictions and the true observations. By fixing other variables, the optimization problem with respect to the scalar $\sigma$ turns to $$\min_{\sigma} \quad \| \sigma \left( \frac{1}{2} J + \frac{1}{2b} H^T G \right) - U \|_F^2 \tag{12}$$ With $M = \frac{1}{2} J + \frac{1}{2b} H^T G$ and the vector representation of the matrix, the problem is equivalent to a least square problem $$\min_{\sigma} \quad \| \sigma \text{vec}(M) - \text{vec}(U) \|_F^2 \tag{13}$$ whose close-form solution will be $$\sigma = \frac{\text{vec}(M)^T \text{vec}(U)}{\text{vec}(M)^T \text{vec}(M)} \tag{14}$$ 2.3.4 Initialization In practice, hashing based on principle component analysis (PCA) can give good initializations of $H$ and $G$ [4]. Specifically, suppose we have the mean vectors $\mu_h$ and $\mu_g$ of the features $U^T$ and $U$ respectively for the two types of correlated entities, then we can obtain the projection matrices $P_h$ and $P_g$ by taking the top $b$ eigenvectors of the covariance matrix $(U^T - \mu_h 1^T)(U^T - \mu_h 1^T)^T$ and $(U - \mu_g 1^T)(U - \mu_g 1^T)$, which preserve the most information in corresponding feature spaces. Based on the projection matrices, we can initialize the compressed feature representations $U_h$ and $U_g$ by $$U_h = P_h^T(U^T - \mu_h 1^T) \quad \text{and} \quad U_g = P_g^T(U - \mu_g 1^T) \tag{15}$$ The orthogonal rotation matrices $R_h$ and $R_g$ will not change the variances of $U_h$ and $U_g$. With the randomly generated $R_h$ and $R_g$, the binary codes can be initialized: $$H = \text{sign}(R_h U_h) \quad \text{and} \quad G = \text{sign}(R_g U_g) \tag{16}$$ 2.4. Out-of-Sample Extension The binary codes for the training entities are learned during the training stage of collaborative hashing. Nevertheless, it is usually required to handle the out-of-sample extension problem in many applications [4, 18]. In our method, we also learn the near-optimal rotation matrices $R_h$ and $R_g$ that balance the binary code assignment to preserve the neighbor relationships globally. Therefore, we can encode the out-of-sample data efficiently using the linear transformations composed of the rotations and the aforementioned projections. This indeed makes our method distinct from the most related work [20] that can only learn binary codes for the training data. Specifically, for hash functions $h_i, g_i, i = 1, \ldots, b$, the projection parameters are given by $W = P_h R_h^T$ and $V = P_g R_g^T$. Given a new entity $x$ from any view, we can encode it using the corresponding hash functions $$h_i(x) = \text{sign} \left( w_i^T (x - \mu_h) \right), \tag{17}$$ $$g_i(x) = \text{sign} \left( v_i^T (x - \mu_g) \right) \tag{18}$$ We list our Collaborative Hashing (CH) in Algorithm 1, which empirically converges fast in less than 20 iterations. 2.5. Applications As aforementioned, the proposed collaborative hashing serves as a general framework for applications following different search paradigms. 2.5.1 Search Inside a Single View First, CH can be directly used to address the standard nearest neighbor search problem widely involved in information retrieval and computer vision. The search process Algorithm 1 Collaborative Hashing (CH). 1: Initialize $U_h, U_g, H, G$ by (15) and (16); 2: repeat 3: Estimate $\sigma$ according to (14); 4: Update the binary codes $H$ and $G$ respectively according to (8) and (9); 5: Update the rotation matrices $R_h$ and $R_g$ respectively according to (10) and (11); 6: until Converge 7: Return the binary codes $H, G$, and hash functions $h$ and $f$ according to (17) and (18). is conducted on the same type of entities (i.e., inside a single view). In computer vision, a well-known example is the image search, where given a query image we expect to get the most similar ones from a large database. In these applications, the feature matrix $U$ is usually described based on the bag-of-words model, and each element $u_{ij}$ represents the occurrence of word $j$ in image $i$. More recently, [11] studied the cross-modal relationships between words and images, beyond simply identifying the word presence. Similarly, CH can also capture the semantic correlations between the coupled views. Unlike prior studies, we mainly focus on the pursuit of discriminative hash codes for fast similarity search inside each view. The search scheme here is exactly the same to that of traditional hashing methods using binary codes. With the hash functions given in (17) or (18), for any query the nearest neighbors in the same view can be found efficiently by Hamming distance ranking or hash table lookup. 2.5.2 Search Across Different Views Another search paradigm supported by our CH is seeking highly correlated entities of different types (i.e., across different views). The collaborative filtering for recommendation is one typical example that suggests the items with highest predicted ratings for specific users. In collaborative filtering, matrix factorization exploits the collective taste patterns from the user-item rating matrix, and improves the search quality by preserving preferences of users over items in a low-dimensional Euclidean space [10]. However, searching over a large database in the continuous space is quite slow. The compact binary codes learned by CH can hopefully help address the problem in a Hamming space. In recommendation applications, the data matrix $U$ records the user-item preferences: each nonzero elements $u_{ij}$ represents the rating given to the item $j$ by user $i$. Since there are lots of unobserved/missing user-item ratings in practice, the observation matrix $U$ will be quite sparse. To tackle such case, only the observed data should be considered in the optimization including (8), (9) and (12). We replace the correlation prediction error in (4) by $$E_{rue} = \frac{1}{\|A\|_1} \| \sigma \left( \frac{1}{2} J + \frac{1}{2b} H^T G \right) \circ A - U \|_F^2,$$ where $\circ$ is the Hadamard product operator, and $A = (a_{ij}) \in \{0,1\}^{n \times m}$ is a binary matrix with nonzero entries $a_{ij}$ indicating whenever $u_{ij}$ is observed (usually $\|A\|_1 \ll nm$). Regarding the estimation of $\sigma$, instead of (14) we have $$\sigma = \frac{\vec{\text{vec}(M \circ A)^T vec(U)}}{\vec{\text{vec}(M \circ A)^T vec(M \circ A)}}$$ With the hash codes $H$ for users and $G$ for items, to user $i$ we can recommend the item $j$ with largest $c(h_i, g_j)$. Therefore, the recommendation problem can also be solved using Hamming distance ranking or hash table lookup. 3. Experiments In this section we will evaluate the proposed collaborative hashing for two useful scenarios: search with bag-of-word features and recommendation using user-item ratings, which respectively correspond to the two search paradigms mentioned above. The proposed collaborative hashing method (CH) will be compared with both a number of state-of-the-arts standard hashing methods such as Locality Sensitive Hashing (LSH) [3], Spectral Hashing (SH) [18], Iterative Quantization (ITQ) [4], and Random Maximum Margin Hashing (RMMH) [9], and existing matrix hashing methods including Laplacian Co-Hashing (LCH) [19] and Binary Codes for Collaborative Filtering (BCCF) [20]. LCH simultaneously hashes both terms and documents according to their semantic similarities. Following the idea of spectral hashing, it learns the hash codes by solving an eigenvalue problem for the term-document similarity graph. BCCF was proposed to generalize the existing hashing works to the context of collaborative filtering. It learns binary codes for both users and items by forcing them to accurately preserve the item preferences of users. To evaluate the hashing performance, we employ two common nearest neighbor search methods following prior hashing research: Hamming distance ranking and hash table lookup. The former ranks all points in the database according to the Hamming distances from the query, while the later constructs a lookup table using the binary codes, and returns points falling within certain Hamming radius (usually 2) from the query codes as the retrieved results. All experiments are conducted on a workstation with Intel Xeon CPU E5645@2.40GHz and 24GB memory, and the results reported in this paper are averaged over ten independent training/testing data splits. For parameter sensitivity, our experiments indicate that CH is relatively robust with respect to $\lambda$ in a large range. Thus we roughly set it to 1,000 in all experiments. For all baselines, we fine tuned their parameters for the best performance. 3.1. Search with Bag of Words ### 3.1.1 Datasets and Protocols Hashing is widely adopted in visual search based on bag of visual words or high dimensional sparse codes. To evaluate our collaborative hashing in visual search following the paradigm “search inside a single view”, we employ the popular Holidays image dataset [8]. It mainly contains 1,491 personal holidays photos of high resolutions: 500 queries representing distinct scenes or objects and 991 corresponding relevant images with various attacks (e.g., rotations, blurring, etc.) to the queries. The dataset covers a very large variety of scene types. Similar to [1, 8], for large-scale retrieval the Holidays dataset is respectively appended with 15K, 25K and 100K Flickr images (forming Holidays+15K, +25K, and +100K). We represent Holidays+15K images using 10K visual vocabularies, and Holidays+15K and +100K using 20K ones (trained based on SIFT features of an independent dataset Flickr60K [8]). In all experiments, 500 queries in Holidays serve as the testing images, and 10K images are randomly sampled from each dataset as the training sets. Following prior hashing research [4, 12], we will report both the precision and recall performance of Hamming distance ranking, and the precision within Hamming radius 2 (PH2) when using hash table lookup. ### 3.1.2 Results and Discussions We will compare our collaborative hashing to the traditional state-of-the-art hashing methods (LSH, SH, RMMH, and ITQ). As to existing hashing methods for data in matrix form, since BCCF cannot tackle the out-of-sample hashing problem, in our experiments we will only adopt LCH that co-hashes both types of entities in the data matrix. <table> <thead> <tr> <th>HOLIDAYS</th> <th>HASH</th> <th>32 BITS</th> <th>64 BITS</th> <th>128 BITS</th> </tr> </thead> <tbody> <tr> <td>+15K</td> <td>LSH</td> <td>1.63±0.29</td> <td>3.63±0.34</td> <td>7.05±0.51</td> </tr> <tr> <td></td> <td>SH</td> <td>12.65±0.67</td> <td>16.36±1.60</td> <td>21.19±1.32</td> </tr> <tr> <td></td> <td>RMMH</td> <td>8.00±0.87</td> <td>11.28±1.40</td> <td>16.56±1.64</td> </tr> <tr> <td></td> <td>ITQ</td> <td>18.86±0.75</td> <td>25.42±1.60</td> <td>30.73±0.72</td> </tr> <tr> <td></td> <td>LCH</td> <td>17.96±0.47</td> <td>25.95±0.72</td> <td>31.87±0.50</td> </tr> <tr> <td></td> <td>CH</td> <td>20.95±0.82</td> <td>27.54±0.49</td> <td>32.34±1.30</td> </tr> <tr> <td>+25K</td> <td>LSH</td> <td>1.01±0.19</td> <td>1.68±0.24</td> <td>4.38±0.56</td> </tr> <tr> <td></td> <td>SH</td> <td>8.84±1.13</td> <td>11.76±0.75</td> <td>15.59±1.05</td> </tr> <tr> <td></td> <td>RMMH</td> <td>5.39±1.03</td> <td>7.59±1.14</td> <td>11.60±0.40</td> </tr> <tr> <td></td> <td>ITQ</td> <td>16.49±0.81</td> <td>22.92±0.96</td> <td>28.52±0.71</td> </tr> <tr> <td></td> <td>LCH</td> <td>12.67±1.13</td> <td>20.94±0.82</td> <td>29.73±0.77</td> </tr> <tr> <td></td> <td>CH</td> <td>18.42±0.56</td> <td>25.61±0.64</td> <td>31.23±0.51</td> </tr> <tr> <td>+100K</td> <td>LSH</td> <td>0.56±0.12</td> <td>1.14±0.13</td> <td>2.69±0.19</td> </tr> <tr> <td></td> <td>SH</td> <td>8.00±0.91</td> <td>8.03±1.13</td> <td>9.09±0.57</td> </tr> <tr> <td></td> <td>RMMH</td> <td>4.22±0.43</td> <td>4.98±0.36</td> <td>7.67±0.93</td> </tr> <tr> <td></td> <td>ITQ</td> <td>12.34±0.60</td> <td>17.21±1.38</td> <td>22.18±1.11</td> </tr> <tr> <td></td> <td>LCH</td> <td>8.67±0.83</td> <td>15.64±1.27</td> <td>22.41±0.70</td> </tr> <tr> <td></td> <td>CH</td> <td>12.53±0.62</td> <td>18.53±0.80</td> <td>24.02±0.23</td> </tr> </tbody> </table> Table 1 presents the mean average precisions (MAP) of different hashing methods on three Holidays datasets. Performances of all methods improve when using longer hash codes, and clearly CH achieves the highest performance in all cases with remarkable superiority (up to 11.08%, 11.80%, and 7.67% performance gains on three datasets over the best competitors). We also compare precision-recall (P-R) performances using 64 bits on all datasets in Figure 2. LCH explores the duality between images and visual words, and achieves better performance than LSH, RMMH and SH. However, its performance is inferior to that of ITQ in most cases, which indicates that the utilization of inner relationships among images plays an indispensable role in the performance improvement. We have the same conclusion from Table 1 by comparing performances of ITQ and LCH using less than 128 hash bits. Here, collaborative hashing, incorporating the correlations between views in addition to the neighbor structure of each view, boosts the discriminative power of the learned hash codes, and thereby obtains the best performance (the largest areas under the curves) in all cases. Besides Hamming ranking evaluation, we also conduct hash table lookup on these datasets, and report retrieval precisions within Hamming radius 2 (PH2) in Figure 3. Although in our experiments as the number of distractor images increases from 15K to 100K, performances of all hashing methods drop, but in all cases CH consistently outperforms other methods with large margins. ### 3.2. Recommend using User-Item Ratings #### 3.2.1 Datasets and Protocols Besides the basic search along a single view, an attractive advantage of collaborative hashing is that the learned compact hash codes, well preserving the correlations between the two views, can efficiently and accurately predict the ratings of unseen items in recommendation systems. We adopt two datasets to evaluate the recommendation performance of CH: MovieLens 1M and Netflikx, whose statistics are summarized as follows: - The MovieLens 1M dataset contains 3,900 movies, 6,040 users and about 1 million ratings. In this dataset, about 4% of the user-movie ratings are observed. The ratings are integers ranging from 1 (bad) to 5 (good). - The Netflix is one of the largest benchmarks for collaborative filtering. It contains over 100 million ratings for 17,770 movies by 480,189 users. All the ratings are also ranged from 1 to 5. We split the two datasets into training and testing sets as follows: for MovieLens, we randomly sample 80% ratings as the training set and the rest 20% is used as the testing one. As discussed in [20], in this dataset a lot of ratings are not observed, which may lead to biased evaluation results. Therefore, as [20] did, on Netflix we construct a relatively dense dataset consisting of 5,000 items with the most ratings and 10,000 users with at least 100 ratings. Then, we also sample 80% ratings and the rest as the training and testing sets respectively. For both datasets, items with ratings equal to 5 are regarded as the groundtruth items recommended to users. In order to comprehensively evaluate the item recommendation performance using binary codes, besides MAP and PH2 we further employ Normalized Discounted Cumulative Gain (NDCG) as prior recommendation research [20] does. NDCG is widely adopted to evaluate the ranking quality in practice, mainly focusing on whether the obtained binary codes can accurately preserve the original relevance orders of the items for different users. We use NDCG calculated at different cutting points (NDCG@5 and @10) in the ranking list as the evaluation metric, and each item rating labeled by users serves as the true relevance value. ### 3.2.2 Results and Discussions The proposed collaborative hashing can capture the item preferences of different users in recommendation systems, and therefore can accurately predict ratings for specific users. Traditional collaborative filtering based on matrix factorization represents users and items in a latent, low-dimensional Euclidean space, and thereby converts the item recommendation to the nearest neighbor search in such space. Instead, collaborative hashing discovers a Hamming space where entities can be encoded using compact binary codes, which largely improves the efficiency of both recommendation and storage. In the scenario of recommendation across views (i.e., users and items), we employ LCH and BCCF designed for recommendation as the baselines. Both methods outperform the standard collaborative filtering using binarized low-rank matrix factorization. Moreover, we also evaluate the traditional hashing methods including LSH and ITQ, which independently hash the entities in each view. Table 2 shows the NDCG results on the two datasets, comparing BCCF, LCH, and naive hashing solutions using LSH and ITQ. As we can see, the NDCG calculated at different cutting points (5 and 10) increases when using more hash bits, and CH consistently achieves the best performance with up to 45.87% and 15.09% performance gains respectively on the two datasets, indicating that CH can preserve the order of user preferences very well. LSH and ITQ, only relying on the inside similarities of each view, give the worst performances in all cases. These observations demonstrate that exploring the duality between views is quite beneficial to the high-quality recommendation. Furthermore, compared to LCH and BCCF, our CH faithfully leverages the preference preservation between two views based on the neighbor patterns in each view, and thus performs best on both datasets. We also depict the MAP of Hamming ranking with respect to 16 - 64 hash bits and PH2 of hash lookup using 16 bits in Figure 4. Again, we can observe that the proposed hashing method ranks first with a large margin compared to the best competitors LCH and BCCF in terms of both MAP and PH2. This fact leads to the conclusion that our collaborative hashing can largely improve performances by elegantly taking advantages of the neighbor structure inside the same view and the correlations across different ones. ### 4. Conclusion In this paper, we proposed a collaborative hashing scheme for data in matrix form that can learn hash codes for both types of entity in the matrix, making the proposed method conceptually unique compared with the existing methods. The key idea of the proposed method is that the learned binary codes of each type of entities should attain their neighbor structure, and meanwhile accurately preserve the correlations between different types of entities. We adopted a loss function in our optimization formulation, consisting of the binary quantization loss for each view and the deviation of predictions based on the binary codes. An efficient alternating optimization method has been proposed to learn both the hash codes and functions well preserving data distributions and the correlations. Comprehensive results over two classic applications are considerably encouraging: the proposed collaborative hashing significantly outperforms the state-of-the-art hashing methods. Acknowledgement This work is supported in part by NSFC 61370125 and 61101250, NCE-T-12-0917, SKLSDE-2013ZX-05 and SKLSDE-2014ZX-07. References [1] R. Arandjelović and A. Zisserman. All about VLAD. In IEEE CVPR, 2013. 6
{"Source-Url": "http://sites.nlsde.buaa.edu.cn/~xlliu/cvpr2014.pdf", "len_cl100k_base": 8881, "olmocr-version": "0.1.50", "pdf-total-pages": 8, "total-fallback-pages": 0, "total-input-tokens": 34735, "total-output-tokens": 10438, "length": "2e13", "weborganizer": {"__label__adult": 0.0004668235778808594, "__label__art_design": 0.00107574462890625, "__label__crime_law": 0.0005736351013183594, "__label__education_jobs": 0.0016021728515625, "__label__entertainment": 0.00032973289489746094, "__label__fashion_beauty": 0.0003001689910888672, "__label__finance_business": 0.0005502700805664062, "__label__food_dining": 0.00043082237243652344, "__label__games": 0.0016374588012695312, "__label__hardware": 0.0016126632690429688, "__label__health": 0.0008845329284667969, "__label__history": 0.0004639625549316406, "__label__home_hobbies": 0.00018084049224853516, "__label__industrial": 0.0006189346313476562, "__label__literature": 0.0005755424499511719, "__label__politics": 0.00032019615173339844, "__label__religion": 0.0005588531494140625, "__label__science_tech": 0.468505859375, "__label__social_life": 0.00022101402282714844, "__label__software": 0.049652099609375, "__label__software_dev": 0.468505859375, "__label__sports_fitness": 0.00029969215393066406, "__label__transportation": 0.0004682540893554687, "__label__travel": 0.0003085136413574219}, "weborganizer_max": "__label__science_tech", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 36885, 0.06402]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 36885, 0.3438]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 36885, 0.87101]], "google_gemma-3-12b-it_contains_pii": [[0, 4436, false], [4436, 8863, null], [8863, 14046, null], [14046, 18768, null], [18768, 24176, null], [24176, 29186, null], [29186, 33363, null], [33363, 36885, null]], "google_gemma-3-12b-it_is_public_document": [[0, 4436, true], [4436, 8863, null], [8863, 14046, null], [14046, 18768, null], [18768, 24176, null], [24176, 29186, null], [29186, 33363, null], [33363, 36885, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 36885, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 36885, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 36885, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 36885, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 36885, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 36885, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 36885, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 36885, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 36885, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 36885, null]], "pdf_page_numbers": [[0, 4436, 1], [4436, 8863, 2], [8863, 14046, 3], [14046, 18768, 4], [18768, 24176, 5], [24176, 29186, 6], [29186, 33363, 7], [33363, 36885, 8]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 36885, 0.09804]]}
olmocr_science_pdfs
2024-11-30
2024-11-30
d629bf64e9546a1a1d68a582e75e69d13ead59d0
[REMOVED]
{"Source-Url": "https://www.cse.iitk.ac.in/users/ktiwari/resources/parallelComputing.pdf", "len_cl100k_base": 13580, "olmocr-version": "0.1.53", "pdf-total-pages": 18, "total-fallback-pages": 0, "total-input-tokens": 53465, "total-output-tokens": 13761, "length": "2e13", "weborganizer": {"__label__adult": 0.0005125999450683594, "__label__art_design": 0.0008111000061035156, "__label__crime_law": 0.0004055500030517578, "__label__education_jobs": 0.001209259033203125, "__label__entertainment": 0.0001577138900756836, "__label__fashion_beauty": 0.00027108192443847656, "__label__finance_business": 0.0004777908325195313, "__label__food_dining": 0.0005230903625488281, "__label__games": 0.00211334228515625, "__label__hardware": 0.03533935546875, "__label__health": 0.0006189346313476562, "__label__history": 0.0007109642028808594, "__label__home_hobbies": 0.0003771781921386719, "__label__industrial": 0.0023899078369140625, "__label__literature": 0.0003390312194824219, "__label__politics": 0.0004019737243652344, "__label__religion": 0.000942707061767578, "__label__science_tech": 0.404541015625, "__label__social_life": 7.289648056030273e-05, "__label__software": 0.015899658203125, "__label__software_dev": 0.52978515625, "__label__sports_fitness": 0.0007252693176269531, "__label__transportation": 0.0013332366943359375, "__label__travel": 0.00034928321838378906}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 48868, 0.03916]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 48868, 0.64854]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 48868, 0.8595]], "google_gemma-3-12b-it_contains_pii": [[0, 2776, false], [2776, 6313, null], [6313, 8137, null], [8137, 11154, null], [11154, 15642, null], [15642, 18040, null], [18040, 21070, null], [21070, 24144, null], [24144, 27114, null], [27114, 31544, null], [31544, 35604, null], [35604, 36981, null], [36981, 37233, null], [37233, 39057, null], [39057, 40776, null], [40776, 44275, null], [44275, 48068, null], [48068, 48868, null]], "google_gemma-3-12b-it_is_public_document": [[0, 2776, true], [2776, 6313, null], [6313, 8137, null], [8137, 11154, null], [11154, 15642, null], [15642, 18040, null], [18040, 21070, null], [21070, 24144, null], [24144, 27114, null], [27114, 31544, null], [31544, 35604, null], [35604, 36981, null], [36981, 37233, null], [37233, 39057, null], [39057, 40776, null], [40776, 44275, null], [44275, 48068, null], [48068, 48868, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 48868, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 48868, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 48868, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 48868, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 48868, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 48868, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 48868, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 48868, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 48868, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 48868, null]], "pdf_page_numbers": [[0, 2776, 1], [2776, 6313, 2], [6313, 8137, 3], [8137, 11154, 4], [11154, 15642, 5], [15642, 18040, 6], [18040, 21070, 7], [21070, 24144, 8], [24144, 27114, 9], [27114, 31544, 10], [31544, 35604, 11], [35604, 36981, 12], [36981, 37233, 13], [37233, 39057, 14], [39057, 40776, 15], [40776, 44275, 16], [44275, 48068, 17], [48068, 48868, 18]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 48868, 0.09283]]}
olmocr_science_pdfs
2024-12-05
2024-12-05
68958a6a5353dd6ca956c4d856b65145fe5d6012
The following full text is a publisher's version. For additional information about this publication click this link. http://hdl.handle.net/2066/103802 Please be advised that this information was generated on 2018-05-03 and may be subject to change. Task-Oriented Programming in a Pure Functional Language Rinus Plasmeijer1 Bas Lijnse1,2 Steffen Michels1 Peter Achten1 Pieter Koopman1 1 Institute for Computing and Information Sciences, Radboud University Nijmegen P.O. Box 9010, 6500 GL, Nijmegen, The Netherlands 2 Faculty of Military Sciences, Netherlands Defense Academy P.O. Box 10000, 1780 CA, Den Helder, The Netherlands {rinus, b.lijnse, s.michels, p.achten, pieter}@cs.ru.nl Abstract Task-Oriented Programming (TOP) is a novel programming paradigm for the construction of distributed systems where users work together on the internet. When multiple users collaborate, they need to interact with each other frequently. TOP supports the definition of tasks that react to the progress made by others. With TOP, complex multi-user interactions can be programmed in a declarative style just by defining the tasks that have to be accomplished, thus eliminating the need to worry about the implementation detail that commonly frustrates the development of applications for this domain. TOP builds on four core concepts: tasks that represent computations or work to do which have an observable value that may change over time, data sharing enabling tasks to observe each other while the work is in progress, generic type driven generation of user interaction, and special combinators for sequential and parallel task composition. The semantics of these core concepts is defined in this paper. As an example we present the iTask3 framework, which embeds TOP in the functional programming language Clean. Categories and Subject Descriptors D.1.1 [Programming Techniques]: Applicative (Functional) Programming; D.2.11 [Software Engineering]: Software Architectures—Languages; D.2.11 [Software Engineering]: Software Architectures—Domain-specific architectures; D.3.2 [Programming Languages]: Language Classifications—Applicative (functional) languages; H.5.3 [Information Interfaces And Presentation]: Group and Organization Interfaces—Computer-supported cooperative work; H.5.3 [Information Interfaces And Presentation]: Group and Organization Interfaces—Web-based interaction Keywords Task-Oriented Programming; Clean; 1. Introduction When humans and software systems collaborate to achieve a certain goal they interact with each other frequently and in various ways. Constructing software systems that support human tasks in a flexible way is hard. In order to do their work properly human beings need to be well informed about the progress made by others. We lack a formalism in which this aspect of work is specified at a high level of abstraction. In this paper we introduce Task-Oriented Programming (TOP), a novel programming paradigm to define interactive systems using tasks as the main abstraction. TOP provides advanced features for task collaboration. We choose tasks as unit of application logic for three reasons. First, they cover many phenomena that have to be dealt with when constructing systems in a natural and intuitive way. In daily life we use this notion to describe activities that have to be done by persons to achieve a certain goal. In computer systems, running processes are also commonly called tasks. On a programming language scale, a function, a remote procedure, a method, or a web service, can all be seen as tasks that can be executed. Second, in daily life it is common practice to split work into parallel and sequential sub-tasks and at the same time, during execution, not to be very strict about their termination behavior and production of results. Progress of work can be guaranteed even though some, or all, sub-tasks produce partial results. This contrasts with the usual concept of computational tasks that are interpreted as well-defined units of work that take some arguments, take some time to complete, and terminate with a result. Third, tasks abstract from the operational details of the work that they describe, assuming that the processor of the task knows how to perform it. The processor must deal with a plethora of issues: generate and handle interactive web pages, communicate with browsers, interact with web services in the cloud, interface with databases, and so on. Application logic is polluted with the management of side effects, the handling of complicated I/O like communication over the web, and the sharing of information with all users and system components. In this pandemonium of technical details one needs to read between the lines to figure out what a program intends to accomplish. Using tasks as abstraction prevents this. For these reasons, we conjecture and show that in the TOP paradigm specifying what the task is that needs to be done, and how it can be divided into simpler tasks is sufficient to create the desired application. We present a foundation for Task-Oriented Programming in a pure functional language. We formalize the notion of tasks as abstract descriptions of interactive persistent units of work. Tasks produce typed, observable, results but have an abstract implementation. When observed by other tasks, a task can either have no (meaningful) value, have a value that is a temporary result that may change, or have a stable final result. We show how to program using this notion of tasks by defining a set of primitive tasks, a model for sharing data between tasks, and a set of operators for composing tasks. Because higher-order function composition provides powerful composition already, only a small set of operators is necessary. These are sequential composition, parallel composition, and the conversion of task results. Most notably, we make the following contributions: - We introduce Task-Oriented Programming as a paradigm for programming interactive multi-user systems composed of interacting tasks. - We present tasks as abstract units of work with observable intermediate values and continuous access to shared information. - We present combinators for composition and transformation of tasks and formally define their semantics. - We demonstrate real-world TOP in Clean using the redesigned and extended iTask3 framework. The remainder of this paper is organized as follows: in Section 2 we informally explain the TOP paradigm by defining its concepts and a non-trivial example in Clean with the iTask3 framework. In Section 3 we formalize the foundations of TOP component-wise: tasks and their evaluation, sharing information, user interaction, and sequential and parallel task composition. In Section 4 we reflect on the pragmatic issues that need to be dealt with in frameworks that facilitate real-world TOP programming. After a discussion of related work in Section 5, we conclude in Section 6. For readability, we use Clean* (van Groningen et al., 2010) which is a dialect of Clean that adapts a number of Haskell language features. In this paper we deploy curried function types (Clean function types have arity), and the unit type () 2. The TOP Paradigm Task-Oriented Programming extends pure Functional Programming with a notion of tasks and operations for composing programs from tasks. Complex interactive multi-user systems are specified as decompositions of the tasks they aim to support. 2.1 TOP Concepts Tasks: Tasks are abstract descriptions of interactive persistent units of work that have a typed value. When a task is executed, by a TOP framework, it has an opaque persistent state. Other tasks can observe the current value of a task in a carefully controlled way. When an executing task is observed, there are three possibilities: 1. The task has no value observable for others: This does not mean that no progress is made, but just means that no value of the right type can be produced that is ready for observation. 2. The task has an unstable value: When a task has an unstable value, it has a value of the correct type but this result may be different after handling an event. It is even possible that the next time the task is observed it has no value. 3. The task has a stable value: The task has a clear final result. This implies that if the task is observed again, it will always have the same value. Tasks may be interactive. Such tasks process events and update their internal state. However, this event processing is abstracted from in Task-Oriented programs. The effects of events are only visible as changes in task results. Many-to-many Communication with Shared Data: When multiple tasks are executed simultaneously, they may need to share data between them. How and where this data is stored however, is often completely irrelevant to the task. What matters is that the data is available and that it is shared. Thus, when one task modifies shared data, the other tasks can observe this change. In TOP we abstract from how and where data is stored and define Shared Data Sources (SDS) as typed abstract interfaces which can be read, written and updated atomically. Generic Interaction: The smallest tasks into which an interactive system can be divided are single interactions, either between the system and its users or between the system and another system. Single interactions can be entering or updating some data, making a choice or just viewing some information. In TOP we abstract from how such interactions are realized unless it is essential to the task. A TOP framework generates user interfaces generically for any type of data used by tasks. This means that it is not necessary to design a user interface and program event handling just to enter or view some information. It is possible to specify interactions in more detail, but it is not needed to get a working program. Task Composition: TOP introduces the notion of tasks as first-class values, but also leverages first-class functions from pure functional programming. This means that only a small carefully designed set of core combinator functions is needed from which complex patterns can be constructed. 1. Sequential composition: TOP uses dynamic sequential composition. Because task values are observable, sequential compositions are not defined by blindly executing one task after another. They are defined by composing an initial task with a set of functions that compute possible next steps from the observed value of the initial task. 2. Parallel composition: Parallel composition is defined as executing a set of tasks simultaneously. Tasks in a parallel set have read-only access to a shared data source that reflects the current values of all sibling tasks in the set. In this way tasks can monitor each other’s progress and react accordingly. 3. Value transformation: Task domains can be converted by pure functions in order to combine tasks in a type consistent way. 2.2 An Example of TOP in Clean To illustrate Task-Oriented Programming in practice, we present a non-trivial example that uses the novel iTask3 framework. In the example, one specific user, the coordinator, has to collaborate with an arbitrary number of users to find a meeting date and time. Figure 1 displays that this task consists of three sub-tasks. This figure consists of actual screenshots of the user interfaces generated by the iTask3 framework. In sub-task one, the coordinator creates a number of date-time pairs. While doing so, he or she can rearrange their order, insert new date-time pairs, or remove them. Once satisfied, the coordinator confirms the work by pressing the Continue button, and steps into sub-task two. This sub-task two consists of a number of tasks running in parallel. The users (Alice, Bob, and Carol in this example) are all asked to make a selection of the proposed date-time pairs (the Enter preferences windows). Meanwhile, the coordinator can monitor and follow the selections being made (the Results so far window). At any time, the coordinator can either choose to restart the entire task all over again, by pressing the Try again button. He or she can also select a date-time pair that is suitable for (the majority of) all users by pressing the Make decision button. In the first case, they step into the plan meeting task afresh, and in the latter case, they step into sub-task three. In sub-task three the system provides the coordinator with an overview of available users per date-time pair, thus helping him or her to make a good decision. The coordinator can also decide not to pick any of the candidate date-time pairs and override them with a proposed alternative. Once satisfied with a choice, the coordinator terminates the entire task by pressing Continue, and returns a stable date-time value. In the remainder of this section we show how to specify this example in a Task-Oriented way. Figure 2 displays the complete specification. It contains TOP-notions explained in detail further on in this paper. The key point of this example is to show how Task-Oriented Programming aids to create a specification that closely matches the description that is shown above. The semantics of the As discussed, the main structure of planMeeting consists of three subsequent sub-tasks (lines 2-4), which are glued together by means of the step combinator >>. The second argument of >>= enumerates the potential subsequent task steps that can be stepped into while the first argument task is in progress. Hence, the first sub-task, enterDateTimeOptions, is followed by askPreferences, which in turn is followed by either tryAgain or decide. Entering user information (performed by enterDateTimeOptions, select, and pick) is an example of a task that may or may not have a task value. This depends on the input provided by the user. The potential task steps which can follow can observe the task value and define whether or not sufficient information is provided to step into the next task. In case of the transition from the first sub-task to the second sub-task, this requires an action from the coordinator (line 12). This is only sensible if the previous task has a task value, which is tested by the predicate hasValue. In that case, the current task value is retrieved (getValue) and used to step into the next sub-task, which is to ask all users to choose preferred date-time pairs. The observable task value is accessible in the step combinator to determine the next task steps chosen. The task value and its access functions are straightforward: hasValue tests for the Val data constructor, and getValue returns that value if present: --- ```haskell :: Stability = Unstable | Stable hasValue :: Value a -> Bool hasValue (Val _) = True hasValue _ = False getValue :: Value a -> a getValue (Val x) = x Tasks with stable values are terminated and can no longer produce a different task value. Hence task values are first-class citizens in Task-Oriented Programming. Two task transformer functions provide access: @? alters the task value of the preceding task, and @ is similar, but only if a Val is present: (?) infixl 1 :: Task a -> (Value a -> Value b) -> Task b | iTask a & iTask b (?) infixl 1 :: Task a -> (a -> b) -> Task b | iTask a & iTask b ``` The second sub-task of the coordinator is to ask all users in parallel to make a selection of the created date-time pairs. In addi- tion, the coordinator constantly monitors their progress. Parallel composition of tasks is defined with the parallel combinator. It is used explicitly in the ask task, and implicitly (by means of the derived parallel-or combinator \( \| \) ) that provides a shorter notation for the common case of choice between two alternative tasks in the pick task. Parallel composition is a core concept in Task-Oriented Programming. The second argument of parallel enumerates the sub-tasks that need to be evaluated in parallel. The progress is shared between all sub-tasks. Relevant to the example is the function \( \text{task} \text{LastState} \), which transforms this shared state to share the current task values. This is used by the monitor task (lines 24-25) to create a view on the current task values of the users. The monitor task uses \( \& \) to explicitly state that its task value never contains a concrete value. These can be provided only by the select sub-tasks. They offer their user the means to make a multiple-choice of the provided date-time pairs, and use \( \& \) to attach the user to identify who made that specific selection (lines 30-31). Finally, the last sub-task can be stepped into when the coordinator either decides to start all over again (lines 34-36) or pick a value (lines 39-40). The first action step is always valid (const True, line 35) and the second action step only when the previous task actually has a value (line 40). The derived combinator \( \| \) evaluates its two task arguments in parallel, and has a task value that is either stable (if one or both sub-tasks have one) or unstable (if one or both have one) or none. Hence, the action step can only occur when the coordinator has either selected one of the suggested date-time pairs or chosen to override them. This example demonstrates how a TOP approach can lead to a concise specification in which tasks are glued together and overall progress can be achieved even though the tasks themselves might not terminate or consume too much time. 3. A Formal Foundation of TOP In this section we introduce and semantically define the core concepts of Task-Oriented Programming. These are task values, tasks and their evaluation (Section 3.1), many-to-many communication (Section 3.2), user-interaction (Section 3.3), sequential task composition (Section 3.4), and parallel task composition (Section 3.5). Except for Section 3.1, every section has the same structure: we first introduce the core concept and illustrate it by means of the iTask3 system, and then formally define the operational semantics using rewrite semantics. The rewrite rules are specified in Clean*. Such a way of formal specification of semantics is somewhat unusual, but this approach has certain advantages over traditional ones (Koopman et al., 2009). The specification is well-defined, concise, compositional, executable, and can express even complicated language constructs as the ones introduced in this paper. Since we are dealing with constructs embedded in a functional language it is an advantage to describe their semantics as pure functions in a functional language as well. We have experimented with several alternative definitions which can easily introduce errors that remain overlooked. It is an advantage that the descriptions are checked by the compiler and that we have been able to test their correct working by applying it to concrete examples. Furthermore, the formal semantics is very suited and also used as blue print for the actual implementation and can serve as a reference implementation for implementations in other programming languages as well. In order to distinguish semantic definitions from iTask3 API and code snippets, we display semantic definitions as framed verbatim text, and iTask3 fragments as unframed verbatim text. 3.1 Tasks and their Evaluation In this section we define task results and task values (Section 3.1.1), tasks (Section 3.1.2), their evaluation (Section 3.1.3), and a number of task transformer functions (Section 3.1.4). 3.1.1 Task Results and Task Values A task of type \( \text{Task} a \) is a description of work which progress can be inspected by a task value of type \( \text{Value} a \) (Section 2.2). Tasks handle events. Events have a time stamp, for which we use an increasing counter, making it possible to determine the temporal order of events. The task result of handling an event may be a new task value. Semantically, we extend the task value with the time stamp of the event that caused the creation of that task value. Tasks that run into an exceptional situation have as task result an exception value instead of a task value. The domains of task results and task values capture these situations: \[ \begin{align*} \text{:: TaskResult} a & = \text{ValRes \ TimeStamp \ (Value} a) \\ & \mid \exists e: \text{ExcRes} e \& \text{iTask} e \\ \text{:: TimeStamp} & : \text{== Int} \\ \text{:: Value} a & : \text{== NoVal | Val} a \text{ Stability} \\ \text{:: Stability} & : \text{== Unstable | Stable} \end{align*} \] The task value of a task result can be in three different states: there can be no value at all (NoVal), there can be an Unstable value which may vary over time, or the value is Stable and fixed. To illustrate, consider the task of writing a paper. At time \( t_0 \) you have no paper at all (ValRes \( t_0 \) NoVal). After a while, at time \( t_1 \) there may be a draft paper \( p_1 \), which is updated many times at subsequent time stamps \( t_2 \ldots t_n \) with draft papers \( p_2 \ldots p_n \) (ValRes \( t_1 \) (Val \( p_1 \) Unstable)). You may even start all over again (ValRes \( t_{n+1} \) NoVal). At a certain point in time, \( t_{n+k} \) say, when you decide that the paper is finished the task has result ValRes \( t_{n+k} \) (Val \( p_{n+k} \) Stable) meaning that the paper can no longer be altered. Some tasks never produce a stable value. Examples are the interactive tasks (enterInformation, viewSharedInformation, enterChoice, enterMultipleChoice) that were used in Section 2.2: a user can create, change or delete a value as many times as wanted. Typical examples of tasks that produce a Stable value are ordinary functions, or system and web service calls. A task can raise an exception value (ExcRes e) in case it is known that it can no longer produce a meaningful value (for instance when a call to a web service turns out to be unavailable). Any value can be thrown as exception and inspected by an exception handler (Section 3.4), using existential quantification \( \exists e \) and the type class context restriction \( \& \text{iTask} e \) Tasks with stable values or exception values have no visualization but memorize their task result forever. The other tasks require a visualization to support further interaction with the user. 3.1.2 Tasks Semantically, we define a task to be a state transforming function that reacts to an event, rewrites itself to a reduct, and accumulates responses to users: \[ \begin{align*} \text{:: Task} a & : \text{== Event} \rightarrow \ast \text{State} \rightarrow \ast \text{(Reduce a, Responses, \ast State)} \\ \text{:: Event} & : \text{== RefreshEvent} \\ & \mid \text{EditEvent TaskNo Dynamic} // \text{Section 3.3.1} \\ & \mid \text{ActionEvent TaskNo Action} // \text{Section 3.4.1} \\ \text{:: \ast State} & : \text{== \{ taskNo \ : \ TaskNo \\ & , timeStamp \ : \ TimeStamp \ // \text{Section 3.3.1} \\ & , men \ : \ [\text{Dynamic}] \ // \text{Section 3.2.1} \\ & , world \ : \ \ast \text{World} \}} \\ \text{:: Reduce a} & : \text{== Reduce (TaskResult} a \) \ (\text{Task} a) \\ \text{:: TaskNo} & : \text{== Int} \\ \text{:: Responses} & : \text{== \{ (TaskNo, Response) \}} // \text{Section 3.3.1} \end{align*} \] We distinguish three sorts of events: a RefreshEvent, e.g. when an user wants to refresh a web page, an EditEvent, e.g. a new value that is committed intended for an interactive task (Section 3.3), and an ActionEvent which is used to tell the step combinator which task to do next (Section 3.4). The latter two cases identify the task that is required to handle the event. The interactive task and step task are provided with a fresh identification value and current time stamp, using the semantic function newTask: ```plaintext newTask :: (TaskNo → TimeStamp → Task a) → Task a newTask ta ev st=[ta(s),st=ta(st=ev no)] ``` Fresh task identification numbers are generated by keeping track of the latest assigned number in the State. The State extends the external environment of type World with internal administration and is passed around in a single-threaded way which is enforced by the uniqueness attribute $\ast$. The reduct contains both the latest task result and a continuation of type Task a, which is the remaining part of the work that still has to be done. This continuation can be further evaluated in the future when the next event arrives. The responses collect all responses of all subtasks the task is composed of. They are used to update every client with the proper information about the latest state of affairs. A client can use this information to adjust the page in the browser or in an app. In the remainder of this paper we define semantic task functions for the core basic tasks and task combinators, thus explaining how these elements rewrite to the next reduct. 3.1.3 Task Evaluation A TOP application consists of one top level task, the main task, which has to be evaluated. The work continues until either an exception escapes handling, or the work at hand has obtained a stable task value. ```plaintext evaluateTask :: Task a → World → (Maybe a, World) | iTask a evaluateTask ta world # st = (ta(s),mem=0,timeStamp=0,world=world) # (ma, st) = rewrite ta st = (ma,.st,world) rewrite :: Task a → World → (Maybe a, World) | iTask a rewrite ta st=[world] # (ev, world) = getNextEvent world # (t, world) = getCurrentTime world # st = (ta(s),mem=0,timeStamp=0,world=world) # (Reduct res nta, resp, st) = ta st ev = case res of ValRes _ (Val a Stable) → (Just a, st) ExcRes _ → (Nothing, st) _ → rewrite nta {st & world = informClients resp st.world} ``` In Clean(*), passing around multiple unique environments explicitly, such as st (::State) and world (::World), is syntactically supported by means of the non-recursive $\ast$-let definitions. The main task is recursively rewritten by the function rewrite. Rewriting is triggered by an event. We abstract from the behaviour of clients and just assume that they send events and handle responses. We assume that all events are collected in a queue. In getNextEvent (line 9) the next event is fetched from this queue. If there are no events, the system waits until there is one. The current time is stored in the state (lines 10-11) to ensure that all tasks which update their value in this rewrite round, will get the same time stamp. Hereafter (line 12), the main task $ta$ is evaluated given the event and current state. Any sub-task defined in the main task is as well, and can be evaluated in the same way; just apply the corresponding task function to the current event and the current state. Rewriting stops when the main task has delivered a stable value (line 14), or an uncaught exception is raised (line 15). Otherwise, the main task is not finished yet, and the continuation task returned in the reduct defines the remaining work which has to be done. First the accumulated responses are sent to the clients (informClients, line 17) to inform them about the latest state-of-affairs. We abstract from the way this is done. Rewriting continues with the continuation $nta$ and the updated state. 3.1.4 Utility Functions for Converting Tasks The semantic function stable, when applied to a time stamp $t$ and value $va$, defines a task that has reached a stable value: ```plaintext stable :: TimeStamp → a → Task a stable t va st = (Reduct (ValRes t (Val va Stable))) (stable t va,[],st) ``` Notice that the continuation of the task stable $t$ va in the reduct is exactly the same function stable $t$ va. It is a kind of fixed point task, which, whenever it is evaluated in some future, always returns the same reduce (value and continuation). With this semantic function, we can define the semantic function of the core task return: ```plaintext return :: a → Task a return va ev st= (Reduct (ExcRes e) (throw e),[],st) ``` Here, return has a similar role as the return function in a monadic setting; it lifts an arbitrary value $va$ of type $a$ to the task domain. Raising an exception is similar, except that the task result is always an exception value: ```plaintext throw :: e → Task e | iTask e throw e _ st = (Reduct (ExcRes e) (throw e),[],st) ``` With operator $\&$ and a function $f$ of type $Value a → Value b$ a task $ta$ of type Task $a$ can be converted to a task of type Task $b$: ```plaintext (?) infixl 1 :: Task a → (Value a → Value b) → Task b | iTask b (f) ta f ev st = case ta ev st of (Reduct (ValRes t aval nta, rsp, nst)) → case f aval of Val b Stable → (Reduct (ValRes t bval) (nta $\&$ f),rsp, nst) (Reduct (ExcRes e) _ _,nst) → throw e ev nst (Reduct (NoVal) _ _,nst) → NoVal (Val a s) s → Val a s ``` First the task $ta$ is evaluated (line 3). Exceptions raised by $ta$ are simply propagated (lines 10-11). The resulting task value, if any, is converted by function $f$. If this results in a stable value, then the entire task becomes stable with the current time stamp (lines 7-8). Notice that this has as consequence that the original task $ta$ is no longer needed. If the result is not stable, the original task may change its value over time, and we need to apply the conversion function to values produced in the future as well. Therefore, the current result $bval$ of the conversion is stored in the reduct with the continuation $nta$, which takes care of the conversion of the new task values produced in the future (line 8). The derived operator $\&$ uses $\&$ to transform task values only when a concrete value is present. 3.2 Many-to-many Communication For collaborating tasks it is important to keep each other up-to-date with the latest developments while the work is going on. Hence we need to be able to share information between tasks and support many-to-many communication. How and where this data is stored, is completely irrelevant to the tasks. What matters is that the data is available and that it is shared. To achieve this abstraction we use the concept of multi-purpose Shared Data Sources (SDS) (Michels and Plasmeijer, 2012). SDSs are typed, abstract interfaces which can be read, written and updated atomically. A SDS can represent a shared file, a shared structured database, reveal the current users of a system, or it can be a physical entity, like the current time or temperature. In general, a SDS abstracts from any shared entity that holds a value that varies over time. :: ROShared x w :: RWShared x w :: WOShared w :: Shared a A SDS has abstract type ROShared x w. Reading its current value returns a value of type x, and writing is done with a new value of type w. Read-only shared objects (ROShared x) only support reading as type x, write-only shared objects (WOShared w) only support writing as type w, and Shared a objects demand that the read and write values have the same type a. As an example, we show a few shares that are offered by the iTask3 system to create SDSs: sharedFile :: Path → a → Shared a | iTask a currentTime :: ROShared Time currentUsers :: WOShared [User] With (sharedFile fname content) a task is described that associates a file identified by fname with an initial value of type a. A task gains access to the current time and registered users with the tasks currentTime and currentUsers. SDSs provide many-to-many communication both between tasks and other applications. We make a difference between external and internal SDSs. External SDSs are abstractions of external objects such as files and databases and can be accessed anywhere in the application. For the internal communication between tasks only, one can create a shared memory SDS of type Shared a which has a limited scope. A task ta can be parameterized with a freshly created shared memory SDS as of type Shared a that has some initial value va using the combinator withShared va (λs → ta): withShared :: a → (Shared a → Task b) → Task b | iTask a In this way, a shared memory is created which can only be accessed by the sub-tasks defined within ta. For an example of its use, see Section 4. To write a value to a SDS, one can connect a task ta with a SDS s using a function $f$ with the combinator ta $\bowtie (f,a)$: (工地) infixl 1 :: Task a → (Value a → x → Maybe w, ROShared x w) → Task a $\bowtie$ ta This enforces $f$ to be repeatedly applied to the current task value of ta (if any) and the currently read value of a, the result of which is written to x. The combinators withShared and $\bowtie$ are defined in Section 3.2.1. SDSs integrate smoothly with interactive tasks. For every basic interactive task (such as enterChoice and enterMultipleChoice) a shared version (such as enterSharedChoice and enterSharedMultipleChoice) is provided that expects a SDS instead of a common value. This is discussed in Section 3.3 in more detail. In this way tasks can monitor and alter SDSs. 3.2.1 Semantics of Memory Shared between Tasks To explain the semantics of SDSs, we restrict ourselves to their use for offering shared memory between (parallel) tasks. These SDSs cannot be accessed by external applications. Hence the semantic definition does not need to handle concurrency and atomicity issues; there is only one rewrite function (Section 3.1.3) that handles rewriting of all tasks defined in an application. A SDS is represented by two access functions $\text{createShared}$ and $\text{updateMaybeShared}$ (Section 3.1.3) that handles rewriting of all tasks defined in an application. These SDSs provide many-to-many communication both between (parallel) tasks. These SDSs provide many-to-many communication both between (parallel) tasks. These SDSs provide many-to-many communication both between (parallel) tasks. These SDSs provide many-to-many communication both between (parallel) tasks. A SDS is represented by two access functions $\text{createShared}$ and $\text{updateMaybeShared}$ (Section 3.1.3) that handles rewriting of all tasks defined in an application. These SDSs provide many-to-many communication both between (parallel) tasks. withShared creates a fresh SDS for its argument task function and applies it to obtain the proper task. The combinator \( \bowtie \) memorizes the previous task value (initially notawal) and the current task continuation (initially the task argument ta) (line 9 and 16). As usual, at each event the current task continuation is evaluated (line 12). Exceptions are propagated (lines 13-14). The only difference is that if the new task value ntval is different from the memorized task value otval, then the SDS is updated using the argument function of the local function updateSDS (line 18). This function only updates the SDS if a new value is computed (lines 23 and 25). In this way unnecessary updates of shared data is avoided. Because \( \bowtie \) keeps checking the SDS using the most recent task value, this leads to reactive behavior: every time the watched task is changing its value, the shared memory also gets updated conditionally, as described above. 3.3 User Interaction In Task-Oriented Programming user-interactions are defined as tasks that allow a user to enter and modify a visualized value of some type. Such an interactive task is called an editor. The type of the value to be edited plays a central role. By using type indexed generic functions (Alimarine, 2005; Hinze, 2000) this visualization is generated fully automatically for any (first order) type. This way one can focus on defining tasks, without having to deal with the complexities of web protocols and formats. Interaction tasks follow a model-view pattern where the value of the task is the model and the visualization is the view. Events in the view are processed by the TOP framework to update the model. Conversely, when the model changes the view is updated automatically by the TOP framework. Interaction tasks are all alike, yet different. In this section we define the semantics of one core editor task (Section 3.3.1). However, to improve readability TOP frameworks can offer a range of predefined interaction tasks derived from this core editor. A few examples from the iTask3 framework are: \[ \begin{align*} \text{enterInformation} & : d \rightarrow [\text{EnterOpt m}] \\ \text{updateInformation} & : d \rightarrow [\text{UpdateOpt m}] \\ \text{viewInformation} & : d \rightarrow [\text{ViewOpt m}] \\ \text{updateSharedInformation} & : d \rightarrow [\text{UpdateOpt r w}] \\ \text{viewSharedInformation} & : d \rightarrow [\text{ViewOpt r w}] \end{align*} \] With enterInformation an editor for type \( m \) is created, no initial value needs to be given. The update-editor variants allow editing of a given local, respectively shared, value. The view-editor variants only display the value of a given local, or shared, value. There are many more similar editor functions predefined in the library, with names like enterChoice, enterSharedChoice, updateChoice, updateSharedChoice, enterSharedMultipleChoice, and so on. The overloaded argument \( d \) of class descr in these tasks is description of the task. This can be a simple string, or a more elaborate description. Although the generated view is certainly good enough for rapid prototyping, more fine-grained control is sometimes desirable. Therefore, the EnterOpt, UpdateOpt and ViewOpt arguments provide hooks for fine-tuning interactions. 3.3.1 Semantics of a Task Editor The iTask3 library provides many different editor task functions because this clarifies in the task descriptions what kind of interaction is required, and aids in creating the desired user interface. However, both in the implementation and the semantics all editor task variants can be created and handled by one single function. To understand how it works we restrict ourselves to a simplified version in which we omit the view list details because these are just trivial mapping functions. Before we discuss this function edit we first have a look at the use of Events and Responses. Due to the model-view nature of editor tasks, every user manipulation of an editor task of a value of type \( a \) can be expressed as sending a new value \( new \) of type \( a \) from the client to the server. If we wrap this value-type pair into a Dynamic and include the task identification number, no say, then this amounts to the (EditMode no (dynamic new :: a)) event. The unique task number is used to map a task described in the code to the corresponding interactive view generated in the client, and is used to label the events and corresponding responses. The responses of the server tell the client what interface should be rendered to the user. \[ \begin{align*} \text{edit} & : \text{String} \rightarrow l \rightarrow \text{RwShared} r w \rightarrow (1 \rightarrow r \rightarrow \text{Maybe a}) \\ \text{edit descr lv sh_rv cv = newTask (edit1 lv)} \end{align*} \] The response to an editor task executed on a client informs the client about the latest state of the editor (EditorResponse) and contains, in serialized form, the current local value to edit and a shared value to show. With these Events and Responses, we can define the semantics of the editor task combinator which updates a local value of type \( a \) while displaying the latest value \( r \) stored in an SDS of type RwShared r w. \[ \begin{align*} \text{edit} & : \text{String} \rightarrow l \rightarrow \text{RwShared} r w \rightarrow (1 \rightarrow r \rightarrow \text{Maybe a}) \\ \text{edit descr lv sh_rv cv = newTask (edit1 lv)} \end{align*} \] The response to an editor task executed on a client informs the client about the latest state of the editor (EditorResponse) and contains, in serialized form, the current local value to edit and a shared value to show. With these Events and Responses, we can define the semantics of the editor task combinator which updates a local value of type \( a \) while displaying the latest value \( r \) stored in an SDS of type RwShared r w. The palindrome task prompts the user to enter a palindrome. As usual, the user can enter a string and change it over time. With \texttt{>>\textgreater\textgreater} two possible action task steps are added. The user can choose action \texttt{Ok}, but only when the entered string is indeed a palindrome. If \texttt{Ok} is chosen, \texttt{Just p} is returned, where \texttt{p} is the entered and checked palindrome. At any time, the user can choose \texttt{Cancel}, and the task returns \texttt{Nothing}. In the second example we implement a traditional monadic bind operator \texttt{>>\textgreater\textgreater} to demonstrate the general nature of \texttt{>>\textgreater\textgreater}: \begin{verbatim} (\texttt{>>\textgreater\textgreater}) infx1 l :: Task a \rightarrow (TaskStep a b) \rightarrow Task b \mid iTask a & iTask b :: TaskStep a b = OnAction (Predicate a) (NextTask a b) | OnValue (Predicate a) (NextTask a b) \mid \exists e: QuException (e \rightarrow Task b) & iTask e :: Predicate a ::= Value a \rightarrow Bool :: NextTask a b ::= Value a \rightarrow Task b :: Action = Action String | ActionOk | ActionCancel | ... \end{verbatim} The complete semantic definition of \texttt{>>\textgreater\textgreater} is given in Figure 3. It is rather long because it needs to handle all \texttt{TaskStep} cases and prioritize them properly. However, each of these cases is rather straightforward. The step combinator is handled by \texttt{step1} which memo- **3.5 Parallel Tasks** Tasks can often be divided into parallel sub-tasks if there is no specific predetermined order in which the sub-tasks have to be done. It might not even be required that all sub-tasks contribute sensibly to a stable result. All variants of parallel composition can be handled by a single parallel combinator: \[ \text{parallel} :: d \rightarrow ([\text{ParallelTaskType}, \text{ParallelTask} a]) \\ \rightarrow \text{Task} ([\text{Time} \text{Stamp}, \text{Value} a]) | \text{descr} d & \text{iTask} a \] \[ :: \text{ParallelTaskType} = \text{Embedded} | \text{Detached} \\ :: \text{ManagementMeta} = \{ \text{worker} :: \text{Maybe User} \\ . \text{role} :: \text{Maybe Role} \\ . \ldots \} \] \[ :: \text{ParallelTask} a ::= \text{SharedTaskList} a \rightarrow \text{Task} a \\ :: \text{SharedTaskList} a ::= \text{RWShared} (\text{TaskList} a) \\ :: \text{TaskList} a = \{ \text{state} :: [\text{Value} a] \\ . . . \} \] We distinguish two sorts of parallel sub-tasks: Detached tasks get distributed to different users and are executed by the current user. The client may present these tasks in different ways. Detached tasks need a window of their own while embedded tasks may be visualized in an existing window. With the ManagementMeta structure properties can be set such as which worker must perform the sub-task, or which role he should have. Whatever its sort, every parallel sub-task can inspect each others progress. Of each parallel sub-tasks its current task value and some other system information is collected in a shared task list. The parallel sub-tasks have read-only access to this task list. The parallel combinator also delivers all task values in a list of type \([\text{Time} \text{Stamp}, \text{Value} a]\). Hence, the progress of every parallel sub-task can also be monitored constantly from the “outside”. For instance, a parallel task can be monitored with the step combinator \(\gg\) to decide if the parallel task as a whole can be terminated because its sub-tasks have made sufficient progress for doing the next step. It is also possible to observe the task and convert its value to some other type using the conversion operator \(?\) (Section 3.1.4). For completeness, we remark that the shared task list is also used to allow dynamic creation and deletion of parallel sub-tasks. We do not discuss this further in this paper. In the iTask3 library parallel is used to predefine several frequently used task patterns. In Section 2.2 the \(\rightarrow\) combinator was used to start to tasks in parallel. --- The complete semantic definition of parallel is given in Figure 4. The semantic function parallel' (lines 15-26) defines the purpose of the parallel combinator: to evaluate each and every sub-task (line 18) until either an exception has been thrown (line 19), or all sub-tasks have become stable (lines 23-24). While this is not the case, parallel' proceeds to rewrite to itself (line 25-26). Both parallel' and its sub-tasks require access to their progress, which is stored in the shared task list which is created as the first step of the parallel combinator (line 4 and lines 7-13). Initially, the task list consists of all initial parallel sub-tasks that have access to the shared task list. The semantic functions evalParTasks and evalParTask define the evaluation of the parallel sub-tasks; evalParTasks collects the current list of sub-tasks (line 31) and applies evalParTask to each and every sub-task (line 32). Evaluation of a sub-task (line 39) might result in an exception (line 41), in which case the exception is propagated throughout the evaluation of all sub-tasks (lines 44-45). If a sub-task does not result in an exception, then its new reduct is stored in the shared task list (line 42), thus allowing the other sub-tasks to inspect its progress (updateFM (pid, \_\_\_) updates any existing element (pid, \_) in the shared task list with (pid, \_\_\_)). The responses of the evaluated sub-task are collected and returned (line 43). --- **4. Practical TOP** Although the TOP paradigm adopts functional programming’s emphasis of what over how, some pragmatic issues remain unavoidable in practical TOP programming. In this section we discuss pragmatics issues that we encountered in the implementation of the TOP concept in the iTask3 toolkit, and show examples of iTask3 programs to illustrate its use in real-world applications. --- **4.1 Pragmatic Issues** **Custom Interaction:** TOP programs focus on defining decompositions of tasks without worrying how interactions of basic tasks are implemented by the TOP framework. The underlying implementation has to take care of that. The iTask3 system follows the By default, if a value of the predefined type Note is used in an iTask3 editor, a text box is presented to the user on the client to enter text. In simpleEdit we create a shared memory for a value of this type Note with initial value Note "" and we define two interactive tasks on this shared value. The first task allows the user to update the initial text (line 8), while the second gives a view on the shared text that is fine-tuned with V足迹 which, in this case, converts the text into a value of type Statistics. As a result, while entering text, the user sees the corresponding statistics. **Customized Layout:** For task compositions a similar need for customization exists. Depending on the composition, it may be more appealing or easier to use when tasks are divided over tabs or windows than when tasks are shown side-by-side. To customize layout, the iTask3 framework provides an annotation operator (<@>) that can be used to annotate tasks with custom layout functions or post-layout processing functions. Such functions combine a set of abstract GUI definitions into a single definition. By default a heuristic layout function is used to provide a sensible default. Post-processing functions modify a GUI definition after a task is laid out. Such modifications are for example changing its size, adding margins or changing to a horizontal layout as is done with the <<@ horizontal annotation in the simple editor. It is defined as: ``` horizontal = AfterLayout (tweakUI (setDirection Horizontal)) ``` **Localization:** Another pragmatic aspect one may need to deal with is localization. Because task definitions contain many prompts, hints and other texts, one needs to deal with localization of such texts without compromising the readability of task definitions. Furthermore, localization may also be required on the task level. To comply with local law and regulations, different task definitions may have to be used in different countries. The iTask3 framework does not offer any special support for localization, but one can make use of the standard modular structure of Clean to create different local versions. **Third Party Formats and Protocols:** To integrate TOP applications with other applications, the gap between the domain of tasks and the formats or protocols required to interact with these systems must be bridged. With TOP one does not escape writing the parsing, formatting and communication code that is necessary for such applications, with additional support for customization for obtaining practical applicable applications. The interactive applications that are generated by default by the system suffice for rapid prototyping. However, aesthetic and ergonomic properties of these interactions affect the ease of use and attractiveness of a system. For example, the task of choosing a file from a file system is performed more easily by navigating a tree structure than by selecting an item from a long list of all files. To allow for such task specific optimization, all interaction tasks in the iTask3 framework have a views parameter, in which optional mappings between the task’s domain and another arbitrary domain can be defined. The library provides types that represent abstract user interface controls with which customized interactions can be composed. Here is an example (see Figure 5): ```haskell parallel :: [ParallelTask a] -> Task [(Timestamp, Value a)] | iTask a parallel ptas ev st # (stt, st) = createTaskList ptas stt = parallel' stt ev st createTaskList :: [ParallelTask a] | sState -> (SharedTaskList a, *State) | iTask a createTaskList ptas stt =: # (stt, st) = createShared [] st = (stt.set (pid, Reduce (ValRes t NoVal) (pta st))), | pta <- ptas & pid <- [0..] | ] st) parallel' :: SharedTaskList a | Task [(Timestamp, Value a)] | iTask a parallel' ptas ev st = case evalParTasks tt ev st of | Left (ExcRes e, st) = throw e ev st | (Right rsp, st) | # (values, st) = get_task_values stt st # maxt = fold max 0 (map fst values) | all (isStable o snd) values = stable maxt values ev st | otherwise = (Reduce (ValRes maxt (Val Values Unstable))) (\(parallel' stt) eps st) evalParTasks :: SharedTaskList a -> Event -> *State | iTask a evalParTasks stt ev st # (tt, st) = stt.get st = foldl (evalParTask tt ev st) (Right [], st) tt evalParTask :: SharedTaskList a -> Event | Either (TaskResult a) Responses, *State | iTask a -+ Either (TaskResult a) Responses, *State | (Pid a, Reduce a) = Either (TaskResult a) Responses, *State evalParTask tt ev st (Right rsp, st) (pid, Reduce _ ta) # (new, nsp, st) = ta ev st # (Reduct ntval, nta) = new | isExcRes ntval = (Left ntval, st) # (_, _st) = updateShared (updateFM (pid, new)) stt st = (Right (nsp ++ tsp, st), st) evalParTask _ _ (Left e, st) _ = (Left e, st) get_task_values :: SharedTaskList a -> eState = +[[(Timestamp, Value a)], *State] get_task_values stt st # (tt, st) = stt.get st = ([t, val] \ (\(Reduce (Val Res t val)_) <- tt, st) ``` Figure 4. The complete semantic definition of parallel. Figure 5. A very simple text editor ``` :: Statistics = { lineCount :: Int, wordCount :: Int } derive class iTask Statistics table :: Task Note simpleEdit = withShared (Note "") edit where edit note = updateSharedInformation "Enter text:" [] note | -1- viewSharedInformation "Statistics:" [ViewWith stats] note <<@ horizontal stat (Note txt) = { lineCount = length lines | , wordCount = length words } where lines = split Newline txt words = split " " (replaceSubString Newline " " txt) ``` Simple Edit:: Task Note simpleEdit = withShared (Note "") edit where edit note = updateSharedInformation "Enter text:" [] note | -1- viewSharedInformation "Statistics:" [ViewWith stats] note <<@ horizontal stat (Note txt) = { lineCount = length lines | , wordCount = length words } where lines = split Newline txt words = split " " (replaceSubString Newline " " txt) integrations, but it can be separated from the application code by moving it to task libraries. 4.2 Examples A Generic Work List: A major leap in the development of TOP as a general paradigm was the insight that, from a user’s point of view, interaction with a “Work List”, in which users can work on tasks assigned to them, is actually part of the work that has to be done. Work list handling e.g. as offered by an email application or a workflow system is commonly hard coded in the systems used. In iTask1 this functionality is defined in the system itself as “just” any other task. Figure 6 shows the generic work list task we offer as a standard example. In the left panel a tree of tasks that can be started is displayed. The tasks to do are displayed in the upper-right pane, similar to an inbox in an email application. The user can work on several tasks at the same time in the lower right pane, by opening them in separate tabs. This complete work list application is defined in less than 200 lines of TOP code. The Incidone Incident Coordination Tool: The Coast Guard case study (Jansen et al., 2010; Lijnse et al., 2011) not only fueled the refinement of the task concept and the TOP paradigm, it also lead to the development of the Incidone tool (Lijnse et al., 2012). A preview of this tool for supporting Coast Guard operations is shown in Figure 7. It is being developed using the iTask3 framework to illustrate the use of TOP for crisis management applications. In this tool immediate information sharing between team members working together is crucial to handle incidents properly. 5. Related Work The TOP paradigm emerged during continued work on the iTask system. In its first incarnation (Plasmeijer et al., 2007), iTask1, the notion of tasks was introduced for the specification of dedicated workflow management systems. In iTask1 and its successor iTask2 (Lijnse and Plasmeijer, 2010), a task is an opaque unit of work that, once completed, yields a result from which subsequent tasks can be computed. When deploying these systems for real-world applications, viz. in telecare (van der Heijden et al., 2011) and modeling the dynamic task of coordinating Coast Guard Search and Rescue operations (Jansen et al., 2010; Lijnse et al., 2011) we experienced that this concept of task is not adequate to express the coordination of tasks where teams constantly need to be informed about the progress made by others. The search for better abstraction has resulted in the TOP approach and task concept as introduced in this paper. Task-Oriented programming touches on two broad areas of research. First the programming of interactive multi-user (web) applications, and second the specification of tasks. There are many languages, libraries and frameworks for programming multi-user web applications. Some academic, and many more in the open-source and proprietary commercial software markets. Examples from the academic functional programming community include: the Haskell cgi library (Meijer, 2000); the Curry approach (Hanus, 2001); writing xml applications (Elsman and Friis Larsen, 2004) in SMLserver (Elsman and Hallenberg, 2003); WashCGI (Thiemann, 2002); the Hop (Loitsch and Serrano, 2007; Serrano et al., 2006) web programming language; Links (Cooper et al., 2006) and formlets (Cooper et al., 2007). All these solutions address the technical challenges of creating multi-user web applications. Naturally, these challenges also need to be addressed within the TOP approach. The principal difference between TOP and these web technologies is the emphasis on using tasks both as modeling and programming unit to abstract from these issues, including coordination of tasks that may or may not have a value. Tasks are an ambiguous notion used in different fields, such as Workflow Management Systems (WFMS), human-computer interaction, and ergonomics. Although the iTask1 system was influenced and partially motivated by the use of tasks in WFMSs (van der Aalst et al., 2002), iTask3 has evolved to the more general TOP approach of structuring software systems. As such, it is more similar in spirit to the WebWorkFlow project (Hemel et al., 2008), which is an object oriented approach that breaks down the logic into separate clauses instead of functions. Cognitive Task Analysis methods (Crandall et al., 2006) seek to understand how people accomplish tasks. Their results are useful in the design of software systems, but they are not software development methods. In Robotics the notion of task and even the “Task-Oriented Programming” moniker are also used. In this field it is used to indicate a level of autonomy at which robots are programmed. To the best of our knowledge, TOP as a paradigm for interactive multi-user systems, rooted in functional programming is a novel approach, distinct from other uses of the notion of tasks in the fields mentioned above. 6. Conclusions and Future Work In this paper we introduced Task-Oriented Programming, a paradigm for programming interactive multi-user applications in a pure functional language. The distinguishing feature of TOP is the ability to concisely describe and implement collaboration and complex interaction of tasks. This is achieved by four core concepts: 1) Tasks observe intermediate values of other tasks and react on these values before the other tasks are completely finished. 2) Tasks running in parallel communicate via shared data sources. Shared data sources enable useful lightweight communication between related tasks. By restricting the use of shared data sources we avoid an overly complex semantics. 3) Tasks interact with users based on arbitrary typed data, the interface required for this type is derived by type driven generic programming. 4) Tasks are composed to more complex tasks using a small set of combinators. The step combinator \( \gg \gg \) subsumes the classic monad bind operator \( \gg \). The presented operational semantics specifies the constructs unambiguously. The development of this semantics was an important anchor point during the design of TOP. TOP is embedded in Clean by offering a newly developed iTasks3 library. We have used TOP successfully for the development of a prototype implementation of a Search and Rescue decision support system for the Dutch Coast Guard. The coordination of such rescue operations requires up-to-date information of sub-tasks, this is precisely the goal of TOP. In collaboration with Dutch industry we started to investigate and validate the suitability of the TOP paradigm to handle specific complex real world distributed application areas. References
{"Source-Url": "http://repository.ubn.ru.nl/bitstream/handle/2066/103802/103802.pdf?sequence=1", "len_cl100k_base": 13279, "olmocr-version": "0.1.53", "pdf-total-pages": 13, "total-fallback-pages": 0, "total-input-tokens": 50052, "total-output-tokens": 14924, "length": "2e13", "weborganizer": {"__label__adult": 0.0002856254577636719, "__label__art_design": 0.0002651214599609375, "__label__crime_law": 0.0002321004867553711, "__label__education_jobs": 0.0006651878356933594, "__label__entertainment": 5.3048133850097656e-05, "__label__fashion_beauty": 0.0001056194305419922, "__label__finance_business": 0.000141143798828125, "__label__food_dining": 0.0002562999725341797, "__label__games": 0.00040841102600097656, "__label__hardware": 0.0004513263702392578, "__label__health": 0.00027108192443847656, "__label__history": 0.00016045570373535156, "__label__home_hobbies": 6.246566772460938e-05, "__label__industrial": 0.0002112388610839844, "__label__literature": 0.00018894672393798828, "__label__politics": 0.00017178058624267578, "__label__religion": 0.0003147125244140625, "__label__science_tech": 0.00449371337890625, "__label__social_life": 7.134675979614258e-05, "__label__software": 0.00443267822265625, "__label__software_dev": 0.98583984375, "__label__sports_fitness": 0.00020933151245117188, "__label__transportation": 0.0003616809844970703, "__label__travel": 0.0001659393310546875}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 60856, 0.01222]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 60856, 0.55745]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 60856, 0.87585]], "google_gemma-3-12b-it_contains_pii": [[0, 251, false], [251, 5478, null], [5478, 12632, null], [12632, 15380, null], [15380, 23487, null], [23487, 29713, null], [29713, 33922, null], [33922, 39824, null], [39824, 41287, null], [41287, 46000, null], [46000, 51884, null], [51884, 57076, null], [57076, 60856, null]], "google_gemma-3-12b-it_is_public_document": [[0, 251, true], [251, 5478, null], [5478, 12632, null], [12632, 15380, null], [15380, 23487, null], [23487, 29713, null], [29713, 33922, null], [33922, 39824, null], [39824, 41287, null], [41287, 46000, null], [46000, 51884, null], [51884, 57076, null], [57076, 60856, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 60856, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 60856, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 60856, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 60856, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 60856, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 60856, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 60856, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 60856, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 60856, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 60856, null]], "pdf_page_numbers": [[0, 251, 1], [251, 5478, 2], [5478, 12632, 3], [12632, 15380, 4], [15380, 23487, 5], [23487, 29713, 6], [29713, 33922, 7], [33922, 39824, 8], [39824, 41287, 9], [41287, 46000, 10], [46000, 51884, 11], [51884, 57076, 12], [57076, 60856, 13]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 60856, 0.0027]]}
olmocr_science_pdfs
2024-12-06
2024-12-06
73780882fc51bccdb6fa919ba0c308c58060358b
Causally Consistent Dynamic Slicing Roly Perera∗1, Deepak Garg2, and James Cheney†3 1 Laboratory for Foundations of Computer Science, University of Edinburgh, Edinburgh, UK rperera@inf.ed.ac.uk and School of Computing Science, University of Glasgow, Glasgow, UK roly.perera@glasgow.ac.uk 2 Max Planck Institute for Software Systems, Saarbrücken, Germany dg@mpi-sws.org 3 Laboratory for Foundations of Computer Science, University of Edinburgh, Edinburgh, UK jcheney@inf.ed.ac.uk Abstract We offer a lattice-theoretic account of dynamic slicing for π-calculus, building on prior work in the sequential setting. For any run of a concurrent program, we exhibit a Galois connection relating forward slices of the start configuration to backward slices of the end configuration. We prove that, up to lattice isomorphism, the same Galois connection arises for any causally equivalent execution, allowing an efficient concurrent implementation of slicing via a standard interleaving semantics. Our approach has been formalised in the dependently-typed language Agda. 1998 ACM Subject Classification D.1.3 Concurrent Programming; D.2.5 Testing and debugging Keywords and phrases π-calculus; dynamic slicing; causal equivalence; Galois connection Digital Object Identifier 10.4230/LIPIcs.CONCUR.2016.18 1 Introduction Dynamic slicing, due originally to Weiser [18], is a runtime analysis technique with applications in debugging, security and provenance tracking. The basic goal is to identify a sub-program, or program slice, that may affect an outcome of interest called the slicing criterion, such as the value of a variable. Dynamic slicing in concurrent settings is often represented as a graph reachability problem, thanks to influential work by Cheng [2]. However, most prior work on dynamic slicing for concurrency does not yield minimum slices, nor allows particularly flexible slicing criteria, such as arbitrary parts of configurations. Systems work on concurrent slicing [8, 13, 17] tends to be largely informal. Perera et al [14] developed an approach where backward dynamic slicing is treated as a kind of (abstract) reverse execution or “rewind” and forward slicing as a kind of (abstract) re-execution or “replay”. Forward and backward slices are related by a Galois connection, ensuring the existence of minimal slices. This idea is straightforward in the sequential setting of the earlier work. However, generalising it to concurrent programs is non-trivial. Suppose ∗ Perera was supported by the Air Force Office of Scientific Research, Air Force Material Command, USAF, under grant number FA8655-13-1-3006. Perera was also supported by UK EPSRC project EP/K034413/1. † Cheney was supported by the Air Force Office of Scientific Research, Air Force Material Command, USAF, under grant number FA8655-13-1-3006. we run a concurrent computation, discover a bug, and then wish to compute a dynamic slice. It would clearly be impractical to require the slice be computed using the exact interleaving of the original run, particularly in a distributed setting. On the other hand, computing the slice using a brand-new concurrent execution may differ non-deterministic choices, producing a slice of a computation other than the one intended. Intuitively, any execution which exhibits the same causal structure should be adequate for computing the slice, and any practical approach to concurrent slicing should take advantage of this. Danos and Krivine [4] make a similar observation about reversible concurrency, arguing that the most liberal notion of reversibility is one that just respects causality: an action can only be undone after all the actions that causally depend on it have been undone. In this paper we formalise dynamic slicing for π-calculus, and show that any causally equivalent execution generates precisely the same slicing information. We do this by formalising slicing with respect to a particular execution $\tilde{l}$, and then proving that slicing with respect to any causally equivalent computation $\tilde{u}$ yields the same slice, after a unique “rewiring” which interprets the path witnessing $\tilde{l} \simeq \tilde{u}$ as a lattice isomorphism relating the two slices. The isomorphism is constructive, rewriting one slice into the other: this allows non-deterministic metadata (e.g. memory addresses or transaction ids) in the slicing execution to be aligned with the corresponding metadata in the original run. We build on an earlier “proof-relevant” formalisation of causal equivalence for π-calculus in Agda [15]. As long as causality is respected, an implementation of our system can safely use any technique (e.g. redex trails, proved transitions, or thread-local memories) to implement rewind and replay. Example: scheduler with non-compliant task. While dynamic slicing cannot automatically isolate bugs, it can hide irrelevant detail and yield compact provenance-like explanations of troublesome parts of configurations. As an example we consider Milner’s scheduler implementation [12, p. 65]. The scheduler controls a set of $n$ tasks, executed by agents $A_1, \ldots, A_n$. Agent $A_i$ sends the message $a_i$ (announce) to the scheduler to start its task, and message $b_i$ (break) to end its task. The scheduler ensures that the actions $a_i$ occur cyclically starting with $a_1$, and that for each $i$ the actions $a_i$ and $b_i$ alternate, starting with $a_1$. Although started sequentially, once started the tasks are free to execute in parallel. Figure 1 shows five transitions of a two-thread scheduler, with the redex selected at each step highlighted in bold. The parts of the configuration which contribute to the final state of thread 1 are in black; the grey parts are discarded by our backward-slicing algorithm. Assume prefixing binds more tightly than either $\cdot | \cdot$ or $\cdot +$. To save space, we omit the $\nu$-binders defining the various names, and write $x.0$ simply as $x$. The names $r_1$, $r_2$, $p_1$ and $p_2$ are used to make recursive calls [12, p. 94]: a recursive procedure is implemented as a server which waits for an invocation request, spawns a new copy of the procedure body, and then returns to the wait state. Here we omit the server definitions, and simply replace a successful invocation by the spawned body; thus in the final step of Figure 1, after the synchronisation on \( c_2 \) the invocation \( r_1 \) is replaced by a fresh copy of the initial state of scheduler thread 1. The final state of Figure 1 has no redexes, and so is stuck. The slice helps highlight the fact that by the time we come to start the second loop of scheduler 1, the task was terminated by message \( b_1 \) from \( A_2 \), before any such message could be sent by \( A_1 \). We can understand the slice of the initial configuration (computed by “rewinding”, or backward-slicing) as sufficient to explain the slice of the stuck configuration by noting that the former is able to compute the latter by “replay”, or forward-slicing. In other words, writing a sliced part of the configuration as \( \square \), and pretending the holes \( \square \) are sub-computations which get stuck, we can derive \[ a_1.c_1.(b_1, \square + \circ) | \pi_1.a_2.\circ | \pi_1.\circ | \pi_2.b_1.\circ_2 \rightarrow^* \pi_2.\circ \] without getting stuck. The slice on the left may of course choose to take the right-hand branch of the choice instead. But if we constrain the replay of the sliced program to follow the causal structure of the original unsliced run – to take the same branches of internal choices, and have the same synchronisation structure – then it will indeed evolve to the slice on the right. This illustrates the correctness property for backward slicing, which is that forward-slicing its result must recompute (at least) the slicing criterion. For this example, the tasks are entirely atomic and so fixing the outcome of + has the effect of making the computation completely sequential. Less trivial systems usually have multiple ways they can evolve, even once the causal structure is fixed. A confluence lemma typically formalises the observational equivalence of two causally equivalent runs. However, a key observation made in [15] is that requiring causally equivalent runs to reach exactly the same state is too restrictive for \( \pi \)-calculus, in particular because of name extrusion. As we discuss in Section 3, two causally unrelated extrusion-rendezvous lead to states which differ in the relative position of two \( \nu \)-binders, reflecting the two possible orderings of the rendezvous. Although technically unobservable to the program, interleaving-sensitive metadata, such as memory locations in a debugger or transaction ids in a financial application, may be important for domain-specific reasons. In these situations being able to robustly translate between the target states of the two executions may be useful. **Summary of contributions.** Section 2 defines the core forward and backward dynamic slicing operations for \( \pi \)-calculus transitions and sequences of transitions (traces). We prove that they are related by a Galois connection, showing that backward and forward slicing, as defined, are minimal and maximal with respect to each other. Section 3 extends this framework to show that the Galois connections for causally equivalent traces compute the same slices up to lattice isomorphism. Section 4 discusses related work and Section 5 offers closing thoughts and prospects for follow-up work. Appendix A summarises the Agda module structure and required libraries; the source code can be found at https://github.com/rolyp/concurrent-slicing, release 0.1. ## 2 Galois connections for slicing \( \pi \)-calculus programs To summarise informally, our approach is to interpret, functorially, every transition diagram in the \( \pi \)-calculus into the category of lattices and Galois connections. For example the interpretation of the transition diagram on the left is the commutative diagram on the right: ### 2.1 Lattices of slices The syntax of names, processes and actions is given in Figure 2. Slices are represented syntactically, via the \( \sqsubseteq \) notation introduced informally in Section 1. Our formalisation employs de Bruijn indices \[5\], an approach with well-known strengths and weaknesses compared to other approaches to names such as higher-order abstract syntax or nominal calculi. **Names.** Only names which occur in the “payload” (argument) position of a message may be erased. The erased name \( \square \) gives rise to a (trivial) partial order \( \sqsubseteq \) over payloads, namely the partial order containing precisely \( \square \leq z \) for any \( z \). The set of slices of \( x \) is written \( \downarrow x \) and defined to be \( \{ z \mid z \leq x \} \); because names are atomic \( \downarrow x \) is simply the two-element set \( \{ \square, x \} \). The set \( \downarrow x \) is a finite lattice with meet and join operations \( \sqcap \) and \( \sqcup \), and top and bottom elements \( x \) and \( \square \) respectively. For any lattice, the meet and join are related to the underlying partial order by \( z \leq z' \iff z \sqcap z' = z' \iff z \sqcup z' = z \). Lattices are closed under component-wise products, justifying the notation \( \downarrow (z, z') \) for \( \downarrow z \times \downarrow z' \). Fig. 3. Labelled transition relation $P \xrightarrow{a} R$ (symmetric variants omitted). Processes. The $\leq$ relation and $\downarrow$ operation extend to processes, via payloads which may be $\circ$, and a special undefined process also written $\circ$. A slice of $P$ is simply $P$ with some sub-terms replaced by $\circ$. The relation $\leq$ is the least compatible partial order which has $\circ$ as least element; all process constructors both preserve and reflect $\leq$, so we assume an equivalent inductive definition of $\leq$ when convenient. A process has a closing context $\Gamma$ enumerating its free variables; in the untyped de Bruijn setting $\Gamma$ is just a natural number. Often it is convenient to conflate $\Gamma$ with a set of that cardinality. Actions. An action $a$ labels a transition (Fig. 3 below), and is either bound or non-bound. A bound action $b$ is of the form $x$ or $\pi$ and opens a process with respect to $x$, taking it from $\Gamma$ to $\Gamma + 1$. A non-bound action $c$ is of the form $\pi(z)$ or $\tau$ and preserves the free variables of the process. The $\leq$ relation and $\downarrow$ operation extend to actions via $\circ$ names, plus a special undefined action also written $\circ$. Renamings. In the lattice setting, a renaming $\rho : \Gamma \rightarrow \Gamma'$ is any function from $\Gamma$ to $\Gamma' \uplus \{\circ\}$; we also allow $\sigma$ to range over renamings. Renaming application $\rho^* P$ is extended with the equation $\rho^* \circ = \circ$. The $\leq$ relation and $\downarrow$ operation apply pointwise. Labelled transition semantics. The late-style labelled transition semantics is given in Fig. 3, and is distinguished only by its adaptation to the de Bruijn setting. The primary reference for a de Bruijn formulation of $\pi$-calculus is [9]; the consequences of such an approach are explored in some depth in [15]. One pleasing consequence of a de Bruijn approach is that the usual side-conditions associated with transition rules can be operationalised via renamings. We briefly explain this, along with other uses of renamings in the transition rules, and refer the interested reader to these earlier works for more details. Definition 1 defines the renamings used in Fig. 3 and Definition 2 the application $\rho^* a$ of $\rho$ to an action $a$. Definition 1 (push, pop, and swap). \[ \begin{align*} \text{push}_\Gamma &: \quad \Gamma \rightarrow \Gamma + 1 \\ push x &= x + 1 \\ \text{pop}_\Gamma z &= z \\ pop z 0 &= x \\ pop z (x+1) &= x \\ \text{swap}_\Gamma &: \quad \Gamma + 2 \rightarrow \Gamma + 2 \\ \text{swap} 0 &= 1 \\ \text{swap} 1 &= 0 \\ \text{swap} (x+2) &= x + 2 \end{align*} \] Definition 2 (Action renaming). Define the following lifting of a renaming to actions. \[ \rho^* : (\Gamma \rightarrow \Gamma') \rightarrow \text{Action} \Gamma \rightarrow \text{Action} \Gamma' \] \[ \begin{align*} \rho^* & = \square \\ \rho^* \pi & = \rho \pi \\ \rho^* \tau & = \tau \\ \rho^* \pi(z) & = \pi(\rho z) \end{align*} \] - push occurs in the transition rule which propagates a bound action through a parallel composition \( P \parallel Q \) (rule \((\star)\) in Figure 3), and rewires \( Q \) so that the name 0 is reserved. The effect is to ensure that the binder being propagated by \( P \) is not free in \( Q \). - push also occurs in the rules which propagate an action through a \( \nu \)-binder (rules \((\dagger)\) and \((\ddagger)\)), where it is applied to the action being propagated using the function defined in Definition 2. This ensures the action does not mention the binder it is propagating through. The use of \( \cdot + 1 \) in the name extrusion rule can be interpreted similarly. - pop \( z \) is used in the event of a successful synchronisation (rule \((\S)\)), and undoes the effect of push, substituting the communicated name \( z \) for index 0. - swap occurs in the rule which propagates a bound action through a \( \nu \)-binder (rule \((\dagger)\)) and has no counterpart outside of the de Bruijn setting. As a propagating binder passes through another binder, their relative position in the syntax is exchanged, and so to preserve naming \( R \) is rewired with a “braid” that swaps 0 and 1. Although its use in the operational semantics is unique to the de Bruijn setting, swap will also play an important role when we consider the relationship between slices of causally equivalent traces (Section 3 below), where it captures how the relative position of binders changes between different (but causally equivalent) interleavings. 2.2 Galois connections for slicing We now compositionally assemble a Galois connection for each component of execution, starting with renamings, and then proceeding to individual transitions and entire traces, which relates forward and backward slices of the initial and terminal state. Slicing renamings. The application \( \rho x \) of a renaming to a name, and the lifting \( \rho^* P \) of that operation to a process give rise to the Galois connections defined here. Definition 3 (Galois connection for \( \rho x \)). Suppose \( \rho : \Gamma \rightarrow \Gamma' \) and \( x \in \Gamma \). Define the following pair of monotone functions between \( \downarrow (\rho, x) \) and \( \downarrow (\rho x) \). \[ \begin{align*} \text{app}_{\rho, x} & : \downarrow (\rho, x) \rightarrow \downarrow (\rho x) \\ \text{unapp}_{\rho, x} & : \downarrow (\rho x) \rightarrow \downarrow (\rho, x) \\ \text{app}_{\rho, x} (\sigma, \square) & = \square \\ \text{app}_{\rho, x} (\sigma, \pi) & = \pi \rho x \\ \text{unapp}_{\rho, x} z & = (x \mapsto \rho z, \rho z^{-1}) \\ \text{app}_{\rho, x} (\sigma, x) & = \sigma x \end{align*} \] where \( x \mapsto_\rho \cdot \) and \( \rho z^{-1} \) denote the least slice of \( \rho \) which maps \( x \) to \( z \). It is convenient to decompose \( \text{unapp}_{\rho, x} \) into two components: \( x \mapsto_\rho z \) denotes the least slice of \( \rho \) which maps \( x \) to \( z \), and \( \rho z^{-1} \) denotes the least slice of \( x \) such that \( \rho x = z \). Lemma 4. \( \text{app}_{\rho, x} \circ \text{unapp}_{\rho, x} \geq \text{id}_{\rho x} \) 1. \( \text{app}_{\rho, x} \circ \text{unapp}_{\rho, x} \geq \text{id}_{\rho x} \) 2. \( \text{unapp}_{\rho, x} \circ \text{app}_{\rho, x} \leq \text{id}_{\rho, x} \) Definition 5 (Galois connection for a renaming $\rho^* P$). Suppose $\rho : \Gamma \rightarrow \Gamma'$ and $\Gamma \vdash P$. Define monotone functions between $\downarrow(\rho, P)$ and $\downarrow(\rho^* P)$ by structural recursion on $\downarrow P$, using the following equations. Here $\pi_{\rho}$ denotes the least slice of $\rho$, namely the renaming which maps every $x \in \Gamma$ to $\pi_{\rho}(x)$. \[ \begin{align*} \text{ren}_{\rho,P}(\sigma, \circ) &= \downarrow(\rho, P) \\ \text{ren}_{\rho,0}(\sigma, 0) &= 0 \\ \text{ren}_{\rho,Q}(\sigma, x) &= \pi_{\rho}(x) \\ \text{ren}_{\rho,P}(\sigma, \rho) &= \text{ren}_{\rho^* P}(\sigma, \rho) \\ \text{unren}_{\rho,P}(\rho, x) &= \rho(x) \\ \text{unren}_{\rho,0}(\rho) &= 0 \\ \text{unren}_{\rho,Q}(\rho) &= \text{unren}_{\rho^* Q}(\rho) \end{align*} \] Lemma 6. $(\text{unren}_{\rho,P}, \text{ren}_{\rho,P})$ is a Galois connection. 1. $\text{ren}_{\rho,P} \circ \text{unren}_{\rho,P} \geq \text{id}_{\rho^* P}$ 2. $\text{unren}_{\rho,P} \circ \text{ren}_{\rho,P} \leq \text{id}_{\rho,P}$ Proof. In each case by induction on $P$, using Lemma 4 and the invertibility of $\cdot + 1$. Slicing transitions. Transitions also lift to the lattice setting, in the form of Galois connections defined by structural recursion over the proof that $t : P \xrightarrow{a} P'$. Figures 4 and 5 define the forward and backward slicing judgements. We assume a determinising convention where a rule applies only if no earlier rule applies. The judgement $R_P \xrightarrow{a} R_P'$ asserts that there is a “replay” transition from $R \leq P$ to $(a', R') \leq (a, P)$, with $R$ the input and $(a', R')$ the output. The judgement $R_P \xleftarrow{a'} R_P'$ asserts that there is a “rewind” transition from $(a', R) \leq (a, P')$ to $R' \leq P'$, with $(a', R)$ the input and $R'$ the output. When writing $R_P$ where $R \leq P$ we exploit the preservation and reflection of $\leq$ by all constructors, for example writing $\nu(R_P | S_Q)$ for $\nu(R | S)_{\nu(P | Q)}$. For backward slicing, we permit the renaming application operator $\ast$ to be used in a pattern-matching form, indicating a use of the lower adjoint unren: given a renaming application $\rho^* P$, the pattern $\sigma^* P$ matches any slice $R$ of $\rho^* P$ such that $\text{unren}_{\rho,P}(R) = (\sigma, P)$. Definition 7 (Galois connection for a transition). Suppose $t : P \xrightarrow{a} P'$. Define the following pair of monotone functions between $\downarrow P$ to $\downarrow(a, P')$. \[ \begin{align*} \text{step}_{\downarrow} : \downarrow P &\rightarrow \downarrow(a, P') \\ \text{unstep}_{\downarrow} : \downarrow(a, P') &\rightarrow \downarrow P \\ \text{step}_{R} : (a', R') &\xrightarrow{a'} R_P \\ \text{unstep}_{R} : (R, a') &\xrightarrow{a'} (R', a') \end{align*} \] We omit the proofs that these equations indeed define total, deterministic, monotone relations. Theorem 8 ((\text{step}_{\downarrow}, \text{unstep}_{\downarrow}) is a Galois connection). 1. $\text{step}_{\downarrow} \circ \text{unstep}_{\downarrow} \geq \text{id}_{\downarrow(a, P')}$ 2. $\text{unstep}_{\downarrow} \circ \text{step}_{\downarrow} \leq \text{id}_{\downarrow P}$ Proof. By induction on $t : P \xrightarrow{a} P'$, using Lemma 6 for the cases involving renaming. Causally Consistent Dynamic Slicing Finally we extend slicing to entire runs of a π-calculus program. A sequence of transitions \( \bar{t} \) is called a trace; the empty trace at \( P \) is written \( \varepsilon_P \), and the composition of a transition \( t : P \xrightarrow{a} R \) and trace \( \bar{t} : R \xrightarrow{\bar{a}} S \) is written \( t \cdot \bar{t} : P \xrightarrow{a \cdot \bar{a}} S \) where actions are composable whenever their source and target contexts match. **Definition 9** (Galois connection for a trace). Suppose \( \bar{t} : P \xrightarrow{a} P' \). Define the following pair of monotone functions between \( \downarrow P \) and \( \downarrow P' \), using variants of \( \text{step}_i \) and \( \text{unstep}_i \), which discard the action slice (going forward) and which use \( \circ \) as the action slice (going backward). \[ \begin{align*} \text{fwd}_{\bar{t}} : & \downarrow P \rightarrow \downarrow P' \\ \text{fwd}_{\bar{t}} : & \downarrow P \rightarrow \downarrow P' \\ \text{bwd}_{\bar{t}} : & \downarrow P' \rightarrow \downarrow P \\ \text{bwd}_{\bar{t}} : & \downarrow P' \rightarrow \downarrow P \\ \text{fwd}_{\bar{t} \circ \bar{t}} & = \text{id}_{\downarrow P} \\ \text{fwd}_{\bar{t} \circ \bar{t}} & = \text{id}_{\downarrow P} \\ \text{fwd}_{\bar{t} \circ \bar{t}} & = \text{id}_{\downarrow P'} \\ \text{fwd}_{\bar{t} \circ \bar{t}} & = \text{id}_{\downarrow P'} \\ \text{step}_i : & \downarrow P \rightarrow \downarrow P' \\ \text{step}_i : & \downarrow P \rightarrow \downarrow P' \\ \text{unstep}_i : & \downarrow P' \rightarrow \downarrow P \\ \text{unstep}_i : & \downarrow P' \rightarrow \downarrow P \\ \text{unstep}_i : & \downarrow P' \rightarrow \downarrow P \\ \text{unstep}_i : & \downarrow P' \rightarrow \downarrow P \\ \text{step}_i R : & R \text{ where } \text{step}_i R = (a', R') \\ \text{unstep}_i R : & R' \text{ where } \text{unstep}_i R = (a, R') \end{align*} \] At the empty trace \( \varepsilon_P \) the Galois connection is simply the identity on \( \downarrow P \). Otherwise, we recurse into the structure of the trace \( t \cdot \bar{t} \), composing the Galois connection for the single transition \( t \) with the Galois connection for the tail of the computation \( \bar{t} \). **Theorem 10** (\( \text{fwd}_{\bar{t}} \circ \text{bwd}_{\bar{t}} \) is a Galois connection). 1. \( \text{fwd}_{\bar{t}} \circ \text{bwd}_{\bar{t}} \geq \text{id}_{\downarrow P} \) 2. \( \text{bwd}_{\bar{t}} \circ \text{fwd}_{\bar{t}} \leq \text{id}_{\downarrow P} \) Note that the trace used to define forward and backward slicing for a computation is not an auxiliary data structure recording the computation, such as a redex trail or memory, but simply the proof term witnessing \( P \xrightarrow{a} P' \). Consider the process $P_0 \overset{\text{def}}{=} (\nu y z) (\tau(z).Q) \mid \tau(y).P$ for some unspecified processes $P$ and $Q$. This process can take two transitions, which we will call $t$ and $t'$. Transition... t : \text{P}_0 \xrightarrow{\sigma(z)} \text{P}_1 \text{ extrudes } y \text{ on the channel } x: P_0 \xrightarrow{\sigma(y)} (\nu z) P | \sigma(z).Q \overset{\text{def}}{=} P_1 whereas transition \( t' : \text{P}_0 \xrightarrow{\sigma(z)} \text{P}_1' \) extrudes \( z \), also on the channel \( x \): \[ P_0 \xrightarrow{\sigma(z)} (\nu y) (\sigma(y).P) | Q \overset{\text{def}}{=} P_1' \] In both cases the output actions are bound, representing the extruding binder. Moreover, \( t \) and \( t' \) are concurrent, written \( t \sim t' \), meaning they can be executed in either order. Having taken \( t \), one can can mutatis mutandis take \( t' \), and vice versa. Concurrency is an irreflexive and symmetric relation defined over transitions which are coinductive (have the same source state). The qualification is needed because \( t' \) will need to be adjusted to operate on the target state of \( t \), if \( t \) is the transition which happens first. If \( t' \) happens first then \( t' \) will need to be adjusted to operate on the target state of \( t \). The adjusted version of \( t' \) is called the residual of \( t' \) after \( t \), and is written \( t'/t \). In this case \( t'/t \) can still extrude \( z \): \[ P_1 = (\nu z) P | \sigma(z).Q \xrightarrow{\sigma(z)} P | Q \overset{\text{def}}{=} P_0' \] whereas the residual \( t'/t' \) can still extrude \( y \): \[ P'_1 = (\nu y) (\sigma(y).P) | Q \xrightarrow{\sigma(y)} P | Q = P_0' \] The independence of \( t \) and \( t' \) is confirmed by the fact that \( t \cdot t'/t \) and \( t' \cdot t/t' \) are cofinal (share a target state), as shown on the left below. We say that the traces \( \bar{t} = t \cdot t'/t \) and \( \bar{u} = t' \cdot t/t' \) are causally equivalent, written \( \bar{t} \simeq \bar{u} \). The commutativity of the right-hand square (Theorem 16 below) means the two interleavings are also equivalent for slicing purposes. Here \( \text{step}_\cdot \), denotes the Galois connection \( \text{(step}_\cdot\text{, unstep}_\cdot) \). However [15], which formalised causal equivalence for \( \pi \)-calculus, showed that causally equivalence traces do not always reach exactly the same state, but only the same state up to some permutation of the binders in the resulting processes. This will become clear if we consider another process \( Q_0 \overset{\text{def}}{=} \langle x(y').R \rangle | x(z').S \) able to synchronise with both of the extrusions raised by \( P_0 \) and consider the two different ways that \( P_0 \) can evolve. First note that \( Q_0 \) can also take two independent transitions: \( u : Q_0 \xrightarrow{x(y')} R | x(z').S \overset{\text{def}}{=} Q_1 \) inputs on \( x \) and binds the received name to \( y' \); and \( u' : Q_0 \xrightarrow{x(z')} \langle x(y').R \rangle | S \overset{\text{def}}{=} Q'_1 \) also inputs on \( x \) and binds the received name to \( z' \). (Assume \( z \) is not free in the left-hand side of \( Q_0 \) and that \( y \) is not free in the right-hand side.) The respective residuals \( Q_1 = R | x(z').S \overset{x(z')}{\xrightarrow{\text{def}}} R | S \overset{\text{def}}{=} Q_0' \) and \( Q'_1 = \langle x(y').R \rangle | S \overset{x(y')}{\xrightarrow{\text{def}}} R | S = Q_0' \) again converge on the same state \( Q_0' \), leading to a diamond for \( Q_0 \) similar to the one for \( P_0 \) above. The subtlety arises when we put \( P_0 \) and \( Q_0 \) into parallel composition, since now we have two concurrent synchronisation possibilities. For clarity we give the derivations, which we call \( s \) and \( s' \): \[ \begin{align*} t : P_0 & \xrightarrow{\sigma(y)} P_1 & u : Q_0 & \xrightarrow{x(y')} Q_1 \\ & s : P_0 | Q_0 \xrightarrow{(\nu y)} (\nu y) P_1 | Q_1 \{ y/y' \} & t' : P_0 & \xrightarrow{\sigma(z)} P_1' & u' : Q_0 & \xrightarrow{x(z')} Q'_1 \\ & s' : P_0 | Q_0 \xrightarrow{(\nu z)} (\nu z) P_1' | Q'_1 \{ z/z' \} \end{align*} \] The labelled transition system is closed under renamings; thus the residual $u'/u$ has an image in the renaming $\cdot\{y'/y\}$, and $u/u'$ has an image in the renaming $\cdot\{z'/z\}$, allowing us to derive composite residual $s'/s$: \[ \frac{u'/u : Q_1 \xrightarrow{\pi(s')} Q_0'}{s'/s : (\nu y) P_1 | Q_1(y/y') \xrightarrow{(\nu y z) (\nu y) P_1 | Q_1(y/y') \xrightarrow{\psi} (\nu y z) P_0 | Q_0(y/z')} \] By similar reasoning we can derive $s/s'$: \[ \frac{s/s' : (\nu z) P_0' | Q_1(y/y') \xrightarrow{(\nu y z) P_0 | Q_0(y/z')}{s'/s : s'/s' \xrightarrow{(\nu y z) P_0 | Q_0(y/z')} \] By side-conditions on the transition rules the renamings $\cdot\{y'/y\}$ and $\cdot\{z'/z\}$ commute and so $Q_0(y/y')\{z/z'\} = Q_0' = Q_0(y/y')\{z/z'\}$. However, the positions of binders $y$ and $z$ are transposed in the terminal states of $s'/s$ and $s/s'$. Instead of the usual diamond shape, we have the pentagon on the left below, where $\phi$ is a braid representing the transposition of the binders. Lifted to slices, $\phi$ becomes the unique isomorphism $\text{braid}_\phi$ relating slices of the terminal states, as shown in the commutative diagram on the right: \[ \begin{array}{c} \xymatrix{P_0 | Q_0 \ar[r]^{\phi} & (\nu y z) P_0' | Q_0' \ar[r]^{\text{braid}_\phi} & (\nu y z) P_0 | Q_0' \ar[r]^{\text{braid}_\phi} & (\nu y z) P_0' | Q_0' \ar[r]^{\text{braid}_\phi} & (\nu y z) P_0 | Q_0'} \end{array} \] In the de Bruijn setting, a braid like $\phi$ does not relate two processes of the form $(\nu y z) R$ and $(\nu y z) R$ but rather two processes of the form $\nu \nu R$ and $\nu \nu (\text{swap}^* R)$: the transposition of the (nameless) binders is represented by the transposition of the roles of indices 0 and 1 in the body of the innermost binder. **Definition 11 (Bound braid $P \times R$).** Inductively define the symmetric relation $P \times R$ using the rules below. \[ \begin{align*} \nu\nu\text{swap}_R & : \nu \nu P \times \nu \nu P' \quad P = \text{swap}^* P' \quad + \quad P \times R \quad P + Q \times R + Q \\ \nu\nu & \quad \quad \quad \quad P + Q \times R + Q \quad P + . \quad Q \times S \quad P + Q \times P + S \quad P \times S \end{align*} \] Following [15], we adopt a compact term-like notation for $\times$ proofs, using the rule names which occur to the left of each rule in Definition 11. For the extrusion example above, $\phi$ (in de Bruijn indices notation) would be a leaf case of the form $\nu\nu\text{-}\text{swap}_{\nu\nu}$.} **Definition 12 (Lattice isomorphism for bound braid).** Suppose $\phi : Q \times Q'$. Define the following pair of monotone functions between $\downarrow Q$ and $\downarrow Q'$ by structural recursion on $\phi$. \[ \begin{align*} \text{braid}_{\phi} & : \downarrow Q \to \downarrow Q' \quad \text{unbraid}_{\phi} : \downarrow Q' \to \downarrow Q \\ \text{braid}_{\nu\nu\text{-}\text{swap}_{\nu\nu} R} & = \nu \nu (\text{ren}_{\nu\nu\text{-}\text{swap}_{\nu\nu} R}(P)) \quad \text{unbraid}_{\nu\nu\text{-}\text{swap}_{\nu\nu} R} = \nu \nu (\text{ren}_{\nu\nu\text{-}\text{swap}_{\nu\nu} R}(P)) \\ \text{braid}_{\phi+S} & = \text{braid}_{\phi} R + S \quad \text{unbraid}_{\phi+S} (R + S) = \text{unbraid}_{\phi} R + S \\ \text{braid}_{R+\phi} & = R + \text{braid}_{\phi} S \quad \text{unbraid}_{R+\phi} (R + S) = R + \text{unbraid}_{\phi} S \\ \text{braid}_{\phi|\phi} & = \text{braid}_{\phi} | S \quad \text{unbraid}_{\phi|\phi} (R | S) = \text{unbraid}_{\phi} R | S \\ \text{braid}_{\phi!(\nu R)} & = \nu(\text{braid}_{\phi} R) \quad \text{unbraid}_{\phi!(\nu R)} (\nu R) = \nu(\text{unbraid}_{\phi} R) \\ \text{braid}_{(\nu! R)} & = !(\text{braid}_{\phi} R) \quad \text{unbraid}_{(\nu! R)} (\nu! R) = !(\text{unbraid}_{\phi} R) \end{align*} \] Lemma 13. 1. \( \text{braid}_\phi \circ \text{unbraid}_\phi = \text{id}_{\downarrow Q} \) 2. \( \text{unbraid}_\phi \circ \text{braid}_\phi = \text{id}_{\downarrow Q} \) Proof. Induction on \( \phi \). In the base case use the idempotence of \( \text{swap} \) lifted to lattices. Definition 14 (Lattice isomorphism for cofinality map). Suppose \( t \downarrow t' \) with \( \text{tgt}(t'/t) = Q \) and \( \text{tgt}(t/t') = Q' \). By Theorem 1 of [15], there exists a unique \( \gamma_{t,t'} \) witnessing \( Q = Q' \), \( Q \times Q' \) or \( Q \times Q' \). Define the following pair of monotone functions between \( \downarrow Q \) and \( \downarrow Q' \). \[ \begin{align*} \text{map}_{\gamma_{t,t'}} & : \downarrow Q \rightarrow \downarrow Q' \\ \text{unmap}_{\gamma_{t,t'}} & : \downarrow Q' \rightarrow \downarrow Q \\ \text{map}_{Q \times Q'} & = \text{id}_{\downarrow Q} \\ \text{unmap}_{Q \times Q'} & = \text{id}_{\downarrow Q'} \\ \text{map}_{\phi, Q \times Q'} & = \text{braid}_\phi \\ \text{unmap}_{\phi, Q \times Q'} & = \text{unbraid}_\phi \end{align*} \] Lemma 15. 1. \( \text{map}_{\gamma_{t,t'}} \circ \text{unmap}_{\gamma_{t,t'}} = \text{id}_{\downarrow Q'} \) 2. \( \text{unmap}_{\gamma_{t,t'}} \circ \text{map}_{\gamma_{t,t'}} = \text{id}_{\downarrow Q} \) Theorem 16. Suppose \( t \downarrow t' \) as on the left. Then the pentagon on the right commutes. Lattice isomorphism for arbitrary causal equivalence. Concurrent transitions \( t \downarrow t' \) induce an “atom” of causal equivalence, \( t \cdot t'/t \simeq t' \cdot t/t' \). The full relation is generated by closing under the trace constructors (for horizontal composition) and transitivity (for vertical composition). In [15] this yields a composite form of cofinality map \( \gamma_\alpha \) where \( \alpha : \tilde{t} \simeq \tilde{u} \) is an arbitrary causal equivalence. We omit further discussion for reasons of space, but note that \( \gamma_\alpha \) is built by composing and translating (by contexts) atomic cofinality maps, and so gives rise, by composition of isomorphisms, to a lattice isomorphism between \( \downarrow \text{tgt}(\tilde{t}) \) and \( \downarrow \text{tgt}(\tilde{u}) \). 4 Related work Reversible process calculi. Reversible process calculi have recently been used for speculative execution, debugging, transactions, and distributed protocols that require backtracking. A key challenge is to permit backwards execution to leverage concurrency whilst ensuring causal consistency. In contrast to our work, reversible calculi focus on mechanisms for reversibility, such as the thread-local memories used by Danos and Krivine’s reversible CCS [4], Lanese et al’s \( \rho\pi \) [10], and Cristescu et al’s reversible \( \pi \)-calculus [3]. We intentionally remain agnostic about implementation strategy, whilst providing a formal guarantee that causally consistent rewind and replay are a suitable foundation for any implementation. Concurrent program slicing. An early example of concurrent dynamic slicing is Duesterwald et al, who consider a language with synchronous message-passing [7]. They give a notion of correctness with respect to a slicing criterion, but find that computing least slices is undecidable, in contrast to our slices which are extremal by construction. Following Cheng [2], most subsequent work has recast dynamic slicing as a dependency-graph reachability problem; our approach is to slice with respect to a particular interleaving, but show how to derive the slice corresponding to any execution with the same dependency structure. Goswami and Mall consider shared-memory concurrency [8], and Mohapatra et al tackle slicing for concurrent Java [13], but both present only algorithms, with no formal guarantees. Tallam et al develop an approach based on dependency graphs, but again offer only algorithms and empirical results [17]. Moreover most prior work restricts the slicing criteria to the (entire) values of particular variables, rather than arbitrary parts of configurations. Provenance and slicing. Our interest in slicing arises in part due to connections with provenance, and recent applications of provenance to security [1]. Others have also considered provenance models in concurrency calculi, including Souliah et al [16] and Dezani-Ciancaglini et al [6]. Further study is needed to relate our approach to provenance and security. 5 Conclusion The main contribution of this paper is to extend our previous approach to slicing based on Galois connections to \(\pi\)-calculus, and show that the resulting notion of slice is invariant under causal equivalence. For this latter step, we build on a prior formalisation of causal equivalence for \(\pi\)-calculus [15]. Although de Bruijn indices significantly complicate the resulting definitions, the formalism is readily implemented in Agda. This paper provides a foundation for future development of rigorous provenance tracing or dynamic slicing techniques for practical concurrent programs, which we plan to investigate in future work. Acknowledgements. The U.S. Government and University of Edinburgh are authorized to reproduce and distribute reprints for their purposes notwithstanding any copyright notation thereon. Umut Acar helped with problem formulation and an earlier approach. Vít Šefl provided valuable Agda technical support. Our anonymous reviewers provided useful comments. References Figure 6 summarises the module structure of the repository concurrent-slicing, which contains the Agda formalisation. The module structure of the auxiliary repositories is described in [15]. All repositories can be found at the URL https://github.com/rolyp. Auxiliary repositories agda-stdlib-ext 0.0.3 Extensions to Agda library proof-relevant-pi 0.3 Concurrent transitions, residuals and causal equivalence Core modules Action.Lattice Action slices $a' \in \downarrow a$ Action.Concur.Lattice Action residual, lifted to slices Action.Ren.Lattice Action renaming, lifting to slices Braiding.Proc.Lattice Bound braids, lifted to slices via $\text{braid}_\phi$ and $\text{unbraid}_\phi$ ConcurrentSlicing Include everything; compile to build project ConcurrentSlicingCommon Common imports from standard library Example Milner’s scheduler example Example.Helper Utility functions for examples Lattice Lattice typeclass Lattice.Product Component-wise product of lattices Name.Lattice Name slices $y \in \downarrow x$ Proc.Lattice Process slices $P' \in \downarrow P$ Proc.Ren.Lattice Process renaming, lifted to slices via $\text{ren}_{\rho,P}$ and $\text{unren}_{\rho,P}$ Ren.Lattice Renaming slices $\sigma \in \downarrow \rho$ and application to slices ($\text{app}_{\rho,x}$ and $\text{unapp}_{\rho,x}$) Ren.Lattice.Properties Additional properties relating to renaming slices Transition.Lattice Slicing functions $\text{step}_t$ and $\text{unstep}_{gt}$ Transition.Ren.Lattice Renaming of transitions, lifted to lattices Transition.Concur.Cofinal.Lattice Braiding $\gamma_{t,t'}$ lifted to slices Transition.Seq.Lattice Slicing functions $\text{fwd}_t$ and $\text{bwd}_t$ Common sub-modules .GaloisConnection Galois connection between lattices defined in parent module Figure 6 concurrent-slicing module overview, release 0.1.
{"Source-Url": "http://drops.dagstuhl.de/opus/volltexte/2016/6158/pdf/LIPIcs-CONCUR-2016-18.pdf", "len_cl100k_base": 10997, "olmocr-version": "0.1.53", "pdf-total-pages": 15, "total-fallback-pages": 0, "total-input-tokens": 60651, "total-output-tokens": 12547, "length": "2e13", "weborganizer": {"__label__adult": 0.0003960132598876953, "__label__art_design": 0.0003800392150878906, "__label__crime_law": 0.0004742145538330078, "__label__education_jobs": 0.0007014274597167969, "__label__entertainment": 8.14199447631836e-05, "__label__fashion_beauty": 0.0001811981201171875, "__label__finance_business": 0.0003371238708496094, "__label__food_dining": 0.0004706382751464844, "__label__games": 0.0007653236389160156, "__label__hardware": 0.0010290145874023438, "__label__health": 0.0007877349853515625, "__label__history": 0.0003192424774169922, "__label__home_hobbies": 0.00013172626495361328, "__label__industrial": 0.0006651878356933594, "__label__literature": 0.00041031837463378906, "__label__politics": 0.0004525184631347656, "__label__religion": 0.0006551742553710938, "__label__science_tech": 0.087890625, "__label__social_life": 0.0001239776611328125, "__label__software": 0.007785797119140625, "__label__software_dev": 0.89453125, "__label__sports_fitness": 0.0003566741943359375, "__label__transportation": 0.0007352828979492188, "__label__travel": 0.00022089481353759768}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 39935, 0.0136]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 39935, 0.2458]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 39935, 0.78349]], "google_gemma-3-12b-it_contains_pii": [[0, 2830, false], [2830, 6188, null], [6188, 10040, null], [10040, 11395, null], [11395, 14079, null], [14079, 17725, null], [17725, 21006, null], [21006, 23780, null], [23780, 23998, null], [23998, 27918, null], [27918, 31644, null], [31644, 34602, null], [34602, 38083, null], [38083, 38341, null], [38341, 39935, null]], "google_gemma-3-12b-it_is_public_document": [[0, 2830, true], [2830, 6188, null], [6188, 10040, null], [10040, 11395, null], [11395, 14079, null], [14079, 17725, null], [17725, 21006, null], [21006, 23780, null], [23780, 23998, null], [23998, 27918, null], [27918, 31644, null], [31644, 34602, null], [34602, 38083, null], [38083, 38341, null], [38341, 39935, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 39935, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 39935, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 39935, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 39935, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 39935, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 39935, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 39935, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 39935, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 39935, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 39935, null]], "pdf_page_numbers": [[0, 2830, 1], [2830, 6188, 2], [6188, 10040, 3], [10040, 11395, 4], [11395, 14079, 5], [14079, 17725, 6], [17725, 21006, 7], [21006, 23780, 8], [23780, 23998, 9], [23998, 27918, 10], [27918, 31644, 11], [31644, 34602, 12], [34602, 38083, 13], [38083, 38341, 14], [38341, 39935, 15]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 39935, 0.0]]}
olmocr_science_pdfs
2024-12-08
2024-12-08
1688c680a25a898ad39c1a11d7a668d168b0d622
Heap-size analysis for assembly programs Jean-Yves Marion, Jean-Yves Moyen To cite this version: Jean-Yves Marion, Jean-Yves Moyen. Heap-size analysis for assembly programs. 2006. hal-00067838 HAL Id: hal-00067838 https://hal.science/hal-00067838 Preprint submitted on 9 May 2006 HAL is a multi-disciplinary open access archive for the deposit and dissemination of scientific research documents, whether they are published or not. The documents may come from teaching and research institutions in France or abroad, or from public or private research centers. L’archive ouverte pluridisciplinaire HAL, est destinée au dépôt et à la diffusion de documents scientifiques de niveau recherche, publiés ou non, émanant des établissements d’enseignement et de recherche français ou étrangers, des laboratoires publics ou privés. Heap-size analysis for assembly programs Jean-Yves Marion INPL-Loria – École Nationale supérieure des Mines de Nancy Campus scientifique BP239 F-54506 Vandœuvre-lès-Nancy Cédex Jean-Yves.Marion@loria.fr Jean-Yves Moyen LIPN-CNRS – Université Paris 13 99 avenue J.-B. Clément F-93430 Villetaneuse jean-Yves.Moyen@lipn.univ-paris13.fr ABSTRACT Our objective is to propose methods for resource-aware compilation inspired by the implicit complexity community. We consider a small assembly-like language and we build abstract finite machine models in order to predict a bound on the maximal heap usage of a program. We propose a polynomial time procedure to detect and certify a broad and meaningful class of non-size increasing programs, which run in a constant size heap. We end by discussing about programs running in linear heap space and discussing how to capture logarithmic space computation. 1. INTRODUCTION 1.1 Motivations The goal of this study is an attempt to predict and control computational resources like space or time, which are used during the execution of a bytecode program. We focus here on heap space management. For this, we have chosen a bytecode language, which is close to a fragment of C. The machine architecture contains registers and a heap memory. The set of instructions consists in arithmetic operations, conditionals and jumps. The memory management is performed by two low level operations new and free dealing with dynamic memory allocations. We present a data flow analysis of the low-level language sketched by means of “Resource Control Graph”, and we think that this is a generic concept from which several memory management policies could be checked. We establish a criterion which implies that each execution of a program needs only a constant number of dynamic memory allocations. Such programs were dubbed Non Size Increasing (NSI) by Hofmann, who has studied them in the context of functional programming with a linear type discipline [13, 14]. Here, we propose a criterion which is decidable in polynomial time. Besides the interest of this criterion to detect NSI programs, it also illustrates the possibilities and advantages of the concept of Resource Control Graph. Lastly, we describe three other 1Partly supported by the CRISS project. 2Partly supported by the CRISS and NoCost projects. Permission to make digital or hard copies of all or part of this work for personal or classroom use is granted without fee provided that copies are not made or distributed for profit or commercial advantage and that copies bear this notice and the full citation on the first page. To copy otherwise, to republish, to post on servers or to redistribute to lists, requires prior specific permission and/or a fee. Copyright 200X ACM X-XXXX-XX-X/XXX ...$5.00. applications: (i) computations with a linear amount of space, (ii) LOGSPACE computations, and (iii) termination by lack of memory. The goal is to develop an efficient static analysis in order to determine whether or not a system is heap safe. Such resource analysis allows to determine how much memory should be allocated and so prevents memory overflow. This is of course crucial for many critical applications, and has strong impact in computer security. There are several approaches which are trying to solve this problem. The first protection mechanism is by monitoring computations. However, if the monitor is compiled with the program, it could crash unpredictably by memory leak. The second is the testing-based approach, which is complementary to static analysis. Indeed, testing provides a lower bound on the memory while static analysis gives an upper bound. The gap between both bounds is of some value in practical. Lastly, the third approach is type checking done by a bytecode verifier. In an untrusted environment (like embedded systems), the type protection policy (Java or.Net) does not allow dynamic allocation. Actually, the former approach relies on a high-level language, which captures and deals with memory allocation features [5]. Our approach guarantees, and even provides, a proof certificate of upper bound on space computation on a low-level language without disallowing dynamic memory allocations. There are other motivations, which are more theoretical. Indeed a lot of works have been done the last ten years to provide syntactic characterisations of complexity classes, see [6, 20] among others. Those characterisations are the base bone of recent research on delineating broad classes of programs that run in some amount of time or space, like Hofmann, but also Niggl and Wunderlich [26], Amadio, Coupet-Grimal, Dal Zilio and Jakubiec [4], and Bonfante, Marion, Moyen [7]. Lastly, the method is a first step for us to prove imperative program termination by adapting ideas of Lee, Jones and Ben-Aram [17] or Abel and Altenkirch [1]. The intuition is that a program terminates when there is no more resource to consume. 1.2 Coping with undecidability All these theoretical frameworks share the common particularity of dealing with behaviours of programs (like time and space complexity) and not only with the inputs/outputs relation which only depends on the computed function. Indeed, a given function can be computed by several programs with different behaviours (in terms of complexity or other). Classical complexity theory deals with functions and computes extensional complexities. Here, we want to compute intensional or implicit complexity, that is try to understand why a given algorithm is more efficient than another to compute the same function. The study of extensional complexity quickly reaches the boundary of Rice’s theorem. Any extensional property of programs is either trivial or undecidable. Intuition and empirical results points out that intensional properties are even harder to decide. Section 2 will formalise this impression. However, several very successful works do exist for studying both extensional properties (like termination) or intensional ones (like time or space complexity). As these works provide decidable criteria, they must be either incomplete (reject a valid program) or unsound (accept an invalid program). Of course, the choice is usually to ensure soundness: if the program is accepted by the criterion then the property (termination, polynomial bound, ...) is guaranteed. This allows the criterion to be seen as a certificate in a proof carrying code paradigm. The property that we study here is Non Size Increasingness (NSI) as first studied by Hofmann [13]. A program is NSI if its computation does not require more memory than what is initially allocated (i.e. the total memory usage is the size of the input, plus some constant amount). This is an intensional property and this is an undecidable property. When studying intensional properties, two different kind of approaches exist. The first one consist of restricting the syntax of programs so that any program written necessarily has the wanted property. This is in the line of the works on primitive recursive functions where the recurrence schemata is restricted to only primitive recursion. This approach gives many satisfactory results, such as the characterisations of PTIME by Cobham [10] or Bellantoni and Cook [6], the works of Leivant and Marion on tiering and predicative analysis [20] or the works of Jones on CONS-free programs [15]. On the logical side, this leads to explicit management of resources in Linear Logic [12]. All these characterisations usually have the very nice property of extensional completeness in the sense that, e.g. every polynomial time computable function can be computed by a bounded recursive function (Cobham). Unfortunately, they’re usually very poor on the intensional completeness, meaning that very few programs fit in the characterisation [11] and programmers have to rewrite their programs in a non-natural way. So, the motto of this first family of methods can be described as leaving the proof burden to the programmer rather than to the analyser. If you can write a program with the given syntax (which, in some cases, can be a real challenge), then certain properties are guaranteed. The other family of methods will go in the other way. Let the programmer write whatever he wants but the analysis is not guaranteed to work. Since syntax is not hampered in these methods, decidability is generally achieved by loosening the semantics during analysis. That is, one will consider more that all the executions a program can have. A trivial example of this idea would be “a program without loop uniformly terminates”. The reason we consider loops as bad is because we assume it is always possible to go through the loop infinitely many time. That is, the control of the loop is completely forgotten by this “analysis”. A more serious example of this kind of characterisation is the Size Change Principle [17]. The set FLOW that is build during the analysis contains all “well-formed call sequences”. Every execution of the program can be mapped to a well-formed call sequence but several (most) of the call sequences do not correspond to any execution of the program. Then, properties (termination) of call sequences in FLOW are necessarily shared by all execution of the program. However, the methods sometimes fail – which is normal since it’s a decidable method for partly solving an undecidable problem – because FLOW does contain well formed call sequences which correspond to no execution of the program but nonetheless do not have the wanted property. This second kind of methods can thus be described as not meddling with the programmer and let the whole proof burden lay on the analysis. Now, what is the situation on the Non Size Increasingness side? All the existing works, either by Hofmann [13] or Aehlig and Schwichtenberg [2] or Aspinall and Compagnoni [5] belongs to the first family of methods. In each case, resource management has to be done by the programmer via the diamond type, meaning that one has to explicitly reuse pointers that are no more needed (via the linear typing). This work is intended to belong to the second family of methods. This means that programs do not have to reuse pointers but the analysis will discover if a reuse is possible. This has a nice consequence in the way that programmers can now freely allocate and de-allocate memory (with the diamonds, one cannot allocate and everything de-allocated is gone for good). So our analysis do not prevent malloc. Of course, in order to have decidability back, we have to loosen semantics as mentioned above. In our case, similarly to the Size Change Principle, this is done by “rendering tests non deterministic”, that is considering that any branch of a if can be taken without looking at the actual result of the test. And of course, there are several programs that are Non Size Increasing but won’t be analysed correctly. The set of falsely rejected programs may appear big at first, however, it is not bigger than in Hofmann’s framework since we can capture any algorithm that is writable in this model. We will discuss this further at the end of Section 5.2. 2. SOME DECIDABILITY ISSUES In this section, we hint that intensional properties are more undecidable than extensional ones by proving this result for polynomial time computation and NSI. Rice’s theorem [28] implies that any extensional property of Turing Machines (or programs) is either trivial or undecidable. An extensional property is one that depends only of the inputs and the output of the machines, i.e. that depends only of the function computed by the machine. A direct application of this theorem leads to the following result: **Proposition 1. The set of programs p whose output size is bounded by their input size \(|p(x)| \leq |x| + c^k\) is not recursive.** However, the Non Size Increasingness property that we want to study is stronger. Indeed, there exists programs who need tremendous amount of memory to compute but only output a small result. Typically, any program solving a decision problem will only output either “yes” or “no”, i.e. bounded size information, but may require arbitrary large amount of memory to compute this answer. The NSI property that we study is actually an intensional property of programs. It depends not only on the inputs and outputs but also on the way the computation is performed. Intensional properties are really properties of programs and not properties of functions. Indeed, a given function can be computed by several programs (e.g. Fibonacci’s numbers can be computed with a naive exponential time algorithm or by a dynamic programming, linear time algorithm). Extensional properties depending only on the inputs/outputs of the programs are shared by all programs computing the same function. Intensional properties are not. For example, the intensional property of “computing in polynomial time” is not shared by all the program computing Fibonacci’s numbers. Intuitively, intensional properties seem even harder to decide that extensional ones. This can be formalised a bit by the following theorem. Here, we consider that a machine is NSI if and only if it never requires more space than a constant value plus the initial space (needed to store the input). **Theorem 1.** Let $p$ be a program. The question "is $p$ NSI?" is undecidable even if we know that $p$ uniformly terminates. Here, uniform termination means that the program terminates for all inputs. **Proof.** Let $q$ be a program and consider the program $p$ that works as follows: - $p$ answer 1 if its input is 0. - On input $x \neq 0$, $p$ simulates $q(0)$ for $x$ steps. - If $q(0)$ halts within $x$ steps, then $p$ answers 0. - Else, $p$ answers $2^x$ (or any other large value depending on $x$). Obviously, $p$ uniformly terminates. Is it NSI? If $q(0)$ terminates, then it does so in $n$ steps. The space used to compute $p$ is bounded by $2^n + S_q(0)$, where $S_q(0)$ is the space needed to compute $q(0)$, i.e. a constant value and so $p$ is NSI. If $q(0)$ does not terminates, then $p$ compute the exponential and is certainly not NSI. So, $p$ is NSI if and only if $q(0)$ terminates. Since the halting problem is not decidable, so is belonging to NSI. Uniform termination of programs, in itself, is a non semi-recursive property. So even with an oracle powerful enough to solve (some) non semi-recursive problems, the computational property of being NSI is still undecidable! Intensional properties are, indeed, much harder than extensional ones. Notice that this proof can be easily adapted to show the undecidability of any complexity class (of programs). It is sufficient to change the function computed by $p$ if $q(0)$ does not terminates. **Remark 1.** A similar proof, for the undecidability of running in polynomial time, based on Hilbert’s tenth problem[23] ($p(x + 1) = 0$ if some polynomial $P$ has a root $x$, $2 \times p(x)$ otherwise) was presented as the Geocal ICC workshop in Feb. 2006 by Terui. This work has been done independently from a similar result presented by Marion in March 2000 at a seminar in ENS Lyon. This is kind of a folklore result but is nonetheless worth mentioning because lot of confusion is done on the subject. The above result can be improved. Indeed, the set of programs that run in polynomial time, or which are NSI, is $\Sigma_2$-complete. Recall, that a typical $\Sigma_2$-complete set is the set of partial computable functions. In order to establish the fact that NSI programs is a $\Sigma_2$-complete set, we take a class $C$ of computable functions which contains all constant functions. Assume also that there is a computable set of function codes $C$ which enumerates all functions in $C$. The set of linear functions $\{x + b \mid b \in \mathbb{N}\}$ satisfies the above hypothesis. Another example is the set of polynomials or the set of affine functions $a \times x + b$. Next, let $\llbracket p \rrbracket$ be the function computed by the program $p$ with respect to an acceptable enumeration of programs. We refer to Rogers’ textbook [16] for background. Say that $T_p(x)$ is the number of steps to execute the program $p$ on input $x$ with respect to some universal (Turing) machine. Now, define the set of programs whose runtime is uniformly bounded by functions in $C$: $$A_T = \{ p \mid \exists e \in C \quad \forall x, T_p(x) < [e](|x|) \}$$ **Theorem 2.** The set $A_T$ is $\Sigma_2$-complete. **Proof.** It is clear that the statement which defines $A_T$ is a $\Sigma_2$ statement. Let $B$ be any $\Sigma_2$ set defined as follows: $$B = \{ q \mid \exists y \forall x, R(q, y, x) \}$$ $R$ is a computable predicate We prove that $B$ is reducible to $A_T$. For this, we construct a binary predicate $Q$ as follows. $Q(q, t)$ tests during $t$ steps whether there is a $y$ with respect to some canonical ordering such that $\forall x, R(q, y, x)$ holds. If it holds, $Q(q, t)$ also holds. Here, the predicate $Q$ is computable with a complete $\Pi_1$ set as oracle. Using the s-m-n theorem, there is a program $q'$ such that $\llbracket q' \rrbracket(t) = Q(q, t)$. 1. Suppose that $q \in B$. We know that there is an $y$ such that $\forall x, R(q, y, x)$. It follows that the witness $y$ will be found by $Q$ after $t$ steps. Since the constant function $\lambda x.t$ is in $C$, we conclude that $q'$ is in $A_T$. 2. Conversely, suppose that $q' \in A_T$. This means that $Q(q', t)$ holds for some $t$, which yields an $y$ verifying $\forall x, R(q, y, x)$ Notice that we may change time by space in the above proof, which leads to the following consequence. **Corollary 1.** Let $$A_S = \{ p \mid \exists e \in C \quad \forall x, S_p(x) < [e](|x|) \}$$ where $S_p(x)$ is the space use by $p$ on $x$. The set $A_S$ is $\Sigma_2$-complete. Depending on the choice of the set of functions $C$, this proves the $\Sigma_2$-completeness of the following sets: - Non-Size Increasing programs (for linear functions and $A_S$). - PTIME (for polynomials functions and $A_T$). - LOGSPACE, PSPACE, . . . any classical complexity class. ## 3. PROGRAMS ### 3.1 Syntax **Definition 1.** A program is defined by the following grammar: - **Programs** - $p ::= \text{lbl1 : i; ... lbln : in;}$ - $i ::= r_1, \ldots, r_l := \text{op(r'_{i_1}, \ldots, r'_{i_k})}$ - $r ::= \text{r'} \mid \text{r := r'}$ - $r ::= \text{newn \mid freer}$ - $\text{jmp~lbl} \mid \text{jr~lbl0 lbl1}$ - $\text{end}$ - **Labels** - $L \ni \text{lbl}$ finite set of labels - **Registers** - $R \ni \text{r}$ finite set of registers - **Operators** - $O \ni \text{op}$ finite set of operators Each operator has a fixed arity $k$ and co-arity $l$ and $n$ is an integer constant. The syntax of a program induces a function $\text{next} : L \rightarrow L$ such that $\text{next(lbl1)} = \text{lbl}_{i+1}$ and a mapping $\text{instr} : L \rightarrow I$ such that $\text{instr(lblk)} = i_k$. The above result can be improved. Indeed, the set of programs that run in polynomial time, or which are NSI, is $\Sigma_2$-complete. Recall, that a typical $\Sigma_2$-complete set is the set of partial computable functions. In order to establish the fact that NSI programs is a $\Sigma_2$-complete set, we take a class $C$ of computable functions which contains all constant functions. Assume also that there is a computable set of function codes $C$ which enumerates all functions in $C$. The set of linear functions $\{x + b \mid b \in \mathbb{N}\}$ satisfies the above hypothesis. Another example is the set of polynomials or the set of affine functions $a \times x + b$. Next, let $\llbracket p \rrbracket$ be the function computed by the program $p$ with respect to an acceptable enumeration of programs. We refer to Rogers’ textbook [16] for background. Say that $T_p(x)$ is the number of steps to execute the program $p$ on input $x$ with respect to some universal (Turing) machine. Machines that we consider are close to the RAM-Machines. There is a memory device, similar to heaps on computers, and a finite number of registers. The heap consists in an unbounded number of memory cells. Each cell stores an integer. Each register also stores an integer whose value may be the address of a heap-cell. Roughly speaking, \( *r \) denotes the value of the memory cell whose address is stored in \( r \). The instruction \( jmp \ lbl \) gives the control to label \( lbl \), \( jz \ r \ lbl \ l1' \) gives the control to either \( l1' \) (if \( r \) contains 0) or \( l1' \). The instruction \( new \ n \) allocates \( n \) consecutive cells of memory in the heap and returns the address of the first one and \( free \) frees the memory cell in the heap at the given address. Memory allocation is done by block because we may require two given to cells have consecutive addresses (e.g. to represent lists) but freeing memory is done cell by cell (unlike, e.g. in \( \mathbb{C} \)) to avoid remembering the size of each allocated block. **Example 1.** The following program reverses a list. A list is here represented by a set of positions, each position consists in two consecutive memory cells. The first cell contains the value of the element in the list and the second contains the address of the next position (or 0 for the end of the list). For the sake of clarity, only labels which play a special role (e.g. destination of jumps) have been mentioned in this example. ``` begin : next := 0; jz r0 end loop; loop : val := *r0; tmp := r0 + 1; free r0; r0 := *tmp; free tmp; r1 := new 2; r1 := val; r1 + +; *r1 := next; r1 := - -; next := r1; jz r0 end loop; end : end; ``` Of course, the use of low-level data structure may imply tedious pointer management. However, we could introduce new operators acting both on registers and on the heap that can be seen as macros. **Definition 2.** A program is a sequence of configurations that can be formally defined as: - \( l := \text{cons}(a, l') \) is equivalent to \( l := \text{new} 2; *l := a; l + +; l := l'; l := - -; \) - \( a, l' := \text{destr}(l) \) is equivalent to \( a := *l; \text{tmp} := l + 1; \text{free} l'; l := \text{tmp}; \text{free} \text{tmp} \) Using these, the program thus becomes: ``` begin : next := 0; l1 := jz r0 end loop; loop : val, r0 := destr(r0); l1 := cons(val, next); l1 := r1; l1 := jz r0 end loop; end : end; ``` We illustrate an execution of the program in Figure 1. Notice that if one wants to write the reverse program within Hofmann’s or Aspinall and Compagnoni’s formalism, one cannot use \( \text{new} \) and \( \text{free} \) and has to explicitly keep the values of pointer (i.e. the diamonds) and tells when they have to be reused. ### 3.2 Semantics The domain of the computation is \( V = \mathbb{N} \), and we interpret each operator \( \circ \) by a function \( [\circ] \) of the same arity an co-arity over \( V \). An environment is a mapping \( \sigma : \mathcal{R} \rightarrow V \), which associates to each register a value. We note \( \{r_i \rightarrow v\} \) the environment that maps \( r_i \) to \( v \) and \( r_j \) to \( r_j' \) (\( i \neq j \)). When no ambiguity can arise, we just write \( r \) instead of \( \{r\} \). A heap is a mapping \( \mu : \mathbb{N} \rightarrow V \cup \{\bot\} \), which returns a value if a heap address is allocated. Otherwise, it returns \( \bot \) when a heap address is unallocated. We note \( \{n \rightarrow v\} \mu \) to say that the heap is updated in such a way that \( \{n \rightarrow v\} \mu(n) = v \) and \( \{n \rightarrow v\} \mu(m) = \{m\} (m \neq n) \). Memory allocation is performed by some external mechanism similar to a call system. In our framework, we have a predicate \( \text{memfree}(k, n) \) which tests whether the memory cells between \( k \) and \( k + n - 1 \) are currently unallocated: \[ \text{memfree}(k, n) = \text{and} (\mu(k) = \bot) \land \ldots \land (\mu(k + n - 1) = \bot) \] During computation, three kind of errors can happen. Namely, (i) accessing an unallocated memory cell (MemError), (ii) lacking free memory to perform a new instruction (MemFull) or (iii) freeing an already unallocated memory cell (FreeError). The MemError rule means that there is a mechanism (either internal or external via system calls performed when memory is read) able to detect dangling pointers. This, of course, is a rather costly operation at runtime and quite hard to perform on static code. On the other hand, memory leaks are not detected. Both these issues can be discarded if we consider that our programs are obtained by compilation of a higher level language with efficient memory management and garbage collection. In the following, we will assume that programs are safe in the sense that they never cause one of the error rules to be triggered. **Definition 3.** Programs are executed using a straightforward small-step semantics whose rules are described in Figure 2. The relation \( p \vdash \theta_1 \rightarrow \theta_2 \) means that the new configuration is \( \theta_2 \) after executing the instruction \( \theta = \text{instr}(\text{IP}) \) where \( \text{IP} \) is the instruction pointer of \( \theta_1 \). An execution of a program \( p \) is a sequence of configurations computed step by step. We write \( p \vdash \theta_0 \rightarrow \theta_1 \rightarrow \ldots \rightarrow \theta_n \) if \( p \vdash \theta_0 \rightarrow \theta_1 \rightarrow \ldots \rightarrow \theta_n \) for each \( i = 0, n - 1 \). Programs compute functions from heaps to heaps as soon as certain conditions on the initial environment (with respect to the initial heap) are respected. The program of Example 1 reverses a list assuming that the heap is really the encoding of a list and that \( r_0 \) initially contains the address of the first cell of the list. ### 3.3 Measuring heap Usage In order to control space resources, we consider the number of new heap cells allocated during any execution of a program. We do not consider the number of cells of the input. So, only the “workspace” is counted like in read-only model of computation. If we want to control the real space usage, we have to take values into account. Indeed, working with unbounded values means that one needs logarithmic space to actually store them. To constantly keep this into mind, we speak of heap complexity rather than the usual space complexity. Of course, in any real computer, the set of values is bounded (e.g., it is the set long int of 32 bits integers). In this case, the real space usage is directly proportional to the heap usage, heap and space complexity are the same up to a multiplicative constant. Definition 4. Let $\theta = (T, P, \mu, \sigma)$ be a configuration. The heap size $|\theta|$ of $\theta$ is $\text{card}\{n, \mu(n) \neq \bot\}$, that is the number of non-$\bot$ elements in $\mu$. The heap measure is a function such that for any program $p$, and any configuration $\theta_0$, $$\text{heap}_p(\theta_0) = \begin{cases} \max_{\theta_1, \ldots, \theta_n} |\theta_1| - |\theta_0| & \text{if } p \vdash \theta_0 \xrightarrow{t_1} \theta_1 \ldots \xrightarrow{t_n} \theta_n \\ \bot & \text{and } \theta_n \text{ final} \\ \perp & \text{otherwise} \end{cases}$$ In other words, the heap usage $\text{heap}_p(\theta_0)$ is the maximal heap size of an encountered configuration when the computation terminates. Given a total function $f : N \rightarrow N$, we define the set of heap-bounded programs: $$\text{Heap}(f) = \{ p \mid \text{heap}_p(\theta) \leq f(|\theta|) \forall \theta, \text{heap}_p(\theta) \neq \bot \}$$ Definition 5. $\text{LinHeap}$ is the class of programs running with a linear heap. That is $\text{LinHeap} = \bigcup \text{Heap}(f)$ where the union ranges over all $f : x \mapsto \beta \times x + \alpha$. $\text{NSI}$ is the class of programs running with at most a constant increase in heap size, that is $\text{NSI} = \bigcup \text{Heap}(f)$ where the union ranges over all $f : x \mapsto \alpha$. 4. RESOURCE PETRI NET 4.1 Petri Nets in a nutshell We briefly describes Petri nets and reader may consult the survey of Murata [25] for more details. A Petri net $N$ is a quadruplet $(S, T, A, \omega)$ where $S$ is a set of places, $T$ is a set of transitions and $A$ is a set of arcs such that $(S, T, A)$ is a bipartite oriented graph. That is, $S$ and $T$ are disjoint and each arrow is either from $S$ to $T$ or from $T$ to $S$. An arrow between $s$ and $t$ ($s,t$) has a weight $\omega(s,t)$ ($\omega(t,s)$). As usual, places are graphically represented by circles while transitions are represented by squares. A marking $M$ assigns to each place $s$ a natural number $M(s)$ which indicates the number of tokens in it. The pre-set of a transition $t$ is $\cdot t = \{ s \in S \mid (s, t) \in A \}$. The post-set of a transition $t$ is $t^* = \{ s \in S \mid (t, s) \in A \}$. A transition $t$ is enabled at marking $M$ if and only if for any place $s$ in $t^*, M(s) - \omega(s,t) \geq 0$. It can then be fired thus reaching marking $M'$: $$M'(s) = M(s) - \omega(s,t) + \omega(t,s)$$ We write $N \vdash M_{n} \xrightarrow{t_{1}} \ldots \xrightarrow{t_{m}} M_{n}$ is a run of the Petri net. 4.2 Control Flow Petri Net Definition 6. Let $p$ be a program, its control flow Petri net (CFPN) $\text{cfpn}(p)$ is defined as follows: - The set of places is exactly the set $L$ of labels of $p$. - For each instruction that is neither $\text{zj}$ nor end, there is a transition $\text{instr}(\text{lbl})$ bearing the same name and for each $\text{zj}$ or $\text{lbl}$ instruction, there are two transitions $r = 0$ and $r \neq 0$. - For each label $\text{lbl}$ such that $\text{instr}(\text{lbl}) \notin \{ \text{zj}, \text{jmp}, \text{end} \}$, there is one arrow from $\text{lbl}$ to $\text{instr}(\text{lbl})$ and one from $\text{instr}(\text{lbl})$ to $\text{next}(\text{lbl})$. Figure 1: An example run of the reverse program. \[ \text{instr}(\text{IP}) = r_1, \ldots, r_k := \text{op}(r'_1, \ldots, r'_l) \quad v_j = \sigma(r'_j) \quad v_1, \ldots, v_l = [\text{op}](v'_1, \ldots, v'_k) \] \[ p \vdash (\text{IP}, \mu, \sigma) \xrightarrow{\text{instr}(\text{IP})}\ (\text{next}(\text{IP}), \mu, \{r_i \leftarrow v_i\}_{i \in 1 \ldots k}) \] \[ \text{instr}(\text{IP}) = r := *r' \quad \text{or} \quad \text{instr}(\text{IP}) = *r := r\quad \mu(r') = \bot \] \[ p \vdash (\text{IP}, \mu, \sigma) \xrightarrow{\text{instr}(\text{IP})}\ (\text{next}(\text{IP}), \mu, \{r \leftarrow v\}_{\sigma}) \] \[ \text{instr}(\text{IP}) = r := *r' \quad \mu(r') = v \] \[ p \vdash (\text{IP}, \mu, \sigma) \xrightarrow{\text{instr}(\text{IP})}\ (\text{next}(\text{IP}), \mu, \{r \leftarrow v\}_{\sigma}) \] \[ \text{instr}(\text{IP}) = *r := r' \quad \mu(r) \in V \] \[ p \vdash (\text{IP}, \mu, \sigma) \xrightarrow{\text{instr}(\text{IP})}\ (\text{next}(\text{IP}), \{\sigma(r) \leftarrow \sigma(r')\}_{\mu}, \sigma) \] \[ \text{instr}(\text{IP}) = r := \text{new } n \quad \forall k \in \mathbb{N}, \neg \text{memfree}(k, n) \] \[ p \vdash (\text{IP}, \mu, \sigma) \xrightarrow{\text{instr}(\text{IP})}\ (\text{next}(\text{IP}), \{k \leftarrow 0, \ldots, k + n - 1 \leftarrow 0\}_{\mu}, \{r \leftarrow k\}_{\sigma}) \] \[ \text{instr}(\text{IP}) = \text{free } r \quad \mu(r) = \bot \] \[ p \vdash (\text{IP}, \mu, \sigma) \xrightarrow{\text{instr}(\text{IP})}\ (\text{next}(\text{IP}), \{\sigma(r) \leftarrow \bot\}_{\mu}, \{r \leftarrow 0\}_{\sigma}) \] \[ \text{instr}(\text{IP}) = \text{free } r \quad \mu(r) \neq \bot \] \[ p \vdash (\text{IP}, \mu, \sigma) \xrightarrow{\text{instr}(\text{IP})}\ (\text{next}(\text{IP}), \{\sigma(r) \leftarrow \bot\}_{\mu}, \{r \leftarrow 0\}_{\sigma}) \] \[ \text{instr}(\text{IP}) = \text{jmp } \text{lbllbl} \] \[ p \vdash (\text{IP}, \mu, \sigma) \xrightarrow{\text{instr}(\text{IP})}\ (\text{lbllbl}, \mu, \sigma) \] \[ \text{instr}(\text{IP}) = \text{jz } r \text{ } \text{lbllbl' } \sigma(r) = 0 \] \[ p \vdash (\text{IP}, \mu, \sigma) \xrightarrow{\text{instr}(\text{IP})}\ (\text{lbllbl}, \mu, \sigma) \] \[ \text{instr}(\text{IP}) = \text{jz } r \text{ } \text{lbllbl' } \sigma(r) \neq 0 \] \[ p \vdash (\text{IP}, \mu, \sigma) \xrightarrow{\text{instr}(\text{IP})}\ (\text{lbllbl'}, \mu, \sigma) \] \[\text{Figure 2: Small-steps semantics}\] The number of tokens in the place $\text{Free}$ represents a heap cell. At the beginning of a program execution, the place $\text{Free}$ contains the number of free cells. When a program requests new cells, then we need to have as many tokens in the corresponding marking $M^0$ of $\text{Free}$ as the current size of the heap (the number of non-$\bot$ cells). The place $\text{Free}$ should contain as many tokens as there is free memory (this depends on the machine used, not only on the program). Definition 7. Let $p$ be a program. The resource Petri net $\text{rpn}(p)$ of $p$ is obtained by adding to $\text{cfpn}(p)$ two places $\text{Free}$ and $\text{Heap}$ and four kind of arrows - An arrow from the $\text{Free}$ place to each new $n$ transition of weight $n$. - An arrow from each new $n$ transition to $\text{Heap}$ place of weight $n$. - An arrow from each free transition to the $\text{Free}$ place of weight 1. - An arrow from the $\text{Heap}$ place to each free transition of weight 1. Inversely, when a free $r$ instruction is executed, then one token is moved from the $\text{Heap}$ place to the $\text{Free}$ one. Thus we recycle discarded heap cells. So, a RPN is a simple model which allows to simulate executions of programs and to check memory usage at the same time. The $\text{Heap}$ place should contain as many tokens as the current size of the heap (the number of non-$\bot$ cells). The $\text{Free}$ place should contain as many tokens as there is free memory (this depends on the machine used, not only on the program). Proposition 2. Let $p$ be a program. If $p \models \theta_0 \xrightarrow{t_1} \ldots \xrightarrow{t_n} \theta_n$ is an execution of $p$, then $\text{cfpn}(p) \models M^{\theta_0} \xrightarrow{t_1} \ldots \xrightarrow{t_n} M^{\theta_n}$ is a run of $\text{cfpn}(p)$. 4.3 Resource Petri Net We now turn to represent the heap memory mechanism by a Resource Petri Net (RPN). In order to define a RPN, we add to CFPN construction described above two new places $\text{Heap}$ and $\text{Free}$. As previously, each program execution is mapped on a RPN run which, unlike the previous CFPN model, is resource-aware. For this, a token represents a heap cell. At the beginning of a program execution, the place $\text{Free}$ contains the number of free cells. When a program requests $n$ new cells, then we need to have $n$ tokens in the place $\text{Free}$. In this case, we put $n$ tokens in the place $\text{Heap}$. Otherwise, there is not enough free memory, and the run of the RPN stalls. The number of tokens in the place $\text{Heap}$ is the number of cells which have been allocated during a program execution. of this edge is the absolute value of $\omega(\text{instr})$ and the direction of it is given by the sign of the weight. Figure 4 illustrates this by showing the RPN of the reverse program. Tokens in the $\text{Heap}$ and $\text{Free}$ places correspond to Hofmann’s diamonds ($\diamond$), that is a fixed amount of space in the heap. Each token represents a diamond, either used by (one of the variable of) the program if in the $\text{Heap}$ place or available if in the $\text{Free}$ place. Memory allocation (such as $\text{cons}$), needs diamonds in order to be performed while memory de-allocation (such as $\text{destr}$) releases diamonds to be used later. **Lemma 1.** In each run of a RPN, the total number of tokens in the $\text{Free}$ and $\text{Heap}$ places is constant. To each configuration $\rho = (\text{IP}, \mu, \sigma)$ of $p$, we associate a marking $M^\rho$ of $\text{rpm}(p)$: \[ M^\rho(\text{Heap}) = |\rho| \quad M^\rho(\text{Free}) = i \] \[ M^\rho(\text{IP}) = 1 \quad M^\rho(1b1) = 0 \quad \text{otherwise} \] **Lemma 2.** Let $p$ be a program, $\rho$ be a configuration such that $p \vdash \rho \Rightarrow \rho'$ and $i$ be an integer such that $i + \omega(t) \geq 0$. Then, $\text{rpm}(p) \vdash M^\rho \rightarrow M^{\rho'} + M^{\rho + \omega(t)}$. **Proof.** Consider that $t = \text{new} n$. We can remove $n$ tokens from $\text{Free}$ because $i + \omega(t) = i - n \geq 0$. So, we can fire the $\text{new} n$ transitions. Next, consider $t = \text{free} r$. The place $\text{Heap}$ contains $|\rho|$ tokens and by hypothesis $p \vdash \rho \Rightarrow \rho'$, so we know that $|\rho| > 0^2$. Therefore, we can remove one token from the place $\text{Heap}$ and fire the transition. \qed **Proposition 3.** Let $p$ be a program and let $N$ be its RPN. Assume that $p \vdash \theta_0 \xrightarrow{t_1} \ldots \xrightarrow{t_n} \theta_n$. Let $i_0$ be a natural number such that $\forall k \leq n$, $i_0 + |\theta_k| - |\theta_0| \geq 0$. Then, there is a run $N \vdash M^{\theta_0}_0 \xrightarrow{t_1} \ldots \xrightarrow{t_n} M^{\theta_n}_{i_n}$ which satisfies $i_k = i_0 + |\theta_k| - |\theta_0|$ for each $k = 0, \ldots, n$. ### 5. Characterization of Heap Complexity The condition $|\rho| - \omega(t) \geq 0$ is not necessarily here. #### 5.1 Heap complexity and resource Petri nets **Theorem 3.** Let $f : \mathbb{N} \rightarrow \mathbb{N}$ be a total function. Let $p$ be a program. If $p \in \text{Heap}(f(x))$ if and only if for each initial configuration $\theta_0$ and for each execution $p \vdash \theta_0 \xrightarrow{t_1} \ldots \xrightarrow{t_n} \theta_n$, we have $\text{rpm}(p) \vdash M^\rho_{f(\theta_0)} \xrightarrow{t_1} \ldots \xrightarrow{t_n} M^\rho_{f(\theta_n)}$ for some $i_1, \ldots, i_n$. The fact that the run exists means that $f(|\theta_0|)$ is a sufficiently large number of tokens to put in $\text{Free}$ to avoid any deadlock. **Proof.** If for each initial configuration $\theta_0$ and each execution $p \vdash \theta_0 \xrightarrow{t_1} \ldots \xrightarrow{t_n} \theta_n$, there is a corresponding run \[ \text{rpm}(p) \vdash M^\rho_{f(\theta_0)} \xrightarrow{t_1} \ldots \xrightarrow{t_n} M^\rho_{f(\theta_n)} \] then for any $k$, \[ |\theta_k| = M^\rho_{f(\theta_0)}(\text{Heap}) \leq M^\rho_{f(\theta_0)}(\text{Heap}) + M^\rho_{f(\theta_0)}(\text{Free}) = |\theta_0| + f(|\theta_0|) \] Conversely, deadlocks in the run may come from three sources: the label places, the $\text{Heap}$ place or the $\text{Free}$ place. The label places cannot cause deadlock due to Proposition 2. The $\text{Heap}$ place may only cause deadlock if a $\text{free}$ transition should be fired but the $\text{Heap}$ place is empty. However, this would correspond to executing a $\text{free}$ instruction on an empty heap, thus triggering the (FreeError) rule. The $\text{Free}$ place can cause deadlock if a $\text{new} n$ transition has to be fired but $\text{Free}$ contains less than $n$ tokens. However, Prop. 3 claims that if we start from marking $M^\rho_{\theta_0}$ such that for all $1 \leq k \leq n$, $i_0 + |\theta_0| - |\theta_k| \geq 0$ there will be no deadlock. Since $p \in \text{Heap}(f)$, $|\theta_k| \leq f(|\theta_0|) + |\theta_0|$ and thus $i_0 + |\theta_0| - |\theta_k| \geq i_0 + f(|\theta_0|)$. So by starting from $M^\rho_{f(\theta_0)}$, there will be no deadlock. \qed Notice that the (implicit) quantifier on the Petri net runs is existential and not universal. To each execution of the program corresponds a run, but some runs correspond to no execution of the program (because the Petri net does not mimic the semantics tightly, especially tests). This means that unless one can decide which run corresponds to an execution, analysis of the Petri net will not capture every programs (because in some cases, the “invalid” runs do not correspond to an execution). This is a necessarily lose if we want our criterion to be decidable, as mentioned in the discussion at the end of Section 1.2. **Corollary 2.** $p \in \text{NSI}$ if and only if there exists a constant $\alpha$ such that for each initial configuration $\theta_0$ and each execution $p \vdash \theta_0 \xrightarrow{t_1} \ldots \xrightarrow{t_n} \theta_n$, we have $\text{cfn}(p) \vdash M^\rho_{\theta_0} \xrightarrow{t_1} \ldots \xrightarrow{t_n} M^\rho_{\theta_n}$ where $i_k = |\theta_0| + \alpha - |\theta_k|$. $\alpha \neq 0$ $p \in \text{LINHEAP}$ if and only if there exists $\alpha$ and $\beta$ such that for each initial configuration $\theta_0$ and each execution $p \vdash \theta_0 \xrightarrow{t_1} \ldots \xrightarrow{t_n} \theta_n$, we have $\text{cfn}(p) \vdash M^\rho_{\theta_0} \xrightarrow{t_1} \ldots \xrightarrow{t_n} M^\rho_{\theta_n}$ where $i_k = (\beta + 1)|\theta_0| + \alpha - |\theta_k|$. #### 5.2 Detection of non-size increasing programs **Theorem 4.** There is a polynomial time procedure to detect if a program is $\text{NSI}$. **Proof.** Let $p$ be a program. We construct a directed graph $G$ from $\text{rpm}(p)$ that we name the resource control graph of $p$ as follows. Nodes are label place. There is an edge from $1b1$ to $1b1'$. --- Figure 5: Control Flow Graph of the reverse program. Edges are labelled after the instruction they represent. Figure 6: Resource Control Graph of the reverse program. Edges are labelled after the instruction they represent. if there is a transition from \( l_1 \) to \( l_1' \) in \( rpm(p) \). The weight assigned to an edge is the weight of the corresponding transition, that is the weight \( \omega(\text{instr}(l_1)) \). In other words, the resource control graph is the control flow graph where each arrow as the same weight as the corresponding instruction. If the resource control graph contains no cycle of strictly negative weight, then the program is in NSI. This criterion can be decided in polynomial time via Bellman-Ford's algorithm. Indeed, any path in the resource control graph correspond to a run in the RPN. The weight of the path being exactly the number of token removed from (if negative) the \( \text{Free} \) place at the end of the run. If there is no cycle of negative weight, then the minimum weight of all paths, \( \alpha \), is well defined. So, no run can remove more than \( \alpha \) token from \( \text{Free} \). Hence, each execution corresponds to a run that can be performed with \( \max(-\alpha, 0) \) token initially in \( \text{Free} \) and \( p \) is NSI. The above demonstration provides also the number of cells which are necessary to perform any computation. Therefore, we may be able to set up a proof procedure, like in proof carrying code paradigm, in polynomial time to calculate and certify that a program uses a fixed amount of heap. Hofmann has shown that Non Size Increasing programs can be compiled into \( C \) without using \texttt{malloc} [13]. That is, in our case, we can write an equivalent program without the \texttt{new} instruction, or, more precisely, starting with a single \texttt{new} \( \alpha \) instruction during the initialization process. Amadio already has a \texttt{PTIME} bound to detect NSI programs in terms of quasi-interpretation [3]. And linear space usage can also be characterized by quasi-interpretations [8]. Lastly, notice that a cycle of positive weight may cause damages by releasing potentially non-allocated heap cells. We do not control this kind of troubles here. Example 2. The resource graph of the reverse program is given in Figure 6. Since there is no cycle of negative weight, so the program is NSI. Moreover, the weight of any path starting from begin is either 0 or +2, so choosing \( \alpha = 0 \) is enough, meaning that the program doesn’t use more memory that initially allocated. Of course, the above method does not capture all non size increasing programs. For example, if in a loop like (written in a \( C \)-like syntax for readability): \[ \text{for}(i = 1, i \leq r, i++) \{ r' := \text{new} 1; \} \] the method fails. However, we can roughly distinguish three cases for this kind of loops. - \( r \) is an immediate value, that is the loop actually is, say, \[ \text{for}(i = 1, i \leq 10, i++) \{ r' := \text{new} 1; \} \] In this case, the allocation can be performed before the loop: \[ r := \text{new} 10; \text{for}(i = 1, i \leq 10, i++) \{ r' := r + i; \} \] This allows to have the same effect but put the allocation out of the loop. - \( r \) is a value stored in a register which happen to be a constant. In this case, constant propagation allows to detect at compile time that \( r \) can be replaced by an immediate value. - \( r \) is the value of a register which depends on the inputs. In this case, the program is probably not NSI because it perform a number of allocations dependant on the inputs. Both the first two transformations can be performed automatically at compile time, just before the analysis is performed. Moreover, construction of the CFG and RCG can help find potentially harmful loops (those with a positive weight) and thus help the transformation of these loops. Of course, programs where constant propagation fails or programs with loops of the third kind will not be detected as NSI. Hopefully, there are few of them among the commonly used algorithms... It is also important to notice that any algorithm that fits into Hofmann’s framework can be detected as NSI by our method. Indeed, Hofmann provides a way to compile NSI programs into \texttt{malloc}-free programs and our method obviously detect \texttt{malloc}-free programs as NSI (since they do not allocate memory, the RCG has no edge of negative weight and cannot have cycle of negative weight). 6. OTHER CHARACTERIZATIONS 6.1 Linear Heap Space The detection of linear space computation is closely related to the one of non size increasing computation, and the previous method can be modified to handle linear heap run. The idea is that each input cell gives new cells when it is deallocated, instead of one in the case of a non-size increasing memory allocation. On the other hand, cells which are allocated during an execution only count for one. To perform this analysis, we consider two kinds of heaps: an \texttt{input heap} that cannot be further re-allocated ; and a \texttt{work heap}, initially empty, that can be allocated. Then, programs have two \texttt{free} instructions: \texttt{free} to free input cells and \texttt{free}_w to free work cells\(^3\). The \texttt{new} only allocates memory on the work heap \( \mu_w \). Now, we extend RPN in order to take into account both new free instructions by assigning the following weights to them: \[ \omega(\text{free}, r) = \beta \quad \omega(\text{free}_w r) = 1 \] Theorem 5. There is a polynomial time procedure to detect if a program is linear heap computable. Proof. The proof is similar to the demonstration of Theorem 4. We need to find \( \beta \) such that the resource control graph has no cycles of strictly negative weight. Notice that this will also give us the values \( \beta \) and \( \alpha \) and a precise bound on the space usage. \( \square \) \(^3\)We cope with the difficulty to detect which free instruction releases memory from the input or work heap. A way is to restrict the use of input register like in [15]. But this value might well be unrelated to the size of the heap (that is the number of allocated cells) just because the allocated cells might be non-contiguous. Indeed, pointers (that is registers containing addresses in the heap) has access to these maps and in addition to allocating some real compute NSI-programs in logarithmic space as soon as the values might have a value as big as the address of any allocated heap-cell. 6.3 Lack of Resources Since it is not possible to free more memory that what is allocated, no execution can free an unbounded number of cells. So, any potentially infinite execution whose corresponding run in the RPN (resp. path in the RCG) removes infinitely many tokens from Heap (resp. has weight $+\infty$) will stop once the heap is empty and does not correspond to a real infinite execution. Similarly, on any real computer, the available memory is finite and bounded. So, any potentially infinite execution whose corresponding run in the RPN (resp. path in the RCG) removes infinitely many tokens from Free (resp. has weight $-\infty$) will stop once all the memory has been allocated and does not correspond to any real infinite execution. This leads to a simple criterion to detect termination by lack of resources. **Proposition 4.** Let $p$ be a program and $G$ be its RCG. If all the infinite paths of $G$ have infinite weight ($\leq \infty$), then all executions of the program terminate by lack of resources. This approach is somewhat similar to the Size Change Principle (SCP) [17] in the sense that we check if a given finite resource (in our case memory) is exhausted during computation. However, SCP is much more efficient that our simple criterion since it takes into account the values of the variables and not only the global amount of memory. Typically, this lack of resources criterion is unable to detect termination of the reverse program while SCP detects it by checking the length of the list. 7. CONCLUSION The main result that we have presented is a (incomplete) criterion to determine if a low-level program runs within a fixed amount of heap memory, and to calculate an upper bound on this heap size. Moreover, this criterion is polynomial time computable. One of the main advantages of our approach compared with the other ones that we have cited in the text, is that we are dealing with a low-level programming language without type annotations. Aspinall and Compagnoni [5] derived a similar characterisation for assembly language but still by using the type discipline originally introduced by Hofmann [14]. We believe that the representation in term of Resources Petri Nets shed some light on Hofmann’s diamond-concept. In particular, we do not need any more the linearity conditions introduced in these works. Moreover, we do not forbid dynamic heap allocation. More generally, our method shows that it is quite easy to control the size of any buffer. In the same way that we control the size of the heap via the `new` and `free` instructions, we could similarly control depth of a data stack (via `push` and `pop`), of a control stack (via `call` and `return`), or the value of a counter (via increment and decrement). We may also deal with several kinds of tokens, which represent different amount of memory. A challenging direction is to compare our (more) theoretical method with the exciting approaches of [27, 9]. Another interesting direction would be to incorporate our methods into the Hoare or Dynamic logic paradigm. For this, we could follow the recent works of Leivant [18, 19]. Finally, we think that our method can be extended in order to control the size of each variable of a program independently. We aim at having a criterion for termination similar to the Size Change Principle. We have started to do so on simple basis in [24, 21] and a bit more elaborated in [22]. We intend to go further in this direction. 8. REFERENCES
{"Source-Url": "https://hal.science/hal-00067838/file/main.pdf", "len_cl100k_base": 13886, "olmocr-version": "0.1.53", "pdf-total-pages": 12, "total-fallback-pages": 0, "total-input-tokens": 47862, "total-output-tokens": 16351, "length": "2e13", "weborganizer": {"__label__adult": 0.00035881996154785156, "__label__art_design": 0.0003414154052734375, "__label__crime_law": 0.0003838539123535156, "__label__education_jobs": 0.0007200241088867188, "__label__entertainment": 6.181001663208008e-05, "__label__fashion_beauty": 0.0001659393310546875, "__label__finance_business": 0.0002467632293701172, "__label__food_dining": 0.00039505958557128906, "__label__games": 0.0007157325744628906, "__label__hardware": 0.0014219284057617188, "__label__health": 0.0006427764892578125, "__label__history": 0.00028204917907714844, "__label__home_hobbies": 0.0001512765884399414, "__label__industrial": 0.0005249977111816406, "__label__literature": 0.0003044605255126953, "__label__politics": 0.00029087066650390625, "__label__religion": 0.0006089210510253906, "__label__science_tech": 0.044189453125, "__label__social_life": 8.207559585571289e-05, "__label__software": 0.0054779052734375, "__label__software_dev": 0.94140625, "__label__sports_fitness": 0.0003075599670410156, "__label__transportation": 0.0007009506225585938, "__label__travel": 0.0002015829086303711}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 55903, 0.02156]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 55903, 0.58693]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 55903, 0.85663]], "google_gemma-3-12b-it_contains_pii": [[0, 826, false], [826, 6546, null], [6546, 13881, null], [13881, 20787, null], [20787, 27139, null], [27139, 30775, null], [30775, 33152, null], [33152, 35820, null], [35820, 42073, null], [42073, 48096, null], [48096, 53638, null], [53638, 55903, null]], "google_gemma-3-12b-it_is_public_document": [[0, 826, true], [826, 6546, null], [6546, 13881, null], [13881, 20787, null], [20787, 27139, null], [27139, 30775, null], [30775, 33152, null], [33152, 35820, null], [35820, 42073, null], [42073, 48096, null], [48096, 53638, null], [53638, 55903, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 55903, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 55903, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 55903, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 55903, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 55903, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 55903, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 55903, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 55903, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 55903, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 55903, null]], "pdf_page_numbers": [[0, 826, 1], [826, 6546, 2], [6546, 13881, 3], [13881, 20787, 4], [20787, 27139, 5], [27139, 30775, 6], [30775, 33152, 7], [33152, 35820, 8], [35820, 42073, 9], [42073, 48096, 10], [48096, 53638, 11], [53638, 55903, 12]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 55903, 0.0]]}
olmocr_science_pdfs
2024-12-07
2024-12-07
71fd782ea3add39404c6a84cd046431a7ed1673a
MEMORANDUM NR. 178 EXCHANGING ROBUSTNESS OF A PROGRAM FOR A RELAXATION OF ITS SPECIFICATION C. BRON M.M. FOKKINGA SEPTEMBER 1977 Department of Applied Mathematics, Twente University of Technology, P.O. Box 217, Enschede, The Netherlands. Contents 0. Introduction 1 1. Correctness and Robustness of Programs 3 2. Exchanging Robustness for Relaxation of the Program Specification 8 3. A Realization: Restricting Abortions 11 4. Abstract Semantics of Restriction of Abortions 13 5. Using rab's as a normal control structure 16 6. Formal Verification of Robustness of Rab-free Programs 19 7. Passing Restrictions of Abortions as Parameter 20 8. Conclusion 21 References 23 Abstract This paper motivates a programming concept which realizes the exchange of some robustness of a correct program part for a relaxation of its specification. The technical tool proposed restricts program abortions to a specified part of the program only, so that the execution of that part can - from the outside - not be distinguished from normal termination. The abstract (= axiomatic) semantics closely reflect the intuitive appeal of the construct. The tool is powerful in the sense that it provides a means to restrict abortions to program parts which may be unknown at the site where the abortion has been "programmed". 0 Introduction There is a general understanding that in program composition the programmer's restriction to control structures which have simple semantic properties is of beneficial value to his product, the program. Thus one considers the goto harmful, Dijkstra (68). Yet there is clearly a need for abnormal flow of control, whenever in the course of a computation conditions arise due to the failure of the input to meet the assumptions on which the program is based. In this paper we express our views on the intrinsic needs for some form of abnormal flow of control and, carefully avoiding to introduce just another control structure, we propose a programming concept with strikingly simple Hoare(69)-like axiomatic semantics. In addition to what has been said in the abstract, one of the attractive features is the fact that programs written on rather strong input assumptions may be adapted to a relaxation of these assumptions by slight additions to to program-text which do not have any impact on the original textual structure. Our proposal constitutes a refinement of the most restrictive form of abnormal flow of control: program abortion as implicitly provided by the guarded commands of Dijkstra (75). It is far more powerful than restricted forms of goto, e.g. Wirth (71), in the sense that the user can react to system detected error occurrences. It is not primarily intended as a proposal for untimely termination of repetitive constructs, like Zahn (74), Knuth (75) and Adams (77), although it may be (mis-)used for that purpose. The paper is organized as follows. In the section 1 we recall the notion of correctness and briefly treat the important notion of robustness and the programming methodology leading to robust programs. Section 2 describes the abstract needs of the programming concept; section 3 gives the operational realization and section 4 the abstract semantics. Section 5 and 6 mainly address to the audience interested in formal verification methods and may be skipped; we do not introduce any formalism so that interested non-experts may appreciate the main ideas as well. For completeness sake some remarks about parametrization are made in section 7. Section 8 reviews the proposal and briefly compares it with other proposals found in the literature. Throughout the paper we will give examples that refer back to the program of example 1. (Note 0. The defining occurrence of a new notion is written in the type font <defining occurrence>. Sometimes the definition is only implicit in the context. End of note 0). Correctness and Robustness of Programs Recall the concept of total correctness: A program part is <correct>, sometimes called totally correct, w.r.t. <precondition> R and <post-condition> S, if its execution in a state satisfying R leads to termination in a state satisfying S. Correctness should not be confused with partial correctness: A program part is <partially correct> w.r.t. R and S if its execution in a state satisfying R either does not lead to termination or does lead to termination in a state satisfying S. * We assume the reader familiar with a methodology for the construction of correct programs, preferably using the alternative and repetitive constructs of Dijkstra (75, 76): if..fi and do..do. An excellent treatment can be found in Dijkstra (76). In this paper it is the alternative construct which plays a fundamental role, the reason being its potential cause of abortion. For completeness sake, we recall the semantics. Consider if Bi \rightarrow stmti []..[] Bn \rightarrow stmtn fi. IF (a) stmti is correct w.r.t. R \land B_i and S, for all i:I..n (b) R \land Bi \lor..\lor Bn THEN the whole construct is correct w.r.t. R and S. Operationally: upon execution of the alternative construct it is required that at least one of the guards B_i is true, otherwise program execution will be aborted; one of the statements stmti whose guard B_i is true, is nondeterministically selected and executed. (Example 1. Cluster Counting Program CCP. The program given below will be frequently referred to in the sequel. We first define some notions; they apply to strings of parentheses (opening par'('and closing par')') only. In extended BNF, where * *) A partially correct program may have false as its postcondition; this implies that the program will not terminate. denotes repetition of zero or more times, we define \[ <\text{cluster}> ::= (\langle \text{cluster} \rangle^*) \] \[ <\text{extensible}> ::= <\text{cluster}>^* | <\text{cluster}>^* <\text{extensible}> \] So a nonempty (sub)string \( S \) is a cluster iff for each initial proper substring of \( S \) the number of opening par's is greater than the number of closing par's, whereas these numbers are equal for the whole string \( S \). Further, a possibly empty string is extensible iff addition of zero or more closing pars to the right yields a sequence of clusters. By \( \langle \text{the clusters in an extensible string} \rangle \) we mean, as the definition of extensibility suggests, those clusters in the string before the first non-matched opening par which are not contained in another cluster. Now let \( A : \text{array}[1..100] \) of \texttt{character} be a non-assignable array of characters and \( m : \text{integer} \) a non-assignable integer and suppose a program is required which on precondition \( \{ 0 \leq m \leq 100 \land A[1..m] \) contains parentheses only and is extensible \} has to establish postcondition \( \{ \text{number of clusters in } A[1..m] \text{ has been printed} \} \). (What is initially true about \( A \) and \( m \) remains so, because they are constants. Throughout the paper we mention such invariantly true assertions only explicitly in the precondition.) The following program fulfils the specification: \[ \text{prelude var } i, \text{ open, close, alus:integer} \] \[ \begin{align*} \text{begin } & i, \text{ open, close, alus:=0,0,0;} \\ \text{do } & if m + i := i + 1; \\ \text{ if } & A[i] = '(', \text{ open:=open+1} \\ \text{ or } & A[i] = ')', \text{ close:=close+1;} \\ \text{ if } & \text{open=close } \rightarrow \text{alus := alus+1} \\ \text{ or } & \text{open>close } \rightarrow \text{skip} \\ \text{fi} \end{align*} \] \[ \text{fi} \] \[ \text{print(alus)} \] \[ \text{end.} \] The correctness may be verified using invariant relation \( \{ 0 \leq i \leq m \land A[1..i] \) contains \( \text{alus} \) clusters and needs \( \text{open-close} \) closing parentheses for extension} and variant function \( (m-i) \). \text{End of example 1).} Less known than the notion of correctness is the notion of robustness, introduced by Dijkstra (76) only informally: A program part is \(<\text{robust in}>\) a \(<\text{robustness condition}>\) \(R\) if its execution in a state satisfying \(R\) leads to abortion. Note that robustness in \(R\) implies robustness in \(R'\) if \(R' \implies R\), and robustness in both \(R\) and \(R'\) implies robustness in \(R \lor R'\). Further, robustness of a procedure carries over to each call. When - due to "external accidents", - a program is executed in a state not satisfying the precondition, abortion is to be preferred, as a kind of alarm, over termination in a state not satisfying the expected postcondition. Note that in general one can hardly require the precondition to be checked before execution of the program, because more often than not this would require a sort of pre-execution of at least some part of the program. Thus preferably a program is robust in that part\(^*)\) of the negation of its precondition which leads to "wrong" termination. Example 2. CCP is robust in \(\{0 \leq m \leq 100 \land A[1..m]\} \) either contains not only parentheses or is not extensible. So "erroneous" input, provided \(0 \leq m \leq 100\), does not give erroneous output: abortion will take place in stead. Example 3. Assuming that the array selection \(A[i]\) is robust in \(\{\text{not}(1 \leq i \leq 100)\}\), CCP is also robust in \(\{\text{not}(0 \leq m \leq 100)\}\). End of examples 2 and 3. The implication on conditions, or equivalently inclusion on sets, induces a partial order on robustness: the weaker (i.e. less restrictive) the robustness condition, the more robust the program is, as more initial states lead to abortion. Robust programs are obtained by choosing the guards of an alternative construct as strong as possible. Indeed, one may weaken the robustness condition \((B\text{\&} \lor \ldots \lor Bm)\) of an alternative construct \(\text{if } B1 + \text{stmt1} \ldots \text{stmti } \text{fi}\) by strengthening the guards \(Bi\) whereas - assuming the validity of the precondition - they yet remain equivalent. Fortunately this way of program construction is quite harmonious with the overall goal of structured programming in the sense that as much as possible is clear by local inspection of the text: a \(\text{*) This part is the negation of the precondition iff the precondition happens to be the weakest one w.r.t. the given postcondition.}\) stronger guard B shows more than a weaker one B', which happens to be equivalent to B only on account of the context. (Example 4. Replacing $A[t] = '{'}$ by $A[t]'\star'\star'$) diminishes both the robustness and the clarity of CCP without disturbing the correctness and correctness proof. End of example 4). Thus alternative constructs may check the validity of essential parts of the precondition and cause abortion if invalidity is detected. For future use we allow alternative constructs to be optionally suffixed with an identifier, the <robustness identification>, to denote the associated robustness condition*). Such use of a robustness identification is termed a <rob-identification>. Distinct constructs need not be distinctly rob-identified if both check the same condition. Constructs not explicitly rob-identified are assumed to be rob-identified "by default" by the standard robustness identification abort, short for "a bit of robustness transmitted." (Example 5. In CCP both fi's could be identified by incorrect-input; more refined identifications might read non-par for the outer fi and non-ext for the inner one. This latter program will be referred to as CCP'. End of example 5). The introduction of rob-identifications suggest a refined notion of robustness. We redefine A program part is <robust in> (id, R) if its execution in a state satisfying the <robustness condition> R leads to abortion due to the execution of an alternative construct rob-identified by the robustness identification id. So, for not rob-identified program parts, robustness in R is robustness in (abort, R). (Example 6. CCP' is robust in (nonpar, $\{0 \leq m \leq 100 \land A[1..m]\}$ does not contain parentheses only but its initial part up to the first non-parenthesis is extensible}). CCP' is also robust in (nonext, $\{0 \leq m \leq 100 \land an \ initial \ part \ of \ A[1..m], \ containing \ parentheses \ only,$ *) At this point one may imagine that the robustness identification is part of the errormessage which will be given when program abortion occurs. is nonextensible}). End of example 6). (Note 1. Due to the nondeterminism it may be impossible to assert any particular robustness for a correct program, whereas without rob-identifications it is non-trivially robust. For example, the following program is correct w.r.t. pre \( x = 0 \) and post \( x = 0 \) and - without identifications - robust in \( \text{abort, } x \neq 0 \). It is however neither robust in \( \text{wrong}x1 \) nor in \( \text{wrong}x2 \): \[ \begin{align*} & \text{if } \text{true} + \text{if } x \neq 0 \rightarrow \text{skip fi } \text{wrong}x1 \\ & \text{true } + \text{if } x \neq 0 \rightarrow \text{skip fi } \text{wrong}x2 \\ & \text{fi} \end{align*} \] Thus the formalism for robustness forces alternative constructs, which are nondeterministically treated alike, to be rob-identified alike as well. End of note 1). (Note 2. The kind of alarm provided for by the \textbf{do-od} construct is nontermination: assuming that \( A[i] \) yields an opening parenthesis for all \( i \), an initial state satisfying \( m < 0 \) leads to nontermination! Here, the methodology is to choose the guards as weak as possible: in CCP the guard reads \( i \neq m \), which is weaker than \( i < m \). Indeed, \( i < m \) would not lead to nontermination. Hehner (76) shows that the use of "recursive refinement" in stead of repetition delivers - o.a. - robustness in stead of non-termination. End of note 2). This completes our treatment of the notion of, and methodology leading to robust programs. 2 Exchanging Robustness for Relaxation of the Program Specification In this section we describe the need and motivation and some requirements for a programming concept. A realization will be proposed in the next section. Once a satisfactory and correct program has been written, it seems yet quite natural to make another step in the development of the program: one may want to exchange some robustness for a relaxation of the correctness specification. For instance, in stead of some robustness one may prefer an error message to be printed, followed by termination of the program. Thus the original program specification, say \((R,S)\), has been relaxed into \((R \lor R', S \lor S')\) where \(R'\) is a robustness condition of the original program and \(S'\) asserts that the error message has been printed. \((\text{Example 7.}\) We may wish to relax the program specification of CCP into precondition \(\{0 \leq m \leq 100\}\) and postcondition \(\{A[1..m]\text{ both contains parentheses only and is extensible and its number of clusters has been printed}\text{ or (otherwise, }"A[1..m]\text{ doesnot contain parentheses only or is not extensible" has been printed}\}\). \text{End of example 7).}\) This holds even for parts of a program: one may prefer, if a program part happens to be invoked when a robustness condition prevails, instead of robustness to be induced to the whole program, the part to be terminated under establishment of a suitable, relaxed, postcondition. One may prefer so if the context is rather independent of the postcondition established by that program part. The whole program is made more useful in the sense that more initial states lead to -suitable - termination. \((\text{Example 8.}\) The relaxation of example 7 is equally well desirable if CCP is used by a larger program which merely processes a series of array's \(A\) and integers \(m\). \((\text{Example 9.}\) If the context of CCP does not allow the condition \(\{A[1..m]\text{ does not contain parentheses only}\}\) to be part of a relaxed postcondition, we still may desire the relaxed precondition \(\{0 \leq m \leq 100 \land A[1..m]\text{ contains parentheses only}\}\) and postcondition \(\{(A[1..m]\text{ is extensible and its number of clusters has been printed}\text{ or (otherwise, both }"A[1..m]\text{ non-extensible" and the greatest }i\text{, for which }A[1..i]\text{ is extensible, have been printed})\}\}. \text{End of examples 8 and 9).} Note that one must be free to choose the program part so large as to have a weak enough postcondition to allow for a relaxation without disturbing the correctness proof in which it has to fit. (Example 10. Addition of "A[i] ≠ ('or') + skip" to the outer alternative construct in CCP does exchange robustness of that very construct for a relaxation of its correctness specification, but the relaxed postcondition does not fit in the context. (The addition modifies rather than relaxes the program (specification)). End of example 10). We consider it essential that "system generated" robustness be treated on equal footing with "programmed" one. On the one hand, each system generated action during the execution of a program can be considered as a procedure ultimately invoked from within the program. Fortunately, robustness of the body of a procedure carries over to each call. So the exchange of robustness of a program part indeed affects as well the robustness induced by the system. Typical robustness identifications we think of are: overflow, index-out-of-bounds, attempt-to-read-beyond-end-of-file, singularity (in a library procedure for matrix inversion). On the other hand, the system part invoking the user program may be considered to exchange all robustness for an extreme relaxation of the program specification: the relaxed precondition is true and the relaxed postcondition merely asserts that the output and/or an appropriate error message (including a dump of the stack) have been sent to the printing device. Indeed, for the remainder of the system program - which takes care of finalizations like closing files and deallocating resources and so on - it is irrelevant what condition has been established by the user program. There seems, moreover, no distinction reasonable for the system in the way it should exchange the robustness in the various identifications invented by the programmer. Hence, user identified robustness may become evident to the system as robustness in, say, the single standard identification abort. (Example 11. For CCP as incremented in example 9 it may be left to the calling environment how and of what program part - if any and of which system part otherwise - to exchange the robustness in non-par (resp. abort) and index-out-of-bounds. End of example 11). Preferably, of course, the incremental step (of exchanging robustness for a relaxation) should in no way influence the original structure of the program, so that it brings about additions to rather than alterations of the original program text, the original documentation and original correctness proof. 3 A Realization: Restricting Abortions We give a realization of the programming concept described in section 2. Consider a program part whose robustness, in \((\text{id}, \text{R}')\) say, has to be exchanged for the relaxation of the correctness specification \((\text{R,S})\) into \((\text{R} \lor \text{R}', \text{S} \lor \text{S}')\) for a suitable \(\text{S}'\). Obviously: 1. the exchange of robustness must be realized by restricting the abortions, caused from within the execution of the program part and "rob-identified" by \text{id}, to just that very program part, so that - as seen from the outside - it is just terminated, and 2. the establishment of \(\text{S}'\) must be realized by the execution of some \(<\text{terminating statements}>\), term say. Syntactically we propose: 3. without loss of generality the program part to be a block and 4. to indicate the \(<\text{restriction of abortions}>\) by the following \(\text{addition}\) to the prelude of the block: \[ \text{rab id by term bar} \] to be termed a \(<\text{rab-definition}>\). Further we define: 5. in order to make valuable errormessages and terminating actions possible (cfr. the \text{i} to be printed in example 9 and the dump of the stack in section 3) the evaluation of \text{term} to take place in the environment (= collection of declared objects) valid for the statement part of the block and 6. the abortions caused from within the execution of \text{term} (and not restricted by the interior of \text{term} itself) to be restricted - if at all - by the restrictions of abortions valid when the block is to be executed. (This decision eliminates recursion but has been motivated by the wish to keep the abstract semantics simple, see section 4 and note 4 in section 5). We complete the realization proposal by: 7. requiring the \text{robustness identifications} to be declared, say in the format: \text{rid id}, so that the scope of this \(<\text{rid-declaration}>\) contains all the \text{rab-definitions} and \text{rob-identifications} of \text{id}, and 8. letting the declaration also mean the implicit definition \text{rab id by if false \& skip fi bar}, thus causing abortions \text{rob-identified by} the standard default identification *abort* for any abortion identified by id which will not be restricted by the programmer. *(Example 12. Examples 11 and 9 may be realized by an addition to the prelude of CCP', so that it reads:* ```plaintext prelude var i, open, close, clus: integer; rid non-ext; rab non-ext by print ("A[1..m] non-extensible", i-1) bar. ``` *If* `rid non-par` *had been added to the prelude too, and no* `rab`-definition, then the context could not restrict those additions: they would cause program abortion (identified by *abort*). *End of example 12.*** Note that abortions caused from within a procedure body (or standard operation) will be restricted by the `rab`-definitions surrounding the site of call rather than the site of declaration. A Abstract Semantics of Restriction of Abortions More important than (or as important as) the precise operational definition are the schemes of reasoning involved in the incremental step of the program development. They need to specify the correctness and robustness of an incremented block in terms of the correctness and robustness of the original block and the terminating statements. Evidently, however the robustness assertions as defined so far are insufficient, due to the inability to express in what state the abortion will be caused and consequently in what state the terminating statements will be executed. So we refine once more the notion of robustness: A program part is <robust in> (id, R, A) if its execution in an initial state satisfying the robustness condition R leads to abortion due to the execution of an alternative construct, rob-identified by id, in a state satisfying the <abortion condition> A. The condition A should be interpreted in the environment valid for the statement part of the block, if the program part happens to be a block. (Or equivalently, by convention the robustness for the statement part of a block is said to hold for the block). Note that abortion condition true always suffices; in general robustness in (id, R, A) implies robustness in (id, R', A') if R' \rightarrow R and A \rightarrow A'. (Example 13. An abortion condition for the robustness in non-ext as asserted in example 6, is \{A[1..i-1] is extensible but A[1..i]is not\}. End of example 13). For the well-known programming concepts there exist intuitively appealing formal methods to verify robustness assertions, similar in nature to formal methods for the verification of correctness. In section 6 we will describe such methods. For the time being we assume that satisfactory methods exist. Now we turn to the semantics of restricting abortions. Consider a block to be incremented by the addition of rab id by term bar to its prelude. The rule for correctness has already been suggested in the motivation of the concept: 1. IF (a) the block has been proved correct w.r.t. R1 and S1 and (b) the block is robust in (id, R2, A) and (c) term is correct w.r.t. A and S2, THEN the incremented block is correct w.r.t. R1 \vee R2 and S1 \vee S2. Second, for the robustness identification id we have 2. IF (a) the block is robust in (id, R, A') and (b) term is robust in (id, A', A), THEN the incremented block is robust in (id, R, A). Third, for any identification id' distinct from id, 3. IF (a) block is robust in (id', R1, B) and (b) block is robust in (id, R2, A) and (c) term is robust in (id', A, B), THEN the incremented block is robust in (id', R1 \vee R2, B). (Example 14. Using the robustness assertion as completed in example 13, it is almost trivial to prove that the incremental step of example 12 indeed yields a program satisfying the relaxed specification of example 11. The robustness assertions for non-par and index-out-of-bounds will not be affected by the incrementation. End of example 14). Now we motivate clause (6) of the operational definition. Consider a block, to be incremented by the addition of \textit{rab} id by term \textit{bar} to its prelude. Two alternatives to (6), which for appropriate reasons might be judged simpler, suggest themselves: the abortions caused from within term are restricted - if at all - either (6') by the \textit{rab}'s valid when the statement part of the block is to be executed (so that, by extending the notion of <environment> to contain as well the valid \textit{rab}'s, clause (5) alone would suffice), or (6'') by the \textit{rab}'s valid when the abortion, identified by id, is caused from within the statement part (so that both for procedures and for \textit{rab}'s, the \textit{rab}-definitions surrounding the site of invocation restrict the abortions caused from within the bodies and terminating statements). Rather unconsciously clause (6'') has been chosen in our first design, Bron et al (76). The abstract semantics however are far more complicated and close inspection revealed a serious flaw, treated in fuller extent in Pokkinga (77) and essentially due to the possibility that restricting abortions to some block B would possibly restrict the abortions to an inner block of B; this is clearly not what we intuitively wanted! In contrast to (6), clause (6') prescribes the rab's to be evaluated (mutually) recursively. This does not only give rise to additional constraint about a variant function in order to guarantee boundedness of recursion - just as in the case of (mutual) recursive procedures - but also to a relaxation, in the first and third rule, of the abortion condition A of the block into A ∨ A', with the additional premise that term is robust in (id, A', A ∨ A'); the second rule however would be simplified: the incremented block would be no longer robust in id. We consider these modifications too inattractive, but the decision might be left open to discussion. 5 Using \texttt{rab}'s as a normal control structure In stead of writing robust programs which in an incremental step are extended by the addition of \texttt{rab}-definitions, one might wish to employ the restrictions of abortions while constructing the program. (An explicit abort-statement is available: \texttt{if fi} always aborts program execution because there does not exist a true guard). We give the abstract semantics for this approach. First of all, it should be noted that the specification for which an inner program part has to be designed, is already the relaxed one and that the programmer is allowed to program abortions, assuming that these will be restricted by the context (at the site of execution). So apparently program parts are intended to be liberally correct rather than correct: A program part is \texttt{<liberally correct>} w.r.t. R and S if its execution in a state satisfying R either leads to abortion or leads to termination in a state satisfying S. The notion of liberal correctness should not be confused with either correctness or partial correctness. (Example 15. Because CCP is robust in the negation of its original precondition, it is liberally correct w.r.t. \texttt{true} and the original postcondition. \textit{End of example 15}). Rather than to give a specific formalism for proving liberal correctness, we give the way any existing formalism for proving correctness should be modified for the present purpose. The modification for the \texttt{formalism} is described below: the \texttt{interpretation} of formulae has to be modified so that what originally did express correctness, does express liberal correctness now. First, we adapt the \textit{language} of the proof system. On the one hand, just like the assumed existence of formulae expressing \texttt{<proc/fun-specifications>}, one should introduce formulae expressing \texttt{<rab-specifications>}: these formulae merely give an \texttt{<abortion condition>} on which it is allowed to invoke an abortion for the robustness identification under consideration. On the other hand, we need to extend the \texttt{proc/fun}-specifications so that they also may express some <assumed rab-specifications>: in this way abortions invoked from within a proc/fun-body will be modelled as implicit parameters, see below. Second, we adapt the rules of the proof system. Obviously, we need one new rule: **Rab-definition** (a) A rab-specification (is an abstraction from the definition and) is verified by showing that the terminating statements, with the abortion condition of the specification as precondition, establish the block's postcondition. Within this verification the rab-specifications allowed to be used are those (assumed to be) valid for the block. (b) A verified rab-specification is valid in the normal, textual, scope of the definition (; redefinitions for the same identification cause a hole in the scope). Three rules of the original proof system need be modified: **Proc/fun-declaration.** A specification is verified (in the normal way) discharging however all rab-specifications valid at the site of declaration and assuming to be valid instead, the assumed rab-specifications as indicated in the proc/fun-specification. **Proc/fun-call.** In addition (to what the original formalism says) it is required to verify the assumed rab-specifications from the rab-specifications currently (assumed to be) valid. This verification requires to show that the abortion condition of the latter rab-specification implies the abortion condition of the former rab-specification. **Alternative construct.** In contrast (to what the original formalism says) it is now not required that at least one of the guards is true, but it is required that the falsity of all guards implies the truth of the abortion condition of the rab-specification currently (assumed to be) valid. All other rules remain unchanged. (Note 3. The above modification is equally well applicable to any formalism for proving partial correctness. The reader may consult Fokkinga (77) for a detailed presentation. End of note 3). Although parts of the program have to be proved liberally correct, the whole program is proved correct if all rab-specifications are assumed to have false as abortion condition. If however those abortion conditions are assumed to be true - as actually validated by the system - , then the whole program is proved liberally correct only. (Note 4. Because in the approach of liberal correctness the correctness and robustness assertions are merged into one assertion, the complications described in the motivation of clause (6) of the operational definitions disappear when alternative (6') is chosen and consequently rab's are evaluated recursively. End of note 4). 6 Formal Verification of Robustness of Rab-free Programs Because we are not interested in formalisms as such but only in the existence of intuitively appealing methods, we will employ the formalism for proving liberal correctness for convenience. We describe first how separate correctness and robustness specifications for a procedure should be translated into a single liberal correctness specification and secondly how robustness of a program part—free of procedure declarations—should be verified in the formalism for liberal correctness. Thus one should verify robustness of procedures separately. Consider a procedure (body), if it is correct w.r.t. R and S and robust in (id, R', A), then it is liberal correct w.r.t. R ∨ R' and S, assuming a rab-specification for id, which has A as abortion condition. Now consider a program part to have been proved robust in (id, R, A). If the program part is proved to be liberally correct w.r.t. R and false, assuming a rab-specification for id which has A as abortion condition and assuming further only rab specifications with false as abortion condition, then the robustness has been verified. Indeed, postcondition false expresses that the program part can impossibly terminate and the only abortions allowed are those identified by id and taking place in a state satisfying condition A. (Example 16. The robustness as completed in example 13 may be verified using the invariant relation {0 ≤ i ≤ m ∧ A[1..i]} is extensible and needs (open-close) closing parentheses for extension]. Indeed, the falsity of both open = close and open > close implies the abortion condition. Further, the invariant relation together with i = m (after the od) imply false, because A[1..m] is not extensible on account of the robustness condition. End of example 16). It is beyond the scope of this paper to treat topics like the soundness of the formalism described in section 5 and 6, the completeness and the conditions under which they are equivalent and so on. 7 Passing Restrictions of Abortions as Parameters Once restricting abortions is used as a normal control structure, we may consider parametrization of procedures by robustness identifications. First of all it is necessary - in order to control the construction of (liberally) correct programs and not to invalidate the previously given abstract semantics! - that within procedures distinct (formal and global) identifiers denote distinct (actual) robustness identifications. (The same applies to variables as well!!). Such distinctness may be obtained either by undesirable syntax constraints or by considering the formal parameter specification of an robustness identification \( f \) as the declaration \( \text{rid } f \) (thus creating a new identity) for which the "default" \( \text{rab-defination is rab } f \) by \( \text{fi if fi a bar} \), where a stands for the actual robustness identification. Second we may choose to define the use in \( \text{rob-identifications to be the only option for such parameters, or we may as well allow the option to give rab-definitions for such parameters. The latter case corresponds to the PASCAL and Algol 60 value parameter transfer, the former case to the original PASCAL constant parameter transfer.} The value-like parameter transfer can very easily be realized by the constant-like parameter transfer; the converse does not hold - in languages such as Algol 60 and PASCAL. As an example, the standard robustness identification \( \text{abort} \) may be considered to be passed to the user program with the only option to use it in \( \text{rob-identifications}. \) 8 Conclusion Based upon abstract, intrinsic needs we have described a programming concept. It is applicable to correct programs, exchanges robustness for a relaxation of the program specification and treats all robustness on the same footing, disregarding the origin (which may lay in the system, a library procedure or the program itself). The operational tool proposed has the attractive feature that it merely brings about additions to the program text without any alteration, so that the original program documentation and correctness proof are not affected but only need be extended. All restricted forms of the goto, as mentioned in the introduction, are unable to deal with system generated errors and even the too unrestricted label variables of Algol 68 and PL/I are unpractical to do so. The Jumpout facility of Pop-2, Burstall (71), and the J-operator of Landin (66) require the presence of procedure variables and have a rather strange (standard) function for what we have made into a syntactic construct. Much of the work done on exception handling does not (only) deal with "fatal errors" - after which the current computation can not be continued - but deal (in the first place) with "relatively infrequent events" so that continuation is possible, be it after some "exception handling". In our opinion other control structures, such as procedure parameters or may be new ones, should solve the (abnormal?) flow of control related to "exceptional events"; they should not be mixed up with the handling of "fatal errors". E.g. Levin (77) proposes to return control after execution of the exception handler to the place of invocation; Goodenough (75)'s proposal and the PL/I-ON construct have in addition the option to abort the current computation. Our proposal might be viewed as a deliberate simplification of the latter two constructs. Most closely related are the exit-facility of Jones (75) - it may be considered as a single standard robustness identification - and the signal-enable facility of BLISS 11, Dec (74), - corresponding to rob-identifications and rob-definitions respectively -. But these and all of the above require to take care of the exceptional cases while constructing the program, thus lacking a separation of concern as made possible by the proposed exchange of robustness. So we hope to have made a proposal in which a remaining trouble spot in the area of control structures has fully been brought on the level of a calculus for the derivation of correct programs. REFERENCES Adams, J.M. (1977); A General Verifiable Iterative Control Structure. IEEE SE-3 (March 77)2, 144-150.
{"Source-Url": "https://maartenfokkinga.github.io/utwente/mmf77.pdf", "len_cl100k_base": 8802, "olmocr-version": "0.1.53", "pdf-total-pages": 26, "total-fallback-pages": 0, "total-input-tokens": 27820, "total-output-tokens": 10780, "length": "2e13", "weborganizer": {"__label__adult": 0.00042057037353515625, "__label__art_design": 0.0003571510314941406, "__label__crime_law": 0.0003552436828613281, "__label__education_jobs": 0.0006566047668457031, "__label__entertainment": 6.490945816040039e-05, "__label__fashion_beauty": 0.00017261505126953125, "__label__finance_business": 0.00020766258239746096, "__label__food_dining": 0.0004193782806396485, "__label__games": 0.0005636215209960938, "__label__hardware": 0.0009388923645019532, "__label__health": 0.0006818771362304688, "__label__history": 0.00023066997528076172, "__label__home_hobbies": 0.00012350082397460938, "__label__industrial": 0.0003879070281982422, "__label__literature": 0.00044655799865722656, "__label__politics": 0.00026798248291015625, "__label__religion": 0.0005860328674316406, "__label__science_tech": 0.0175018310546875, "__label__social_life": 9.512901306152344e-05, "__label__software": 0.0034008026123046875, "__label__software_dev": 0.970703125, "__label__sports_fitness": 0.0004024505615234375, "__label__transportation": 0.0007061958312988281, "__label__travel": 0.00019729137420654297}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 40046, 0.02093]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 40046, 0.27159]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 40046, 0.89182]], "google_gemma-3-12b-it_contains_pii": [[0, 242, false], [242, 1308, null], [1308, 2703, null], [2703, 3867, null], [3867, 5668, null], [5668, 7875, null], [7875, 10351, null], [10351, 12421, null], [12421, 13943, null], [13943, 16398, null], [16398, 18710, null], [18710, 19014, null], [19014, 21222, null], [21222, 21998, null], [21998, 23956, null], [23956, 26355, null], [26355, 27010, null], [27010, 29192, null], [29192, 31464, null], [31464, 31792, null], [31792, 33793, null], [33793, 35415, null], [35415, 37733, null], [37733, 37926, null], [37926, 39641, null], [39641, 40046, null]], "google_gemma-3-12b-it_is_public_document": [[0, 242, true], [242, 1308, null], [1308, 2703, null], [2703, 3867, null], [3867, 5668, null], [5668, 7875, null], [7875, 10351, null], [10351, 12421, null], [12421, 13943, null], [13943, 16398, null], [16398, 18710, null], [18710, 19014, null], [19014, 21222, null], [21222, 21998, null], [21998, 23956, null], [23956, 26355, null], [26355, 27010, null], [27010, 29192, null], [29192, 31464, null], [31464, 31792, null], [31792, 33793, null], [33793, 35415, null], [35415, 37733, null], [37733, 37926, null], [37926, 39641, null], [39641, 40046, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 40046, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 40046, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 40046, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 40046, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 40046, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 40046, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 40046, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 40046, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 40046, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 40046, null]], "pdf_page_numbers": [[0, 242, 1], [242, 1308, 2], [1308, 2703, 3], [2703, 3867, 4], [3867, 5668, 5], [5668, 7875, 6], [7875, 10351, 7], [10351, 12421, 8], [12421, 13943, 9], [13943, 16398, 10], [16398, 18710, 11], [18710, 19014, 12], [19014, 21222, 13], [21222, 21998, 14], [21998, 23956, 15], [23956, 26355, 16], [26355, 27010, 17], [27010, 29192, 18], [29192, 31464, 19], [31464, 31792, 20], [31792, 33793, 21], [33793, 35415, 22], [35415, 37733, 23], [37733, 37926, 24], [37926, 39641, 25], [39641, 40046, 26]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 40046, 0.0]]}
olmocr_science_pdfs
2024-12-10
2024-12-10
9f5c0726db6c7231f49a039dc554654c224b69f6
Correct-by-construction Process Composition Using Classical Linear Logic Inference Citation for published version: Link: Link to publication record in Edinburgh Research Explorer Document Version: Peer reviewed version Published In: 28th International Symposium on Logic-Based Program Synthesis and Transformation General rights Copyright for the publications made accessible via the Edinburgh Research Explorer is retained by the author(s) and / or other copyright owners and it is a condition of accessing these publications that users recognise and abide by the legal requirements associated with these rights. Take down policy The University of Edinburgh has made every reasonable effort to ensure that Edinburgh Research Explorer content complies with UK legislation. If you believe that the public display of this file breaches copyright please contact openaccess@ed.ac.uk providing details, and we will remove access to the work immediately and investigate your claim. Correct-by-construction Process Composition Using Classical Linear Logic Inference Petros Papapanagiotou and Jacques Fleuriot School of Informatics, University of Edinburgh 10 Crichton Street, Edinburgh EH8 9AB, United Kingdom {ppapapan, jdf}@inf.ed.ac.uk Abstract. The need for rigorous process composition is encountered in many situations pertaining to the development and analysis of complex systems. We discuss the use of Classical Linear Logic (CLL) for correct-by-construction resource-based process composition, with guaranteed deadlock freedom, systematic resource accounting, and concurrent execution. We introduce algorithms to automate the necessary inference steps for binary compositions of processes in parallel, conditionally, and in sequence. We combine decision procedures and heuristics to achieve intuitive and practically useful compositions in an applied setting. Keywords: process modelling, composition, correct by construction, workflow, linear logic 1 Introduction The ideas behind process modelling and composition are common across a variety of domains, including program synthesis, software architecture, multi-agent systems, web services, and business processes. Although the concept of a “process” takes a variety of names – such as agent, role, action, activity, and service – across these domains, in essence, it always captures the idea of an abstract, functional unit. Process composition then involves the combination and connection of these units to create systems that can perform more complex tasks. We typically call the resulting model a (process) workflow. Viewed from this standpoint, resource-based process composition then captures a structured model of the resource flow across the components, focusing on the resources that are created, consumed, or passed from one process to another within the system. Workflows have proven useful tools for the design and implementation of complex systems by providing a balance between an intuitive abstract model, typically in diagrammatic form, and a concrete implementation through process automation. Evidence can be found, for example, in the modelling of clinical care pathways where workflows can be both understandable by healthcare stakeholders and yet remain amenable to formal analysis [10][15]. A scalable approach towards establishing trust in the correctness of the modelled system is that of correct-by-construction engineering [12][26]. In general, this refers to the construction of systems in a way that guarantees correctness properties about them at design time. In this spirit, we have developed the WorkflowFM system for correct-by-construction process composition [21]. It relies on Classical Linear Logic (see Section 2.1) to rigorously compose abstract process specifications in a way that: 1. systematically accounts for resources and exceptions; 2. prevents deadlocks; 3. results in a concrete workflow where processes are executed concurrently. The inference is performed within the proof assistant HOL Light, which offers systematic guarantees of correctness for every inference step [11]. The logical model can be translated through a process calculus to a concrete workflow implementation in a host programming language. There are numerous aspects to and components in the WorkflowFM system, including, for instance, the diagrammatic interface (as shown in Fig. 1), the code translator, the execution engine, the process calculus correspondence, and the architecture that brings it all together [21]. In this particular paper we focus on the proof procedures that make such resource-based process compositions feasible and accessible. These are essential for creating meaningful workflow models with the correctness-by-construction properties highlighted above, but without the need for tedious manual CLL reasoning. Instead, the user can use high level composition actions triggered by simple, intuitive mouse gestures and without the need to understand the underlying proof, which is guaranteed to be correct thanks to the rigorous environment of HOL Light. It is worth emphasizing that our work largely aims at tackling pragmatic challenges in real applications as opposed to merely establishing theoretical facts. We rely on existing formalisms, such as the proofs-as-processes theory described below, in our attempt to exploit its benefits in real world scenarios. As a result, the vast majority of our design decisions are driven by practical experience and the different cases we have encountered in our projects. Table 1 is a list of some of our case studies in the healthcare and manufacturing domain that have driven the development of WorkflowFM. It includes an indication of the size of each case study based on (1) the number of (atomic) component processes, (2) the number of different types of resources involved in the inputs and outputs of the various processes (see Section 3), (3) the number of binary composition actions performed to construct the workflows (see Section 4), and (4) the total number of composed workflows. 2 Background The systematic accounting of resources in our approach can be demonstrated through a hypothetical example from the healthcare domain [21]. Assume a process DeliverDrug that corresponds to the delivery of a drug to a patient by a nurse. Such a process requires information about the Patient, the Dosage of the drug, and some reserved NurseTime for the nurse to deliver the drug. The possible outcomes are that either the patient is Treated or that the drug Failed. In the latter case, we would like to apply the Reassess process, which, given some allocated clinician time (ClinTime) results in the patient being Reassessed. A graphical representation of these 2 processes, where dashed edges denote the optional outcomes of DeliverDrug, is shown at the top of Fig. 1. If we were to compose the 2 processes in a workflow where the drug failure is always handled by Reassess, what would be the specification (or specifically the output) of the composite process? ![Fig. 1. The visualisation of the DeliverDrug and Reassess processes (top) and their sequential composition. The auxiliary triangle helps properly display the output.](image) Given the workflow representation in Fig. 1, one may be inclined to simply connect the Failed edge of DeliverDrug to the corresponding edge of Reassess, leading to an overall output of either Treated or Reassessed. However, this would be erroneous, as the input ClinTime, is consumed in the composite process even if Reassess is never used. Using our CLL-based approach, the workflow output is either Reassessed which occurs if the drug failed, or Treated coupled with the unused ClinTime, as shown at the bottom of Fig. 1. Systematically accounting for such unused resources is non-trivial, especially considering larger workflows with tens or hundreds of processes and many different outcomes. The CLL inference rules enforce this by default and the proof reflects the level of reasoning required to achieve this. In addition, the process code generated from this synthesis is fully asynchronous and deadlock-free, and relies on the existence of concrete implementations of DeliverDrug and Reassess. 2.1 Classical Linear Logic Linear Logic, as proposed by Girard [9], is a refinement to classical logic where the rules of contraction and weakening are limited to the modalities ! and ?. Propositions thus resemble resources that cannot be ignored or copied arbitrarily. In this work, we use a one-sided sequent calculus version of the multiplicative additive fragment of propositional CLL without units (MALL). Although there exist process translations of full CLL and even first-order CLL, the MALL fragment allows enough expressiveness while keeping the reasoning complexity at a manageable level (MALL is PSPACE-complete whereas full CLL is undecidable [13]). The inference rules for MALL are presented in Fig. 2. \[ \begin{align*} \vdash A, A & \quad \text{Id} \\ \vdash \Gamma, A & \quad \vdash \Delta, B \\ \vdash \Gamma, \Delta, A \otimes B & \quad \otimes \\ \vdash \Gamma, A & \quad \vdash \Gamma, A \oplus B & \quad \oplus_L \\ \vdash \Gamma, A & \quad \vdash \Gamma, B & \quad \oplus_R \\ \vdash \Gamma, \Delta, C & \quad \vdash \Delta, C \perp & \quad \text{Cut} \end{align*} \] Fig. 2. One-sided sequent calculus versions of the CLL inference rules. In this version of MALL, linear negation (\(\perp\)) is defined as a syntactic operator with no inference rules, so that both \(A\) and \(A \perp\) are considered atomic formulas. The de Morgan style equations in Fig. 3 provide a syntactic equivalence of formulas involving negation [27]. This allows us to use syntactically equivalent formulas, such as \(A \perp \equiv B \perp\) and \((A \otimes B) \perp\) interchangeably. In fact, in the proofs presented in this paper we choose to present formulas containing \(\otimes\) and \(\oplus\) over their counterparts \(\otimes\) and \& due to the polarity restrictions we introduce in Section 3. \[ \begin{align*} (A \perp) \equiv & A \\ (A \otimes B) \perp & \equiv A \perp \otimes B \perp \\ (A \otimes B) \perp & \equiv A \perp \otimes B \perp \end{align*} \] Fig. 3. The equations used to define linear negation for MALL. In the 90s, Abramsky, Bellin and Scott developed the so-called proofs-as-processes paradigm [24]. It involved a correspondence between CLL inference and concurrent processes in the \(\pi\)-calculus [18]. They proved that cut-elimination in a CLL proof corresponds to reductions in the \(\pi\)-calculus translation, which in turn correspond to communication between concurrent processes. As a result, \(\pi\)-calculus terms constructed via CLL proofs are inherently free of deadlocks. The implications of the proofs-as-processes correspondence have been the subject of recent research in concurrent programming by Wadler [28], Pfenning et al. [31, 29], Dardha [7, 8] and others. Essentially, each CLL inference step can be translated to an executable workflow, with automatically generated code to appropriately connect the component processes. As a result, the CLL proofs have a direct correspondence to the “piping”, so to speak, that realises the appropriate resource flow between the available processes, such that it does not introduce deadlocks, accounts for all resources explicitly, and maximizes runtime concurrency. The current paper examines CLL inference and we take the correspondence to deadlock-free processes for granted. 2.2 Related work Diagrammatic languages such as BPMN [20] are commonly used for the description of workflows in different organisations. However, they typically lack rigour and have limited potential for formal verification [23]. Execution languages such as BPEL [19] and process calculi such as Petri Nets [1] are often used for workflow management in a formal way and our CLL approach could potentially be adapted to work with these. Linear logic has been used in the context of web service composition [22], but in a way that diverges significantly from the original theory and compromises the validity of the results. Finally, the way the resource flow is managed through our CLL-based processes is reminiscent of monad-like structures such as Haskell’s arrows 3 Process Specification Since CLL propositions can naturally represent resources, CLL sequents can be used to represent processes, with each literal representing a type of resource that is involved in that process. These abstract types can have a concrete realisation in the host programming language, from primitive to complicated objects. Our approach to resource-based composition is to construct CLL specifications of abstract processes based on their inputs (and preconditions) and outputs (and effects), also referred to as IOPEs. This is standard practice in various process formalisms, including WSDL for web services [6], OWL-S for Semantic Web services [16], PDDL for actions in automated planning [17], etc. The symmetry of linear negation as shown in Fig. 3 can be used to assign a polarity to each CLL connective in order to distinctly specify input and output resources. We choose to treat negated literals, $\neg$, and $\&$ as inputs, and positive literals, $\otimes$, and $\oplus$ as outputs, with the following intuitive interpretation: - Multiplicative conjunction (tensor $\otimes$) indicates a pair of parallel outputs. - Additive disjunction (plus $\oplus$) indicates exclusively optional outputs (alternative outputs or exceptions). - Multiplicative disjunction (par $\forall$) indicates a pair of simultaneous inputs. - Additive conjunction (with $\&$) indicates exclusively optional input. 1 https://www.haskell.org/arrows Based on this, a process can be specified as a CLL sequent consisting of a list of input formulas and a single output formula. In this, the order of the literals does not matter, so long as they obey the polarity restrictions (all but exactly one are negative). In practice, we treat sequents as multisets of literals and manage them using particular multiset reasoning techniques in HOL Light. The description of these techniques is beyond the scope of this paper. The polarity restrictions imposed on our process specifications match the specification of Laurent’s Polarized Linear Logic (LLP) \[13\], and has a proven logical equivalence to the full MALL. Moreover, these restrictions match the programming language paradigm of a function that can have multiple input arguments and returns a single (possibly composite) result. 4 Process Composition Using CLL process specifications as assumptions, we can produce a composite process specification using forward inference. Each of the CLL inference rules represent a logically legal way to manipulate and compose such specifications. The axiom $\vdash A, A \perp$ represents the so-called axiom buffer, a process that receives a resource of type $A$ and outputs the same resource unaffected. Unary inference rules, such as the $\oplus_L$ rule, correspond to manipulations of a single process specification. For example, the $\oplus_L$ rule (see Fig. 2) takes a process $P$ specified by $\vdash \Gamma, A$, i.e. a process with some inputs $\Gamma$ and an output $A$, and produces a process $\vdash \Gamma, A \oplus B$, i.e. a process with the same inputs $\Gamma$ and output either $A$ or $B$. Note that the produced composite process relies on $P$ and therefore will in practice always produce $A$ and never $B$. Binary inference rules, such as the $\otimes$ rule, correspond to binary process composition. The $\otimes$ rule in particular (see Fig. 2) takes a process $P$ specified by $\vdash \Gamma, A$ and another process $Q$ specified by $\vdash \Delta, B$ and composes them, so that the resulting process $\vdash \Gamma, \Delta, A \otimes B$ has all their inputs $\Gamma$ and $\Delta$ and a simultaneous output $A \otimes B$. Notably, the Cut rule corresponds to the composition of 2 processes in sequence, where one consumes a resource $A$ given by the other. Naturally, these manipulations and compositions are primitive and restricted. Constructing meaningful compositions requires several rule applications and, therefore, doing this manually would be a very tedious and impractical task. Our work focuses on creating high level actions that use CLL inference to automatically produce binary process compositions that are correct-by-construction based on the guarantees described above. More specifically, we introduce actions for parallel (TENSOR), conditional (WITH), and sequential composition (JOIN). Since we are using forward inference, there are infinitely many ways to apply the CLL rules and therefore infinite possible compositions. We are interested in producing compositions that are intuitive for the user. It is practically impossible to produce a formal definition of what these compositions should be. Instead, as explained earlier, we rely on practical experience and user feedback from the various case studies for workflow modelling (see Table 1). Based on this, we have introduced a set of what can be viewed as unit tests for our composition actions, which describe the expected and logically valid results of example compositions. As we explore increasingly complex examples in practice, we augment our test set and ensure our algorithms satisfy them. Selected unit tests for the WITH and JOIN actions are shown in Tables 2 and 3 respectively. Moreover, as a general principle, our algorithms try to maximize resource usage, i.e. involve as many resources as possible, and minimize the number of rule applications to keep the corresponding process code more compact. <table> <thead> <tr> <th>P</th> <th>Q</th> <th>Result</th> </tr> </thead> <tbody> <tr> <td>⊢ X⊥, Z</td> <td>⊢ Y⊥, Z</td> <td>⊢ (X ⊕ Y⊥)⊥, Z</td> </tr> <tr> <td>⊢ X⊥, Z</td> <td>⊢ Y⊥, W</td> <td>⊢ (X ⊕ Y⊥)⊥, A⊥, B⊥, Z ⊕ W</td> </tr> <tr> <td>⊢ X⊥, A⊥, B⊥, Z</td> <td>⊢ Y⊥, Z</td> <td>⊢ (X ⊕ Y⊥)⊥, A⊥, B⊥, Z ⊕ (Z ⊗ A ⊗ B)</td> </tr> <tr> <td>⊢ X⊥, A⊥, B⊥, C⊥, Z</td> <td>⊢ Y⊥, B⊥, W</td> <td>⊢ (X ⊕ Y⊥)⊥, A⊥, B⊥, C⊥, (Z ⊗ B) ⊕ (W ⊗ A)</td> </tr> <tr> <td>⊢ X⊥, A ⊗ B</td> <td>⊢ Y⊥, B ⊗ A</td> <td>⊢ (X ⊕ Y⊥)⊥, A ⊗ B</td> </tr> <tr> <td>⊢ X⊥, A⊥, Z ⊗ A</td> <td>⊢ Y⊥, Z</td> <td>⊢ (X ⊕ Y⊥)⊥, A⊥, Z ⊗ A</td> </tr> <tr> <td>⊢ X⊥, Z ⊗ (Z ⊗ A)</td> <td>⊢ Y⊥, Z</td> <td>⊢ (X ⊕ Y⊥)⊥, A⊥, Z ⊗ (Z ⊗ A)</td> </tr> </tbody> </table> Table 2. Examples of the expected result of the WITH action between X⊥ of a process P and Y⊥ of a process Q. All our algorithms are implemented within the Higher Order Logic proof tactic system of HOL Light. As a result, the names of some methods have the _TAC suffix, which is conventionally used when naming HOL Light tactics. 5 Auxiliary Processes During composition, we often need to construct auxiliary processes that manipulate the structure of a CLL type in particular ways. We have identified 2 types of such processes: buffers and filters. Buffers: Similarly to the axiom buffer introduced in the previous section, composite buffers (or simply buffers) can carry any composite resource without affecting it. This is useful when a process is unable to handle the entire type on its own, and some resources need to be simply buffered through. For example, if a process needs to handle a resource of type A ⊗ B, but only has an input of type A⊥, then B will be handled by a buffer. More formally, buffers are processes specified by ⊢ A⊥, A, where A is arbitrarily complex. Such lemmas are always provable in CLL for any formula A. We have introduced an automatic procedure BUFFER_TAC that can accomplish this, but omit the implementation details in the interest of space and in favour of the more interesting composition procedures that follow. We also introduce the concept of a parallel buffer, defined as a process \( \vdash A_1^\perp, A_2^\perp, ..., A_n^\perp, A_1 \otimes A_2 \otimes ... \otimes A_n \). Such buffers are useful when composing processes with an optional output (see Section 8.3). Their construction can also be easily automated with a decision procedure we call PARBUF_TAC. **Filters:** Often during process composition by proof, resources need to match exactly for the proof to proceed. In some cases, composite resources may not match exactly, but may be manipulated using the CLL inference rules so that they end up matching. For example, the term \( A \otimes B \) does not directly match \( B \otimes A \). However, both terms intuitively represent resources \( A \) and \( B \) in parallel. This intuition is reflected formally to the commutativity property of \( \otimes \), which is easily provable in CLL: \( \vdash (A \otimes B)^\perp, B \otimes A \). We can then use the Cut rule with this property to convert an output of type \( A \otimes B \) to \( B \otimes A \) (similarly for inputs). We call such lemmas that are useful for converting CLL types to equivalent ones, **filters**. In essence, a filter is any provable CLL lemma that preserves our polarity restrictions. We prove such lemmas automatically using the proof strategies developed by Tammet [24]. We give some examples of how filters are used to match terms as we go through them below. However, as a general rule the reader may assume that, for the remainder of this paper, by “equal” or “matching” terms we refer to terms that are equal modulo the use of filters. A main consequence of this is that our algorithms often attempt to match literals that do not match. For example, the attempt to compose \( \vdash A^\perp, B \) in sequence with \( \vdash C^\perp, D^\perp, E \) would generate and try to prove 2 false conjectures \( \vdash B^\perp, C \) and \( \vdash B^\perp, D \) in an effort to match the output \( B \) with any of the 2 inputs \( C^\perp \) and \( D^\perp \) before failing\(^2\). This highlights the need for an efficient proof procedure for filters, with an emphasis on early failure. 6 Parallel Composition - The TENSOR Action The TENSOR action corresponds to the parallel composition of two processes so that their outputs are provided in parallel. It trivially relies on the tensor (\( \otimes \)) inference rule. Assuming 2 processes, \( \vdash A^\perp, C^\perp, D \) and \( \vdash B^\perp, E \), the TENSOR action will perform the following composition: \[ \vdash A^\perp, C^\perp, D \vdash B^\perp, E \\ \vdash A^\perp, B^\perp, C^\perp, D \otimes E \] 7 Conditional Composition - The WITH Action The WITH action corresponds to the conditional composition of two processes. This type of composition is useful in cases where each of the components of an optional output of a process needs to be handled by a different receiving process.\(^2\) In practice, the user will have to select a matching input to attempt such a composition (see Section 8). For example, assume a process $S$ has an optional output $A \oplus C$ where $C$ is an exception. We want $A$ to be handled by some process $P$, for example specified by $\vdash A^\perp, B^\perp, X$, while another process $Q$ specified by $\vdash C^\perp, Y$ plays the role of the exception handler for exception $C$. For this to happen, we need to compose $P$ and $Q$ together using the $\text{WITH}$ action so that $A \oplus C$ from $S$ can be taken as input in one go. This composition can be viewed as the construction of an if-then statement where if $A$ is provided then $P$ will be executed (assuming $B$ is also provided), and if $C$ is provided then $Q$ will be executed in a mutually exclusive choice. The generated proof tree for this particular example is the following: \[ \begin{align*} \vdash A^\perp, B^\perp, X & \quad \vdash C^\perp, Y & \vdash B^\perp, B \\ \vdash A^\perp, B^\perp, X \oplus R & \quad \vdash C^\perp, B^\perp, Y \otimes B & \vdash C^\perp, B^\perp, X \oplus (Y \otimes B) & \quad & \vdash (A \oplus C)^\perp, B^\perp, X \oplus (Y \otimes B) \\ \vdash (A \oplus C)^\perp, B^\perp, X \oplus (Y \otimes B) & \quad & \vdash (A \oplus C)^\perp, X \oplus Y & \vdash (A \oplus C)^\perp, X \oplus Y & \vdash (A \oplus C)^\perp, X \oplus Y \\ \vdash \Gamma, A^\perp, X \oplus L & \quad & \vdash \Gamma, C^\perp, Y \oplus R & \quad & \vdash \Gamma, (A \oplus C)^\perp, X \oplus Y & \vdash \Gamma, (A \oplus C)^\perp, X \oplus Y \\ \end{align*} \] The $\text{WITH}$ action fundamentally relies on the $\&$ rule of CLL. The following derivation allows us to compose 2 processes with different outputs $X$ and $Y$: \[ \begin{align*} \vdash \Gamma, A^\perp, X \oplus L & \quad \vdash \Gamma, C^\perp, Y \oplus R & \vdash \Gamma, (A \oplus C)^\perp, X \oplus Y & \vdash \Gamma, (A \oplus C)^\perp, X \oplus Y \\ \end{align*} \] The particularity of the $\&$ rule is that the context $\Gamma$, i.e. all the inputs except the ones involved in the $\text{WITH}$ action, must be the same for both the involved processes. In practice, this means we need to account for unused inputs. In the example above, $P$ apart from input $A^\perp$ has another input $B^\perp$ which is missing. from Q. In the conditional composition of P and Q, if exception C occurs, the provided B will not be consumed since P will not be invoked. In this case, we use a buffer to let B pass together with the output Y of Q. More generally, in order to apply the & rule to 2 processes P and Q, we need to minimally adjust their contexts \( \Gamma_P \) and \( \Gamma_Q \) (i.e. their respective multisets of inputs excluding the ones that will be used in the rule) so that they end up being the same \( \Gamma = \Gamma_P \cup \Gamma_Q \). In order to accomplish this for process Q, we calculate the multiset of "missing" inputs \( \Delta_Q = \Gamma_P \setminus \Gamma_Q \). In the previous example in (1), we obtain \( \Delta_Q = \{ \perp \} \). We then construct a parallel buffer (see Section 5) of type \( \otimes \Delta_Q \perp \) using PARBUF_TAC. In the example, this is an atomic C buffer. The parallel composition between this buffer and Q results in the process \( \vdash \Gamma_Q, \Delta_Q, C \perp, Y \otimes (\otimes \Delta_Q) \). The same calculation for P yields \( \Delta_P = \emptyset \) so no change is required for P. Since \( \Gamma_P \uplus \Delta_P = \Gamma_Q \uplus \Delta_Q = \Gamma \) (where \( \uplus \) denotes multiset union), the & rule is now applicable and derivation (2) yields the following process: \[ \vdash \Gamma, (X \oplus (\otimes \Delta_P)) \oplus (Y \otimes (\otimes \Delta_Q)) \tag{3} \] The output Y of Q has now been paired with the buffered resources \( \Delta_Q \). Finally, we consider the special case where the following holds: \[ (X \otimes (\otimes \Delta_P)) = (Y \otimes (\otimes \Delta_Q)) = G \tag{4} \] In this case, the output of the composition in (3) will be \( G \oplus G \). Instead we can apply the & directly without derivation (2), yielding the simpler output G. Note that, as discussed in Section 5, the special case above does not strictly require equality. The special case can also be applied if we can prove and use the filter \( \vdash (X \otimes (\otimes \Delta_P))^{-1}, (Y \otimes (\otimes \Delta_Q)) \). These results and the complexity underlying their construction demonstrate the non-trivial effort needed to adhere to CLL’s systematic management of resources and, more specifically, its systematic accounting of unused resources. 8 Sequential Composition - The JOIN Action The JOIN action reflects the connection of two processes in sequence, i.e. where (some of) the outputs of a process are connected to (some of) the corresponding inputs of another. More generally, we want to compose a process P with specification \( \vdash \Gamma, X \), i.e. with some (multiset of) inputs \( \Gamma \) and output X in sequence with a process Q with specification \( \vdash \Delta, C \perp, Y \), i.e. with an input \( C \perp \), output Y, and (possibly) more inputs in context \( \Delta \). We also assume the user selects a subterm A of X in P and a matching subterm A of the input \( C \perp \) in Q. The strategy of the algorithm behind the JOIN action is to construct a new input for Q based on the chosen \( C \perp \) such that it directly matches the output X \[ \otimes \{a_1, ..., a_n\} \perp = a_1 \perp \otimes ... \otimes a_n \perp \] of \( P \) (and prioritizing the output selection \( A \)). This will enable the application of the \textit{Cut} rule, which requires the cut literal to match exactly. In what follows, we present how different cases for \( X \) are handled. 8.1 Atomic or Matching Output If \( X \) is atomic, a straightforward use of the \textit{Cut} rule is sufficient to connect the two processes. For example, the \textit{JOIN} action between \( \vdash A^\perp, B^\perp, X \) and \( \vdash X^\perp, Z \) results in the following proof: \[ \begin{array}{c} \vdash A^\perp, B^\perp, X \\ \vdash A^\perp, B^\perp, Z \\ \vdash X^\perp, Z \\ \vdash A^\perp, B^\perp, Z, \text{Cut} \end{array} \] The same approach can be applied more generally for any non-atomic \( X \) as long as a matching input of type \( X^\perp \) (including via filtering) is selected in \( Q \). 8.2 Parallel Output If \( X \) is a parallel output, such as \( B \otimes C \), we need to manipulate process \( Q \) so that it can receive an input of type \((B \otimes C)^\perp \). If \( Q \) has both inputs \( B^\perp \) and \( C^\perp \), then we can use the \( \otimes \) rule to combine them. For example, the generated proof tree of the \textit{JOIN} action between \( \vdash A^\perp, D^\perp, B \otimes C \) and \( \vdash B^\perp, C^\perp, E^\perp, Y \) is the following: \[ \begin{array}{c} \vdash A^\perp, D^\perp, B \otimes C \\ \vdash B^\perp, C^\perp, E^\perp, Y \\ \vdash (B \otimes C)^\perp, E^\perp, Y \\ \vdash A^\perp, B^\perp, E^\perp, Y, \text{Cut} \end{array} \] As previously mentioned, the \textit{JOIN} action attempts to connect the output of \( P \) to \( Q \) maximally, i.e. both \( B \) and \( C \), regardless of the user choice. The user may, however, want to only connect one of the two resources. We have currently implemented this approach as it is the most commonly used in practice, but are investigating ways to enable better control by the user. If \( Q \) has only one of the two inputs, for example \( B^\perp \), i.e. \( Q \) is of the form \( \vdash \Delta, B^\perp, Y \) and \( C^\perp \not\in \Delta \), then \( C \) must be buffered. In this case, we use the following derivation: \[ \begin{array}{c} \vdash \Delta, B^\perp, Y \\ \vdash \Delta, B^\perp, C^\perp, Y \otimes C \\ \vdash \Delta, (B \otimes C)^\perp, Y \otimes C, \otimes \end{array} \] We use \texttt{BUFFER_TAC} from Section 5 to prove the buffer of \( C \). Depending on the use of the \( \otimes \) rule in (5), the resulting output could be either \( Y \otimes C \) or \( C \otimes Y \). We generally try to match the form of \( P \)’s output, so in this case we would choose \( Y \otimes C \) to match \( B \otimes C \). Our algorithm keeps track of this orientation through the \texttt{orient} parameter (see Section 8.4). 8.3 Optional Output If $X$ is an optional output, such as $B \oplus C$, then we need to manipulate process $Q$ to synthesize an input $(B \oplus C)\perp$. Assume $Q$ can handle $B$ (symmetrically for $C$) and thus has specification $\vdash \Delta, B\perp, Y$. We construct a parallel buffer (using PARBUF_TAC, see Section 5) of type $(\otimes \Delta) \otimes C$ (converting all inputs in $\Delta$ to outputs). We then apply derivation (2) as follows: \[ \frac{\vdash \Delta, B\perp, Y}{\vdash \Delta, (B \oplus C)\perp, Y \oplus (\otimes \Delta) \otimes C} \] Similarly to the WITH action, the particular structure of the $\&$ rule ensures the systematic management of unused resources. In the example above, if $C$ is received then $Q$ will never be executed. As a result, any resources in $\Delta$ will remain unused and need to be buffered together with $C$. This is the reason behind the type $(\otimes \Delta) \otimes C$ of the constructed buffer (as opposed to plainly using type $C$). The proof tree of an example of the JOIN action between process $P$ specified by $\vdash A\perp, D\perp, B \oplus C$ and process $Q$ specified by $\vdash B\perp, E\perp, Y$ is shown below: \[ \frac{\vdash B\perp, E\perp, Y}{\vdash (B \oplus C)\perp, E\perp, Y \oplus (C \otimes E) \&} \quad \frac{\vdash C\perp, C}{\vdash E\perp, E \otimes} \quad \frac{\vdash C\perp, E\perp, C \otimes E}{\vdash E\perp, Y \oplus (C \otimes E) \&} \quad \text{Cut} \] It is interesting to consider a couple of special cases. Case 1: If $\vdash \Delta, C\perp, Y$ is a parallel buffer, (6) can be simplified as follows: \[ \frac{\vdash B\perp, E\perp, Y}{\vdash (B \oplus C)\perp, E\perp, Y \oplus (C \otimes E) \&} \quad \frac{\vdash C\perp, C}{\vdash E\perp, E \otimes} \quad \frac{\vdash C\perp, E\perp, C \otimes E}{\vdash E\perp, Y \oplus (C \otimes E) \&} \quad \text{Cut} \] This may occur, for example, if $\Delta = \emptyset$ and $Y = C$. Such cases arise in processes used to recover from an exception. For instance, a recovery process $\vdash \text{Exception} \perp, \text{Resource}$ can convert an output $\text{Resource} \oplus \text{Exception}$ to simply $\text{Resource}$ (which either was there in the first place, or was produced through the recovery process). Case 2: If \( Y = D \oplus E \) for some \( D \) and \( E \) such that \( \vdash \Delta, C^\perp, D \) (or symmetrically \( \vdash \Delta, C^\perp, E \)) is a parallel buffer, then we can apply the following derivation: \[ \begin{align*} \vdash \Delta, B^\perp, D \oplus E & \quad Q \\ \vdash \Delta, C^\perp, D \oplus E & \quad \oplus L \\ \vdash \Delta, (B \oplus C)^\perp, D \oplus E & \quad & (8) \end{align*} \] This may occur, for example, if \( \Delta = \emptyset \) and \( Y = C \oplus E \). The recovery process above may itself throw an exception: \( \vdash \text{Exception}^\perp, \text{Resource} \oplus \text{Failed} \). This will convert output \( \text{Resource} \oplus \text{Exception} \) to \( \text{Resource} \oplus \text{Failed} \) (either we had the \( \text{Resource} \) from the beginning, or we recovered and still got a \( \text{Resource} \), or the recovery process failed) instead of \( (\text{Resource} \oplus \text{Failed}) \oplus \text{Resource} \). ### 8.4 Putting It All Together In the general case, the output \( X \) of \( P \) can be a complex combination of multiple parallel and optional outputs. For that reason, we apply the above proof strategies in a recursive, bottom-up way, prioritizing the user selections. We call the algorithm that produces the appropriate input \( X^\perp \) (or equivalent) from \( Q \) “\( \text{INPUT\_TAC} \)” and it has the following arguments (see Algorithm 1): - \( \text{sel} \): optional term corresponding to the user selected input \( C^\perp \) of \( Q \). - \( \text{priority} \): a list representing the path of the user selected subterm \( A \) in the syntax tree of the output \( X \) of \( P \). For example, if the user selects \( B \) in the output \( (A \otimes B) \oplus C \), the priority is \([\text{Left}; \text{Right}]\). - \( \text{orient} \): our latest path (left or right) in the syntax tree of \( X \) so that we add the corresponding buffers on the same side (see Section 8.2). - \( \text{inputs} \): a list of inputs of \( Q \). We remove used inputs from this to avoid reuse. - \( \text{target} \): the input term we are trying to construct. This is initially set to \( X \), but may take values that are subterms of \( X \) in recursive calls. - \( \text{proc} \): the CLL specification of \( Q \) as it evolves. The \( \text{priority} \) parameter is useful when more than one subterms of the output either (a) are the same or (b) have the same matching input in \( Q \). Table 4 shows examples of how different priorities change the result of \( \text{INPUT\_TAC} \). Algorithm 1 Manipulates the specification “proc” to synthesize an input of type “target”. Returns a new process specification that is logically derived from the original. 1: function INPUT_TAC(sel, priority, orient, inputs, target, proc) 2: Try to match target with sel (if provided) or one of the inputs 3: if it matches then return proc 4: else if target is atomic then 5: if priority ≠ None then fail ▷ we couldn’t match the user selected output 6: else Create a target buffer using [5] depending on orient 7: end if 8: else if target is L ⊗ R then 9: if priority = Left then 10: proc’ = INPUT_TAC(sel, tail(priority), orient, inputs, L, proc) 11: proc = INPUT_TAC(None, None, Right, inputs - {L}, R, proc’) 12: else 13: proc’ = INPUT_TAC(sel, tail(priority), orient, inputs, R, proc) 14: proc = INPUT_TAC(None, None, Left, inputs - {R}, L, proc’) 15: end if 16: Use the 3 rule to create the (L ⊗ R)⊥ input 17: else if target is L ⊕ R then 18: if priority = Left then 19: proc = INPUT_TAC(sel, tail(priority), orient, inputs, L, proc) 21: else if priority = Right then 22: proc = INPUT_TAC(sel, tail(priority), orient, inputs, R, proc) 24: else 25: Try as if priority = Left orElse Try as if priority = Right 26: else Create a target buffer using [5] depending on orient 27: end if 28: end if 29: return proc 30: end function 9 Conclusion CLL’s inherent properties make it an ideal language to reason about resources. CLL sequents (under polarity restrictions) can be viewed as resource-based specifications of processes. The CLL inference rules then describe the logically legal, but primitive ways to manipulate and compose such processes. We presented algorithms that allow intuitive composition in parallel, conditionally, and in sequence. We call these composition actions TENSOR, WITH, and JOIN respectively, and they are implemented in HOL Light. We analysed how each action functions in different cases and examples. As a result of the rigorous usage of CLL inference rules, the constructed compositions have guaranteed resource accounting, so that no resources disappear or are created out of nowhere. The proofs-as-processes paradigm and its recent evolutions allow the extraction of process calculus terms from these proofs, for concurrent and guaranteed deadlock-free execution. In the future, we intend to work towards relaxing identified limitations along 2 main lines: (a) functionality, by incorporating and dealing with increasingly more complex specifications including those requiring formulation of more complex filters, and (b) expressiveness, by extending the fragment of CLL we are using while keeping a balance in terms of efficiency. Through this work, it is made obvious that intuitive process compositions in CLL require complex applications of a large number of inference rules. Our algorithms automate the appropriate deductions and alleviate this burden from the user. We have tied these with the diagrammatic interface of WorkflowFM [21], so that the user is not required to know or understand CLL or theorem proving, but merely sees inputs and outputs represented graphically. They can then obtain intuitive process compositions with the aforementioned correctness guarantees with a few simple clicks. Acknowledgements This work was supported by the “DigiFlow: Digitizing Industrial Workflow, Monitoring and Optimization” Innovation Activity funded by EIT Digital. References
{"Source-Url": "https://www.research.ed.ac.uk/portal/files/74847636/Correct_by_construction_process_composition_using_classical_linear_logic_inference.pdf", "len_cl100k_base": 10078, "olmocr-version": "0.1.53", "pdf-total-pages": 17, "total-fallback-pages": 0, "total-input-tokens": 59685, "total-output-tokens": 12711, "length": "2e13", "weborganizer": {"__label__adult": 0.0004401206970214844, "__label__art_design": 0.0005578994750976562, "__label__crime_law": 0.0004906654357910156, "__label__education_jobs": 0.0012388229370117188, "__label__entertainment": 0.00012123584747314452, "__label__fashion_beauty": 0.0002090930938720703, "__label__finance_business": 0.0004699230194091797, "__label__food_dining": 0.0005474090576171875, "__label__games": 0.0007376670837402344, "__label__hardware": 0.0009412765502929688, "__label__health": 0.0012922286987304688, "__label__history": 0.0003559589385986328, "__label__home_hobbies": 0.0001537799835205078, "__label__industrial": 0.0007948875427246094, "__label__literature": 0.0005245208740234375, "__label__politics": 0.00036025047302246094, "__label__religion": 0.0006403923034667969, "__label__science_tech": 0.133056640625, "__label__social_life": 0.00014257431030273438, "__label__software": 0.00801849365234375, "__label__software_dev": 0.84765625, "__label__sports_fitness": 0.00036215782165527344, "__label__transportation": 0.0007443428039550781, "__label__travel": 0.00022470951080322263}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 44312, 0.02144]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 44312, 0.62938]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 44312, 0.84716]], "google_gemma-3-12b-it_contains_pii": [[0, 1328, false], [1328, 3790, null], [3790, 6796, null], [6796, 8557, null], [8557, 11400, null], [11400, 14060, null], [14060, 17397, null], [17397, 20346, null], [20346, 23384, null], [23384, 25586, null], [25586, 28806, null], [28806, 31611, null], [31611, 33872, null], [33872, 36446, null], [36446, 38763, null], [38763, 41484, null], [41484, 44312, null]], "google_gemma-3-12b-it_is_public_document": [[0, 1328, true], [1328, 3790, null], [3790, 6796, null], [6796, 8557, null], [8557, 11400, null], [11400, 14060, null], [14060, 17397, null], [17397, 20346, null], [20346, 23384, null], [23384, 25586, null], [25586, 28806, null], [28806, 31611, null], [31611, 33872, null], [33872, 36446, null], [36446, 38763, null], [38763, 41484, null], [41484, 44312, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 44312, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 44312, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 44312, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 44312, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 44312, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 44312, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 44312, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 44312, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 44312, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 44312, null]], "pdf_page_numbers": [[0, 1328, 1], [1328, 3790, 2], [3790, 6796, 3], [6796, 8557, 4], [8557, 11400, 5], [11400, 14060, 6], [14060, 17397, 7], [17397, 20346, 8], [20346, 23384, 9], [23384, 25586, 10], [25586, 28806, 11], [28806, 31611, 12], [31611, 33872, 13], [33872, 36446, 14], [36446, 38763, 15], [38763, 41484, 16], [41484, 44312, 17]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 44312, 0.03767]]}
olmocr_science_pdfs
2024-12-10
2024-12-10
79fca398077ed7e18c890213c41bf0aaa9534ee4
[REMOVED]
{"Source-Url": "https://hal.archives-ouvertes.fr/hal-01301829/file/paper.pdf", "len_cl100k_base": 8293, "olmocr-version": "0.1.49", "pdf-total-pages": 16, "total-fallback-pages": 0, "total-input-tokens": 43579, "total-output-tokens": 11243, "length": "2e13", "weborganizer": {"__label__adult": 0.0005335807800292969, "__label__art_design": 0.0006451606750488281, "__label__crime_law": 0.0007877349853515625, "__label__education_jobs": 0.00193023681640625, "__label__entertainment": 0.0002027750015258789, "__label__fashion_beauty": 0.0003681182861328125, "__label__finance_business": 0.0006494522094726562, "__label__food_dining": 0.0005221366882324219, "__label__games": 0.001308441162109375, "__label__hardware": 0.0012350082397460938, "__label__health": 0.0015172958374023438, "__label__history": 0.00070953369140625, "__label__home_hobbies": 0.00019919872283935547, "__label__industrial": 0.0008625984191894531, "__label__literature": 0.0005679130554199219, "__label__politics": 0.00063323974609375, "__label__religion": 0.0008082389831542969, "__label__science_tech": 0.33056640625, "__label__social_life": 0.0001951456069946289, "__label__software": 0.0091400146484375, "__label__software_dev": 0.64453125, "__label__sports_fitness": 0.0006146430969238281, "__label__transportation": 0.0010595321655273438, "__label__travel": 0.0003483295440673828}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 41362, 0.06781]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 41362, 0.23522]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 41362, 0.89438]], "google_gemma-3-12b-it_contains_pii": [[0, 1008, false], [1008, 3857, null], [3857, 7149, null], [7149, 10761, null], [10761, 13771, null], [13771, 16639, null], [16639, 19668, null], [19668, 20731, null], [20731, 23565, null], [23565, 26657, null], [26657, 29963, null], [29963, 30911, null], [30911, 31578, null], [31578, 34553, null], [34553, 37883, null], [37883, 41362, null]], "google_gemma-3-12b-it_is_public_document": [[0, 1008, true], [1008, 3857, null], [3857, 7149, null], [7149, 10761, null], [10761, 13771, null], [13771, 16639, null], [16639, 19668, null], [19668, 20731, null], [20731, 23565, null], [23565, 26657, null], [26657, 29963, null], [29963, 30911, null], [30911, 31578, null], [31578, 34553, null], [34553, 37883, null], [37883, 41362, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 41362, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 41362, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 41362, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 41362, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 41362, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 41362, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 41362, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 41362, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 41362, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 41362, null]], "pdf_page_numbers": [[0, 1008, 1], [1008, 3857, 2], [3857, 7149, 3], [7149, 10761, 4], [10761, 13771, 5], [13771, 16639, 6], [16639, 19668, 7], [19668, 20731, 8], [20731, 23565, 9], [23565, 26657, 10], [26657, 29963, 11], [29963, 30911, 12], [30911, 31578, 13], [31578, 34553, 14], [34553, 37883, 15], [37883, 41362, 16]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 41362, 0.14054]]}
olmocr_science_pdfs
2024-11-24
2024-11-24
7eb65bb88a08388ea97568f6d4ff387166e7f853
Synthetic Data Generation from JSON Schemas Hugo André Coelho Cardoso University of Minho, Braga, Portugal José Carlos Ramalho Department of Informatics, University of Minho, Braga, Portugal Abstract This document describes the steps taken in the development of DataGen From Schemas. This new version of DataGen is an application that makes it possible to automatically generate representative synthetic datasets from JSON and XML schemas, in order to facilitate tasks such as the thorough testing of software applications and scientific endeavors in relevant areas, namely Data Science. This paper focuses solely on the JSON Schema component of the application. DataGen’s prior version is an online open-source application that allows the quick prototyping of datasets through its own Domain Specific Language (DSL) of specification of data models. DataGen is able to parse these models and generate synthetic datasets according to the structural and semantic restrictions stipulated, automating the whole process of data generation with spontaneous values created in runtime and/or from a library of support datasets. The objective of this new product, DataGen From Schemas, is to expand DataGen’s use cases and raise the datasets specification’s abstraction level, making it possible to generate synthetic datasets directly from schemas. This new platform builds upon its prior version and acts as its complement, operating jointly and sharing the same data layer, in order to assure the compatibility of both platforms and the portability of the created DSL models between them. Its purpose is to parse schema files and generate corresponding DSL models, effectively translating the JSON specification to a DataGen model, then using the original application as a middleware to generate the final datasets. 2012 ACM Subject Classification Software and its engineering → Domain specific languages; Theory of computation → Grammars and context-free languages; Information systems → Open source software Keywords and phrases Schemas, JSON, Data Generation, Synthetic Data, DataGen, DSL, Dataset, Grammar, Randomization, Open Source, Data Science, REST API, PEG.js Digital Object Identifier 10.4230/OASIcs.SLATE.2022.5 1 Introduction The current landscape of the technological and software development market is being increasingly occupied with scientific areas that operate with large amounts of data. A prime example is that of Data Science, which aims to apply methods of scientific analysis and algorithms to bulky datasets, in order to try to extract knowledge and conclusions from the available information, which may then be used for several other means. Another case is that of Machine Learning, which looks to use this method to equip informatic systems with the capacity of self-learning, accessing data and learning from its analysis, as to become more efficient in their function. However, in a world where the need for bulky and representative datasets increases by each passing day, data privacy policies and other concerns related to the privacy and safety of users [5] present themselves as difficult obstacles to the growth of these sciences and to the progression of many projects in the development [4] and testing phases. In this context, the generation of synthetic data arises as a possible solution for these problems, under the premise of being able to create realistic, large datasets artificially, from the given structural specifications. This approach was originally proposed by Rubin in 1993 [6], as an alternative that made it possible to use and share data without disrespecting the present rigorous regulations regarding the handling of sensitive data (such as the European Union’s GDPR [10]), since the data in question, although very similar to corporate datasets concerning real users, would not be obtained by direct measurement. Since then, this method has been further explored and refined, being applied in the most diverse areas such as Smart Homes [2], spatial microsimulation models [8], Internet of Things (IoT) [1], Deep Learning [3] and automotive applications [9]. This paper intends to expose and document the processes of ideation and development of the application DataGen From Schemas, specifically its JSON Schema component, whose objective is to generate synthetic datasets directly from JSON schemas. This application must fulfill two requisites: on the one hand, it must be able to generate datasets of ample size and with realistic information; on the other hand, it must also be able to parse the users’ schemas and obey their specifications, so that the created data is formally and structurally compliant. In order to satisfy these conditions, the platform will be built upon another existing application, DataGen, that will be contextualized in the following section. ## 2 DataGen DataGen is a versatile tool that allows the quick prototyping of datasets and testing of software applications. Currently, this solution is one of the few available that offers both the complexity and the scalability necessary to generate datasets adequate for demanding tasks, such as the performance review of data APIs or complex applications, making it possible to gauge their ability to handle an appropriate volume of heterogeneous data. The core of DataGen is its own Domain Specific Language (DSL), which was created for the purpose of specifying datasets, both at a structural level (field nesting, data structures) and a semantic level (values’ data types, relations between fields). This DSL is endowed with a wide range of functionalities that allow the user to specify different types of data, local relations between fields, the usage of data from support datasets depicting different categories, the structural hierarchy of the dataset and many other relevant properties, as well as powerful mechanisms of repetition, fuzzy generation, etc. This allows for the generation of very miscellaneous and representative datasets in either JSON or XML, while dealing with intricate and demanding requirements. It is strongly encouraged to check the published paper on DataGen’s development and functionality [7] first, in order to be better contextualized in the capacities of this product and have a greater understanding of what will serve as the foundation for the new software described. For the sake of brevity, DataGen’s DSL mechanisms will not be explained in this document and it will be assumed that the reader is familiar with them, going forward. In the current scheme of software development, any enterprise that operates with JSON or XML data must have well-defined and thorough formal specifications to control and monitor the data flow in their applications, in order to assure that incoming information is well-structured and compliant with the software’s requirements and outgoing data is presented as intended and does not produce unexpected behaviour. As such, it is essential to formulate schemas for semantic and structural validation, by modeling data either internally or via third parties with tools oriented to this goal, in order to restrict and enforce the content intended for each solution. Considering the present necessity for these schemas in enterprises’ business models and its recurring usage, it stands to reason that a program capable of producing large and accurate datasets from JSON/XML schemas is an incredibly valuable asset, as it provides the capacity to quickly and effortlessly create representative datasets to test and debug platforms in development, as well as evaluate their performance under heavy stress, without having to manually concoct the information or wait for third parties to provide such resources. As such, DataGen From Schemas emerges as a complement and an extension to its prior version, looking to generate datasets directly from JSON schemas. By doing this, the user is given the option to specify the structure of the intended dataset in JSON Schema. This arises as an alternative to the definition of the operational rules of the dataset in DataGen’s native DSL, for which the user must first learn how to use it, through the lengthy documentation available. With this, the formulation of the DSL model becomes an intermediate step executed in the background and the user only has to interact with the JSON schema and the resulting dataset. However, the generated DSL model will also be made available, to enable further customizability in DataGen. As such, this new product aims to offer a solution for a present and generalized need in the software development process and increase DataGen’s use cases significantly, making the dataset generation process simpler and more accessible to any user. This new component acts as an abstraction layer over the existing application, ignoring the necessity to learn how to use the DSL from its documentation and greatly expediting the process of structural specification of the dataset. The intended workflow for this JSON Schema component is depicted in the following image: ![Intended workflow for the JSON Schema component.](image) The program will accept the user’s input in the form of a JSON schema, which will then be parsed by a PEG.js grammar-based compiler. The parser will generate an intermediate data structure with the relevant information and a converter program will then translate it to a DSL model. Afterwards, DataGen will take care of the remaining workload, parsing the model and generating a dataset, finally converting it to either JSON or XML format, according to the user’s preference. DataGen’s prior version was created by the same authors of this new tool, so there is access to the original application. The goal is to place the new compilers and translators in DataGen’s own backend, in order to centralize the functionalities, avoiding additional requests between servers and possible downtime, as would be the case if DataGen From Schemas was deployed in an entirely separate web application and had to communicate with DataGen’s API routes via HTTP requests to generate datasets from its models. This section aims to give a bit of contextualization about the format JSON, in order to have a better grasp of what DataGen From Schemas must be able to analyse and parse, what data is relevant to be extracted, and also to understand the limits and potential of this simple, yet versatile format and why it was chosen for this application, instead of another of many popular data formats nowadays, i.e. its relevance and adequacy to this particular project. As mentioned in section 2, DataGen already has the ability of generating JSON and XML instances from DSL models, so this new product’s focus is uniquely translating the data in a JSON schema to a DSL model, basically the opposite procedure. What will be exposed about JSON also applies to JSON Schema, as the latter is a JSON vocabulary, which is to say, it is written in JSON and operates under a strict set of rules, where specific keys have precise meanings and can be used to annotate or validate JSON documents. This common syntax makes it easy to interpret the schema and validate the instance. JavaScript Object Notation (JSON) is a lightweight data exchange format derived from the programming language Javascript, whose simplicity and readability contributed to its current vast popularity. It has ample and growing support in countless programming languages (C++, Java, JavaScript, Python, etc), which make it a strong candidate for fast and compact exchange of information between applications. This format is utilized to represent structured information, i.e. data with rigid and well-defined configurations, where no divergencies are allowed from the structures established in the schema, namely a different data type for a certain field. This reflects in the JSON syntax, where there are only four different primitive types for values - string, number, boolean or null - and the instances are built upon solely two different data structures: objects (non-ordered collections of key-value pairs) and arrays (ordered lists of values). DataGen’s own DSL is built upon the JSON format, so there is very high compatibility with JSON Schema and a guarantee that all kinds of data specified in the schema can be represented in the model. In addition, DataGen also has a tool named interpolation functions, which makes it possible to randomize the value of a certain field, given its type and some other restrictions. With this, it is possible to convert a JSON schema into a corresponding non-deterministic DSL model, where the final values are not hard-coded, but decided in runtime, which may result in endless different valid datasets from a single schema. ### Development In order to generate DSL models from JSON schemas, DataGen From Schemas will need two different components: firstly, a grammar-based parser to analyze the schema and extract all useful information. For this, PEG.js was the technology of choice, as it was already used in DataGen and proved adequate and capable of parsing JSON-like structures. Lastly, a program capable of translating the intermediate structure into a DSL model, for which JavaScript was used, for direct compatibility with PEG.js (that also incorporates this programming language) and JSON. The user may input one or more schemas into the program, which is necessary to allow cross-schema referencing. In this case, the user must indicate which is the primary schema from which the dataset is to be generated. The parser then analyzes all schemas sequentially, building an intermediate structure for each of them, a procedure that will be explained in detail in this section. 4.1 Grammar The grammar was built with a JSON grammar available in the PEG.js Github as its foundation, given that JSON Schema uses the same syntax. JSON Schema's specification is made available by drafts, which represent versions. Each time the vocabulary is majorly updated, a new draft is released, where new features can be found and existing ones altered. These drafts are not backward compatible, for example there are cases in which a certain key has entirely different semantics depending on the draft considered. As such, it seemed only logical to adapt the most recent draft to the application, which is, at the time of writing this document, JSON Schema 2020-12. As such, the aforementioned JSON grammar was modified into a dialect (a specific version of JSON Schema) grammar for this particular draft: the set of keywords and semantics that can be used to evaluate a schema was restricted to those made available in the draft and custom vocabularies defined by the user are not accepted. With this, it was possible to implement other important features in this grammar, namely: - **restriction of each keyword’s value to its rigid lexical space** – for example, the keyword `uniqueItems`’s value must be a boolean and nothing else, while the value of the keyword `additionalProperties` may be any subschema; - **rigorous semantic validation of the schema** – in JSON Schema, it is possible to create invalid and contradictory schemas. This may range from something as simple as a number with a `maximum` of 20 and `minimum` of 50, to more contrived cases such as establishing that a schema must be both of type boolean and string, with the keyword `allOf`. As such, a semantic validation procedure was created for this grammar, that checks for erroneous combinations of values or other incongruities in the schema’s logic. This validation only does not work with references, since these are only resolved posteriorly; - **error reports** – following the previous points, whenever the parser finds an error, be it a syntactic or semantic error, it halts the execution of the pipeline and reports it to the users, for them to correct and try again. The other central point of the grammar is building the intermediate data structure, to where it extracts the relevant information. Before addressing this topic, it is best to categorize and explain the different kinds of JSON Schema keywords. It is encouraged to follow this section of the paper along with the official JSON Schema documentation, as it has all the keywords listed and sorted in a relevant taxonomy. For this solution, the following categorization was used: - **type-specific keywords** – these are keywords that apply only to the data type in question. For example, numeric types have a way of specifying a numeric range, that would not be applicable to other types; - **generic keywords** – `const`, `enum`, and `type`. The latter defines the type(s) that the schema validates, the others may be or contain values of any of those types; schema composition keywords – the purpose of these is to combine together schemas, and they correspond to well-known algebra concepts like AND, OR, XOR, and NOT; keywords to apply subschemas conditionally – based on logical conditions or the presence of certain properties in the final object; structural keywords – $id, $anchor, $ref, and $defs. These keywords do not reflect values of the schema explicitly, but are used to structure complex schemas, allowing the user to break them down into simpler, reusable subschemas, and to reference these from anywhere, to avoid duplication and write schemas that are easier to read and maintain; ignored keywords – comments and annotation/media keywords (string-encoding non-JSON data). The parser recognizes these keywords but willingly ignores them, since they have little to no use in a dataset generation context. After thorough reflection, it was concluded that the best approach would be a type-oriented structure, where the keywords and respective values would be stored under the type of data they produce. There are multiple points in favor of this line of reasoning: - each data type has a specific set of keywords that applies to them and only them (the aforementioned type-oriented keywords), so it is easy to separate most keywords by type; - a single JSON schema may validate against multiple data types - the same schema can have keywords respective to arrays, numbers, and strings, for example. As such, it is useful to know, at all times, exactly what data types are producable from the schema; - following the previous point, a certain type may be established and then “disallowed” further into the schema, with a keyword of schema composition. As such, it would simply be removed from the intermediate structure, preventing its generation or further unnecessary parsing; - this kind of organization makes it easy to update the structure for each new keyword parsed and facilitates the translation exercise executed later on. With this, the translation program will need only to choose a random type and parse the keywords associated with that type, ignoring all others. It is efficient and compact. However, not all keywords are related strictly to a single type. Generic and schema composition keywords, as defined previously, plus if/then/else (that apply subschemas conditionally), may take values or subschemas of multiple types. In these cases, the grammar follows the ensuing method: firstly, it makes sure each of the keyword’s values has a single type. For generic keywords, this is already the case, as its values are already the final product. However, the values of the other keywords mentioned are subschemas, which may be multi-type: if so, the grammar breaks down the subschema into smaller subschemas, one per each of its types. Then, it separates the keyword’s values by type and introduces one instance of said keyword in each of its generateable data types, in the intermediate structure, along with that type’s respective values. An example of this is shown below: ![Figure 3 Example of parsing done on a schema composition keyword.](image) With this algorithm, the program is able to classify these keywords and, by extension, all JSON Schema keywords by type, which makes it possible to use the described data structure to store all relevant data, in a way designed to facilitate and make more efficient the following translator program’s routine. In conclusion, the main objective of the grammar, and consequent parser, was to reproduce the JSON Schema syntax meticulously and collect data from any given schema to a well thought-out and efficient data structure, to set up the next phase of the process - the construction of the DSL model. Furthermore, it was also to make the solution as sturdy and fault-tolerant as possible, preventing it from trying to parse impossible schemas and crashing or producing unexpected behaviour, which in turn helps the user understand their schema better and detect unwilling errors. 4.2 Referencing JSON Schema references can vary a lot: there are absolute and relative references, depending on if they include the schema’s base URI. It is not mandatory for a schema to have an id, which is its URI-reference, but without one, it is unable to be referenced by other schemas, although it can still have local references. Furthermore, a subschema may be referenced either by JSON pointer, which describes a slash-separated path to traverse the keys of the objects in the document, or by anchor, using the keyword $anchor to create a named anchor in the subschema to be referenced. The reader is invited to check out the official documentation on schema structuring, in order to gain a more in-depth understanding of schema identification and referencing, which is crucial for this component of the solution. DataGen From Schemas supports all types of referencing defined in JSON Schema 2020-12 and standardizes that any schema’s base URI must begin with https://datagen.di.uminho.pt/json-schemas/ and be followed by the schema’s name. Besides the configuration exposed in the previous subsection, the intermediate data structure has two additional sections: one for storing the object pointers to all references found in the schema, and another for separately storing all subschemas with their own declared identifier. This division is useful to resolve all references later on, after the parser has finished analyzing every schema submitted by the user. The program is unable to resolve references as it is reading the schemas, since they might be pointing to schemas or subschemas that have yet to be reached. For the sake of consistency and efficiency, instead of checking if that is the case whenever a new reference is found, the parser simply caches the references and subschemas, in a way that it is ultimately able to quickly find each referenced subschema and substitute its content in the main body. Thereby, it becomes possible to generate datasets from schemas with local and/or external references, as well as more intricate mechanisms, such as recursion and bundling. 4.3 Creating the DSL model Once the intermediate structure of the main schema is finalized and all references resolved, it is then sent to the translator program to begin creating the correspondent DSL model. This component interprets the keywords present on the structure and generates an according DSL string, taking into account how they influence each other. For the sake of brevity, the keywords will not be explained minutely in this paper, so it is strongly recommended to follow along this subsection with the official JSON Schema documentation, as it thoroughly details the function of every keyword, illustrated with meaningful and intuitive examples. The intermediate structure is type-oriented, meaning that each value of the schema is described by a JavaScript object that maps each of its createable data types to their respective keywords, and values are organized in a hierarchical structure. To produce the model for the whole schema, the program recursively iterates this intermediate structure, generating its values’ DSL strings from the leaves to the root and joining them together. The types present in the structure of each value already reflect the whole logic of its schema, since the parser relates the keywords and determines the generateable data types common to all of them, as described in subsection 4.1. Take the following example, illustrated below: even though the keyword `type` defines that the instance may be either a string or a number, the keyword `allOf` implies that only a number is valid, since all its subschemas are only of that type. As such, the section of the intermediate data structure that describes this value will not have the string type: ``` [ "type": ["string", "number"], "maxLength": 10, "maximum": 90, "allOf": [ { "type": "number", "multipleOf": 3, }, { "type": "number", "multipleOf": 5 } ] ] ``` ![Figure 4](Image.png) Example of parsing done on a apparent multi-type schema. The program then randomly selects one of the generateable types and moves on to translating its keywords. The first step is to resolve any keywords of schema composition or conditional application of subschemas that there may be - these keywords are not directly translated to the DSL string, but rather parsed and its contents added to the structure. In JSON Schema, the aforementioned keywords are not used to extend or merge schemas, in the sense of object-oriented inheritance. Instead, instances must independently validate against each of the keywords. This is understandable when validating instances against schemas, which is the purpose of JSON Schema. However, DataGen From Schemas reverses this workflow and looks to create instances from schemas, so the same logic does not apply. It is not possible to generate a different value for each of these keywords and ultimately merge the values together. This method would result in values valid against individual parts of the schema, but possibly not the whole of it. As such, in the context of data generation, it is necessary to parse these “compound” keywords beforehand and extend the base schema with their content, obtaining a cohesive and coherent final schema, with only type-specific keywords, that incorporates the restraints specified in these keywords. Since these “compound” keywords’ values are or contain schemas, which may, in turn, have nested such keywords, the program recursively checks all subschemas for these keywords and resolves them, before using these subschemas in the extension process, so that ultimately the base schema is extended only with type-specific keywords. ### 4.3.1 Schema composition keywords There are four keywords belonging to this category: `allOf`, `anyOf`, and `oneOf` allow the user to define an array of subschemas, against all, one or more, or exclusively one of which the data must be valid, respectively; `not` declares that an instance must not be valid against the given subschema. For the first three, a subset of their values’ schemas is chosen: with `allOf`, all of its schemas are considered; for `anyOf` and `oneOf`, either an arbitrary number of its schemas or only one of them, respectively, are randomly selected. The base schema is then extended with these, sequentially, and the original keywords are erased from the structure. As for `not`, the program must first “invert” this keyword’s schema, in order to obtain a complementary/opposite schema, which ensures that no value that is valid against it, also validates against the original schema. Then, the base schema is extended with this inverted schema and the keyword `not` is removed from the structure. For this purpose, a schema inverter capable of generating complementary schemas was developed, which takes into account the meaning of each JSON Schema type-specific keyword. There is never a need to invert any other kind of keyword, since those are parsed recursively before the actual schema to which they belong (as was described in subsection 4.3), which guarantees that the schema to be inverted will only have type-specific keywords. On the same note, the solution also incorporates a schema extender program to manually and sequentially extend a base schema with each type-specific keyword of others. For each data type, the new keyword is compared to the already existing ones and incorporated in a reasonable way - the result may be different depending on whether the base schema already has the same keyword or not, for example. This solution must handle each individual JSON Schema keyword differently, as they all have different meanings. Due to its complexity, the functionality of these two components will not be addressed in detail in this document. The reader can find their explanation in another more substantial and exhaustive academic paper on the entirety of DataGen From Schemas that will be published in the near future. 4.3.2 Keywords that apply subschemas conditionally These keywords are the reason for JSON Schema’s dynamic semantics, i.e. their meaning can only be uncovered after the context has actually been instantiated, since these keywords establish conditions based on actual values of the instance. Take the following example: ``` { "type": "object", "properties": { "street_address": { "type": "string" }, "country": { "default": "United States of America", "enum": ["United States of America", "Canada"] } } } if { "properties": { "country": { "const": "United States of America" } } } then { "properties": { "postal_code": { "pattern": "[0-9][0-9][A-Z]" } } } else { "properties": { "postal_code": { "pattern": "[A-Z][0-9][A-Z][0-9][0-9]" } } } ``` Figure 5 Example of a schema with dynamic semantics. In this case, the schema will only know what schema to validate the property 'postal_code' with after checking the actual instance for the value of the property 'country', and never before. While with other keywords, the schema can determine a priori the structure of the instance, with these it is not possible to do so. Once again, this approach is not reasonable for a solution such as DataGen From Schemas, since it is not viable to generate an intermediate value from the rest of the schema and only then exert these keywords, which may imply large changes to the remaining schema - at least with if, then, and else. Since the keywords dependentRequired and dependentSchemas are specific to the object data type, it is possible to incorporate them into the translation procedure of object schemas, as will be detailed ahead in subsection 4.4.3. The solution found for the keywords if, then, and else was to determine their outcome probabilistically - unless the if schema is explicitly true or false, in which case it is deterministic whether the instance should be validated with either then or else, respectively. Otherwise, the program determines the veracity of the condition based on a probability, customizable by the user (by default, a 50/50% chance) - if true, the base schema is extended with the if and then schemas, otherwise it is extended with a complementary schema of if (produced with the aforementioned schema inverter) and the schema of else. This way, it is possible to produce a coherent, simpler schema that incorporates the logic of these conditional keywords and to generate the final instance in a single iteration. 4.4 Translating the intermediate structure Finally, once the intermediate structure of the selected data type is finalized and possesses only type-oriented keywords and/or const and enum, the program is able to generate a DSL string that translates the logic of the original schema. In this subsection, it will be carefully detailed the method behind translating each type of value. The first step is to check if the intended value must belong to a fixed set of values, i.e. the usage of any of the keywords const or enum, which, at this point, already reflect the absence of any values unallowed with not. If any of these are present, the remaining keywords are ignored and the DSL string is generated from these alone. In case of both keywords, const takes precedence over enum, as it defines that the value is constant and immutable. The output DSL string produced from these keywords is a random choice from all of their respective values (typically, const will map to a single value, but if the user composes multiple instances of this keyword in the same schema, it will be treated as an alternative between several). If no fixed set of values is defined, the solution goes on to actually translate the type’s- oriented keywords. Data types null and boolean are basic, since they possess no specific keywords. These and the previously addressed keywords are translated as follows: ![Figure 6 Translation of the keywords enum and const.] 4.4.1 String type The string type only has four different keywords: pattern, format, and minLength/maxLength. Only in this case, it was decided that there would be an order of precedence to these keywords since, realistically speaking, they would very rarely be used together (except for both length keywords): for example, it does not make much sense to define a string value according to a regular expression or format and then further constrain its length, as the former keywords already establish a very rigid template. As such, if the schema has the keyword pattern, that will be the one to be translated, followed by format and, finally, the length keywords. While pattern and length keywords translate directly to one of DataGen’s interpolation functions, format is more contrived, since there is a need to program a different DSL string for each format, to generate an according value, some of which map directly to existing interpolation functions and others that do not. Below are presented some examples of the models generated from this data type’s keywords: 4.4.2 Numeric types As for numeric types, there are five applicable keywords: `multipleOf`, `minimum`, `exclusiveMinimum`, `maximum`, and `exclusiveMaximum`. The constraints on numeric types can get a lot more complicated if the user specifies, via schema composition keywords, that the value must be a multiple of several numbers simultaneously and/or not a multiple of one or more values. Let’s first consider simpler cases where the `not` keyword is not used. If the instance must be a multiple of one or more values, the program starts by calculating the least common multiple (LCM) of all these numbers. This way, it is possible to consider a single value for the multiplicity of the instance, since the LCM and its multiples are the easiest way to obtain any number simultaneously multiple of the original values. If the type in question is an integer, this is also taken into account before determining the LCM, by considering that the instance must also be a multiple of 1. Next, the range keywords are evaluated, if present. The program determines the biggest and smallest integers that it is possible to multiply by the LCM (or 1, if no `multipleOf` constraint exists), in order to obtain values that belong to the intended range. This is doable by rounding down the result of the division of the upper bound by the LCM and rounding up the result of the division of the lower bound by the LCM, respectively. If the schema only has either an upper or lower range boundary, the other one is offset by 100 units to provide comfortable margin for generateable values. At this point, there are three different possible outcomes, detailed next and further illustrated in the image below: - if only the type is specified and nothing else, the program simply generates a DSL string for a random integer or float, accordingly; - if no range keys are used (the only type-specific is `multipleOf`), the DSL’s interpolation function with the same name is used to generate a multiple of the LCM; - if both range and multiplicity constraints are present, the value is calculated by randomly choosing an integer between the predetermined bounds and multiplying it by the LCM. However, the negation of the keyword `multipleOf` makes these use cases a lot more contrived, since there is the necessity to further restrict the set of producable values. As such, the DSL string produced in such occasion is different for all the alternatives above. Only one variant will be explained, since the same logic applies across all others: As seen in the preceding image, the schema has impositions on the range of the value, as well as what it must and must not be a multiple of. This translates to the DSL via a JavaScript anonym function, where DataGen first calculates all valid multiples in the designated range and stores them in an array, then removing all elements that are multiples of unallowed numbers. The final value is selected randomly from the alternatives with the interpolation function `random`, however the program firstly does a safety check to ensure that the final array is not empty: if that is not the case, then its impossible to produce a value that obeys all restrictions specified in the schema, so it simply selects a regular multiple in the range from the first array. 4.4.3 Object type The set of type-specific keywords for objects is `properties` and `patternProperties`, to specify property schemas according to their key, `additionalProperties` and `unevaluatedProperties`, for unspecified properties, `required`, to make properties mandatory, `propertyNames`, to validate the properties’ keys, and finally size keywords (`minProperties` and `maxProperties`). DataGen From Schemas also treats `dependentRequired` (used to require properties based on the presence of others) and `dependentSchemas` (to apply subschemas if certain properties exist) as object-specific keywords - for every new property selected for the final instance, the solution also checks these keywords for dependencies. In case of the former, if any properties are dependent on the newest property, these are also translated and added to the object. As for the latter, if there is a subschema dependent on the latest property, it is parsed and used to extend the current object schema. This verification is executed for every property produced along the pipeline, required or not. For this type, the instance’s model is firstly delineated in an intermediate object, mapping each key to the DSL string of their respective value, in order to manage more easily all the different properties that may be produced. Only after determining all properties does the program produce a DSL string for the whole object, from this second intermediate structure. The first operation executed by the program is determining a random size for the final object, taking into account all relevant factors such as `minProperties` and `maxProperties`, `required` properties and the permission or not of unspecified properties (`additionalProperties`, `unevaluatedProperties`). The calculated size will always necessarily allow room for at least the required properties, and if only the object type is specified and no other keywords are used, the program will generate an object with between 0 and 3 properties, where both the key and value are random. Then, DataGen From Schemas iterates the required properties and generates an according DSL string for each of their value’s schema, storing the pair in the intermediate object structure. Once the required properties have been produced, the solution executes the following pipeline sequentially, until it reaches the designated size for the final instance: - iterates the non-required properties sequentially, producing the DSL strings of their respective values and storing the pairs in the intermediate object; - iterates the value of the keyword patternProperties - for each pair, there is a probability (customizable by the user) to produce, at most, one according instance property, where the name of the property is obtained through a regular expression value generator; - if additional properties are not allowed or not explicitly mentioned in the schema, the intermediate structure is considered finalized with the properties it currently has. Do note the mention of explicitly allowing additional properties - if neither of the keywords additionalProperties and unevaluatedProperties are specified, then the user most likely wants an instance with only the properties covered by the keywords properties and patternProperties - as such, it would not make much sense to generate other random properties, just because it is not explicitly disallowed; - if the schema specifies additional properties, additionalProperties has precedence over unevaluatedProperties, so if both keywords are specified, additionalProperties’s schema prevails, else it is the only used keyword’s. The program translates this schema into a DSL string and generates random names for the properties keys, either according to the propertyNames schema, if present, or by generating small chunks of lorem ipsum. Having finalized the intermediate object with each property’s DSL string, these properties are all joined in a string encased by curly braces, in the syntax of a regular JavaScript object that DataGen is able to parse and then generate the according dataset. ![Figure 10](translation_of_an_object_type_schema.png) | 4.4.4 Array type | There are several keywords for this data type: items and prefixItems, the main way to evaluate items, additionalItems and unevaluatedItems, for others that do not validate against former keywords, contains, minContains, and maxContains, for inclusion of items with certain schemas, and finally length keywords (minItems, maxItems) and uniqueItems, to determine the uniqueness of items in the instance. For this data type, the program creates an intermediate array structure firstly, in order to maleably plot the intended array, and only at the end converts it to a DSL string. The solution keeps track, at all times, of the allowed number of items, which can be established with minItems and maxItems. If the maximum amount of items is ever reached (and also never before the minimum is attained), the program stops the execution of the pipeline that will be described ahead and produces the DSL string from the intermediate array as is. The first step of the algorithm is to check for prefixed items in the schema: if any were specified, the program sequentially generates their respective values’ DSL strings and pushes these to the intermediate array, in order. Then, DataGen From Schemas parses the inclusion keywords. In the workflow of this solution, these keywords effectively have a dynamic semantic, since it is impossible to validate the array for the inclusion of elements with the specified schema before generating it, even in the DSL model. As such, a compromise was needed to adapt these keywords: after parsing the prefixed items, if more items are allowed in the array, then the solution with push the necessary amount of new elements with the structure of the `contains` schema (one if `minContains` and `maxContains` are not used, otherwise a random number in the indicated range). Note that if the intent of the user is for the values validated against the inclusion keys to be some of the prefixed items, then the program cannot guarantee this. Once all the “hard-coded” elements are in the intermediate array, the program then checks for other items. The keyword `additionalItems` has precedence over `unevaluatedItems`, so if additional items are allowed and both keywords are specified, `additionalItems`'s schema is considered, otherwise it is the only specified keyword’s. If the user also disallowed any instance of the keyword `contains`, their schemas are inverted (using the schema inverter mentioned in 4.3.1) and used to extend the schema for additional items, in order to guarantee that all additional items wholly conform to the user’s configuration. This final schema is used to sequentially generate a random amount of additional items’ DSL strings, within the intended range for the array, which are appended to the intermediate structure. Finally, DataGen From Schemas checks if all these items must be unique or not (`uniqueItems`). This keyword, as is the case with the inclusion keys, demands a compromise and an intelligent workaround, since it is impossible to check for the items’ uniqueness before generating them, and is the reason that warrants the usage of an intermediate array to store the DSL strings of each element, instead of simply building a single string and appending each item to it. As such, depending on the value of this keyword, two different types of DSL strings for the final array may be created: - **not unique items** – if either the keyword is not specified or its value is false, then the procedure is to simply create a string of an array, where its elements are the DSL strings stored in the intermediate array structure maintained along this pipeline. DataGen can interpret this syntax and generate all elements according to their respective model; ![Figure 11 Translation of an array type schema with non-unique items.](image) - **unique items** – in this case, a DataGen anonym function is used to implement an algorithm that attempts to generate an array where all elements are different. As can be observed below, the procedure is the following: whenever DataGen creates the next item, it checks if the array already contains the new value. If not, it pushes the element to the array and moves on to the next one. Else, it generates the same item again (which can produce a different result, since the DSL strings accommodate margin for randomness), for a maximum of 10 tries per item. In case none of them produces a new value, the value of the latest try is pushed to the array anyway, to prevent crashing the program, and the resulting array ends up not obeying the `uniqueItems` restriction. As a by-product of this algorithm, another compromise arises: DataGen From Schemas can only attempt to generate arrays with unique items if all items are elementary, i.e. neither objects nor arrays. This is the case because DSL strings for complex values are bigger, more convoluted and impossible to incorporate in a DataGen function syntax, in the same way a basic interpolation or anonym function can. To summarize, DataGen From Schemas is not the best tool to adapt the keyword `uniqueItems` in specific, due to its ill-suitability to the workflow and DataGen’s DSL, however it is still possible to satisfy some use cases. 5 Conclusion The main contributions of this paper are the design of a synthetic data generator from JSON schemas and its implementation, which culminate in DataGen From Schemas - a quick and sturdy solution built upon DataGen that effectively greatly expands the base application’s functionality and makes it more accessible to any user, by allowing their input to be in a vastly popular and utilized vocabulary, JSON Schema, and automating the creation of DataGen’s DSL model. With this software, it becomes possible to very quickly specify a dataset and generate several different instances of it, given that the program randomizes its values with each attempt, as well as further customizing its requirements directly in DataGen, via the provided intermediate DSL model, with support from custom datasets and other tools provided by the base application, which is not possible to do in JSON Schema’s syntax. DataGen From Schemas has been experimented with real-life cases and convoluted schemas that use mechanisms such as bundling or recursion, and proves to be an adequate solution, capable of interpreting the schemas it is given and generating representative datasets accordingly. The product will soon be put in a production environment and made available for the general public, as a free and open-source application, after an arduous yet successful development phase. References 5:16 Synthetic Data Generation from JSON Schemas
{"Source-Url": "https://drops.dagstuhl.de/opus/volltexte/2022/16751/pdf/OASIcs-SLATE-2022-5.pdf", "len_cl100k_base": 9466, "olmocr-version": "0.1.48", "pdf-total-pages": 16, "total-fallback-pages": 0, "total-input-tokens": 36612, "total-output-tokens": 11034, "length": "2e13", "weborganizer": {"__label__adult": 0.00029659271240234375, "__label__art_design": 0.0003535747528076172, "__label__crime_law": 0.0002925395965576172, "__label__education_jobs": 0.0005555152893066406, "__label__entertainment": 6.121397018432617e-05, "__label__fashion_beauty": 0.00013780593872070312, "__label__finance_business": 0.00019466876983642575, "__label__food_dining": 0.0002751350402832031, "__label__games": 0.0004208087921142578, "__label__hardware": 0.0006885528564453125, "__label__health": 0.00039839744567871094, "__label__history": 0.00020372867584228516, "__label__home_hobbies": 7.653236389160156e-05, "__label__industrial": 0.0003197193145751953, "__label__literature": 0.00022685527801513672, "__label__politics": 0.00019478797912597656, "__label__religion": 0.00038051605224609375, "__label__science_tech": 0.0278778076171875, "__label__social_life": 7.939338684082031e-05, "__label__software": 0.0099029541015625, "__label__software_dev": 0.95654296875, "__label__sports_fitness": 0.00019049644470214844, "__label__transportation": 0.0003204345703125, "__label__travel": 0.00015592575073242188}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 50520, 0.01428]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 50520, 0.36573]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 50520, 0.89439]], "google_gemma-3-12b-it_contains_pii": [[0, 3526, false], [3526, 7460, null], [7460, 10111, null], [10111, 13121, null], [13121, 16727, null], [16727, 20167, null], [20167, 23949, null], [23949, 27555, null], [27555, 30871, null], [30871, 33817, null], [33817, 35992, null], [35992, 39146, null], [39146, 42443, null], [42443, 45856, null], [45856, 48436, null], [48436, 50520, null]], "google_gemma-3-12b-it_is_public_document": [[0, 3526, true], [3526, 7460, null], [7460, 10111, null], [10111, 13121, null], [13121, 16727, null], [16727, 20167, null], [20167, 23949, null], [23949, 27555, null], [27555, 30871, null], [30871, 33817, null], [33817, 35992, null], [35992, 39146, null], [39146, 42443, null], [42443, 45856, null], [45856, 48436, null], [48436, 50520, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 50520, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 50520, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 50520, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 50520, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 50520, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 50520, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 50520, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 50520, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 50520, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 50520, null]], "pdf_page_numbers": [[0, 3526, 1], [3526, 7460, 2], [7460, 10111, 3], [10111, 13121, 4], [13121, 16727, 5], [16727, 20167, 6], [20167, 23949, 7], [23949, 27555, 8], [27555, 30871, 9], [30871, 33817, 10], [33817, 35992, 11], [35992, 39146, 12], [39146, 42443, 13], [42443, 45856, 14], [45856, 48436, 15], [48436, 50520, 16]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 50520, 0.00431]]}
olmocr_science_pdfs
2024-11-25
2024-11-25
3b0f321cb88935aa21774acb50471dd7ef220b9e
2. Application Layer Chapter 2: Application Layer application transport network link physical Chapter 2: Application Layer Our Goal: • Conceptual, implementation aspects of network application protocols • Transport-layer service models • Client-server paradigm • Peer-to-peer paradigm • Content distribution networks • Learn about protocols by examining popular application-level protocols • HTTP • SMTP / POP3 / IMAP • DNS • Creating network applications • socket API Chapter 2: Outline - Principles of network applications - Socket Programming with UDP and TCP - Web and HTTP - Electronic Mail (SMTP, POP3, IMAP) - DNS - P2P Applications - Video Streaming and Content Distribution Networks Creating a network app Write programs that: • run on (different) *end systems* • communicate over network • e.g., web server software communicates with browser software No need to write software for network-core devices • network-core devices do not run user applications • applications on end systems allows for rapid app development, propagation Application architectures Possible structure of applications: • Client-server • Peer-to-peer (P2P) • Hybrid Client-server architecture **server:** always-on host - permanent IP address - data centers for scaling **clients:** - communicate with server - may be intermittently connected - may have dynamic IP addresses - do not communicate directly with each other P2P architecture • *no* always-on server • arbitrary end systems directly communicate • peers request service from other peers, provide service in return to other peers • *self scalability* – new peers bring new service capacity, as well as new service demands P2P architecture • *no* always-on server • arbitrary end systems directly communicate • peers request service from other peers, provide service in return to other peers • *self scalability* – new peers bring new service capacity, as well as new service demands P2P architecture • *no* always-on server • arbitrary end systems directly communicate • peers request service from other peers, provide service in return to other peers • *self scalability* – new peers bring new service capacity, as well as new service demands • Peers are intermittently connected and change IP addresses • *Complex Management* Hybrid of client-server and P2P Skype - Internet telephony app - Finding address of remote party: centralized server(s) - Client-client connection is direct (not through server) Instant messaging - Chatting between two users is P2P - Presence detection/location centralized: - User registers its IP address with central server when it comes online - User contacts central server to find IP addresses of buddies Case Study: Napster Vs Gnutella Any problem with this architecture? Processes communicating **process:** program running within a host - within same host, two processes communicate using inter-process communication (defined by OS) - processes in different hosts communicate by exchanging messages **clients, servers** **client process:** process that initiates communication **server process:** process that waits to be contacted aside: same process can be both a client and a server for different connections; e.g., in P2P networks Sockets - process sends/receives messages to/from its **socket** - socket analogous to mailbox - App A puts message in mailbox/socket - App A relies on transport infrastructure to pick up message from A’s socket/mailbox and deliver it to B’s socket Addressing processes • to receive messages, process must have *identifier* • host device has unique 32-bit IP address • **Q:** does IP address of host on which process runs suffice for identifying the process? ▪ **A:** no, *many* processes can be running on same host • *identifier* includes both IP address and port numbers associated with process on host. • example port numbers: • HTTP server: 80 • mail server: 25 • to send HTTP message to gaia.cs.umass.edu web server: • IP address: 128.119.245.12 • port number: 80 • more shortly... App-layer protocol defines - types of messages exchanged, - e.g., request, response - message syntax: - what fields in messages & how fields are delineated - message semantics - meaning of information in fields - rules for when and how processes send & respond to messages open protocols: - defined in RFCs - allows for interoperability - e.g., HTTP, SMTP proprietary protocols: - e.g., Skype What transport service does an app need? **Data loss** - some apps (e.g., file transfer, web transactions) require 100% reliable data transfer - other apps (e.g., audio) can tolerate some loss **Timing** - some apps (e.g., Internet telephony, interactive games) require low delay to be “effective” **Throughput** - some apps (e.g., multimedia) require minimum amount of throughput to be “effective” - other apps (“elastic apps”) make use of whatever throughput they get Why is bandwidth different from timing constraints? ## Transport service requirements: common apps <table> <thead> <tr> <th>application</th> <th>data loss</th> <th>throughput</th> <th>time sensitive</th> </tr> </thead> <tbody> <tr> <td>file transfer</td> <td></td> <td></td> <td></td> </tr> <tr> <td>e-mail</td> <td></td> <td></td> <td></td> </tr> <tr> <td>Web documents</td> <td></td> <td></td> <td></td> </tr> <tr> <td>real-time audio/video</td> <td></td> <td></td> <td></td> </tr> <tr> <td>stored audio/video</td> <td></td> <td></td> <td></td> </tr> <tr> <td>interactive games</td> <td></td> <td></td> <td></td> </tr> <tr> <td>text messaging</td> <td></td> <td></td> <td></td> </tr> </tbody> </table> ## Transport service requirements: common apps <table> <thead> <tr> <th>application</th> <th>data loss</th> <th>throughput</th> <th>time sensitive</th> </tr> </thead> <tbody> <tr> <td>file transfer</td> <td>no loss</td> <td>elastic</td> <td>no</td> </tr> <tr> <td>e-mail</td> <td>no loss</td> <td>elastic</td> <td>no</td> </tr> <tr> <td>Web documents</td> <td>no loss</td> <td>elastic</td> <td>no</td> </tr> <tr> <td>real-time audio/video</td> <td>loss-tolerant</td> <td>audio: 5kbps-1Mbps, video:10kbps-5Mbps</td> <td>yes, 100’s msec, yes, few secs</td> </tr> <tr> <td>stored audio/video</td> <td>loss-tolerant</td> <td>same as above</td> <td>yes, 100’s ms</td> </tr> <tr> <td>interactive games</td> <td>loss-tolerant</td> <td>few kbps up</td> <td>yes and no</td> </tr> <tr> <td>text messaging</td> <td>no loss</td> <td>elastic</td> <td>no</td> </tr> </tbody> </table> Internet transport protocols services TCP service: - **reliable transport** between sending and receiving process - **flow control**: sender won’t overwhelm receiver - **congestion control**: throttle sender when network overloaded - **does not provide**: timing, minimum throughput guarantee, security - **connection-oriented**: setup required between client and server processes UDP service: - **unreliable data transfer** between sending and receiving process - **does not provide**: reliability, flow control, congestion control, timing, throughput guarantee, security, or connection setup, **Q**: why bother? Why is there a UDP? **Internet apps: application, transport protocols** <table> <thead> <tr> <th>application</th> <th>application layer protocol</th> <th>underlying transport protocol</th> </tr> </thead> <tbody> <tr> <td>e-mail</td> <td>SMTP [RFC 2821]</td> <td></td> </tr> <tr> <td>remote terminal access</td> <td>Telnet [RFC 854], SSH</td> <td></td> </tr> <tr> <td>Web</td> <td>HTTP [RFC 2616]</td> <td></td> </tr> <tr> <td>file transfer</td> <td>FTP [RFC 959]</td> <td></td> </tr> <tr> <td>streaming multimedia</td> <td>HTTP (e.g., YouTube), RTP [RFC 1889]</td> <td></td> </tr> <tr> <td>Internet telephony</td> <td>SIP, RTP, proprietary (e.g., Skype)</td> <td></td> </tr> <tr> <td>naming</td> <td>DNS</td> <td></td> </tr> </tbody> </table> Chapter 2: Outline ✓ Principles of network applications ❑ Socket Programming with UDP and TCP ❑ Web and HTTP ❑ Electronic Mail (SMTP, POP3, IMAP) ❑ DNS ❑ P2P Applications ❑ Video Streaming and Content Distribution Networks Socket programming **goal:** learn how to build client/server applications that communicate using sockets **socket:** door between application process and end-to-end transport protocol Two socket types for two transport services: - **UDP**: unreliable datagram (User Datagram Protocol) - **TCP**: reliable, byte stream-oriented (Transmission Control Protocol) Application Example: 1. client reads a line of characters (data) from its keyboard and sends data to server 2. server receives the data and converts characters to uppercase 3. server sends modified data to client 4. client receives modified data and displays line on its screen Socket programming *with UDP* UDP: no “connection” between client & server - no handshaking before sending data - sender explicitly attaches IP destination address and port # to each packet - receiver extracts sender IP address and port# from received packet UDP: transmitted data may be lost or received out-of-order Application viewpoint: - UDP provides *unreliable* transfer of groups of bytes (“datagrams”) between client and server Client/server socket interaction: UDP **server (running on serverIP)** create socket, port= x: serverSocket = socket(AF_INET,SOCK_DGRAM) read datagram from serverSocket write reply to serverSocket specifying client address, port number **client** create socket: clientSocket = socket(AF_INET,SOCK_DGRAM) Create datagram with server IP and port=x; send datagram via clientSocket read datagram from clientSocket specifying client address, port number close clientSocket Example app: UDP client C UDPClient ```c #include<sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <netdb.h> serverPort = 12000 clientSocket = socket(AF_INET, SOCK_DGRAM, 0) sendto(clientSocket, message, msg_length, dest_info, dest_info_len); close (clientSocket) ``` Port to create at the client create an endpoint for communication (socket file descriptor) Send message to server Include C's socket headers Server's information Close socket Example app: UDP server **C UDP Server** ```c #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <netdb.h> serverPort = 12000 serverSocket = socket(AF_INET, SOCK_DGRAM, 0) bind(serverSocket, own_addr_info, addr_len) while (1) { numbytes = recvfrom(serverSocket, buf, buf_len, 0, (struct sockaddr *)&their_addr, &addr_len) print buf } ``` local port number 12000 ➔ serverPort = 12000 create UDP socket FD ➔ serverSocket = socket(AF_INET, SOCK_DGRAM, 0) Bind to the socket FD ➔ bind(serverSocket, own_addr_info, addr_len) Read from UDP socket into buf, getting client’s address (client IP and port) ➔ numbytes = recvfrom(serverSocket, buf, buf_len, 0, (struct sockaddr *)&their_addr, &addr_len) print buf ➔ Who did we receive message from? Socket programming with TCP client must contact server • server process must first be running • server must have created socket (door) that welcomes client’s contact client contacts server by: • Creating TCP socket, specifying IP address, port number of server process • when client creates socket: client TCP establishes connection to server TCP • when contacted by client, server TCP creates new socket for server process to communicate with that particular client • allows server to talk with multiple clients • source port numbers used to distinguish clients (more in Chap 3) application viewpoint: TCP provides reliable, in-order byte-stream transfer ("pipe") between client and server Client/server socket interaction: TCP server (running on hostid) client create socket, port=x, for incoming request: serverSocket = socket() wait for incoming connection request connectionSocket = serverSocket.accept() TCP connection setup read request from connectionSocket write reply to connectionSocket close connectionSocket create socket, connect to hostid, port=x clientSocket = socket() send request using clientSocket read reply from clientSocket close clientSocket Example app: TCP client C TCP Client #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <netdb.h> #include <arpa/inet.h> serverName = 'servername' serverPort = 12000 clientSocket = socket(AF_INET, SOCK_STREAM, 0) connect(clientSocket, server_info, server_info_len)) numbytes = recv(clientSocket, buf, buf_size, 0) close(clientSocket) Example app: TCP server C TCP Server ```c #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <netdb.h> #include <arpa/inet.h> serverPort = 12000 serverSocket = socket(AF_INET, SOCK_STREAM, 0) bind(serverSocket, serverAddr, serverAddr_len) listen(serverSocket, queueSize) while 1 { new_fd = accept(serverSocket, theirAddr, theirAddr_len) send(new_fd, "Hello, world!", 13, 0) close(new_fd); } close(serverSocket) ``` Some Details Communication with diverse systems Utility function for address and service translation ``` int getaddrinfo(const char *node, const char *service, const struct addrinfo *hints, struct addrinfo **res); ``` Utility functions for byte-ordering ``` uint32_t htonl(uint32_t hostlong); uint16_t htons(uint16_t hostshort); uint32_t ntohl(uint32_t netlong); uint16_t ntohs(uint16_t netshort); ``` Networks use big-endian byte ordering Little endian Big endian Utility functions for converting IPv4 and IPv6 addresses from binary to text form ``` const char *inet_ntop(int af, const void *src, char *dst, socklen_t size); ``` Chapter 2: Outline - Principles of network applications - Socket Programming with UDP and TCP - Web and HTTP - Electronic Mail (SMTP, POP3, IMAP) - DNS - P2P Applications - Video Streaming and Content Distribution Networks First, a review... - **web page** consists of *objects* - object can be HTML file, JPEG image, Java applet, audio file,... - web page consists of *base HTML-file* which includes *several referenced objects* - each object is addressable by a *URL*, e.g., ``` www.someschool.edu/someDept(pic.gif) ``` *host name* *path name* HTTP overview HTTP: hypertext transfer protocol • Web’s application layer protocol • client/server model • client: browser that requests, receives, (using HTTP protocol) and “displays” Web objects • server: Web server sends (using HTTP protocol) objects in response to requests HTTP overview *Uses TCP:* - client initiates TCP connection (creates socket) to server, port 80 - server accepts TCP connection from client - HTTP messages (application-layer protocol messages) exchanged between browser (HTTP client) and Web server (HTTP server) - TCP connection closed *HTTP is “stateless”* - server maintains no information about past client requests Aside protocols that maintain “state” are complex! - past history (state) must be maintained - if server/client crashes, their views of “state” may be inconsistent, must be reconciled HTTP connections **non-persistent HTTP** - at most one object sent over TCP connection - connection then closed - downloading multiple objects required multiple connections **persistent HTTP** - multiple objects can be sent over single TCP connection between client, server Non-persistent HTTP suppose user enters URL: www.someSchool.edu/someDepartment/home.index 1a. HTTP client initiates TCP connection to HTTP server (process) at www.someSchool.edu on port 80 1b. HTTP server at host www.someSchool.edu waiting for TCP connection at port 80. “accepts” connection, notifying client 2. HTTP client sends HTTP request message (containing URL) into TCP connection socket. Message indicates that client wants object someDepartment/home.index 3. HTTP server receives request message, forms response message containing requested object, and sends message into its socket 4. HTTP server closes TCP connection. 5. HTTP client receives response message containing html file, displays html. Parsing html file, finds 10 referenced jpeg objects 6. Steps 1-5 repeated for each of 10 jpeg objects Non-persistent HTTP: response time RTT (Round Trip Time): time for a small packet to travel from client to server and back HTTP response time: - one RTT to initiate TCP connection - one RTT for HTTP request and first few bytes of HTTP response to return - file transmission time - non-persistent HTTP response time = 2RTT + file transmission time Persistent HTTP Persistent HTTP: • server leaves connection open after sending response • subsequent HTTP messages between same client/server sent over open connection • client sends requests as soon as it encounters a referenced object • as little as one RTT for all the referenced objects Other optimizations • Pipelining • Send several requests at once ![Diagram showing pipelining with time and RTT labels] - initiate TCP connection - RTT - request file - RTT - request new files Other optimizations • Pipelining • Send several requests at once • HTTP/2 • Push resources Other optimizations • Pipelining • Send several requests at once • HTTP/2 • Push resources • QUIC • Eliminate first RTT - initiate QUIC connection - request file RTT send file push objects time time HTTP request message - two types of HTTP messages: request, response - HTTP request message: - ASCII (human-readable format) ``` GET /index.html HTTP/1.1\r\nHost: www-net.cs.umass.edu\r\nUser-Agent: Firefox/3.6.10\r\nAccept: text/html,application/xhtml+xml\r Accept-Language: en-us,en;q=0.5\r\nAccept-Encoding: gzip,deflate\r\nAccept-Charset: ISO-8859-1,utf-8;q=0.7\r\nKeep-Alive: 115\r\nConnection: keep-alive\r\n\r ``` carriers return, carriage return character line feed at start line-feed character de of line indicates e of header lines HTTP request message: general format - **Request line** - method - URL - version - **Header lines** - header field name - value - **Entity body** Uploading form input **POST method:** - web page often includes form input - input is uploaded to server in entity body **URL method:** - uses GET method - input is uploaded in URL field of request line: www.somesite.com/animalsearch?monkeys&banana Method types HTTP/1.0: - GET - POST - HEAD - asks server to leave requested object out of response HTTP/1.1: - GET, POST, HEAD - PUT - uploads file in entity body to path specified in URL field - DELETE - deletes file specified in the URL field HTTP response message status line (protocol status code status phrase) HTTP/1.1 200 OK Date: Sun, 26 Sep 2010 20:09:20 GMT Server: Apache/2.0.52 (CentOS) Last-Modified: Tue, 30 Oct 2007 17:00:02 GMT ETag: "17dc6-a5c-bf716880" Accept-Ranges: bytes Content-Length: 2652 Keep-Alive: timeout=10, max=100 Connection: Keep-Alive Content-Type: text/html; charset=ISO-8859-1 data data data data data data data ... header lines status line data, e.g., requested HTML file HTTP response status codes - status code appears in 1st line in server-to-client response message. - some sample codes: **200 OK** - request succeeded, requested object later in this msg **301 Moved Permanently** - requested object moved, new location specified later in this msg (Location:) **400 Bad Request** - request msg not understood by server **404 Not Found** - requested document not found on this server **505 HTTP Version Not Supported** Trying out HTTP (client side) for yourself 1. Telnet to your favorite Web server: ``` telnet gaia.cs.umass.edu 80 ``` opens TCP connection to port 80 (default HTTP server port) at gaia.cs.umass.edu. anything typed in will be sent to port 80 at gaia.cs.umass.edu 2. type in a GET HTTP request: ``` GET /kurose_ross/interactive/index.php HTTP/1.1 Host: gaia.cs.umass.edu ``` by typing this in (hit carriage return twice), you send this minimal (but complete) GET request to HTTP server 3. look at response message sent by HTTP server! (or use Wireshark to look at captured HTTP request/response) User-server state: cookies Many Web sites use cookies **four components:** 1) Cookie header line of HTTP *response* message 2) Cookie header line in next HTTP *request* message 3) Cookie file kept on user’s host, managed by user’s browser 4) Back-end database at Website **example:** - Susan always access Internet from PC - visits specific e-commerce site for first time - when initial HTTP requests arrives at site, site creates: - unique ID - entry in backend database for ID Cookies: keeping “state” (cont.) One week later: - eBay 8734 - Amazon 1678 **usual http request msg** **cookie file** **usual http response msg** **set-cookie: 1678** **usual http request msg** **cookie: 1678** **usual http response msg** Cookies (continued) **what cookies can be used for:** - authorization - shopping carts - recommendations - user session state (Web e-mail) **how to keep “state”:** - protocol endpoints: maintain state at sender/receiver over multiple transactions - cookies: http messages carry state **aside — cookies and privacy:** - cookies permit sites to learn a lot about you - you may supply name and e-mail to sites Web caches (proxy server) goal: satisfy client request without involving origin server • user sets browser: Web accesses via cache • browser sends all HTTP requests to cache • object in cache: cache returns object • else cache requests object from origin server, then returns object to client More about Web caching - cache acts as both client and server - server for original requesting client - client to origin server - typically cache is installed by ISP (university, company, residential ISP) **why Web caching?** - reduce response time for client request - reduce traffic on an institution’s access link - Internet dense with caches: enables “poor” content providers to effectively deliver content Caching example: **assumptions:** - avg object size: **1 Mbit** - avg request rate from browsers to origin servers: **15/sec** - avg data rate to browsers: **15 Mbps** - RTT from institutional router to any origin server: **2 sec** - access link rate: **15.4 Mbps** **consequences:** - LAN utilization: **1.5%** - access link utilization = **97%** - total delay = Internet delay + access delay + LAN delay = **2 sec + minutes + usecs** Problem! Caching example: **assumptions:** - avg object size: **1 Mbit** - avg request rate from browsers to origin servers: **15/sec** - avg data rate to browsers: **15 Mbps** - RTT from institutional router to any origin server: **2 sec** - access link rate: **15.4 Mbps** **consequences:** - LAN utilization: **1.5%** - access link utilization = **97%** - total delay = Internet delay + access delay + LAN delay = **2 sec + minutes + usecs** Cost: increased access link speed (not cheap!) Caching example: **assumptions:** - avg object size: **1 Mbit** - avg request rate from browsers to origin servers: **15/sec** - avg data rate to browsers: **15 Mbps** - RTT from institutional router to any origin server: **2 sec** - access link rate: **15.4 Mbps** **consequences:** - LAN utilization: **1.5%** - access link utilization = ?? - total delay = Internet delay + access delay + LAN delay = ?? *How to compute link utilization, delay?* Caching example: Calculating access link utilization, delay with cache: - suppose cache hit rate is 0.4 - 40% requests satisfied at cache, 60% requests satisfied at origin access link utilization: - 60% of requests use access link - data rate to browsers = 0.6*15 Mbps = 9 Mbps - utilization = 9/15.4 = 0.58 → 58% total delay - = 0.6 * (delay from origin servers) + 0.4 * (delay when satisfied at cache) - = 0.6 (2.01) + 0.4 (~msecs) = ~ 1.2 secs - < less than with 100 Mbps link Cost: web cache (cheap!) Conditional GET - **Goal:** don’t send object if cache has up-to-date cached version - no object transmission delay - lower link utilization - **cache:** specify date of cached copy in HTTP request - `If-modified-since: <date>` - **server:** response contains no object if cached copy is up-to-date: - HTTP/1.0 304 Not Modified - `HTTP request msg If-modified-since: <date>` - `HTTP response HTTP/1.0 304 Not Modified` - `HTTP request msg If-modified-since: <date>` - `HTTP response HTTP/1.0 200 OK <data>` Chapter 2: Outline ✓ Principles of network applications ✓ Socket Programming with UDP and TCP ✓ Web and HTTP ❑ Electronic Mail (SMTP, POP3, IMAP) ❑ DNS ❑ P2P Applications ❑ Video Streaming and Content Distribution Networks Electronic mail Three major components: • user agents • mail servers • SMTP: Simple Mail Transfer Protocol User Agent • a.k.a. “mail reader” • composing, editing, reading mail messages • e.g., Outlook, Thunderbird, iPhone mail client • outgoing, incoming messages stored on server Electronic Mail: Mail Servers Mail Servers: - **mailbox** contains incoming messages for user - **message queue** of outgoing (to be sent) mail messages - **SMTP protocol** between mail servers to send email messages - client: sending mail server - “server”: receiving mail server ![Diagram of mail servers and their connections with SMTP protocol] Electronic Mail: SMTP [RFC 2821] • uses TCP to reliably transfer email message from client to server, port 25 • direct transfer: sending server to receiving server • three phases of transfer • handshaking (greeting) • transfer of messages • closure • command/response interaction (like HTTP) • commands: ASCII text • response: status code and phrase • messages must be in 7-bit ASCII Scenario: Alice sends message to Bob 1) Alice uses UA to compose message “to” bob@someschool.edu 2) Alice’s UA sends message to her mail server; message placed in message queue 3) Client side of SMTP opens TCP connection with Bob’s mail server 4) SMTP client sends Alice’s message over the TCP connection 5) Bob’s mail server places the message in Bob’s mailbox 6) Bob invokes his user agent to read message Sample SMTP interaction S: 220 hamburger.edu C: HELO crepes.fr S: 250 Hello crepes.fr, pleased to meet you C: MAIL FROM: <alice@crepes.fr> S: 250 alice@crepes.fr... Sender ok C: RCPT TO: <bob@hamburger.edu> S: 250 bob@hamburger.edu ... Recipient ok C: DATA S: 354 Enter mail, end with "." on a line by itself C: Do you like ketchup? C: How about pickles? C: . S: 250 Message accepted for delivery C: QUIT S: 221 hamburger.edu closing connection SMTP: final words • SMTP uses persistent connections • SMTP requires message (header & body) to be in 7-bit ASCII • SMTP server uses CRLF.CRLF to determine end of message comparison with HTTP: • HTTP: pull • SMTP: push • both have ASCII command/response interaction, status codes • HTTP: each object encapsulated in its own response message • SMTP: multiple objects sent in multipart message Mail message format SMTP: protocol for exchanging email messages RFC 822: standard for text message format: - header lines, e.g., - To: - From: - Subject: - different from SMTP MAIL FROM, RCPT TO: commands! - Body: the “message” - ASCII characters only Mail access protocols - **SMTP**: delivery/storage to receiver’s server - **mail access protocol**: retrieval from server - **POP**: Post Office Protocol [RFC 1939]: authorization, download - **IMAP**: Internet Mail Access Protocol [RFC 1730]: more features, including manipulation of stored messages on server - **HTTP**: gmail, Hotmail, Yahoo! Mail, etc. Chapter 2: Outline ✓ Principles of network applications ✓ Socket Programming with UDP and TCP ✓ Web and HTTP ✓ Electronic Mail (SMTP, POP3, IMAP) ❑ DNS ❑ P2P Applications ❑ Video Streaming and Content Distribution Networks DNS: domain name system people: many identifiers: • SSN, name, passport # Internet hosts, routers: • IP address (32 bit) - used for addressing datagrams • “name”, e.g., www.yahoo.com - used by humans Q: how to map between IP address and name, and vice versa? Domain Name System: • distributed database implemented in hierarchy of many name servers • application-layer protocol: hosts, name servers communicate to resolve names (address/name translation) • note: core Internet function, implemented as application-layer protocol • complexity at network’s “edge” DNS: services, structure **DNS services** - hostname to IP address translation - host aliasing - canonical, alias names - mail server aliasing - load distribution - replicated Web servers: many IP addresses correspond to one name **why not centralize DNS?** - single point of failure - traffic volume - distant centralized database - maintenance A: *doesn’t scale!* client wants IP for www.amazon.com; 1st approximation: - client queries root server to find com DNS server - client queries .com DNS server to get amazon.com DNS server - client queries amazon.com DNS server to get IP address for www.amazon.com DNS: Root Name Servers • Contacted by local name server that cannot resolve name • Root name server: • Contacts authoritative name server if name mapping not known • Gets mapping • Returns mapping to local name server 13 logical root name “servers” worldwide • each “server” replicated many times TLD, Authoritative DNS Servers Top-level domain (TLD) servers: • responsible for com, org, net, edu, aero, jobs, museums, and all top-level country domains, e.g.: uk, fr, ca, jp • Network Solutions maintains servers for .com TLD • Educause for .edu TLD Authoritative DNS servers: Organization’s own DNS server(s), providing authoritative hostname to IP mappings for organization’s named hosts • can be maintained by organization or service provider Local DNS name server • does not strictly belong to hierarchy • each ISP (residential ISP, company, university) has one • also called “default name server” • when host makes DNS query, query is sent to its local DNS server • has local cache of recent name-to-address translation pairs (but may be out of date!) • acts as proxy, forwards query into hierarchy DNS name resolution example - host at cs.stanford.edu wants IP address for csl.illinois.edu *iterated query:* - contacted server replies with name of server to contact - “I don’t know this name, but ask this server” DNS name resolution example recursive query: - puts burden of name resolution on contacted name server - heavy load at upper levels of hierarchy? DNS: caching, updating records • once (any) name server learns mapping, it caches mapping • cache entries timeout (disappear) after some time (TTL) • TLD servers typically cached in local name servers • thus root name servers not often visited • cached entries may be out-of-date (best effort name-to-address translation!) • if name host changes IP address, may not be known Internet-wide until all TTLs expire • update/notify mechanisms proposed IETF standard • RFC 2136 DNS records **DNS**: distributed database storing resource records (RR) RR format: (name, value, type, ttl) - **type=A** - name is hostname - value is IP address - **type=NS** - name is domain (e.g., foo.com) - value is hostname of authoritative name server for this domain - **type=CNAME** - name is alias name for some “canonical” (the real) name - value is canonical name - **www.ibm.com** is really **servereast.backup2.ibm.com** - **type=MX** - value is name of mail server associated with name DNS protocol, messages - **query** and **reply** messages, both with same **message format** **message header** - **identification**: 16 bit # for query, reply to query uses same # - **flags**: - query or reply - recursion desired - recursion available - reply is authoritative <table> <thead> <tr> <th>Field</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td>identification</td> <td>2 bytes</td> </tr> <tr> <td># questions</td> <td>2 bytes</td> </tr> <tr> <td># authority RRs</td> <td>2 bytes</td> </tr> <tr> <td># answer RRs</td> <td>2 bytes</td> </tr> <tr> <td># additional RRs</td> <td>2 bytes</td> </tr> <tr> <td>questions</td> <td>(variable # of questions)</td> </tr> <tr> <td>answers</td> <td>(variable # of RRs)</td> </tr> <tr> <td>authority</td> <td>(variable # of RRs)</td> </tr> <tr> <td>additional info</td> <td>(variable # of RRs)</td> </tr> </tbody> </table> ### DNS protocol, messages <table> <thead> <tr> <th>Field</th> <th>Length</th> </tr> </thead> <tbody> <tr> <td>identification</td> <td>2 bytes</td> </tr> <tr> <td>flags</td> <td>2 bytes</td> </tr> <tr> <td># questions</td> <td></td> </tr> <tr> <td># answer RRs</td> <td></td> </tr> <tr> <td># authority RRs</td> <td></td> </tr> <tr> <td># additional RRs</td> <td></td> </tr> <tr> <td>questions (variable # of questions)</td> <td></td> </tr> <tr> <td>answers (variable # of RRs)</td> <td></td> </tr> <tr> <td>authority (variable # of RRs)</td> <td></td> </tr> <tr> <td>additional info (variable # of RRs)</td> <td></td> </tr> </tbody> </table> - **name, type fields for a query** - **RRs in response to query** - **records for authoritative servers** - **additional “helpful” info that may be used** Inserting records into DNS • example: new startup “Network Utopia” • register name networkuptopia.com at DNS registrar (e.g., Network Solutions) • provide names, IP addresses of authoritative name server (primary and secondary) • registrar inserts two RRs into .com TLD server: (networkutopia.com, dns1.networkutopia.com, NS) (dns1.networkutopia.com, 212.212.212.1, A) • create authoritative server type A record for www.networkuptopia.com; type NS record for networkutopia.com Chapter 2: Outline ✓ Principles of network applications ✓ Socket Programming with UDP and TCP ✓ Web and HTTP ✓ Electronic Mail (SMTP, POP3, IMAP) ✓ DNS ❑ P2P Applications ❑ Video Streaming and Content Distribution Networks Pure P2P architecture • *no* always-on server • arbitrary end systems directly communicate • peers are intermittently connected and change IP addresses *examples:* • file distribution (BitTorrent) • Streaming (KanKan) • VoIP (Skype) **File distribution: client-server vs P2P** **Question:** how much time to distribute file (size $F$) from one server to $N$ peers? - peer upload/download capacity is limited resource File distribution time: client-server - **Server transmission**: must sequentially send (upload) \( N \) file copies: - time to send one copy: \( F/u_s \) - time to send \( N \) copies: \( NF/u_s \) - **Client**: each client must download file copy - \( d_{min} = \min \) client download rate - min client download time: \( F/d_{min} \) \[ \text{Time to distribute } F \text{ to } N \text{ clients using client-server approach} = D_{c-s} \geq \max\{NF/u_s, F/d_{min}\} \] Increases linearly in \( N \) File distribution time: P2P - **Server transmission:** must upload at least one copy - time to send one copy: \( F/u_s \) - **Client:** each client must download file copy - min client download time: \( F/d_{\text{min}} \) - **Clients:** must download total \( NF \) bits \( \rightarrow \) still need to upload \( NF \) bits - max upload rate (limiting max download rate) is \( u_s + \sum u_i \) \[ D_{P2P} \geq \max\{F/u_s, F/d_{\text{min}}, NF/(u_s + \sum u_i)\} \] *Time to distribute \( F \) to \( N \) clients using P2P approach* increases linearly in \( N \) ... ... but so does this, as each peer brings service capacity Client-server vs. P2P: example client upload rate = $u$, $F/u = 1$ hour, $u_s = 10u$, $d_{\min} \geq u_s$ P2P file distribution: BitTorrent - File divided into 256Kb chunks - Peers in torrent send/receive file chunks **tracker:** tracks peers participating in torrent **torrent:** group of peers exchanging chunks of a file Alice arrives ... ... obtains list of peers from tracker ... and begins exchanging file chunks with peers in torrent P2P file distribution: BitTorrent - peer joining torrent: - has no chunks, but will accumulate them over time from other peers - registers with tracker to get list of peers, connects to subset of peers (“neighbors”) - while downloading, peer uploads chunks to other peers - peer may change peers with whom it exchanges chunks - *churn*: peers may come and go - once peer has entire file, it may (selfishly) leave or (altruistically) remain in torrent BitTorrent: requesting, sending file chunks **requesting chunks:** - at any given time, different peers have different subsets of file chunks - periodically, Alice asks each peer for list of chunks that they have - Alice requests missing chunks from peers, rarest first **sending chunks: tit-for-tat** - Alice sends chunks to those four peers currently sending her chunks *at highest rate* - other peers are choked by Alice (do not receive chunks from her) - re-evaluate top 4 every 10 secs - every 30 secs: randomly select another peer, starts sending chunks - “optimistically unchoke” this peer - newly chosen peer may join top 4 BitTorrent: tit-for-tat (1) Alice “optimistically unchokes” Bob (2) Alice becomes one of Bob’s top-four providers; Bob reciprocates (3) Bob becomes one of Alice’s top-four providers higher upload rate: find better trading partners, get file faster! Distributed Hash Table (DHT) - Hash table - DHT paradigm - Circular DHT and overlay networks - Peer churn Simple Database Simple database with (key, value) pairs: - key: human name; value: social security # <table> <thead> <tr> <th>Key</th> <th>Value</th> </tr> </thead> <tbody> <tr> <td>John Washington</td> <td>132-54-3570</td> </tr> <tr> <td>Diana Louise Jones</td> <td>761-55-3791</td> </tr> <tr> <td>Xiaoming Liu</td> <td>385-41-0902</td> </tr> <tr> <td>Rakesh Gopal</td> <td>441-89-1956</td> </tr> <tr> <td>Linda Cohen</td> <td>217-66-5609</td> </tr> <tr> <td>.......</td> <td>........</td> </tr> <tr> <td>Lisa Kobayashi</td> <td>177-23-0199</td> </tr> </tbody> </table> - key: movie title; value: IP address **Hash Table** - More convenient to store and search on numerical representation of key - key = hash(original key) <table> <thead> <tr> <th>Original Key</th> <th>Key</th> <th>Value</th> </tr> </thead> <tbody> <tr> <td>John Washington</td> <td>8962458</td> <td>132-54-3570</td> </tr> <tr> <td>Diana Louise Jones</td> <td>7800356</td> <td>761-55-3791</td> </tr> <tr> <td>Xiaoming Liu</td> <td>1567109</td> <td>385-41-0902</td> </tr> <tr> <td>Rakesh Gopal</td> <td>2360012</td> <td>441-89-1956</td> </tr> <tr> <td>Linda Cohen</td> <td>5430938</td> <td>217-66-5609</td> </tr> <tr> <td></td> <td></td> <td></td> </tr> <tr> <td>Lisa Kobayashi</td> <td>9290124</td> <td>177-23-0199</td> </tr> </tbody> </table> • More convenient to store and search on numerical representation of key • key = hash(original key) Distributed Hash Table (DHT) - Distribute (key, value) pairs over millions of peers - pairs are evenly distributed over peers - Any peer can **query** database with a key - database returns value for the key - To resolve query, small number of messages exchanged among peers - Each peer only knows about a small number of other peers - Robust to peers coming and going (churn) Assign key-value pairs to peers • rule: assign key-value pair to the peer that has the closest ID. • convention: closest is the immediate successor of the key. • e.g., ID space {0,1,2,3,...,63} • suppose 8 peers: 1, 12, 13, 25, 32, 40, 48, 60 • If key = 51, then assigned to peer 60 • If key = 60, then assigned to peer 60 • If key = 61, then assigned to peer 1 Silly Strawman Circular DHT - each peer *only* aware of immediate successor and predecessor. What is the value associated with key 53? $O(N)$ messages on average to resolve query, when there are $N$ peers. Circular DHT with shortcuts (Chord) - each peer keeps track of IP addresses of predecessor, successor, short cuts. - reduced from 6 to 3 messages. - possible to design shortcuts with $O(\log N)$ neighbors, $O(\log N)$ messages in query What is the value for key 53? Peer churn display: peer churn: ❖ peers may come and go (churn) ❖ each peer knows address of its two successors ❖ each peer periodically pings its two successors to check aliveness ❖ if immediate successor leaves, choose next successor as new immediate successor example: peer 5 abruptly leaves Peer churn handling peer churn: ❖ peers may come and go (churn) ❖ each peer knows address of its two successors ❖ each peer periodically pings its two successors to check aliveness ❖ if immediate successor leaves, choose next successor as new immediate successor example: peer 5 abruptly leaves • peer 4 detects peer 5’s departure; makes 8 its immediate successor • 4 asks 8 who its immediate successor is; makes 8’s immediate successor its second successor. P2P Motivation – Revisited • Client-server dominates the mainstream. Why? • Performance • Economies of scale • Round trip times • (Mass file distribution is a rare exception) • So, why peer-to-peer? • Avoid single points of failure • Technological ➔ Robustness, Survivability • ...and social ➔ Power to the people Chapter 2: Outline ✓ Principles of network applications ✓ Socket Programming with UDP and TCP ✓ Web and HTTP ✓ Electronic Mail (SMTP, POP3, IMAP) ✓ DNS ✓ P2P Applications ❑ Video Streaming and Content Distribution Networks Video Streaming and CDNs: context - video traffic: major consumer of Internet bandwidth - Netflix, YouTube: 37%, 16% of downstream residential ISP traffic - ~1B YouTube users, ~75M Netflix users - challenge: scale - how to reach ~1B users? - single mega-video server won’t work (why?) - challenge: heterogeneity - different users have different capabilities (e.g., wired versus mobile; bandwidth rich versus bandwidth poor) - solution: distributed, application-level infrastructure Multimedia: video - video: sequence of images displayed at constant rate - e.g., 24 images/sec - digital image: array of pixels - each pixel represented by bits - coding: use redundancy *within* and *between* images to decrease # bits used to encode image - spatial (within image) - temporal (from one image to next) **Spatial coding example:** instead of sending $N$ values of same color (all purple), send only two values: color value (*purple*) and number of repeated values ($N$) **Temporal coding example:** instead of sending complete frame at $i+1$, send only differences from frame $i$ ### Multimedia: video - **CBR: (constant bit rate):** video encoding rate fixed - **VBR: (variable bit rate):** video encoding rate changes as amount of spatial, temporal coding changes - **examples:** - MPEG 1 (CD-ROM) 1.5 Mbps - MPEG2 (DVD) 3-6 Mbps - MPEG4 (often used in Internet, < 1 Mbps) **spatial coding example:** instead of sending $N$ values of same color (all purple), send only two values: color value (purple) and number of repeated values ($N$) **temporal coding example:** instead of sending complete frame at $i+1$, send only differences from frame $i$ Video Compression - Color Encoding: - RGB - YUV Video Compression - Color Encoding: YUV 4:2:0 Sampling Video Compression - Spatial Encoding: Frequency domain compression using DCT (Discrete Cosine Transform) <table> <thead> <tr> <th>Original pixel data</th> </tr> </thead> <tbody> <tr> <td>114 108 100 99 109 129 152 166</td> </tr> <tr> <td>109 102 95 94 104 124 146 161</td> </tr> <tr> <td>99 93 85 84 94 114 137 151</td> </tr> <tr> <td>86 80 72 71 82 102 124 138</td> </tr> <tr> <td>73 66 58 57 68 88 110 125</td> </tr> <tr> <td>60 53 46 45 55 75 97 112</td> </tr> <tr> <td>50 43 36 35 45 65 88 102</td> </tr> <tr> <td>45 38 31 30 40 60 82 97</td> </tr> </tbody> </table> <table> <thead> <tr> <th>DCT coefficient data</th> </tr> </thead> <tbody> <tr> <td>700 200 0 0 0 0 0 0</td> </tr> <tr> <td>-150 0 0 0 0 0 0 0</td> </tr> <tr> <td>110 0 0 0 0 0 0 0</td> </tr> <tr> <td>0 0 0 0 0 0 0 0</td> </tr> <tr> <td>0 0 0 0 0 0 0 0</td> </tr> <tr> <td>0 0 0 0 0 0 0 0</td> </tr> <tr> <td>0 0 0 0 0 0 0 0</td> </tr> <tr> <td>0 0 0 0 0 0 0 0</td> </tr> </tbody> </table> Video Compression - **Spatial Encoding**: Frequency domain compression using DCT (Discrete Cosine Transform) - Divide into 8x8 Blocks - Take DCT of block - Quantize and Compress block ![Diagram](image-url) Video Compression - Spatial Encoding: Frequency domain compression using DCT (Discrete Cosine Transform) - Divide into 8x8 Blocks - Take DCT of block - Quantize and Compress block Video Compression - Temporal Encoding: Motion Compensation Video Compression - Temporal Encoding: Motion Compensation ![Diagram showing temporal encoding with motion compensation](image) Video Compression - Temporal Encoding: Motion Compensation Streaming stored video: simple scenario: video server (Stored video) client Internet Streaming multimedia: DASH - **DASH: Dynamic, Adaptive Streaming over HTTP** - **server:** - divides video file into multiple chunks - each chunk stored, encoded at different rates - *manifest file:* provides URLs for different chunks - **client:** - periodically measures server-to-client bandwidth - consulting manifest, requests one chunk at a time - chooses maximum coding rate sustainable given current bandwidth - can choose different coding rates at different points in time (depending on available bandwidth at time) Streaming multimedia: DASH - **DASH:** Dynamic, Adaptive Streaming over HTTP - **“intelligence” at client:** client determines - *when* to request chunk (so that buffer starvation, or overflow does not occur) - *what encoding rate* to request (higher quality when more bandwidth available) - *where* to request chunk (can request from URL server that is “close” to client or has high available bandwidth) Content distribution networks • **challenge:** how to stream content (selected from millions of videos) to hundreds of thousands of simultaneous users? • **option 1:** single, large “mega-server” • single point of failure • point of network congestion • long path to distant clients • multiple copies of video sent over outgoing link ....quite simply: this solution **doesn’t scale** Content distribution networks - **challenge:** how to stream content (selected from millions of videos) to hundreds of thousands of simultaneous users? - **option 2:** store/serve multiple copies of videos at multiple geographically distributed sites (*CDN*) - **enter deep:** push CDN servers deep into many access networks - close to users - used by Akamai, 1700 locations - **bring home:** smaller number (10’s) of larger clusters near (but not within) access networks - used by Limelight Content Distribution Networks (CDNs) - CDN: stores copies of content at CDN nodes - e.g. Netflix stores copies of “House of Card” - subscriber requests content from CDN - directed to nearby copy, retrieves content - may choose different copy if network path congested Chapter 2: summary our study of network apps now complete! • application architectures • client-server • P2P • application service requirements: • reliability, bandwidth, delay • Internet transport service model • connection-oriented, reliable: TCP • unreliable, datagrams: UDP • specific protocols: • HTTP • SMTP, POP, IMAP • DNS • P2P: BitTorrent • video streaming, CDNs • socket programming: TCP, UDP sockets Chapter 2: summary Most importantly: learned about protocols! - Typical request/reply message exchange: - Client requests info or service - Server responds with data, status code - Message formats: - Headers: fields giving info about data - Data: info(payload) being communicated Important themes: - Control vs. messages - Centralized vs. decentralized - Stateless vs. stateful - Reliable vs. unreliable message transfer - “Complexity at network edge”
{"Source-Url": "https://courses.engr.illinois.edu/ece438/fa2019/Lectures/ECE438_FA19_2_Application.pdf", "len_cl100k_base": 12516, "olmocr-version": "0.1.51", "pdf-total-pages": 125, "total-fallback-pages": 0, "total-input-tokens": 188278, "total-output-tokens": 16881, "length": "2e13", "weborganizer": {"__label__adult": 0.0005655288696289062, "__label__art_design": 0.00051116943359375, "__label__crime_law": 0.0005826950073242188, "__label__education_jobs": 0.01378631591796875, "__label__entertainment": 0.0005645751953125, "__label__fashion_beauty": 0.0002187490463256836, "__label__finance_business": 0.0007939338684082031, "__label__food_dining": 0.0004935264587402344, "__label__games": 0.00261688232421875, "__label__hardware": 0.0067596435546875, "__label__health": 0.0006327629089355469, "__label__history": 0.0009326934814453124, "__label__home_hobbies": 0.00019216537475585935, "__label__industrial": 0.0006875991821289062, "__label__literature": 0.0010852813720703125, "__label__politics": 0.0003108978271484375, "__label__religion": 0.0006074905395507812, "__label__science_tech": 0.332763671875, "__label__social_life": 0.0003643035888671875, "__label__software": 0.11773681640625, "__label__software_dev": 0.51513671875, "__label__sports_fitness": 0.000507354736328125, "__label__transportation": 0.001575469970703125, "__label__travel": 0.00043129920959472656}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 47386, 0.02507]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 47386, 0.34092]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 47386, 0.75261]], "google_gemma-3-12b-it_contains_pii": [[0, 21, false], [21, 95, null], [95, 490, null], [490, 714, null], [714, 1069, null], [1069, 1179, null], [1179, 1436, null], [1436, 1705, null], [1705, 1969, null], [1969, 2319, null], [2319, 2736, null], [2736, 2805, null], [2805, 3276, null], [3276, 3530, null], [3530, 4095, null], [4095, 4497, null], [4497, 5023, null], [5023, 5746, null], [5746, 6501, null], [6501, 7140, null], [7140, 8121, null], [8121, 8345, null], [8345, 8532, null], [8532, 8987, null], [8987, 9428, null], [9428, 9906, null], [9906, 10402, null], [10402, 11205, null], [11205, 11904, null], [11904, 12387, null], [12387, 12755, null], [12755, 13216, null], [13216, 13856, null], [13856, 14080, null], [14080, 14408, null], [14408, 14692, null], [14692, 15249, null], [15249, 15527, null], [15527, 16346, null], [16346, 16701, null], [16701, 16997, null], [16997, 17195, null], [17195, 17292, null], [17292, 17507, null], [17507, 18056, null], [18056, 18215, null], [18215, 18469, null], [18469, 18722, null], [18722, 19191, null], [19191, 19679, null], [19679, 20278, null], [20278, 20765, null], [20765, 21013, null], [21013, 21423, null], [21423, 21722, null], [21722, 22139, null], [22139, 22593, null], [22593, 23083, null], [23083, 23534, null], [23534, 24046, null], [24046, 24569, null], [24569, 24793, null], [24793, 25076, null], [25076, 25432, null], [25432, 25827, null], [25827, 26241, null], [26241, 26687, null], [26687, 27081, null], [27081, 27351, null], [27351, 27715, null], [27715, 27939, null], [27939, 28522, null], [28522, 28897, null], [28897, 29143, null], [29143, 29449, null], [29449, 29904, null], [29904, 30269, null], [30269, 30487, null], [30487, 30634, null], [30634, 31121, null], [31121, 31643, null], [31643, 32551, null], [32551, 33219, null], [33219, 33704, null], [33704, 33928, null], [33928, 34169, null], [34169, 34354, null], [34354, 34868, null], [34868, 35509, null], [35509, 35616, null], [35616, 35955, null], [35955, 36412, null], [36412, 37054, null], [37054, 37305, null], [37305, 37412, null], [37412, 37934, null], [37934, 38647, null], [38647, 39031, null], [39031, 39400, null], [39400, 39494, null], [39494, 39608, null], [39608, 39876, null], [39876, 40173, null], [40173, 40637, null], [40637, 40979, null], [40979, 41203, null], [41203, 41694, null], [41694, 42299, null], [42299, 42878, null], [42878, 42931, null], [42931, 42987, null], [42987, 43609, null], [43609, 43823, null], [43823, 44010, null], [44010, 44070, null], [44070, 44200, null], [44200, 44260, null], [44260, 44349, null], [44349, 44893, null], [44893, 45305, null], [45305, 45700, null], [45700, 46210, null], [46210, 46486, null], [46486, 46924, null], [46924, 47386, null]], "google_gemma-3-12b-it_is_public_document": [[0, 21, true], [21, 95, null], [95, 490, null], [490, 714, null], [714, 1069, null], [1069, 1179, null], [1179, 1436, null], [1436, 1705, null], [1705, 1969, null], [1969, 2319, null], [2319, 2736, null], [2736, 2805, null], [2805, 3276, null], [3276, 3530, null], [3530, 4095, null], [4095, 4497, null], [4497, 5023, null], [5023, 5746, null], [5746, 6501, null], [6501, 7140, null], [7140, 8121, null], [8121, 8345, null], [8345, 8532, null], [8532, 8987, null], [8987, 9428, null], [9428, 9906, null], [9906, 10402, null], [10402, 11205, null], [11205, 11904, null], [11904, 12387, null], [12387, 12755, null], [12755, 13216, null], [13216, 13856, null], [13856, 14080, null], [14080, 14408, null], [14408, 14692, null], [14692, 15249, null], [15249, 15527, null], [15527, 16346, null], [16346, 16701, null], [16701, 16997, null], [16997, 17195, null], [17195, 17292, null], [17292, 17507, null], [17507, 18056, null], [18056, 18215, null], [18215, 18469, null], [18469, 18722, null], [18722, 19191, null], [19191, 19679, null], [19679, 20278, null], [20278, 20765, null], [20765, 21013, null], [21013, 21423, null], [21423, 21722, null], [21722, 22139, null], [22139, 22593, null], [22593, 23083, null], [23083, 23534, null], [23534, 24046, null], [24046, 24569, null], [24569, 24793, null], [24793, 25076, null], [25076, 25432, null], [25432, 25827, null], [25827, 26241, null], [26241, 26687, null], [26687, 27081, null], [27081, 27351, null], [27351, 27715, null], [27715, 27939, null], [27939, 28522, null], [28522, 28897, null], [28897, 29143, null], [29143, 29449, null], [29449, 29904, null], [29904, 30269, null], [30269, 30487, null], [30487, 30634, null], [30634, 31121, null], [31121, 31643, null], [31643, 32551, null], [32551, 33219, null], [33219, 33704, null], [33704, 33928, null], [33928, 34169, null], [34169, 34354, null], [34354, 34868, null], [34868, 35509, null], [35509, 35616, null], [35616, 35955, null], [35955, 36412, null], [36412, 37054, null], [37054, 37305, null], [37305, 37412, null], [37412, 37934, null], [37934, 38647, null], [38647, 39031, null], [39031, 39400, null], [39400, 39494, null], [39494, 39608, null], [39608, 39876, null], [39876, 40173, null], [40173, 40637, null], [40637, 40979, null], [40979, 41203, null], [41203, 41694, null], [41694, 42299, null], [42299, 42878, null], [42878, 42931, null], [42931, 42987, null], [42987, 43609, null], [43609, 43823, null], [43823, 44010, null], [44010, 44070, null], [44070, 44200, null], [44200, 44260, null], [44260, 44349, null], [44349, 44893, null], [44893, 45305, null], [45305, 45700, null], [45700, 46210, null], [46210, 46486, null], [46486, 46924, null], [46924, 47386, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 47386, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 47386, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 47386, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 47386, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 47386, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 47386, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 47386, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 47386, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 47386, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, true], [5000, 47386, null]], "pdf_page_numbers": [[0, 21, 1], [21, 95, 2], [95, 490, 3], [490, 714, 4], [714, 1069, 5], [1069, 1179, 6], [1179, 1436, 7], [1436, 1705, 8], [1705, 1969, 9], [1969, 2319, 10], [2319, 2736, 11], [2736, 2805, 12], [2805, 3276, 13], [3276, 3530, 14], [3530, 4095, 15], [4095, 4497, 16], [4497, 5023, 17], [5023, 5746, 18], [5746, 6501, 19], [6501, 7140, 20], [7140, 8121, 21], [8121, 8345, 22], [8345, 8532, 23], [8532, 8987, 24], [8987, 9428, 25], [9428, 9906, 26], [9906, 10402, 27], [10402, 11205, 28], [11205, 11904, 29], [11904, 12387, 30], [12387, 12755, 31], [12755, 13216, 32], [13216, 13856, 33], [13856, 14080, 34], [14080, 14408, 35], [14408, 14692, 36], [14692, 15249, 37], [15249, 15527, 38], [15527, 16346, 39], [16346, 16701, 40], [16701, 16997, 41], [16997, 17195, 42], [17195, 17292, 43], [17292, 17507, 44], [17507, 18056, 45], [18056, 18215, 46], [18215, 18469, 47], [18469, 18722, 48], [18722, 19191, 49], [19191, 19679, 50], [19679, 20278, 51], [20278, 20765, 52], [20765, 21013, 53], [21013, 21423, 54], [21423, 21722, 55], [21722, 22139, 56], [22139, 22593, 57], [22593, 23083, 58], [23083, 23534, 59], [23534, 24046, 60], [24046, 24569, 61], [24569, 24793, 62], [24793, 25076, 63], [25076, 25432, 64], [25432, 25827, 65], [25827, 26241, 66], [26241, 26687, 67], [26687, 27081, 68], [27081, 27351, 69], [27351, 27715, 70], [27715, 27939, 71], [27939, 28522, 72], [28522, 28897, 73], [28897, 29143, 74], [29143, 29449, 75], [29449, 29904, 76], [29904, 30269, 77], [30269, 30487, 78], [30487, 30634, 79], [30634, 31121, 80], [31121, 31643, 81], [31643, 32551, 82], [32551, 33219, 83], [33219, 33704, 84], [33704, 33928, 85], [33928, 34169, 86], [34169, 34354, 87], [34354, 34868, 88], [34868, 35509, 89], [35509, 35616, 90], [35616, 35955, 91], [35955, 36412, 92], [36412, 37054, 93], [37054, 37305, 94], [37305, 37412, 95], [37412, 37934, 96], [37934, 38647, 97], [38647, 39031, 98], [39031, 39400, 99], [39400, 39494, 100], [39494, 39608, 101], [39608, 39876, 102], [39876, 40173, 103], [40173, 40637, 104], [40637, 40979, 105], [40979, 41203, 106], [41203, 41694, 107], [41694, 42299, 108], [42299, 42878, 109], [42878, 42931, 110], [42931, 42987, 111], [42987, 43609, 112], [43609, 43823, 113], [43823, 44010, 114], [44010, 44070, 115], [44070, 44200, 116], [44200, 44260, 117], [44260, 44349, 118], [44349, 44893, 119], [44893, 45305, 120], [45305, 45700, 121], [45700, 46210, 122], [46210, 46486, 123], [46486, 46924, 124], [46924, 47386, 125]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 47386, 0.07432]]}
olmocr_science_pdfs
2024-12-03
2024-12-03
742adb1df0ecc4bdc9fd4ed4f7f3cf3fd3760c78
Supporting Expressive Procedural Art Creation through Direct Manipulation Jennifer Jacobs¹,², Sumit Gogia¹, Radomír Měch², Joel Brandt² ¹ MIT Media Lab ² Adobe Research jacobsj@media.mit.edu, summit@mit.edu {rmech, joel.brandt}@adobe.com ABSTRACT Computation is a powerful artistic medium. Artists with experience in programming have demonstrated the unique creative opportunities of using code to make art. Currently, manual artists interested in using procedural techniques must undergo the difficult process of learning to program, and must adopt tools and practices far removed from those to which they are accustomed. We hypothesize that, through the right direct manipulation interface, we can enable accessible and expressive procedural art creation. To explore this, we developed Para, a digital illustration tool that supports the creation of declarative constraints in vector artwork. Para's constraints enable procedural relationships while facilitating live manual control and non-linear editing. Constraints can be combined with duplication behaviors and ordered collections of artwork to produce complex, dynamic compositions. We use the results of two open-ended studies with professional artists and designers to provide guidelines for accessible tools that integrate manual and procedural expression. INTRODUCTION New tools and technologies have emerged that support the production of procedural, parametric, and generative forms of art. While differing in their applications, these art forms share the common property of being defined by a representational system of rules, relationships, and behaviors, which makes them flexible, adaptable, and capable of systematic revision. Currently, most professional procedural art is produced through computer programming. Describing art with code allows artists to manage complex structures, automate processes, and generalize and reuse operations [38, 27]. More broadly, procedural tools support exploration, experimentation, and play because their processes can be revised and iterated upon without loss of quality or affordance [26]. There is increasing interest in the artistic applications of programming, as indicated by the growth of coding platforms for art [37, 3]. Yet programming still presents many challenges for artists. In general, programming is challenging to learn. Programming languages present barriers to incremental learning by requiring people to learn many concepts before accomplishing even simple tasks [20]. Furthermore, while manual artists and craftspeople learn mainly through observation and action of tacit manual skills [26], programming education often emphasizes a structured top-down approach of learning formal principles for application to concrete, predefined tasks [10]. Victor states that learning programming may always be challenging because learning abstraction is hard [53], but he argues that tools can be designed to make that challenge more tractable [51]. In addition to the challenges of learning to program, there are significant interaction differences between programming tools and software for manual art. Graphic illustration soft- ware is concrete: it approximates physical art media through direct manipulation interactions. Concrete tools often have a gradual learning curve [46], and can play an important role in engendering creative diversity [41] and supporting the conception of new ideas [45]. Programming tools, by comparison, are typically representational [50], where users edit a description of the work rather than the work itself. Representational tools can present an additional challenge for artists accustomed to working with and thinking in terms of concrete mediums. Contrasting the creative opportunities of procedural art with the challenges of programming raises our research question: Can we support accessible and expressive procedural art by enabling people to describe procedural relationships through direct manipulation? Prior work in developing accessible procedural tools for art has focused on creating simplified textual programming languages and environments [34, 35, 14], augmenting graphical user interface (GUI)-based tools with visual programming languages [7], or linked editing between textual programming and direct manipulation [15, 2, 6, 11]. Our approach is to augment the conventions of graphic art software to support the creation and modification of procedural relationships exclusively through manipulation of concrete artwork. In doing so, we build on prior work using direct manipulation to create dynamic relationships in data visualization [53], interactivity [17], and architecture [24], but with the new objective of supporting and extending the practices of manual fine artists. This goal is challenging because it requires developing a procedural representation that supports expressive creation, yet is compatible with direct-manipulation conventions. This paper makes the following contributions: First, we introduce Para, a new direct-manipulation tool that supports procedural art through live, non-linear, and continuous manipulation. Second, we demonstrate core declarative procedural operations that can be expressed through direct manipulation, are easy to use, and enable diverse creative outcomes. These operations include declarative geometric and stylistic constraints, visually represented ordered lists that can be used to specify how constraints map to collections of objects, and declarative duplication to enable dynamic copying. Constraints, lists, and duplication can be combined in different ways to produce different outcomes. Third, we provide evidence for how the direct manipulation of procedural relationships can extend manual practice through two open-ended studies. These studies evaluate the accessibility and expressiveness of our system in the hands of professional artists by examining how they work and the artifacts they produce. To our knowledge, these are the first open-ended studies in the domain of direct manipulation procedural art. Fourth, we provide recommendations for building expressive direct-manipulation procedural tools, as gleaned from evaluation. BACKGROUND AND RELATED WORK To inform the development of Para, we reviewed literature that discussed support for learning and expressiveness through programming. We also examined research about the practices of fine and commercial artists and visual designers. While artists and designers differ in their goals, they frequently rely on the same tools; for example, Photoshop and Processing are both used for art and design. Questions about how tools support different creative motivations are outside the scope of this paper. Rather, our research focused on how different tools support or hinder creative practice. Therefore, we examine creative tool use in commercial and fine-art. In the comparison of procedural and manual tools for art and design, we focused on two primary tensions: ease of use versus expressiveness, and concrete versus representational tools. Ease of use versus expressiveness Programming languages are challenging for end users because they must learn a great deal in order to produce simple results [28]. This tension is reflected in procedural tools for art and design. Creative coding applications like openFrameworks [23] and Processing [35] are extremely expressive; however, these tools require people to learn numerous textual programming conventions and lengthy APIs before producing basic artwork. These severe learning thresholds are common in end-user programming and can present insurmountable barriers to novices [20]. Visual programming languages [7, 1, 39, 8] can provide a more accessible entry point by providing an impression of directly constructing a program, rather than abstractly designing it [29], and represent an important initiative to support artists, designers, and other end-users in programming. We describe interaction differences between visual languages and our system in the following subsection. A similar conflict between ease of use and expressiveness also exists in computer-aided design (CAD). Entry-level parametric tools often enable customization of existing designs, however the ability to compose new designs requires learning significantly more advanced tools and workflows. Many GUI-based CAD tools, including Rhino and Inventor, support procedural and parametric functionality by enabling designers to author scripts and programs that act on objects created in the GUI. These features offer new opportunities but are difficult to use and learn in comparison with the GUI [24]. When adapted for people without formal knowledge in math, geometry, and logic, CAD tools often take the form of customizable parametric models [13, 42]. Although these tools can increase participation, studies indicate that they do not produce a diversity of creative outcomes, nor scaffold novice use of advanced, open-ended CAD tools [30]. We seek to create accessible procedural tools that retain forms of expressiveness relevant to a specific domain. Research that demonstrates this approach in other domains includes interaction design via parallel source editing and tunable control interfaces [9], user-interface (UI) programming through combination of declarative constraints, state machines, and a live, visual notation [32], and the specification of UI behaviors through direct manipulation of their ordering [25]. In developing procedural tools for artists, much can be borrowed from research in supporting novice programmers in other domains. In supporting young people and novice CAD users, it is important to balance accessibility with expressiveness. Often this can be achieved by presenting a small number of programming concepts in a relevant, creative context. Resnick and Silverman asserted that for young people, a little bit of programming goes a long way, and focused on developing tools with a minimal number of carefully selected programming concepts. This enables children to explore a variety of creative outcomes, while minimizing learning thresholds [40]. The Logo [34] and Scratch [39] programming languages are two examples of this approach, and apply carefully designed simple languages with computational drawing and interactive storytelling, respectively. Similarly, in the CAD domain, MetaMorphe presents a digital fabrication design framework in a format similar to web scripting, making parametric design accessible and expressive for people with familiarity in web programming [48], and Jacobs and Buechley assisted novices in expressive forms of computational design by linking a constrained programming environment with physical crafting [14]. We designed Para around a minimal set of programming concepts in order to make it accessible to novice coders. We structured these concepts within the software so that they could be used to produce diverse outcomes. Concrete interaction versus symbolic representation In fine art, concrete tools and media are common. These range from the physical (brushes, carving tools, hands), to digital (using direct-manipulation software to manually adjust bitmaps or vectors). There is evidence that concrete engagement aids creative decision making; designers often conceive ideas through reflection-in-action and through direct engagement with physical media [45]. Many digital interaction designers find it difficult to conceive of novel concepts while working in the immaterial domain of software [33]. Concrete engagement also can play a role in learning. Klemmer describes how concrete interactions can support learning of new concepts in ways that reading and listening do not [19]. In contrast to concrete media, programming is abstract and often requires working through a textual representation. Visual programming languages can reduce some of the challenges of textual languages; however, they still require the artist to work through an abstract representation of the artwork rather than on an artifact itself [50]. Our approach is different from both textual and visual programming languages because it uses direct manipulation of the artwork to define and manipulate procedural relationships. While it is difficult to describe certain computational concepts in concrete form, direct manipulation can be used to describe dynamic relationships in ways that are comparable to programming languages. The earliest example is SketchPad, which demonstrated that parametric relationships could be described by selecting and manipulating geometric shapes [47]. More recently, Kitty and Skuid aimed to reduce difficulty in animations and interactive infographics by creating dynamic behaviors through direct manipulation of a relational graph [17, 18] and Recursive Drawing enabled nonlinear editing of self-similar designs through the nesting of drawing canvases [43]. Hoarau and Conversy demonstrated graphic design tools that enable users to indicate dependencies between the properties of objects [12], Xia et al. applied object-oriented principles to reduce reliance on WIMP UIs for touch and tablet interfaces [54], and Blackwell demonstrated a direct-manipulation system for procedural editing of bitmaps [5]. In data visualization, Drawing Dynamic Data Visualizations [53] and Apparatus [44] support the creation of interactive visualizations through direct manipulation. Our work is differentiated from prior work in two ways: the domain in which we work, and our approach to evaluation. Whereas prior tools support data visualization, interactivity, and animation, or emphasize new interaction modalities, our objective is to develop accessible procedural tools that extend the practices of fine artists. This distinction is emphasized by Para’s support of iterative variation and dynamic duplication, which is absent from prior tools [12, 54, 17, 18]. We are inspired by prior work that suggests the creative potential of dynamic direct manipulation, but recognize the need to evaluate this approach in actual art practice. Much of the prior research lacks evaluation; Hoarau and Conversy are unsure if their interface is understandable due to lack of user evaluation, and Victor recognizes his tools are untested stating that they are “not necessarily the correct way of doing things” but rather a starting point for exploring new interfaces [53]. Other tools are evaluated, but focus on tool accessibility and efficiency through predefined tasks [54, 17, 18]. Conversely, we seek to understand the expressive potential of our system in professional art practice; therefore, we evaluate it through extended open-ended studies and present polished, original artwork in our results. Para software design and implementation Para is a software tool aimed at accessible yet expressive integration of procedural techniques in visual art through a direct-manipulation interface. Before building Para, we developed design guidelines by compiling procedural artworks by professional artists including Joshua Davis, Casey Reas, Marius Watz, Emilie Gobielle, Theo Watson, Christopher Coleman, and Erik Natzke. Analysis of this artwork revealed procedural aesthetics and methods consistent across the artworks (table 1, common). We also highlighted qualities found in only a few artworks that blended manual and procedural creation (table 1, rare). Following this initial analysis, we prototype interactions that supported similar approaches and aesthetics but were compatible with direct manipulation. The primary conventions we sought to preserve were image-based communication of structural and organizational relationships, support for live and non-linear edits, removal of textual commands and expressions, and integration of interface components from direct manipulation art tools. We iteratively re- <table> <thead> <tr> <th>Common</th> <th>Rare</th> </tr> </thead> <tbody> <tr> <td>Complex forms and patterns through procedural duplication and object-oriented programming.</td> <td>Close integration of procedural and manual illustration.</td> </tr> <tr> <td>Iterative variation across scale, form and color.</td> <td>Procedural transformation of hand-drawn artwork.</td> </tr> <tr> <td>Regular geometric/ symmetrical distribution of form.</td> <td></td> </tr> <tr> <td>Generative compositions through random distributions (normal, uniform, etc.)</td> <td></td> </tr> </tbody> </table> Table 1. Techniques identified in professional procedural artwork. A uniform distribution of random values between the min and max values of the reference. Random seed is re-calculated when min or max is manually changed. A normal distribution of values with the mean derived from the first reference object and a standard deviation derived from the distance between the first and last object. Polar values based on a diameter determined by the min and max values of the reference. A series which cycles through the values of the objects in the reference (e.g for reference values 360,45,250 the result will be 360,45,250,360,45, ...) Table 2. Iterative constraint behavior options. <table> <thead> <tr> <th>Iterative Behavior</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td>Interpolation</td> <td>Evenly distributed values sampled from a Lagrange polynomial derived from the reference.</td> </tr> <tr> <td>Random</td> <td>A uniform distribution of random values between the min and max values of the reference.</td> </tr> <tr> <td>Gaussian</td> <td>A normal distribution of values with the mean derived from the first reference object and a standard deviation derived from the distance between the first and last object.</td> </tr> <tr> <td>Radial</td> <td>Polar values based on a diameter determined by the min and max values of the reference.</td> </tr> <tr> <td>Alternate</td> <td>A series which cycles through the values of the objects in the reference (e.g. for reference values 360,45,250 the result will be 360,45,250,360,45,...)</td> </tr> </tbody> </table> Figure 2. Variations on many-to-many constraints. (a) Basic list constraint between 8 relatives and 2 references. (b) Radial pattern produced through radial distribution with two reference shapes. (c) Arc patterns and color gradient produced with polynomial interpolation. (d-f) Variations of polynomial, radial, and random distributions. Figure 3. Random starfield creation: (a) duplicating a star, (b) creating a row of stars, (c) creating variation in scale and color, (d) producing a random distribution, (e) manually manipulating points of star, and (f) finished starfield. list section of the document structure panel (fig 2 a). Manual transformations on a list are mapped to each member. For example, rotating a list will rotate each member around its own center, rather than the centroid as happens in geometric groups. This behavior allows one-to-many constraints where multiple objects are subject to one constraint. In the flower example, we can constrain the 14 small orange outer portions of each petal (fig 1) using a list and a single constraint. Para’s lists also facilitate iterative variation similar to that found in textually generated procedural art. This is achieved through many-to-many constraints: constraints in which both the reference and relative are lists. Many-to-many constraints create iterative mappings where each object in the relative list is constrained differently based on its index. This behavior is possible because unlike other tools [12, 17], Para’s lists are ordered. The values to constrain the relative are calculated by interpolating across the values of the objects in the reference list. Figure 2 demonstrates how a many-to-many constraint can be used to dynamically modify the distribution of a pattern. In this example, the shapes of a repeating ellipse and diamond pattern are constrained on the x and y axes by a reference list containing two green rectangles (fig 2 a). The artist can update the distribution of the diamond ellipse pattern by modifying the position of the rectangles. In the process, the geometric offsets are maintained between each member of the reference and relative. Different types of distributions can be created by altering the content of the reference list. If the reference list contains more than two members, a non-linear reference value set is produced (fig 2 c). These values are sampled from a Lagrange polynomial that is produced from the values of the objects of the reference list. Moving the second rectangle in the reference list up or down changes the polynomial and results in a curved distribution of the relative pattern. This interpolation technique can produce many different types of non-linear distributions across any property, including parabolas, waves, and ellipses, by adding more shapes to the reference list. Because interpolation does not support all distributions, Para allows artists to select different mapping behaviors for constraints from a drop-down menu in the constraint inspector (fig 2 c). Table 2 lists the current options and their calculation mechanisms and figure 2, b, e, and f demonstrate distributions derived from radial and random mappings. The constraint inspector also enables artists to modify the individual offsets for each member of the reference list using the relative index selector, or exclude a relative member from being affected using the exception button (fig 2 b). Duplicators Our analysis of procedural art demonstrated the importance of automatically creating new forms for generative compositions. Constraints and lists facilitate procedural relationships, but cannot generate new objects by themselves. To address this, we added duplicators to Para. Duplicators are specialized lists with the ability to declaratively control the number of objects they contain. Duplicators are initialized on a single object. Doing so generates or deletes new shapes when the count is increased or decreased. When first created, duplicators contain self-referencing constraints on all geometric and stylistic properties. Practically, this results in iterative variations across all members of a duplicator on any property by directly manipulating either the first or last objects. Updates to the number of copies of a duplicator will preserve these variations. Like other constraints, duplicator constraints can be modified using the constraint interface to change offsets, specify exceptions, and change constraint behavior for different properties and sub-properties. Duplicators also can act as references or relatives in manually created constraints. To preserve correspondence across the geometry of their members, duplicators enact a constraint-like behavior on the paths of all of the duplicates wherein changes to the points of any individual shape are propagated across the other copies. Duplicators build on the low-level functionality of lists and constraints to enable creation and management of distributions with many shapes, for example, the creation of a random star field in Figure 3. A single five-point star is drawn and duplicated (fig 3 a). The start and end copies are manually altered by position, scale, and fill color to produce a diagonal line of stars growing in size and brightness (fig 3 b). The x-position constraint mapping is changed to random, producing a vertical gradient from light to dark (fig 3 c). Changing the mapping of the y-position constraint to random results in a field of stars with a random distribution of brightness and scale (fig 3 d). The random distribution can be recalculated by manually dragging the first or last star, and the number of stars can be increased by modifying the count. The shape of each star can be altered by modifying the points of any individual star (fig 3 f). Geometric groups also can be converted into duplicators, thereby enabling more complex distributions (fig 4). Groups are a structural way to make compound objects and do not serve a procedural purpose on their own. For group duplicators, constraints are created between each respective member of a group across each copy to ensure that correspondence between each copy is maintained if the structure of a single group is altered (fig 4 d-f). In Para’s internal representation, duplicator constraints are identical to many-to-many constraints. Duplicator constraints are between a reference list consisting of the first and last member of the duplicator, and a relative list consisting of the duplicator’s children. Self-referencing is possible because objects in Para can be in multiple lists simultaneously. EVALUATIONS The evaluation of Para had two objectives: to evaluate the accessibility and expressiveness of Para in an open-ended setting and to understand how procedural tools could support manual artists. We conducted two studies targeting both objectives. The first evaluation was a breadth-based workshop with 11 artists, aimed at revealing the creative trade-offs between direct and textual tools. The second evaluation was an in-depth study with a single artist, aimed at evaluating Para’s performance in realistic creative practice. Building from the opportunities and challenges highlighted in our background research and our analysis of professional procedural artwork, we developed the following evaluation criteria: Ease of use: Is it easy for novice programmers to use the tool? Can people understand the tool’s artistic applications? Creative outcomes: Does the tool support the creation of different procedural aesthetics? Does the tool enable creating variations of a piece? Process: How does working with the tool compare to traditional art tools? Can artists integrate their prior expertise? Can people move between manual and procedural creation? Reflection: Does the tool encourage thinking about procedural relationships? Does the tool affect how people think about making art? In each study we collected data through recorded discussions, surveys, and participant artwork. Surveys contained attitudinal questions relating to our evaluation criteria, using 5-point Likert scales, with 5 as the optimal response. Survey results, discussion transcripts, and artwork were analyzed with respect to our evaluation criteria. The majority of the results are qualitative, triangulated from open-ended survey responses and group or individual discussions. When scale data are used, we present the median and standard deviation. Workshop study methodology Our workshop was conducted with 11 participants from a range of art and design backgrounds. The majority were inexperienced programmers (table 3). The workshop lasted 14 hours over two days and covered Para and the textual procedural art tool Processing. We compared Para to Processing because Processing shares many of the same accessibility objectives as Para. Our goal was to compare Para’s accessibility and expressiveness to textual procedural tools, therefore we did not compare Para to non-procedural design tools like Adobe Illustrator. Illustrator emphasizes manual drawing tools, which are not the focus of Para’s innovation. Participants were first introduced to Para and given incremental demonstrations in the use of duplicators and groups, followed by a period for free experimentation. Participants then were introduced to Processing and provided instruction in syntax, drawing and transforming shapes, loops, mathematical expressions and conditionals and then given opportunities to freely experiment. Our instruction in Processing was based on approaches for beginners from the Processing Handbook [36], and demonstrated methods for producing designs that were similar to those possible using Para. Following the instruction period, participants had 3 hours to work on a piece of their choice with either or both tools. We also allowed participants to use other tools in conjunction with Processing and Para (e.g., Photoshop and Illustrator) for bitmap manipulation and detailed manual drawing, tasks not intended to be supported by Para or Processing. Limitations Our study required professionals to rely on prototype software with less sophisticated drawing tools than commercial software, which people found limiting. This is common in systems-building research. Although Processing was the most relevant textual procedural art tool to compare with Para, it also includes features for animation and interactivity. These features do not exist in Para and are, therefore, not directly comparable. We compensated in our study by focusing on Processing’s capabilities for static procedural art. Para’s cycle-prevention feature was not implemented prior to our workshops; however, we notified participants of the issue, and with few exceptions, people did not create cycles. Our in-depth study surveys the experiences of one person; however, evaluations with additional artists from different backgrounds would likely reveal additional insights. We believe the variety of aesthetics and styles produced by one person suggests the potential of our approach to support a variety of artists. Finally, it is challenging to measure expressiveness because different artists are expressive in different ways. We therefore present the artwork created with our system in order to provide concrete examples of its expressiveness. Workshop results Overall results indicate that participants found the direct-manipulation interface of Para more intuitive to use than textual programming in Processing. People who specialized in graphic design and illustration prior to the workshop felt that Para fit well with their current practices and they were interested in using it in the future. People with backgrounds outside of graphic art and illustration were less interested. Participants felt that textual code could provide greater control for experienced programmers. In the following section, we detail these results in the context of our evaluation criteria. Ease of use: All participants were able to follow our instructions for using Para but struggled to understand our instructions for Processing. These observations were substantiated by survey responses: seven participants stated that they felt Para was easy to learn, and three felt Processing was easy to learn. Many participants said the difficulty of Processing increased their desire to practice it when they had the benefit of instructor support. Conversely, participants said Para was familiar and felt confident they could learn it independently. Process: All participants experimented with both Processing and Para throughout the workshop. Participants exhibited a mix of responses with regard to how Processing fit with their prior art practice (mean: 3.6, std: 0.92); however, nearly all participants expressed interest in using the tool in the future (mean: 4.3, std: 0.47). In survey and verbal responses, participants indicated they struggled with understanding the logic of Processing programs. Several people described their process as one of trial and error. In addition, people were frustrated by not being able to adjust artwork manually. Despite the challenges in learning Processing, several people talked about how they could exercise greater control and perform tasks not possible in Para. Four participants stated that Para fit well with their existing practice, and six (including the first four) stated that they could see themselves using Para in future work. People who had expertise in manual art and minimal programming experience were the most interested in using Para in the future. For people with interest in using procedural tools for 3D design and interactivity, Para was less relevant by design. Primary frustrations with Para centered on reduced sophistication of the direct-manipulation tools in comparison with commercial equivalents. Creative outcomes: Because of time constraints, participants were not able to create polished artwork with either Para or Processing, although participants made a series of sketches that suggested different directions for more sophisticated work (fig 5). Participants who relied exclusively on Processing primarily created variations of a radial distribution example we presented in the instruction, incorporating randomness on opacity, scale, or rotation of shapes (fig 5 a,b). Participants who used Para exhibited a range of approaches: one person used portions of an illustration created prior to the workshop in a duplicated pattern (fig 5 c), while another experimented with the duplication functionality to simulate 3D rotated columns. Another participant generated a series of incrementally rotated geometric shapes. Using Illustrator, he combined these forms with a radial pattern from Processing (fig 5 d). Eight people stated that Processing enabled them to create things they would have difficulty creating otherwise (mean: 4, std: 1). Ten people stated that Para enabled them to create things they would have difficulty making otherwise (mean: 4.1, std: 0.83). Reflection: In discussions and surveys, most participants felt that textual programming could be a powerful tool for art; however, they had a mix of reactions to using Processing. For several participants, using Processing underscored their prior associations of textual programming as inaccessible. The majority of participants felt that they would have to practice extensively with Processing to create sophisticated projects. In discussion and open-ended responses, participants expressed greater levels of confidence using Para because it had features similar to digital illustration programs. Others described Para’s interface as more intuitive than Processing. Several people wrote that they found the live feedback in Para helpful; however, these responses were solely from people with prior experience with textual programming tools. None of the people new to programming commented on the live aspects, suggesting that people who only use direct manipulation may take liveness as a given in digital tools. Several participants talked about using Para and Processing for different purposes. One participant said Para was ideal for creating complex static illustrations, but Processing offered the opportunity for interactive pieces. Another participant said that Para and Processing were appropriate for different points in her artistic process, and said she would use Processing if she had a clear goal in mind. In-depth study methodology The workshop underscored the learnability of our system but did not demonstrate how Para performs in real art practice. We performed a second study to understand what kinds of artwork a person could create with Para through extended use. We commissioned the professional artist Kim Smith to use Para for two weeks to create several pieces of art. Smith has extensive experience in abstract painting (fig 7 a), realistic illustration (fig 6 k,l), and graphic design. She is an expert with both manual and digital tools (table 3). She had an interest in applying procedural techniques in her work but was reluctant to invest the time needed to learn programming. We met with Smith in person six times over the course of the study, every 2-3 days, for 1-2 hours apiece. First, we introduced her to Para in a 1-hour training session. In later meetings we reviewed the artwork she produced and discussed her experience. We gave her the choice of what to create during the study, but suggested experimenting with abstract and illustrative styles. Similar to the workshop, we allowed her to incorporate other digital tools into her work with Para. In the results, we distinguish between portions of artwork produced with Para and those produced by other means. In addition to written surveys and interviews, Smith wrote short reflections after every working session. We used automated surveys within Para to assess her experience while using the system [40]. Automated dialogs appeared every 20 minutes asking questions about her current task, goals and difficulties, and a snapshot of her work was saved. Throughout the study, we used Smith’s feedback to iterate on Para’s functionality. In-depth study results Smith found Para to be intuitive and felt she could use it more effectively and with greater confidence than textual programming and parametric CAD tools. She produced seven finished pieces and applied Para to abstract and illustrative styles. In her artwork, she used duplicators and iteratively constrained lists, but did not find one-to-one constraints as useful. Smith felt Para was compatible with her painting practice and also offered new opportunities for creative exploration. Using Para altered the way she thought about her artistic process, and she requested to continue using the software afterwards. Ease of use: Smith’s feedback from the experience sampling indicated that she struggled initially with Para’s vector selection and editing tools, which were less refined than those in commercial software. Otherwise, she described the Para interface as accessible and enjoyable. Specifically, she said the emphasis on visual manipulation was “welcoming and friendly,” and contrasted this with using complex CAD software and textual programming tools. She also stated that Para made her “comfortable starting with a blank canvas” because the visual interface gave her confidence that she could produce something, and develop a process. When asked about the minimal procedural feature set, she said, “I think there’s a lot of options in a very small parameter set.” Smith contrasted her use of Para with her use of textual programming tools: It’s like this big wall that is slowing me down. I would imagine if I was good with Processing there would be a lot more I could do with it... But the entry point for me is high. For a long time it’s going to be in my way. Smith found some procedural aspects of Para to be difficult. Initially she struggled with understanding the order in which shapes should be selected for one-to-one constraints. We modified the constraint tool to automatically pull up the property selection interface for selected objects when the tool was enabled. Smith said these revisions made the tool more intuitive. Although she experimented with one-to-one constraints and felt they might be useful for other artists, Smith never found a way to use them in her work. Smith also encountered organizational challenges when creating extremely complex work. At times it was difficult for her to identify and select specific procedural relationships. We partially addressed this by adding the ability to label constraints, lists, and geometry; however, organization remained an issue. In discussion, Smith pointed out how organization was also a challenge in non-procedural digital art tools, but felt that organizational mechanisms were particularly important for tools like Para because they made it easier to quickly build complexity. Creative Outcomes: In week 1, Smith created four abstract pieces using Para (see examples in (fig 7 b,d). She produced them by drawing vector shapes in Para, and used duplicators to create multiple copies with iterative changes in color, scale, and position. In week 2, Smith made two more abstract pieces. These incorporated procedural variation of opacity and blend modes, and constrained lists (fig 7 c). She also made an illustration (fig 6 j), that applied duplicators, lists, and iterative constraints to the creation of flowers (fig 6 a-d) and a snake (fig 6 e-i). In abstract and illustrative pieces, Smith used Photoshop to add additional color and texture by using painted imagery as a transparent overlay and background. extend existing digital art tools. ...cedural structure of Para demonstrated how our system could effectively incorporate features from Photoshop into the procedural art. The ability to quickly and control of opacity and blend enabled her to use subtractive masks in a dynamic fashion. The lack of refined drawing tools made the illustrative work laborious at times. While Smith found constraints and duplicators useful in both abstract and illustrative work, she used other procedural aspects less. Lists were confusing at first, and it was labor-intensive to manually constrain them. We simplified lists to function similar to duplicators with automatically created self-referencing constraints. Smith said this modification corresponded with her objectives, and applied the new lists in her illustrations (fig 6 j) and abstract work (fig 7 c). Producing numerous variations with Para led Smith to identify the need for versioning functionality. **Reflection:** Smith reflected on how Para was uniquely suited for combining abstract and illustrative forms: *I think there’s a space between abstraction and representation* ... *this ambiguous in-between space where Para could be very useful.* She also described how the process behind a work of art was as important as the work itself: *I want to create things that surpass the tool and it’s not so obvious that some other process did all the interesting work.* As a result, she felt more successful when using Para in a way that obscured the use of obvious procedural aesthetics. In the closing interview, Smith described how working with Para had changed the way she thought about her own art process: *The inclusion of Para changes not just the visual output. It changes the process, and that’s a lot of what I think about — how the tool changes the way you make things.* **DISCUSSION** The components of Para provide one entry point into procedural art. Here we discuss the creative opportunities that resulted from the design of those components through three principle questions. Was Para compatible with the skills of manual artists? Did Para offer meaningful creative opportunities? What are the limitations of direct manipulation? In addressing these questions, we provide the following recommendations for building expressive direct manipulation procedural tools: 1) Extending manual drawing tools with declarative relationships allows experienced artists to leverage existing skills. 2) It is possible to preserve expressiveness in direct-manipulation procedural tools by designing the tool around a small number of procedural concepts that can be combined in different ways to produce different outcomes. 3) Procedural tools with concretely represented relationships can enable productive exploration of form, color, and composition for professional artists. **Was Para compatible with the skills of manual artists?** The design of Para was partially based on the theory that a direct-manipulation procedural tool would be compatible with manual practice and enable manual artists to leverage existing skills. Two points of evidence support this theory. First, there are clear stylistic similarities between Smith’s --- Footnotes: 3Blend mode determines how an object is composited with those beneath it. 4Referring to abstract vs realistic (illustrative) imagery. results of our studies demonstrate that Para’s accessibility tools are, the less expressive they become. However, the commonalities suggest that in addition to making use of its procedural affordances, Smith was able to transfer her prior skills and practices to Para. Second, both Smith and participants in the workshop described Para as “intuitive”, “enjoyable” and “familiar,” in contrast to their experience with textual tools. The intuitive qualities of Para are important because, aside from supporting accessibility, intuitive tools support specific creative practices. People who think through movement, intuition, and visual impression require computational tools that validate intuitive and relational mindsets in order to be personally expressive [49]. In line with this, Smith and many of our workshop participants stated that intuition played an important role in their art. This suggests that direct-manipulation procedural tools offer two ways to extend manual practices: by enabling intuitive manipulation of procedural relationships and by providing procedural techniques that are aligned with both the affordances and interaction paradigms of conventional graphic art tools. **Did Para offer meaningful creative opportunities?** A common trade-off in tool design is that the more accessible tools are, the less expressive they become. However, the results of our studies demonstrate that Para’s accessibility did not prohibit expressive creation by professionals. Although our system contained a minimal number of procedural concepts, the artwork people created contained procedural forms and patterns comparable to those created with textual tools. The sketches produced in the workshop (fig 5 d) demonstrated radial distributions comparable in complexity and appearance to those created in Processing (fig 5 a-b). Smith’s illustration demonstrates parametric modulation in color, scale, and rotation across repeated forms, and her illustrative and abstract work contains generative forms and patterns. Parametric variation, generative form, and complexity via repetition are considered to be primary affordances of applying programming to art and design [38]. Para also offered new creative opportunities by facilitating new processes for making art. Smith described how the ability to rapidly produce and manipulate complex compositions facilitated exploration and iteration. She also felt that the generativity in Para led to new ways of thinking about the creative process, describing it as “a way of expanding one’s creative mind”. Finally, Smith identified unique creative opportunities in combining procedural exploration with manual control, which she noted were unique to Para. Overall study results and participant artwork demonstrate how a small number of reconfigurable procedural concepts can support new processes and aesthetics through procedural exploration of form, color, and composition, as well as support new ways of thinking about the creative process itself. **What are the limitations of direct manipulation?** Despite the intuitive qualities of direct-manipulation tools, they are limited in some ways compared to textual tools. In Para, people sometimes struggled with interpreting and controlling complex relationships. Symbolic textual expressions can concisely and unambiguously represent complex relationships in ways that images cannot [26]. People also became frustrated attempting to make precise patterns through direct selection, or in managing the organization of particularly complex compositions. In comparison to Para, and direct-manipulation software in general, textual programming tools can better support numerical evaluation and accuracy. Furthermore, computational abstraction as expressed through textual tools can greatly aid in complex organizational tasks. While the representational nature of programming can create a barrier for manual creation, it also offers opportunities for reflection. Code can simultaneously serve as a functional object and as a record of ideas and process [22]; thus, writing code can enable active reflection on the relationships that define one’s work. Understanding abstraction is difficult [52], and our studies demonstrate that on its own, direct manipulation does not lead to the understanding of representational concepts. However, given the confidence people expressed when using Para, direct manipulation of procedural relationships may provide a way to make the challenge of learning abstract representational tools more approachable. Alan Kay theorized that direct manipulation might aid in the learning process of representational systems by helping people to develop mental maps of abstract concepts [16]. With further development, tools like Para could assist manual artists in the process of understanding computational abstraction and benefiting from its application to their art. Overall we believe there is potential expand the expressiveness of systems like Para through close integration of direct manipulation and textual programming paradigms. Systems that enable artists to express relationships textually and then experiment with them through direct manipulation may scaffold learning and support new forms of creative expression. **CONCLUSION AND FUTURE WORK** Through development and evaluation of a direct manipulation procedural art tool, we demonstrate that it is possible to support concrete and manual creation while simultaneously enabling expressive forms of procedural design. Going forward, we see additional opportunities to evaluate procedural direct manipulation within the context of self efficacy and our system’s correspondence with the mental models of visual artists. We are also excited about the creative opportunities of procedural direct manipulation, and the potential for future systems that integrate this approach with other forms of programming. Overall, we see Para as a platform for developing new technologies that further support the combination of manual and procedural creation. **ACKNOWLEDGMENTS** We thank all the artists that participated in our workshop. Special thanks to Kim Smith, and also to Michael Craig for contributing to development. We would also like to thank N. Gillian, R. Jacobs, D. Mellis, A. Zoran, E. Natzke, D. Ito, the Dynamic Medium Group, and M. Resnick and the Lifelong Kindergarten Group. REFERENCES
{"Source-Url": "http://joelbrandt.com/publications/jacobs-chi2017-supporting-expressive-procedural-art.pdf", "len_cl100k_base": 8983, "olmocr-version": "0.1.53", "pdf-total-pages": 12, "total-fallback-pages": 0, "total-input-tokens": 38232, "total-output-tokens": 12786, "length": "2e13", "weborganizer": {"__label__adult": 0.0015726089477539062, "__label__art_design": 0.273681640625, "__label__crime_law": 0.0009708404541015624, "__label__education_jobs": 0.028289794921875, "__label__entertainment": 0.0011262893676757812, "__label__fashion_beauty": 0.0011653900146484375, "__label__finance_business": 0.001033782958984375, "__label__food_dining": 0.0012941360473632812, "__label__games": 0.0027484893798828125, "__label__hardware": 0.00331878662109375, "__label__health": 0.0016727447509765625, "__label__history": 0.0017900466918945312, "__label__home_hobbies": 0.0009927749633789062, "__label__industrial": 0.0018472671508789065, "__label__literature": 0.003528594970703125, "__label__politics": 0.0005812644958496094, "__label__religion": 0.0027790069580078125, "__label__science_tech": 0.1964111328125, "__label__social_life": 0.0005373954772949219, "__label__software": 0.037689208984375, "__label__software_dev": 0.43408203125, "__label__sports_fitness": 0.0006880760192871094, "__label__transportation": 0.0015878677368164062, "__label__travel": 0.0006432533264160156}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 58994, 0.03054]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 58994, 0.42492]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 58994, 0.91346]], "google_gemma-3-12b-it_contains_pii": [[0, 3152, false], [3152, 9630, null], [9630, 16442, null], [16442, 18193, null], [18193, 23297, null], [23297, 28301, null], [28301, 34569, null], [34569, 39484, null], [39484, 42824, null], [42824, 49200, null], [49200, 53806, null], [53806, 58994, null]], "google_gemma-3-12b-it_is_public_document": [[0, 3152, true], [3152, 9630, null], [9630, 16442, null], [16442, 18193, null], [18193, 23297, null], [23297, 28301, null], [28301, 34569, null], [34569, 39484, null], [39484, 42824, null], [42824, 49200, null], [49200, 53806, null], [53806, 58994, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 58994, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 58994, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 58994, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 58994, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 58994, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 58994, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 58994, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 58994, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 58994, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 58994, null]], "pdf_page_numbers": [[0, 3152, 1], [3152, 9630, 2], [9630, 16442, 3], [16442, 18193, 4], [18193, 23297, 5], [23297, 28301, 6], [28301, 34569, 7], [34569, 39484, 8], [39484, 42824, 9], [42824, 49200, 10], [49200, 53806, 11], [53806, 58994, 12]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 58994, 0.07975]]}
olmocr_science_pdfs
2024-12-07
2024-12-07
979f94de3d6573f6b1142c3af8653e4f4e24d465
This is the accepted version of a paper presented at *CGO 2017, February 4–8, Austin, TX.* **Citation for the original published paper:** N.B. When citing this work, cite the original published paper. **Permanent link to this version:** http://urn.kb.se/resolve?urn=urn:nbn:se:uu:diva-316480 Abstract To enhance the performance of memory-bound applications, hardware designs have been developed to hide memory latency, such as the out-of-order (OoO) execution engine, at the price of increased energy consumption. Contemporary processor cores span a wide range of performance and energy efficiency options: from fast and power-hungry OoO processors to efficient, but slower in-order processors. The more memory-bound an application is, the more aggressive the OoO execution engine has to be to hide memory latency. This proposal targets the middle ground, as seen in a simple OoO core, which strikes a good balance between performance and energy efficiency and currently dominates the market for mobile, hand-held devices and high-end embedded systems. We show that these simple, more energy-efficient OoO cores, equipped with the appropriate compile-time support, considerably boost the performance of single-threaded execution and reach new levels of performance for memory-bound applications. Clairvoyance generates code that is able to hide memory latency and better utilize the OoO engine, thus delivering higher performance at lower energy. To this end, Clairvoyance overcomes restrictions which yielded conventional compile-time techniques impractical: (i) statically unknown dependencies, (ii) insufficient independent instructions, and (iii) register pressure. Thus, Clairvoyance achieves a geometric execution time improvement of 7% for memory-bound applications with a conservative approach and 13% with a speculative but safe approach, on top of standard O3 optimizations, while maintaining compute-bound applications’ high-performance. Highly efficient designs are needed to provide a good balance between performance and power utilization and the answer lies in simple, limited out-of-order (OoO) execution cores like those found in the HPE Moonshot m400 [5] and the AMD A1100 Series processors [6]. Yet, the effectiveness of moderately-aggressive OoO processors is limited when executing memory-bound applications, as they are unable to match the performance of the high-end devices, which use additional hardware to hide memory latency. This work aims to improve the performance of highly energy-efficient, limited OoO processors, with the help of advanced compilation techniques. The static code transformations are specially designed to hide the penalty of last-level cache misses and to better utilize the hardware resources. One primary cause for slowdown is last-level cache (LLC) misses, which, with conventional compilation techniques, result in a sub-optimal utilization of the limited OoO engine that may stall the core for an extended period of time. Our method identifies potentially critical memory instructions through advanced static analysis and hoists them earlier in the program’s execution, even across loop iteration boundaries, to increase memory-level parallelism (MLP). We overlap the outstanding misses with useful computation to hide their latency and thus increase instruction-level parallelism (ILP). There are a number of challenges that need to be met to accomplish this goal. 1. Finding enough independent instructions: A last level cache miss can cost hundreds of cycles [7]. Conventional instruction schedulers operate on the basic-block level, limiting their reach, and, therefore, the number of independent instructions that can be scheduled in order to hide long latencies. More sophisticated techniques (such as software pipelining [8, 9]) schedule across basic-block boundaries, but instruction reordering is severely restricted in general-purpose applications when pointer aliasing and loop-carried dependencies cannot be resolved at compile-time. Solutions are needed that can cope with statically unknown dependencies in order to effectively increase the reach of the compiler while ensuring correctness. 2. Chains of dependent long latency instructions are serialized: Dependence chains of long latency instructions... would normally serialize, as the evaluation of one long latency instruction is required to execute another (dependent) long latency instruction. This prevents parallel accesses to memory and may stall a limited OoO core. Novel methods are required to increase memory level parallelism and to hide latency, which is particularly challenging in tight loops and codes with numerous (known and unknown) dependencies. 3. **Increased register pressure**: Separating loads and their uses in order to overlap outstanding loads with useful computation increases register pressure. This causes additional register spilling and increases the dynamic instruction count. Controlling register pressure, especially in tight loops, is crucial. **Contributions:** Clairvoyance looks ahead, reschedules long latency loads, and thus improves MLP and ILP. It goes beyond static instruction scheduling and software pipelining techniques, and optimizes general-purpose applications, which contain large numbers of indirect memory accesses, pointers, and complex control-flow. While previous compile-time techniques are inefficient or simply inapplicable to such applications, we provide solutions to well-known problems, such as: 1. Identifying potentially delinquent loads at compile-time; 2. Overcoming scheduling limitations of statically unknown memory dependencies; 3. Reordering chains of dependent memory operations; 4. Reordering across multiple branches and loop iterations, without speculation or hardware support; 5. Controlling register pressure. Clairvoyance code runs on real hardware prevalent in mobile, hand-held devices and in high-end embedded systems and delivers high-performance, thus alleviating the need for power-hungry hardware complexity. In short, Clairvoyance increases the performance of single-threaded execution by up to 43% for memory bound applications (13% geometric improvement) on top of standard O3 optimizations, on hardware platforms which yield a good balance between performance and energy efficiency. 2. **The Clairvoyance Compiler** This section outlines the general code transformation performed by Clairvoyance while each subsection describes the additional optimizations, which make Clairvoyance feasible in practice. Clairvoyance builds upon techniques such as software pipelining [9, 10], program slicing [11], and decoupled access-execute [12–14] and generates code that exhibits improved memory-level parallelism (MLP) and instruction-level parallelism (ILP). For this, Clairvoyance prioritizes the execution of critical instructions, namely loads, and identifies independent instructions that can be interleaved between loads and their uses. Figure 1 shows the basic Clairvoyance transformation, which is used as a running example throughout the paper. The transformation is divided into two steps: **Loop Unrolling** To expose more instructions for reordering, we unroll the loop by a loop unroll factor $\text{count}_{\text{unroll}} = 2^n$ with $n = \{0, 1, 2, 3, 4\}$. Higher unroll counts significantly increase code size and register pressure. In our examples, we set $n = 1$ for the sake of simplicity. **Access-Execute Phase Creation** Clairvoyance hoists all load instructions along with their requirements (control flow and address computation instructions) to the beginning of the loop. The group of hoisted instructions is referred to as the Access phase. The respective uses of the hoisted loads and the remaining instructions are sunk in a so-called Execute phase. **Access** phases represent the program slice of the critical loads, whereas **Execute** phases contain the remaining instructions (and guarding conditionals). When we unroll the loop, we keep non-statically analyzable exit blocks. All exit blocks (including goto blocks) in Access are redirected to Execute, from where they will exit the loop after completing all computation. The algorithm is listed in Algorithm 1 and proceeds by unrolling the original loop and creating a copy of that loop (the Access phase, Line 3). Critical loads are identified (FindLoads, Line 4) together with their program slices (instructions required to compute the target address of the load and control instructions required to reach the load, Lines 5 - 9). Instructions which do not belong to the program slice of the critical loads are filtered out of Access (Line 10), and instructions hoisted to Access are removed from Execute (Line 11). The uses of the removed instructions are replaced with their corresponding clone from Access. Finally, Access and Execute are combined into one loop (Line 12). ``` Input: Loop $L$, Unroll Count $\text{count}_{\text{unroll}}$ Output: Clairvoyance Loop $L_{\text{Clairvoyance}}$ 1 begin 2 $L_{\text{unrolled}} \leftarrow \text{Unroll}(L, \text{count}_{\text{unroll}})$ 3 $L_{\text{access}} \leftarrow \text{Copy}(L_{\text{unrolled}})$ 4 hoist_list $\leftarrow \text{FindLoads}(L_{\text{access}})$ 5 to_keep $\leftarrow \emptyset$ 6 for load in hoist_list do 7 requirements $\leftarrow \text{FindRequirements}(\text{load})$ 8 to_keep $\leftarrow \text{Union}(\text{to_keep}, \text{requirements})$ 9 end 10 $L_{\text{access}} \leftarrow \text{RemoveUnlisted}(L_{\text{access}}, \text{to_keep})$ 11 $L_{\text{execute}} \leftarrow \text{ReplaceListed}(L_{\text{access}}, L_{\text{unrolled}})$ 12 $L_{\text{Clairvoyance}} \leftarrow \text{Combine}(L_{\text{access}}, L_{\text{unrolled}})$ 13 return $L_{\text{Clairvoyance}}$ end ``` **Algorithm 1:** Basic Clairvoyance algorithm. The Access phase is built from a copy of the unrolled loop. The Execute phase is the unrolled loop itself, while all already computed values in Access are reused in Execute. Figure 1. The basic Clairvoyance transformation. The original loop is first unrolled by \texttt{count\_unroll} which increases the number of instructions per loop iteration. Then, for each iteration, Clairvoyance hoists all (critical) loads and sinks their uses to create a memory-bound Access phase and a compute-bound Execute phase. This code transformation faces the same challenges as typical software pipelining or global instruction scheduling: (i) selecting the loads of interest statically; (ii) disambiguating pointers to reason about reordering memory instructions; (iii) finding sufficient independent instructions in applications with entangled dependencies; (iv) reducing the instruction count overhead (e.g., stemming from partly duplicating control-flow instructions); and (v) overcoming register pressure caused by unrolling and separating loads from their uses. Each of these challenges and our solutions are detailed in the following subsections. 2.1 Identifying Critical Loads \textbf{Problem:} Selecting the right loads to be hoisted is essential in order to avoid code bloat and register pressure and to ensure that long latency memory operations overlap with independent instructions. \textbf{Solution:} We develop a metric, called indirection count, based on the number of memory accesses required to compute the memory address (indirections) \cite{14} and the number of memory accesses required to reach the load. For example, $x[y[z[i]]]$ has an indirection count of two, as it requires two loads to compute the address. The latter interpretation of indirection count is dependent on the control flow graph (CFG). If a load is guarded by two if-conditions that in turn require one load each, then the indirection count for the CFG dependencies is also two. Figure 2 shows an example of load selection with indirection counts. A high value of indirection indicates the difficulty of predicting and prefetching the load in hardware, signaling an increased likelihood that the load will incur a cache miss. For each value of this metric, a different code version is generated (i.e., hoisting all loads that have an indirection count less than or equal to the certain threshold). We restrict the total number of generated versions to a fixed value to control code size increase. Runtime version selection (orthogonal to this proposal) can be achieved with dedicated tools such as Protean code \cite{15} or VMAD \cite{16,17}. 2.2 Handling Unknown Dependencies \textbf{Problem:} Hoisting load operations above preceding stores is correct if and only if all read-after-write (RAW) dependencies are respected. When aliasing information is not known at compile-time, detecting dependencies (or guaranteeing the lack of dependencies) is impossible, which either prevents reordering or requires speculation and/or hardware support. However, speculation typically introduces considerable overhead by squashing already executed instructions and requiring expensive recovery mechanisms. \textbf{Solution:} We propose a lightweight solution for handling statically known and unknown dependencies, which ensures correctness and efficiency. Clairvoyance embraces\textit{ safe specu-} Figure 3. Handling of may-aliasing loads. Loads that may alias with any preceding store operation are not safe to hoist. Instead, we prefetch the unsafe load. Clairvoyance, which brings the benefits of going beyond conservative compilation, without sacrificing simplicity and lightness. We propose a hybrid model to hide the latency of delinquent loads even when dependencies with preceding stores are unknown (i.e., may-alias). Thus, loads free of dependencies are hoisted to Access and the value is used in Execute, while loads that may alias with stores are prefetched in Access and safely loaded and used in their original position in Execute. May-aliases, however, are an opportunity, since in practice may-aliases rarely materialize into real aliasing at runtime [18]. Prefetching in the case of doubt is powerful: (1) if the prefetch does not alias with later stores, data will have been correctly prefetched; (2) if aliasing does occur, the prefetched data becomes overwritten and correctness is ensured by loading the data in the original program order. Figure 3 shows an example in which an unsafe load is turned into a prefetch-load pair. The proposed solution is safe. In addition to this solution, we will analyze variations of this solution that showcase the potential of Clairvoyance when assuming a stronger alias analysis. These more speculative variations are allowed to hoist whole chains of may-aliasing loads and will be introduced during the experimental setup in Section 3. ### 2.3 Handling Chains of Dependent Loads **Problem:** When a long latency load depends on another long latency memory operation, Clairvoyance cannot simply hoist both load operations into Access. If it did, the processor might stall, simply because the second critical load represents a use of the first long latency load. As an example, in Figure 4 we need to load the branch predicate $t_1$ before we can load $t_2$ (control dependency). If $t_1$ is not cached, an access to $t_1$ will stall the processor if the out-of-order engine cannot reach ahead far enough to find independent instructions and hide the load’s latency. **Solution:** We propose to build multiple Access phases, by splitting dependent load chains into chains of dependent Access phases. As a consequence, loads and their uses within access phase are separated as much as possible, enabling more instructions to be scheduled in between. By the time the dependent load is executed, the data of the previous load may already be available for use. Each phase contains only independent loads, thus increasing the separation between loads and their uses. In Figure 4 we separate the loads into two Access phases. For the sake of simplicity, this example uses count_unroll = 2, hence there are only two independent loads to collect into the first Access phase and four into the second Access phase. The algorithm to decide how to distribute the loads into multiple Access phases is shown in Algorithm 2. The compiler first collects all target loads in remaining_loads, while the distribution of loads per phase phase_loads is initialized to empty-set. As long as the loads have not yet been distributed (Line 4), a new phase is created (Line 5) and populated with loads whose control-requirements (Line 8) and data-requirements (Line 9) do not match any of the loads that have not yet been distributed in a preceding Access phase (Line 10 and 11-14). Loads distributed in the current phase are removed from the remaining_loads only at the end (Line 15), ensuring that no dependent loads are distributed to the same Access phase. The newly created set of loads phase is added to the list of phases (Line 16) and the algorithm continues until all critical loads have been distributed. Next, we generate each Access phase by following Algorithm 1 corresponding to a set of loads from the list phase_loads. ### 2.4 Overcoming Instruction Count Overhead **Problem:** The control-flow-graph is partially duplicated in Access and Execute phases, which, on one hand, enables instruction reordering beyond basic block boundaries, but, on the other hand, introduces overhead. As an example, the branch using predicate $t_1$ (left of Figure 5) is duplicated in each Access phase, significantly increasing the overhead in Input: Set of loads Output: List of sets phase_loads begin remaining_loads ← loads phase_loads ← [] while remaining_loads ≠ ∅ do phase ← ∅ for ld in remaining_loads do reqs ← ∅ FindCFGRequirements (ld, reqs) FindDataRequirements (ld, reqs) is_independent ← Intersection(reqs, remaining_loads) == ∅ if is_independent then phase ← phase + ld end end remaining_loads ← remaining_loads \ phase phase_loads ← phase_loads + phase end return phase_loads end Algorithm 2: Separating loads for multiple Access phases. Figure 5. Early evaluation of branches enables the elimination of duplicated branches in Clairvoyance mode. Relevant branches are evaluated at the beginning of the loop. If the evaluated branches are taken, the optimized Clairvoyance code with merged basic blocks is executed; otherwise, the decoupled unrolled code (with branch duplication) is executed. The branches selected for clustering affect how often the optimized version will be executed. If we select all branches, the probability of all of them evaluating to true shrinks. Deciding the optimal combination of branches is a trade-off between branch duplication and the ratio of executing the optimized vs. the unoptimized version. As a heuristic, we only cluster branches if they statically have a probability above a given threshold. See Section 4 for more details. 2.5 Overcoming Register Pressure Problem: Early execution of loads stretches registers’ live ranges, which increases register pressure. Register pressure is problematic for two reasons: first, spilling a value represents an immediate use of the long latency load, which may stall the processor (assuming that Clairvoyance targets critical loads, whose latency cannot be easily hidden by a limited OoO engine); second, spill code increases the number of instructions and stack accesses, which hurts performance. Solution: To overcome this limitation, Clairvoyance generates an optimized version where selected branches are clustered at the beginning of a loop. If the respective branch predicates evaluate to true, Clairvoyance can then execute a version in which their respective basic blocks are merged. The right of Figure 5 shows the transformed loop, which checks $t_1$ and $t_2$ and if both predicates are true (i.e., both branches are taken), execution continues with the optimized version, in which the duplicated branch is eliminated. If $t_1$ or $t_2$ are false, then a decoupled unrolled version is executed. The branches selected for clustering affect how often the optimized version will be executed. If we select all branches, the probability of all of them evaluating to true shrinks. Deciding the optimal combination of branches is a trade-off between branch duplication and the ratio of executing the optimized vs. the unoptimized version. As a heuristic, we only cluster branches if they statically have a probability above a given threshold. See Section 4 for more details. 2.6 Heuristic to Disable Clairvoyance Transformations Clairvoyance may cause performance degradation despite the efforts to reduce the overhead. This is the case for loops with long latency loads guarded by many nested if-else branches. We define a simple heuristic to decide when the overhead of branches may outweigh the benefits, namely, if the number of targeted loads is low in comparison to the number of branches. To this end, we use a metric which accounts for the number of loads to be hoisted and the number of branches required to reach the loads: $$\frac{\text{loads}}{\text{branches}} < 0.7$$. and disable Clairvoyance transformations if the condition is met. ### 2.7 Parameter Selection: Unroll Count and Indirection We rely on state-of-the-art runtime version selectors to select the best performing version. In addition, simple static heuristics are used to simplify the configuration selection: small loops with few loads profit from a high unroll count to increase MLP; loops containing a high number of nested branches should have a low unroll and indirection count to reduce instruction count overhead; loops with large basic blocks containing both loads and computation may profit from a hybrid model using loads and prefetches to balance register pressure and instruction count overhead. ### 2.8 Limitations Currently, Clairvoyance relies on the LLVM loop unrolling, which is limited to inner-most loops. To tackle outer-loops, standard techniques such as unroll and jam are required. Unroll and jam refers to partially unrolling one or more loops higher in the nest than the innermost loop, and then fusing (“jamming”) the resulting loops back together. ### 3. Experimental Setup Our transformation is implemented as a separate compilation pass in LLVM 3.8 [20]. We evaluate a range of C/C++ benchmarks from the SPEC CPU2006 [21] and NAS benchmark [22–24] suites on an APM X-Gene processor [25], see Table 1 for the architectural specifications. The remaining benchmarks were not included due to the difficulties in compilation with LLVM or simply because they were entirely compute-bound. Clairvoyance targets loops in the most time-intensive functions (listed in Table 2), such that the benefits are reflected in the application’s total execution time. For SPEC, the selection was made based on previous studies [26], while for NAS we identified the target functions using Valgrind [27]. In Section 2.4 we introduced an optimization to merge basic blocks if the static branch prediction indicates a probability above a certain threshold. For the following evaluation, we cluster branches only if the probability is above 90%. ### 3.1 Evaluating LLVM, DAE and Clairvoyance We compare our techniques to Software Decoupled Access-Execute (DAE) [13, 14] and the LLVM standard instruction schedulers list-ilp (prioritizes ILP), list-burr (prioritizes register pressure) and list-hybrid (balances ILP and register pressure). DAE reduces the energy consumption by creating a duplicated loop that prefetches data ahead of time, while running at low frequency and maintaining its original performance. We further attempt to compare Clairvoyance against software pipelining and evaluate a target-independent, readily available software pipelining pass [28]. The pass fails to pipeline the targeted loops (all except of one fail) due to the high complexity (control-flow and memory dependencies). LLVM’s software pipeliner is not readily applicable for the target architecture, and could thus not be evaluated in this work. In the following, we will evaluate three techniques: **LLVM-SCHED** LLVM’s best-performing scheduling technique (one of list-ilp, list-burr, and list-hybrid). **DAE** Best performing DAE version. **CLAIRVOYANCE** Best performing Clairvoyance version. ### 3.2 A Study on Speculation Levels For Clairvoyance we evaluate a number of versions that vary in their speculative nature. **Consv** is a conservative version. which only hoists safe loads. In case of a chain of dependent loads, it turns the first unsafe load into a prefetch and does not target the remaining loads. Spec-safe is a speculative but safe version. It hoists safe loads, but unlike the consv version, in case of a chain of dependent loads, spec-safe duplicates unsafe loads in Access such that it is able to reach the entire chain of dependent loads. Then it turns the last unsafe load of each chain into a prefetch, and reloads the unsafe loads in Execute. Spec is a speculative but unsafe version which hoists all safe and unsafe loads and reuses them in Execute. Finally, multi-spec-safe and multi-spec represent the multiple-access versions of the previous two. The exploration of different speculation levels is a study to give an overview on Clairvoyance’s performance assuming increasingly accurate pointer analysis. The conservative consv version shows what we can safely transform at the moment, while spec indicates a perfect alias analyzer. We expect that state-of-the-art pointer analyses [29] approach the accuracy of spec. Spec-safe demonstrates the effect of combining both prefetches and loads. A better pointer analysis would enable Clairvoyance to safely load more values, and consequently we would have to cope with increased register pressure. To this end, spec-safe is a version that balances between loads and prefetches, and thus between register spills and increased instruction count overhead. The speculative but safe versions (spec-safe, multi-spec-safe) may cause a segmentation fault in Access when speculatively accessing memory locations to compute the target address of the prefetch. Since our transformation ensures that only safely loaded values are reused in Execute, segmentation faults that are triggered during an Access can be safely caught and ignored, for example by overwriting the segmentation fault handler. During code generation we can differentiate between speculative loads (loads hoisted above may-aliasing stores) and non-speculative loads (no-aliasing loads). If the address of a speculative load matches the address of the segmentation fault, the fault handler ignores it; otherwise, the fault is exposed to the user. In practice, however, none of the analyzed benchmarks caused such a fault. Spec and multi-spec are intended as an oracle with perfect alias-analysis. We do not implement a correction mechanism, as it would require alternative execution paths and is beyond the goal of this proposal. The results for spec, despite the speculative nature, are verified at runtime as being correct. ### 4. Evaluation In this section, we first compare different versions of Clairvoyance, starting with the conservative approach and gradually increasing the speculation level. Next we discuss the performance and energy improvements of the applications compiled with Clairvoyance. #### 4.1 Comparing Clairvoyance’s Speculation Levels Figure 6 compares the normalized runtimes of all Clairvoyance versions across all benchmarks. For the majority of workloads, the different degrees of speculation do not play a major role for the final performance. For hmm and libquantum we observe a significant difference between the more conservative versions (consv, spec-safe, multi-spec-safe) and the speculative ones (spec, multi-spec). Hmmer is a compute bound benchmark whose workload fits in the cache; therefore, there is little expected improvement. Furthermore, the target loop consists of one main basic block that contains a large number of loads interleaved with store instructions. The prefetches added by the conservative versions are not separated enough from their actual uses and thus translate to pure instruction count overhead, especially for a compute-bound application. Since the speculative versions only reorder the instructions, there is no additional overhead. This also applies to libquantum: libquantum consists of very small and tight loops, such that any added instruction count overhead quickly outweighs the benefits of Clairvoyance. On the other hand, there are workloads that benefit from a less aggressive hoisting of loads, such as lbm—which shows best results with spec-safe and multi-spec-safe. Separating a high number of potentially delinquent loads from their uses can increase register pressure significantly. Since spec-safe and its multiple access version multi-spec-safe use a combination of reordering loads and prefetches, these versions introduce less register pressure compared to spec. #### 4.2 Understanding Clairvoyance Best Versions We categorize the benchmarks into memory-bound applications (mcf, milc, soplex, libquantum, lbm, omnetpp, <table> <thead> <tr> <th>Name</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td>Consv</td> <td>Conservative, only hoists safe loads</td> </tr> <tr> <td>Spec-safe</td> <td>Speculative (but safe), hoists may-aliasing load chains, but safely reloads them in Execute</td> </tr> <tr> <td>Spec</td> <td>Speculative (unsafe), hoists may-aliasing load chains and reuses all data in Execute</td> </tr> <tr> <td>Multi-spec-safe</td> <td>Multi-access version of spec-safe</td> </tr> <tr> <td>Multi-spec</td> <td>Multi-access version of spec</td> </tr> </tbody> </table> **Table 3.** Clairvoyance evaluated versions. <table> <thead> <tr> <th>Benchmark</th> <th>Version</th> <th>Unroll</th> <th>Indir</th> </tr> </thead> <tbody> <tr> <td>429.mcf</td> <td>consv</td> <td>8</td> <td>0</td> </tr> <tr> <td>433.milc</td> <td>multi-spec-safe</td> <td>2</td> <td>0</td> </tr> <tr> <td>450.soplex</td> <td>spec</td> <td>2</td> <td>0</td> </tr> <tr> <td>462.libquantum</td> <td>spec</td> <td>4</td> <td>1</td> </tr> <tr> <td>470.lbm</td> <td>multi-spec-safe</td> <td>16</td> <td>1</td> </tr> <tr> <td>471.omnetpp</td> <td>Disabled</td> <td></td> <td></td> </tr> <tr> <td>473.astar</td> <td>Disabled</td> <td></td> <td></td> </tr> <tr> <td>CG</td> <td>spec</td> <td>4</td> <td>1</td> </tr> </tbody> </table> **Table 4.** Best performing versions for memory-bound benchmarks [30]. Access phases that may hurt performance. ...versions rely on a high unroll count and a low indirection count. The branch-merging optimization that allows for a higher unroll count is particularly successful for mcf, as the branch operations connecting the unrolled iterations are merged, showing low overhead across loop iterations. As the memory-bound applications contain a high number of long latency loads which can be hoisted to the Access phase, we are able to improve MLP while hiding the increased instruction count overhead. Clairvoyance was disabled for omnetpp and astar by the heuristic that prevents generating heavy-weight Access phases that may hurt performance. For compute-bound benchmarks the best performing versions have a low unroll count and a low indirection count, yielding versions that are very similar to the original. This is expected as Clairvoyance cannot help if the entire workload fits in the cache. However, if applied on compute-bound benchmarks, Clairvoyance will reorder instructions hiding even L1 cache latency. ### 4.3 Runtime and Energy Figure 7 compares the normalized runtimes when applying Clairvoyance and state-of-the-art techniques designed to hide memory latency: DAE and the optimal LLVM instruction scheduler selected for each particular benchmark. Clairvoyance-consv shows the performance achieved with the most conservative version, while Clairvoyance-best shows the performance achieved by the best Clairvoyance version (which may be consv or any of the speculative versions spec-safe, multi-spec-safe, spec, multi-spec). The baseline represents the original code compiled with -O3 using the default LLVM instruction scheduler. Measurements were performed by executing the benchmarks until completion. We attempted a comparison with available software pipeliners [20, 28] are either not available for our target machine, or cannot transform our target loops. For memory-bound applications we observe a geometric improvement of 7% with Clairvoyance-consv and 13% with Clairvoyance-best, outperforming both DAE and the LLVM instruction schedulers. The best performing applications are mcf (both Clairvoyance versions) and lbm (with Clairvoyance-best), which show considerable improvements in the total benchmark runtime (43% and 31% respectively). These are workloads with few branches and very "condensed" long latency loads (few loads responsible for most of the LLC misses). DAE is competitive to Clairvoyance, but fails to leverage the same performance for mcf. An analysis of the generated code suggests that DAE fails to identify the correct set of delinquent loads. Benchmarks with small and tight loops such as libquantum suffer from the additional instruction count overhead introduced by DAE, which duplicates target loops in order to prefetch data in advance. A slight overhead is observed with Clairvoyance-consv for tight loops, due to partial instruction duplication, but this limitation would be alleviated by a more precise pointer analysis, as indicated by Clairvoyance-best. We further observe that astar suffers from performance losses when applying DAE. Astar has multiple nested if-then-else branches, which are duplicated in Access and thus hurt performance. In contrast, our simple heuristic disables Clairvoyance optimization for loops with a high number of nested branches, and therefore avoids degrading performance. For the compute-bound applications, both the conservative and best versions of Clairvoyance preserve the O3 performance, on-par with the standard LLVM instruction schedulers, except for h264ref, where Clairvoyance-consv introduces an overhead. Again, a precise pointer analysis could alleviate this overhead and allow Clairvoyance to hide L1 latency, as in the case of h264ref. Figure 8 shows per loop runtimes, normalized to the original loop execution. Highly memory-bound benchmarks show significant speed-ups, mcf-68%, milc-20% and lbm-31%. Clairvoyance-consv introduces a small overhead for libquantum, which is corrected by Clairvoyance-best (assuming a more precise pointer analysis). As mentioned previously, Clairvoyance was disabled for omnetpp and astar. Overall, Clairvoyance-consv improves per loop runtime by 15%, approaching the performance of Clairvoyance-best (20%). We collect power numbers using measurement techniques similar to Spiliopoulos et al. [31]. Figure 9 shows the normalized energy consumption for all memory-bound benchmarks. The results align with the corresponding runtime trends: benchmarks as mcf and lbm profit the most with an energy reduction of up to 25%. For memory-bound benchmarks, we achieve a geomean improvement of 5%. By overlapping outstanding loads we increase MLP, which in turn results in shorter runtimes and thus lower total energy consumption. 5. Related Work Hiding long latencies of memory accesses to deliver high-performance has been a monumental task for compilers. Early approaches relied on compile-time instruction schedulers [32–36] to increase instruction level parallelism (ILP) and hide memory latency by performing local- or global-scheduling. Local scheduling operates within basic block boundaries and is the most commonly adopted algorithm in mainstream compilers. Global scheduling moves instructions across basic blocks and can operate on cyclic or acyclic control-flow-graph. One of the most advanced forms of static instruction schedulers is modulo scheduling [8, 9], also known as software pipelining, which interleaves different iterations of a loop. Clairvoyance overcomes challenges that led static instruction schedulers to generate suboptimal code: (1) Clairvoyance identifies potential long latency loads to compensate for the lack of dynamic information; (2) Clairvoyance combines prefetching with safe-reordering of accesses to address the problem of statically unknown memory dependencies; (3) Clairvoyance performs advanced code transformations of the control-flow graph, yielding Clairvoyance applicable on general-purpose applications, which were until now not amenable to software-pipelining. We emphasize that off-the-shelf software pipelining is tailored for independent loop iterations and is readily applicable on statically analyzable code, but it cannot handle complex control-flow, statically unknown dependencies, etc. Furthermore, among the main limitations of software pipelining are the prologues and epilogues, and high register pressure, typically addressed with hardware support. Clairvoyance advances the state-of-the-art by demonstrating the efficiency of these code transformations on codes that abound in indirect memory accesses, pointers, entangled dependencies, and complex, data-dependent control-flow. Typically, instruction scheduling and register allocation are two opposing forces [37–39]. Previous work attempts to provide register pressure sensitive instruction scheduling, in order to balance instruction level parallelism, latency, and spilling. Chen et al. [40] propose code reorganization to maximize ILP with a limited number of registers, by first applying a greedy superblock scheduler and then pushing over-hoisted instructions back. Yet, such instruction schedulers consider simple code transformations and compromise on other optimizations for reducing register pressure. Clairvoyance naturally releases register pressure by precisely increasing the live-span of certain loads only, by combining instruction re-ordering with prefetching and by merging branches. Hardware architectures such as Very Long Instruction Word (VLIW) and EPIC [41, 42], identify independent instructions suitable for reordering, but require significant hardware support such as predicated execution, speculative loads, verification of speculation, delayed exception handling, memory disambiguation, etc. In contrast, Clairvoyance is readily applicable on contemporary, commodity hardware. Clairvoyance decouples the loop, rather than simply reordering instructions; it generates optimized code that can reach delinquent loads, without speculation or hardware support for predicated execution and handles memory and control dependencies purely in software. Clairvoyance provides solutions that can re-enable decades of research on compiler techniques for VLIW-like and EPIC-like architectures. Software prefetching [43] instructions, when executed timely, may transform long latencies into short latencies. Clairvoyance attempts to fully hide memory latency with independent instructions (ILP) and to cluster memory operations together and increase MLP by decoupling the loop. Software Decoupled Access-Execute (DAE) [13, 14] targets reducing energy expenditure using DVFS, while maintaining performance, whereas Clairvoyance focuses on increasing performance. DAE generates Access-Execute phases that merely prefetch data and duplicate a significant part of the original loop (control instructions and address computation). Clairvoyance’s contribution consists in finding the right balance between code rematerialization and instruction reordering, to achieve high degrees of ILP and MLP, without the added register pressure. DAE uses heuristics to identify the loads to be prefetched which take into consideration memory-dependencies. In addition, Clairvoyance combines information about memory- and control- dependencies, which increases the accuracy and effectiveness of the long latency loads identification. Helper threads [44–46] attempt to hide memory latency by warming up the cache using a prefetching thread. Clairvoyance uses a single thread of execution, reuses values already loaded in registers (between Access and Execute phases) and resorts to prefetching only as a mechanism to safely handle unknown loop carried dependencies. Software-hardware co-designs such as control-flow decoupling (CFD) [47] prioritize the evaluation of data-dependent branch conditions, and support a similar decoupling strategy for splitting load-use chains as our multi-access phases (however, their multi-level decoupling is done manually [48]). Contrary to Clairvoyance, CFD requires hardware support to ensure low-overhead communication between the decoupled phases. A software only version, Data-flow Decoupling (DFD), relies on prefetch instructions and ensures communication between phases by means of caches, akin to DAE [13, 14], using code duplication. As the CFD solution is not entirely automatic and requires manual intervention, Clairvoyance provides the missing compiler support and is readily applicable to decouple the CFG and hoist branch-evaluation, in lieu of long latency loads. Moreover, Clairvoyance provides software solutions to replace the hardware support for efficient communication between the decoupled phases. CFD makes use of decoupled producer phases for branches, similar to Clairvoyance’s multi-access phases, but low-overhead communication is achieved with hardware support. 6. Conclusion Improving the performance, and therefore the energy-efficiency, of today’s power-limited, modern processors is extremely important given the end of Dennard scaling. While aggressive out-of-order designs achieve high performance, they do so at a high cost. Instead of improving performance with aggressive out-of-order processors, limited, efficient out-of-order processors can be used. Unfortunately, the reach of these efficient processors – as measured by the number of dynamic instructions that they can track before becoming stalled – tends to be much less than in aggressive cores. This limits the performance of the more efficient out-of-order processors for memory-intensive applications with high latency, distant independent instructions. In this work, we propose a new technique to improve a processor’s performance by increasing both memory and instruction-level-parallelism and therefore the amount of useful work that is done by the core. The Clairvoyance compiler techniques introduced by this work overcome limitations imposed by may-alias loads, reordering dependent memory operations across loop iterations, and controlling register pressure. Using these techniques, we achieve performance improvements of up to 43% (7% geomean improvement for memory-bound applications with a conservative approach and 13% with a speculative but safe approach) on real hardware. The use of Clairvoyance enables optimizations that move beyond standard instruction reordering to achieve energy efficiency and overall higher performance in the presence of long latency loads. Acknowledgments We would like to thank Andreas Scherman for his contribution to the branch clustering strategy. This work is supported, in part, by the Swedish Research Council UPMARC Linnaeus Centre and by the Swedish VR (grant no. 2010-4741). References A. Artifact Description A.1 Abstract This artifact contains the source code to LLVM 3.8, the Clairvoyance passes, and the scripts to compile and run all benchmarks presented in our paper. To get started, we provide a Vagrantfile that will set up and install the required software. We conducted our experiments on an APM X-Gene Octa-A57. A.2 Description A.2.1 Check-List (Artifact Meta Information) - Program: C/C++ code - Compilation: make - Transformations: access-execute phase generation, lowering uses, branch clustering, multiple access phases - Binary: O3, LLVM-SCHED, Clairvoyance - Data set: NAS: C data set, SPEC CPU 2006: ref - Run-time environment: Vagrant, Virtual Box - Hardware: APM X-Gene AArch64 Octa-A57 - Execution: Experiments use perf - Output: perf output - Experiment workflow: build project, build binaries, run binaries, compare runtime - Publicly available?: Yes A.2.2 How Delivered Clone: https://github.com/ktran/clairvoyance The repository structure is shown in Table 5 and contains: - a vagrant configuration file (Vagrantfile) - a setup script (setup.sh) that will be used by vagrant - the compiler (clairvoyance/compiler) - the experiments directory (clairvoyance/experiments) for building and running binaries from our paper A.2.3 Hardware Dependencies We evaluated on an APM X-Gene Octa-A57. Clairvoyance is designed to improve performance of limited out-of-order cores, therefore we recommend similar platforms for the evaluation. For building LLVM, provide a minimum 4GB of RAM to the virtual machine (default set up). A.2.4 Software Dependencies Vagrant (tested: 1.8.5) and Virtual Box (tested: 5.1.8). A.2.5 Datasets NAS benchmarks: "C" data set size, SPEC CPU 2006: ref. A.3 Installation Currently, vagrant is set up such that it will use use 4 GB of RAM and 2 CPUs. If you have more resources you can change the Vagrantfile by modifying these lines: <table> <thead> <tr> <th>Directory Name</th> <th>Path</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td>clairvoyance</td> <td></td> <td>root directory</td> </tr> <tr> <td>experiments</td> <td></td> <td>files to build and run benchmarks</td> </tr> <tr> <td>sources</td> <td></td> <td>benchmarks sources and scripts to build</td> </tr> <tr> <td>runs</td> <td></td> <td>scripts to run and parse outputs</td> </tr> </tbody> </table> Table 5. The artifact folder structure. <table> <thead> <tr> <th>Command</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td>vagrant up</td> <td>starting up the virtual machine</td> </tr> <tr> <td>vagrant halt</td> <td>shutting down the virtual machine</td> </tr> <tr> <td>vagrant ssh</td> <td>ssh to your virtual machine</td> </tr> <tr> <td>vagrant destroy</td> <td>destroys the virtual machine</td> </tr> </tbody> </table> Table 6. Vagrant commands. Never run vagrant init as this will overwrite the Vagrantfile. Next, ssh into the machine and install the project. Running make will compile the project (LLVM, Clairvoyance): $ (sudo) vagrant ssh $ cd /var/www/clairvoyance/compiler $ make -j 2 A.4 Experiment Workflow For benchmark configuration changes see Section A.6 This section only explains how to build and run the pre-configured benchmarks. A.4.1 Building the Binaries Build the pre-configured binaries by running make: $ cd /var/www/clairvoyance/experiments/ swoop/sources $ make -j 2 A.4.2 Running the Binaries The run_experiments script in experiments/swoop/ runs can be used to run the binaries of the provided bench- Table 7. Options for the run_experiments script <table> <thead> <tr> <th>Option</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td>-i [ref, train, test]</td> <td>Select the input (all same for NAS)</td> </tr> <tr> <td>-r $r</td> <td>Number of times the benchmark should be run (default 1)</td> </tr> <tr> <td>-n</td> <td>Dry-run</td> </tr> </tbody> </table> This table shows the options and their semantics. Here, we run each configured binary once with the reference input: ``` $ cd /var/www/clairvoyance/experiments/ swoop/runs $ ./run_experiments.py -i ref -r 1 ``` This script will start the experiments, collect statistics, take the average (if repeat > 1) and write everything to the test directory. Each binary has a dedicated directory. The statistics are in stderr.txt, the output is written to stdout.txt, and if the output differs from the reference output, it will also contain an error file. We have configured the scripts such that they run the original (O3) and up to two Clairvoyance versions. CG takes approximately 15 minutes, LU 50 and UA 25 minutes per version (on our machine). This script may thus run for 270 minutes. A.5 Evaluation and Expected Results For CG, UA, LU, alias analysis can disambiguate memory accesses in the three NAS benchmarks, therefore no speculation is required (versions are similar or equivalent). A.5.1 Parsing the Output Parse the output that was gathered in the test directory: ``` $ cd /var/www/clairvoyance/ experiments/swoop/runs $ ./parse_experiments.py -d test ``` This will read the stderr.txt files and generate a csv file test/results.csv which summarizes gathered statistics. A.5.2 Plotting the Results Run the plot_experiments.py script (in the runs directory). Pass the test/results.csv file and choose one out of three options: --print-best, print best best speculative versions, --plot-version-comparison plot best speculative versions, and --plot-best, compares LLVM schedulers, DAE (not described here) and Clairvoyance. ``` $ ./plot_experiments.py \ -i test/results.csv --plot-best \ --inputset ref ``` All numbers are normalized to O3 (plots require O3 runs). A.5.3 Expected Results We expect that Clairvoyance will reduce the total execution time of CG (memory-bound), but that the runtimes of UA and LU (compute-bound or medium memory-bound) are less affected. The memory- vs compute-bound characteristics are target dependent, the results may vary on different hardware. A.6 Experiment Customization A.6.1 Compiling Existing Benchmarks In order to compile another version of CG, UA, LU, follow step 3 in Section A.6.2. For changing the running scripts, look at the files jobs.py (which benchmarks to run) and benchmarks.py (which Clairvoyance parameters to use) in experiments/swoop/runs/. A.6.2 Compiling Different Benchmarks 1. Add the Source Files. Copy the sources/CG directory and rename it to your benchmark. Then, (i) replace the source files in the new directory with your own source files, (ii) adapt the Makefile in that directory: change the flags, source files and set the benchmark name (should be different from any source file name). 2. Mark the Loops. Mark the loops that should be transformed using Clairvoyance with a pragma: ``` #pragma clang loop vectorize_width (1337) for (int i = 0; i < N; ++i) { // some code } ``` Clairvoyance only transforms inner most loops. It is best to select loops that have hard to predict data accesses. 3. Determine the Versions to Build. The Makefile.target file in experiments/swoop/source/common/SWOOP determines which versions are build. In order to change the unroll count and indirection count, modify the UNROLL_COUNT and INDIR_COUNT variables. 4. Add Benchmark to Makefile. Add your benchmark name to the BENCHMARKS variable in sources/Makefile. A.6.3 Running and Evaluating New Benchmarks All scripts are already set up for SPEC CPU 2006. For new benchmarks it might be easier to run perf directly: ``` $ perf stat -r repeat -e cycles,instructions benchmark ``` A.7 Notes Box Could Not Be Found On OSX, you might need to run: ``` $ sudo rm /opt/vagrant/embedded/bin/curl ``` SWOOP Clairvoyance generates binaries that are called SWOOP (SW-OoO execution). DAE If you wish to evaluate DAE, please go to https://github.com/etascale/daedal Artifact Evaluation For submission and reviewing guidelines, see http://ctuning.org/ae/artifacts.html
{"Source-Url": "http://uu.diva-portal.org/smash/get/diva2:1077941/FULLTEXT01.pdf", "len_cl100k_base": 11036, "olmocr-version": "0.1.53", "pdf-total-pages": 15, "total-fallback-pages": 0, "total-input-tokens": 51610, "total-output-tokens": 14812, "length": "2e13", "weborganizer": {"__label__adult": 0.0004353523254394531, "__label__art_design": 0.0005154609680175781, "__label__crime_law": 0.00033736228942871094, "__label__education_jobs": 0.0004475116729736328, "__label__entertainment": 9.059906005859376e-05, "__label__fashion_beauty": 0.0002092123031616211, "__label__finance_business": 0.0002720355987548828, "__label__food_dining": 0.0003936290740966797, "__label__games": 0.00086212158203125, "__label__hardware": 0.005615234375, "__label__health": 0.0004191398620605469, "__label__history": 0.00039124488830566406, "__label__home_hobbies": 0.00015795230865478516, "__label__industrial": 0.0007829666137695312, "__label__literature": 0.0002334117889404297, "__label__politics": 0.00034999847412109375, "__label__religion": 0.0006937980651855469, "__label__science_tech": 0.067626953125, "__label__social_life": 6.93202018737793e-05, "__label__software": 0.006526947021484375, "__label__software_dev": 0.912109375, "__label__sports_fitness": 0.0003905296325683594, "__label__transportation": 0.00093841552734375, "__label__travel": 0.00026607513427734375}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 60970, 0.02546]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 60970, 0.41602]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 60970, 0.85571]], "google_gemma-3-12b-it_contains_pii": [[0, 551, false], [551, 4543, null], [4543, 10261, null], [10261, 13460, null], [13460, 17745, null], [17745, 21069, null], [21069, 24803, null], [24803, 30529, null], [30529, 34696, null], [34696, 37365, null], [37365, 43284, null], [43284, 48811, null], [48811, 53105, null], [53105, 56381, null], [56381, 60970, null]], "google_gemma-3-12b-it_is_public_document": [[0, 551, true], [551, 4543, null], [4543, 10261, null], [10261, 13460, null], [13460, 17745, null], [17745, 21069, null], [21069, 24803, null], [24803, 30529, null], [30529, 34696, null], [34696, 37365, null], [37365, 43284, null], [43284, 48811, null], [48811, 53105, null], [53105, 56381, null], [56381, 60970, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 60970, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 60970, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 60970, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 60970, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 60970, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 60970, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 60970, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 60970, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 60970, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 60970, null]], "pdf_page_numbers": [[0, 551, 1], [551, 4543, 2], [4543, 10261, 3], [10261, 13460, 4], [13460, 17745, 5], [17745, 21069, 6], [21069, 24803, 7], [24803, 30529, 8], [30529, 34696, 9], [34696, 37365, 10], [37365, 43284, 11], [43284, 48811, 12], [48811, 53105, 13], [53105, 56381, 14], [56381, 60970, 15]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 60970, 0.10029]]}
olmocr_science_pdfs
2024-12-07
2024-12-07
4619ea47d18845e1972744e59e37caf18ebbd344
[REMOVED]
{"Source-Url": "http://www.proofs-workshop.org/2021/papers/paper2.pdf", "len_cl100k_base": 8574, "olmocr-version": "0.1.49", "pdf-total-pages": 17, "total-fallback-pages": 0, "total-input-tokens": 43404, "total-output-tokens": 11115, "length": "2e13", "weborganizer": {"__label__adult": 0.00045108795166015625, "__label__art_design": 0.0003628730773925781, "__label__crime_law": 0.0008831024169921875, "__label__education_jobs": 0.0004749298095703125, "__label__entertainment": 7.367134094238281e-05, "__label__fashion_beauty": 0.0001876354217529297, "__label__finance_business": 0.00018656253814697263, "__label__food_dining": 0.00033164024353027344, "__label__games": 0.0008406639099121094, "__label__hardware": 0.00202178955078125, "__label__health": 0.0005922317504882812, "__label__history": 0.00024819374084472656, "__label__home_hobbies": 9.447336196899414e-05, "__label__industrial": 0.0005025863647460938, "__label__literature": 0.00024080276489257812, "__label__politics": 0.00033926963806152344, "__label__religion": 0.0004854202270507813, "__label__science_tech": 0.044769287109375, "__label__social_life": 8.535385131835938e-05, "__label__software": 0.006999969482421875, "__label__software_dev": 0.93896484375, "__label__sports_fitness": 0.00031876564025878906, "__label__transportation": 0.0005240440368652344, "__label__travel": 0.00016736984252929688}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 46137, 0.02918]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 46137, 0.17348]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 46137, 0.90097]], "google_gemma-3-12b-it_contains_pii": [[0, 2830, false], [2830, 6457, null], [6457, 9647, null], [9647, 12067, null], [12067, 15252, null], [15252, 16120, null], [16120, 19336, null], [19336, 21988, null], [21988, 23330, null], [23330, 25766, null], [25766, 28931, null], [28931, 32395, null], [32395, 35067, null], [35067, 36509, null], [36509, 39850, null], [39850, 43491, null], [43491, 46137, null]], "google_gemma-3-12b-it_is_public_document": [[0, 2830, true], [2830, 6457, null], [6457, 9647, null], [9647, 12067, null], [12067, 15252, null], [15252, 16120, null], [16120, 19336, null], [19336, 21988, null], [21988, 23330, null], [23330, 25766, null], [25766, 28931, null], [28931, 32395, null], [32395, 35067, null], [35067, 36509, null], [36509, 39850, null], [39850, 43491, null], [43491, 46137, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 46137, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 46137, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 46137, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 46137, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 46137, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 46137, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 46137, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 46137, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 46137, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 46137, null]], "pdf_page_numbers": [[0, 2830, 1], [2830, 6457, 2], [6457, 9647, 3], [9647, 12067, 4], [12067, 15252, 5], [15252, 16120, 6], [16120, 19336, 7], [19336, 21988, 8], [21988, 23330, 9], [23330, 25766, 10], [25766, 28931, 11], [28931, 32395, 12], [32395, 35067, 13], [35067, 36509, 14], [36509, 39850, 15], [39850, 43491, 16], [43491, 46137, 17]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 46137, 0.10309]]}
olmocr_science_pdfs
2024-11-24
2024-11-24
3bfa332d938fe7007eb7cd447bc622e1bf302c74
**VERCORS: a Layered Approach to Practical Verification of Concurrent Software** Afshin Amighi Stefan Blom Marieke Huisman Formal Methods and Tools University of Twente Enschede, The Netherlands Email: \{a.amighi, s.blom, m.huisman\}@utwente.nl **Abstract**—This paper discusses how several concurrent program verification techniques can be combined in a layered approach, where each layer is especially suited to verify one aspect of concurrent programs, thus making verification of concurrent programs practical. At the bottom layer, we use a combination of implicit dynamic frames and CSL-style resource invariants, to reason about data race freedom of programs. We illustrate this on the verification of a lock-free queue implementation. On top of this, layer 2 enables reasoning about resource invariants that express a relationship between thread-local and shared variables. This is illustrated by the verification of a reentrant lock implementation, where thread-locality is used to specify for a thread which locks it holds, while there is a global notion of ownership, expressing for a lock by which thread it is held. Finally, the top layer adds a notion of histories to reason about functional properties. We illustrate how this is used to prove that the lock-free queue preserves the order of elements, without having to reverify the aspects related to data race freedom. I. INTRODUCTION Over the last years, the ever-growing demands on software performance have led to a significant increase in the use of concurrency. As a side-effect of this development, we also see a growing need for techniques to reason about concurrent software. Software applications are omnipresent, and their failure can have significant economic, societal, and even life-threatening consequences. Naturally, also sequential software should be without failures, however the major complexity of concurrent software makes that the absence of failures only can be guaranteed by using tool-supported formal techniques. In earlier work, we have introduced the VERCORS tool set [1], which is an annotation based program verifier. VERCORS encodes concurrent Java programs into the intermediate language of Viper [2]) and then uses the Silicon tool to generate proof obligations, which are discharged using Z3 [3]. This paper discusses how VERCORS supports a layered approach to verification, combining different logic-based verification techniques. Each layer captures a different category of properties. In the lowest layer, we care only about data race freedom; in the middle layer we verify resource invariants that relate thread-local variables to globally shared variables, while in the top layer we verify arbitrary functional correctness properties. Strictly speaking, this separation in layers is not necessary, but it helps to keep the specification and verification tractable and to make mechanical verification feasible. At layer 1, to reason about data race freedom of multiple threads independently modifying a shared object, we use a combination of Implicit Dynamic Frames (IDF) [4] and Concurrent Separation Logic (CSL) resource invariants [5]. In our approach, IDF is used to specify whether a thread has read or write access to a certain location, while CSL-style resource invariants are used to associate synchronizers to shared data (including atomic variables acting as a synchronizer). The combination of these two allows one to verify that a shared-memory concurrent program is free of data races in a thread-modular way: if a thread has write access to a location, then no other thread can simultaneously access this location, and thus no other thread can observe the changes made to this location; if a thread has read access to a location, then any other thread can also only have read access to this location, and thus the value stored in this location cannot be changed. If shared data is protected by a synchronizer, the synchronizer operations ensure that either one thread has exclusive access to the data protected by the resource invariant; or multiple threads have shared read-only access. This approach works for lock-based programs, as well as for programs that use atomic operations for synchronization. However, in more complex examples, the resource invariant often needs to express a relationship between thread-local and global/shared state. Therefore, in the 2nd layer, we add the notion of thread-local state. Permissions to access this local state can be split between the CSL invariant of the shared object and the threads, in such a way that when a thread holds the invariant, it can update the shared state and its own local state, while it is able to inspect the state of all other threads. Hence every thread can keep track of its own actions through its own local state, while the CSL invariant expresses consistency between the local state and the shared object. Finally, in the top layer, we add the notion of history [6], which allows us to verify functional properties in addition to data race freedom. A history captures abstractly the updates to data. Updates to histories are traced locally, and when threads synchronize, their local histories are merged into a global history, capturing the possible interleavings between the local updates. Note that functional properties could be accounted for using resource invariants and thread-locality only. However, this would give rise to large and complex invariants, because the invariant has to take into account how everything fits. This paper describes for each layer of the verification stack how the verification is handled in VERCORS. The key idea behind the VERCORS tool set is that it works as a transforming compiler, reducing complex verification problems into a verification problem for basic Separation Logic. As a back end, we use the silicon verifier [2], thus all annotated programs are encoded into annotated Silver programs, which is the intermediate language used by Silicon, and has dedicated support to reason about access permissions. For each layer in the verification stack, we describe how the encoding into silicon is defined. Because of our layered approach to verification, the transformation is easily manageable, and can be guaranteed to be correct. We illustrate the usability of our layered approach by presenting a non-trivial verification example for each layer. At the lowest layer, we verify data race freedom of a lock-free queue implementation, derived from the standard Java API lock-free queue. At the middle layer, we show how a relation between thread-local and shared variables is used to verify an implementation of reentrant locks, again derived from the Java API implementation, ensuring that two threads never can simultaneously hold the lock. At the top layer, we use histories to prove that the lock-free queue implementation preserves the order of elements stored in the queue. It should be noted that this approach differs from recent proposals for a large range of powerful and expressive logics to reason about concurrent software, such as CAP [7], iCAP [8] and CaReSL [9], in that we do not aim at a highly expressive logic, but instead focus on an easily manageable approach to the verification of concurrent software, by breaking down the verification problem into smaller, more manageable problems. Moreover, the focus of our work is on efficient tool support, reusing currently available technologies, while the focus of these logics is expressiveness, and the ability to capture all concurrent programming patterns. To summarize, the main contributions of this paper are: - a layer-based approach to the verification of concurrent software, identifying different kinds of verification problems, which all need their own level of annotations; - for each verification layer, a discussion how the verification problem is encoded into a simpler verification problem in basic Separation Logic; and - example verifications at each layer of the verification stack. The paper is structured as follows: Section II briefly introduces CSL, IDF, and the VERCORS specification language. Section III discusses how the combination of IDF and CSL-style resource invariants allows to verify data race freedom. Section IV then discusses how the relation between global properties and thread-local state can be maintained as part of the resource invariant, while Section V discusses the verification of functional properties. Finally, Sections VI and VII discuss related work and conclusions. ### II. BACKGROUND #### A. Concurrent Separation Logic (CSL) Concurrent Separation Logic (CSL) [5] is used to reason about concurrent programs. It employs the `points-to` predicate, along with the `separating conjunction` operator of Separation Logic [6]. The `points-to` predicate specifies the contents of a specific location of the heap, and the `separating conjunction` operator \( \phi \land \psi \) expresses that formulas \( \phi \) and \( \psi \) hold for disjoint parts of the heap. CSL’s parallel composition rule expresses that each thread can be verified in isolation, provided they affect disjoint parts of the heap. Data that is shared by different threads can be specified using a `resource invariant`. Access to the data specified by the resource invariant can only be obtained (1) by using an exclusive synchronizer, e.g., a lock, or (2) by executing the body of an atomic operation, e.g., a compare-and-set operation; provided that the thread leaving the synchronizer or the atomic operation can re-establish the resource invariant. To encode the behavior of language constructs that are not part of IDF, we will use two of its proof commands. The `exhale` command first asserts that a formula is true and then drops the resources specified by the formula. The `inhale` command assumes the given formula and adds the resources specified by the formula. #### B. Implicit Dynamic Frames (IDF) IDF [4] is another program logic that extends Hoare Logic with the ability to reason about access to the heap by means of access permissions to heap locations, similar to PBSL. However, IDF and PBSL differ in how value-specifications are handled: in IDF, one uses side-effect-free expressions in the underlying programming language, while in PBSL, one first relates the program variables to logical variables and then states properties about these logical variables. To encode the behavior of language constructs that are not part of IDF, we will use two of its proof commands. The `exhale` command first asserts that a formula is true and then drops the resources specified by the formula. The `inhale` command assumes the given formula and adds the resources specified by the formula. #### C. VERCORS Specification Language The VERCORS specification language uses a JML-like syntax [13], combined with PBSL and IDF ingredients: resource invariants are essentially defined in PBSL, while our encoding of the related language Silicon uses IDF exclusively. In VERCORS, predicates have type `resource`, the separating conjunction is written `\( \times \)`, a full permission is written `Perm(x,1)`, and a fractional permission is written $\text{Perm}(x,p)$ where $p \in (0,1)$. If the value of $p$ is not known or unimportant, then one may write $\text{Perm}(x,\text{read})$ or $\text{Value}(x)$. Some resource formulas, known as groups, can be split into multiple parts that may be shared. To denote such a share of a group, we use the notation $\text{[\text{\textless fraction\textgreater}]\\text{-\\textless group\textgreater}}$. The VERCORS specification language also supports ghost variables and specification commands, such as $\text{assert}$. When evaluating expressions, it may be necessary to inject ghost code just before evaluating a subexpression. This is what the $\text{with}(G)$ annotation does, where $G$ can be arbitrary ghost code, including proof hints. Similarly, the annotation $\text{then}(G)$ inserts ghost code immediately after the evaluation of a sub-expression. Moreover, in case of a method call, the $\text{with}$ block may be used to pass ghost in-parameters to the method, using assignments, and the $\text{then}$ block may be used to inspect the value of ghost out-parameters. III. LAYER 1: PERMISSIONS AND RESOURCE INVARIANTS At the bottom layer of the VERCORS verification stack, a combination of IDF and CSL is used to reason about data race freedom. As explained, resource invariants capture access to the shared state. There are two ways to access shared state: by using locks (and other synchronizers), and by using atomics. Here we focus on atomic operations, and their encoding into Silicon, however reasoning about shared state protected by a lock is done in a similar way. We illustrate our approach by discussing the verification of a lock-free queue, derived from ConcurrentLinkedQueue in the Java API. This example was also specified and verified by Jacobs et al. in richer logics [14], [15], but our version is a third shorter in length. A. Reasoning about Atomic Blocks In the VERCORS tool, internally an atomic operation on object $o$ with body $S$ is modeled as $\text{atomic}(o)(S)$. The resources associated to object $o$ are specified by defining an appropriate resource invariant $\text{csl\_invariant}$, which has to be established when the object is initialized, thus making it an implicit postcondition of all constructors of the class that defines the resource invariant. To reason about atomic operations, CSL uses the rule $\text{[\text{\textit{Atomic}}]}$ [16], which expresses the following: any thread executing an atomic operation with a body $S$, obtains the shared state specified by the resource invariant $\text{csl\_invariant}$; then, while executing $S$ it is allowed to violate $\text{csl\_invariant}$, but after the execution of $S$, $\text{csl\_invariant}$ has to be re-established and released to the shared state. \[ \frac{\{o.\text{csl\_invariant}() + P\}\ S\ \{o.\text{csl\_invariant}() + Q\}}{P\ \text{atomic}(o)(S)\ Q} \quad \text{[\text{\textit{Atomic}}]} \] B. Encoding of Atomic Blocks In Java, we do not directly write $\text{atomic}$ statements. Instead, the java.util.concurrent.atomic package provides several classes, whose methods perform the atomic operations $\text{get}$, $\text{set}$, and $\text{compareAndSet}$ for all Java types. Thus, the encoding of atomic methods from Java into Silicon is done in two steps: first the atomic method call is transformed into a VERCORS $\text{atomic}$ instruction, and in the next step, the use of the proof rule $\text{[\text{\textit{Atomic}}]}$ is encoded into Silicon. Java’s atomic operations are encoded as VERCORS $\text{atomic}$ instructions, using several additional ghost variables to store the results of argument evaluation. For example, if $\text{var}$ is an AtomicInteger then $\text{res}=$var.compareAndSet(expect,replace) is internally transformed into: \[ \text{int obj=var; int x=expect; int v=replace;} \] \[ \text{atomic(this)} \] \[ \text{if (obj.val==x) \{ obj.val=v; res=true; \}} \] \[ \text{else \{ res=false; \}} \] Note that var, expect and replace are evaluated outside of the atomic block. The call to $\text{compareAndSet}$ might be annotated with ghost annotations $\text{with}(G1)$ $\text{then}(G2)$, to maintain the resource invariant, or to provide proof hints to prove correctness of the atomic body. In that case, these ghost instructions are evaluated inside the atomic block, after lines 2 and 4, respectively. Finally, the encoding of the $\text{[\text{\textit{Atomic}}]}$ proof rule in Silicon is simple: each occurrence of the statement $\text{atomic}(o)(S)$ is replaced by the sequence: \[ \text{inhale o.csl\_invariant();} \] \[ \text{S;} \] \[ \text{exhale o.csl\_invariant();} \] This transformation, first, uses the instruction $\text{inhale}$ to add the resources and knowledge of the resource invariant. Then, using the added resources the body of the atomic block $S$ is verified, and finally, $\text{exhale}$ checks that the resource invariant holds and then removes it. C. Verification of a Non-blocking Queue We demonstrate the usability of our approach by verifying data race freedom of the essential methods of ConcurrentLinkedQueue from the java.util.concurrent library, which implements a lock-free queue as proposed by Michael and Scott [17]. First, we briefly explain the data structure, and then we describe how the class is specified and verified. 1) Implementation: The queue consists of (1) two atomic references: head and tail, and (2) a chain of nodes, where each node contains a value field and an atomic reference field to the next node. The head points to a sentinel node, i.e., its value does not contribute to the queue. The last node of the queue can be identified by its null-valued next field. A queue is empty when both the head and the tail point to the sentinel node with a null-valued next field. 2) Specification: The main part of the specification is the resource invariant, which characterizes a valid queue structure. The specification additionally uses two ghost fields with type Node: (1) begin, which represents the original head of the queue, i.e., the head of the queue when the data structure is initialized, and (2) last, which points to the last node of the queue. The resource invariant uses several auxiliary predicates. First, RPerm and RPointsTo, which combine permission to read an AtomicNode with Perm and PointsTo on the embedded field, respectively. Next, the reachable \((n,m)\) predicate captures that there is a path from \(n\) to \(m\), and chain\((n,m)\) specifies full ownership of the data element in the nodes of the queue located between \(n\) and \(m\). The resource invariant (see Fig. 1) states that begin can be read and is immutable. The fields head.val, tail.val, and last are writable and reach from begin. The elements between head and last are fully owned and the last.next is writable and null. 3) Verification: The essential part in the verification of the lock-free queue is proving that all atomic operations preserve the resource invariant. In addition to our encoding, this uses the following lemmas (which all have inductive proofs): (i) The reachable predicate is transitive. (ii) Given a node from which both the last node and some other node are reachable, either the other node is the last node, or the next node of the other node is also reachable. (iii) Appending one node to a permission chain yields a permission chain. Fig. 2 shows a fully specified implementation of the method try_deq, which attempts to dequeue a node of the queue. First, it copies the current head of the queue to \(n1\). Next, it copies the next of \(n1\) to \(n2\), which is allowed because of lemma (ii) we have either read or write. If \(n2\) is not null then the queue was not empty and compareAndSet is used to change the head to the next node. Upon success the element is returned as an Integer. In all other cases null is returned to signal failure. A full specification of the queue and online version of the tool is available at [18]. IV. LAYER 2: RELATING THREAD-LOCAL AND GLOBAL VARIABLES To understand why in layer 2 we add the notion of thread-local state, it is important to realize that the queue specification above does not allow threads to express any property about the elements in the queue, even though the specification of the queue describes the queue’s behavior in terms of all elements the queue has held and still holds. This list, however, is only available for reasoning during atomic operations, because the access permissions on the list are maintained in the invariant. Hence, it is not possible for threads to reason about the elements of the queue outside of atomic regions, and worse, because a thread does not have any permission on these variables outside of atomic regions, it is forced to forget all knowledge about them: after all, any other thread might modify them. The simplest way to avoid this loss of information is to add thread-local state and to keep this thread-local state synchronised with the global state. The concept of thread-local state is old; it is already used in the classical example of Owicki-Gries [19] where two threads independently atomically increment a variable by one. To prove that the end result increases the initial value by two, two thread-local ghost variables are used that account for the behavior of each thread. These ghost variables are then used to state a resource invariant that precisely captures the value of the shared variable. In our approach, this combination of thread-local and global state is achieved as follows. Full permission on the shared variable is kept in the invariant, thus it may be modified during atomic operations. For thread-local state, half the permission is held by the invariant, thus it may be read to specify the relation with the shared state. In addition, each thread holds the other half permission on its own thread-local state, which means that it can read its thread-local state at any time during execution, and moreover, it has the ability to change its own thread-local state when it holds the resource invariant, i.e., during atomic operations. A. Encoding The concept of a thread-local variable is present in many programming languages. Typically, thread-locality is not a primitive of the language, but it is added by means of a library. For the moment, we use a manual encoding of thread-locality on top of layer 1. Our encoding assumes that an application has access to a fixed number of unique objects (or integers) identifying each of the threads, which allows to encode thread-local variables as an array, where each array element corresponds to the thread-local variable for the corresponding array index. Additionally, a special treatment is required for reasoning about the current thread id. We have a specification construct \texttt{current\_thread}, which yields the id of the current thread. Thus, as its semantics depends on the thread in which it is evaluated, \texttt{current\_thread} cannot be used in invariants. In fact, it may not be used in any predicate, unless the specification modifier thread\_local is used for the predicate. Moreover, any predicate that invokes a thread\_local predicate has to be marked thread\_local itself. We encode \texttt{current\_thread} by adding it as an argument to all methods, constructors, and thread\_local predicates and all their invocations. This allows us to detect illegal use of \texttt{current\_thread}, i.e., in a non-thread local predicate, because every illegal use would result in a local variable that was not declared. Moreover, we check that \texttt{csl\_invariant} is not declared thread local. B. Specification and Verification of a Reentrant Lock. To illustrate the kind of verifications that can be done at layer 2, we discuss the specification and verification of the implementation of a reentrant lock. The specification is adapted from [12], [20], while the implementation is a simplified version of OpenJDK6 java.concurrent.locks.ReentrantLock. The major challenge in specification and verification is the reentrant lock behavior. In separation logic, the specification of the behavior of non-reentrant locks is simple: when obtaining the lock, the resource invariant attached to the lock, i.e., access to the shared data protected by the lock, is also obtained and upon unlocking the invariant must be released. Assuming that double locking leads to an unchecked error or a deadlock, this behavior can be specified with straightforward contracts. However, for reentrant locks more care is required: the resource invariant is only obtained upon locking for the first time and it must be yielded when unlocking for the last time only. This means that when obtaining the lock, the invariant can only be obtained if there is proof that the lock is obtained for the first time. 1) Implementation: We follow the ReentrantLock implementation in OpenJDK6 by having two fields: an atomic integer count and an integer owner. The latter variable is set to the thread id of the current owner of the lock, or -1 otherwise. If a thread already is the owner then a (re)lock is done by atomically increasing count. Otherwise, the lock must be obtained by changing count from 0 to 1 using compare-and-set. To release the lock, the count is decreased, where the owner must be cleared before the final decrease to 0. 2) Specification: The specification of a reentrant lock (see Listing 3) uses the predicate lockset(S), where S is a multi-set of locks. The predicate lockset(S) holds for a thread if the multiplicity of any lock in the lock set is the number of times the thread holds that lock. Hence, obtaining a lock adds the lock to the lock set, while releasing a lock means removing it from the lock set. Moreover, when a lock does not occur in the lock set before locking, the resource invariant is obtained, and when it is no longer present after unlocking, it has to be yielded. In our previous work [12], the lockset(S) was added to the specification language as a primitive. In this paper, we will define it in terms of the current thread and an invariant. 3) Invariant: To define the invariant for a lock (see Fig. 4), we use several ghost variables. Without loss of generality, we assume a fixed number of threads (T), which is also a ghost variable. We use a ghost array held with T entries that functions as the thread-local count for each thread. And we use a ghost variable holder that tracks the owner of the lock. Note that we cannot use the implementation field owner because it cannot change at the same time as the implementation field count changes. Ghost fields can change at the same time and thus preserve an invariant. Permission for the various fields of a lock are divided between the invariant and the lockset_part predicate that will be used in the lockset definition. The invariant holds permission \( \frac{1}{2} \) on each element of the held array and the count and owner atomic fields. The other \( \frac{1}{2} \) for held elements is held in the corresponding lockset, while the other \( \frac{1}{2} \) for the atomic fields is kept in the lockset for the owning thread and in the invariant if the lock is free. The lockset predicate is defined in Fig. 5. The most important lines are the last two: for every lock, the lockset holds the permissions defined in lockset_part and the held count for the current thread is precisely the multiplicity of the lock id in the lockset. The full listing of the lockset specified implementation of our reentrant lock can be found online [18]. V. LAYER 3: FUNCTIONAL PROPERTIES USING HISTORIES Invariants, with or without thread-locals, are adequate for specifying and verifying data race freedom and basic functional properties. The verification of more complex functional properties, however, can get very tedious because all interactions between threads have to be specified in great detail. Therefore, this section discusses a different approach, adding the notion of histories [6] on top of layer 2, and uses this to prove that the order of elements is preserved in the lock-free queue. A. Reasoning with Histories The key idea of history-based reasoning is that functional verification is not performed on the program directly, but on an abstract model of the program. This idea combines data abstraction [21] with process algebra [22]. An abstract model is defined in terms of variables and actions on those variables. Each action abstracts away from a concrete operation that can be carried out on the program data: an action contract specifies which concrete operations the action corresponds to. For example, the method HistInit of Fig. 7 specifies an abstract model for queues: \( q \) specifies a queue state, while \( \text{get} \) is an abstract action on the queue. Actions can be combined into processes using standard operators, known from process algebra, such as choice, sequential composition, and parallel composition. To capture action repetition, the behavior of processes also can be described using a recursive definition, which must be paired with a contract. See for example the definition of process get_all in Fig. 7 (lines 11-14). In the method specifications, we record the local history of the actions performed in a thread. For example, the method specification of method \( \text{get} \) in Fig. 8 expresses that this method performs an abstract \( \text{get} \) action. In the method bodies, annotations are added to mark blocks that implement actions. For example, in the method \( \text{try} \) in Fig. 2 we add ```plaintext \{ \text{action} \text{hist}, p, P, \text{hist.get}()/\text{this}.val\}; \text{hist,q}=\text{tail}(\text{hist,q}); \} ``` after the unfold at line 11, stating that we extend the history hist, for which we own a fraction \( p \) and which is \( P \), with an action \( \text{get} \). This is done by removing the head element from \( \text{hist.q} \). Typically, whenever a thread is created, it starts with an empty local history. When threads terminate and are joined, the local history of the terminated thread is merged with the history of the joining thread. Eventually, this results in one global history of abstract actions over which the desired functional property can be verified. To guide the verification, some additional annotations for the treatment of histories may be provided as proof hints: initialize a new, empty history over a set of program fields, destroy a history etc., see [6] for a full overview. The verification of these annotations consists of two main tasks. First, the code must be verified to ensure that it implements a linearizable sequence of actions, as specified in the history annotations. Second, the history specification has to be verified to ensure that every possible trace satisfies the behavior specified in the form of the process contracts. This has two advantages for the verification of functional properties. First, we can abstract from implementation details (e.g. the linked list in the queue becomes a sequence in the history). Second, because we have already verified data race freedom, we can verify the properties in a non-deterministic sequential setting, which makes it less complicated. ### B. Encoding In theory, histories are defined over arbitrary sets of locations. The input language for the tool however does not use locations as first class citizens, so it defines histories over the fields of a History class. Actions and processes are also defined using an appropriate ADT in the same class. The predicate Hist that describes (part of) the recorded history has three arguments: a reference to a history object (instead of a set of locations), a fraction and a process expression that denotes the history accounted for. The initial state of a history is specified using the predicate HistInit, whose arguments are a reference to a history and a formula. For example, starting with an empty queue is specified as HistInit(hist,q=\( \text{seq}<\text{int}>\{-\}) To complete the first verification task i.e., to ensure linearizability, modifications of the fields of the history object have to be grouped in action blocks, which must keep full permission on every field written during the action for the duration of the entire action. This is managed by having three forms of permissions on the fields: normal (Perm), passive (HPerm) and active (APerm). Passive permissions can only be used to read from history fields. To write a field you need full active permission. Permission changes, as described in [6], are encoded by replacing every history annotation by a method call whose contract matches the behavior of the proof rules for the annotation. For example, Fig. 6 shows the method that encodes the creation of a history. Note how the initial state is in an extra ghost field (\( q_{\text{init}} \)) in order to be able to reason about it. The Hist\_passive predicate encodes Hist(this,1,empty). Note how the empty expression is replaced by an expression in the ADT. The verification of action blocks records the initial state of the variables to be modified in ghost fields (for checking the actions post-condition), exchanges full passive for full active permission, and assumes any pre-condition of the action. In addition, the encoding of the primitive Hist predicate is inhaled. At the end of the action block, it asserts the post-condition of the action and changes the permissions back. In addition, the encoding of the Hist predicate with an extra action appended is exhaled. The second part of the verification is to show that every execution trace of a history satisfies its contract. To do this, we generate a method for every defined process, whose body is constructed as follows: sequential composition on processes becomes sequential composition of statements, choice on processes becomes a non-deterministic choice, and every mention public class History {/** @param q modifies q; ensures \(q==\text{seq}<\text{int}>\{e\}\); process get(int e); modifies q; ensures \(q==\text{es}+q\); process get_all(seq<int> es)= \{ \text{es}\ = 0?empty:(\text{get(head(es)})+\text{get_all}(\text{tail(es)})); \} ensures get_all(es)+\text{get}(e)==\text{get_all(es}+\text{seq}<\text{int}>\{e\}); void get_lemma(seq<\text{int}> es, int e) \{ if ((\text{es}<0)\{ \text{get_lemma}(\text{tail(es)},e); \} \} modifies q; ensures \(q==\text{old(q)}+\text{es};\) void put_all(seq<\text{int}> es) \{ if ((\text{es}\ ==0)\{ \} else \{ put(head(es)); put_all(\text{tail}(es)); \} \} Fig. 7. Fragment of History Specification for Queues of an action or a defined process becomes a method invocation. For example, the method generated for put_all is \[ \text{ensures } q == \text{old(q)} + \text{es}; \] \[ \text{void put_all(seq<\text{int}> es)}\{ \} \] Note that we call put_all in the body. This is safe because this call is guarded by a call to the action method put, which means that by induction on the length of a trace we can assume that this call satisfies its contract. If a process expression contains unguarded calls, the laws of process algebra are used to compute an equivalent guarded form. C. Verification of a Queue History To illustrate reasoning about complex functional properties using histories, we prove a functional property for the lock-free queue discussed in layer 1: if one thread is given an array with elements that it puts into an empty queue, and a second thread is given an array of the same length that it fills by getting elements from the queue then, once both threads terminate, the contents of both arrays are identical. Essentially, this captures that the order of elements is preserved in the queue. First, Fig. 7 shows part of the history specification. The data managed by the history is a single field q that contains a sequence of integers, i.e., an abstraction of the queue contents. Next, the contract of the get action shows that it removes the first element of q. Then, we define process get_all, which appends a whole sequence of integers to the queue. The history specification is extended with a lemma that shows a useful property about the get_all process, namely that the sequential composition of a get_all and a get is again a get_all. Finally, we define the feed process on whose contract the whole verification hinges; it states the behavior of putting and getting two sequences in parallel: the old contents plus the new elements have to be the same as the retrieved elements plus the current state. Fig. 9 shows the run method of the receiver, annotated with a loop invariant that describes its behavior (the method contract itself is not shown as it is essentially an instance of the loop invariant). The body of the loop uses the get method specified in Fig. 8 to fill the array. Note how the ghost field vals is used to maintain the list of elements written into the array. Also note that the loop invariant only refers to the output array and the vals field: the specification does not depend on the behavior of other threads that may operate on the queue. The comparison of the orders of the input and the output occurs when the two threads are joined by the thread that forked them. This thread knows that: (i) at first q was empty, (ii) the program in parallel put all input array elements into the queue and got all output array elements from the queue. (iii) these arrays have the same length. What (ii) says is that the program performed the process feed (Fig. 7, line 16) for the contents of the two arrays. From the contract of that process, it can be inferred that those contents are the same and the current q is empty too. Thus, modular verification is achieved. Finally, we revisit the lock free queue try_deq method in Fig. 2. To add history support we do the following: - We add a ghost field History hist; to keep the history state. - We add a ghost variable boolean hist_active=true; that denotes if the history is active. - We modify the definition of chain to have a third argument that contains the contents of the chain, and we propagate this change to all uses of chain, including the lemmas. - We change chain(head,ref,last) in the invariant to \[ \text{Perm}(\text{hist_active},1/2) \implies \text{Value}(\text{hist}) \implies (\text{hist_active} == > \text{HPerm(hist,q,1)} && \text{chain(head,ref,last,hist.q)}) \] i.e., we can access list-active and hist, and while the history is active we hold protected permission for hist.q, whose value is precisely the contents of the queue. - We insert an action block after the unfold at line 11 to keep the queue contents and hist.q equal, as discussed above: ```action hist, p, P, hist.get(n2.val); hist.q=tail(hist.q);``` VI. RELATED WORK As already mentioned above, various program logics have recently been proposed to reason about concurrent programs, e.g. CAP [7], iCAP [8], CaReSL [9], TaDA [23] and IRIS [24]. These are all highly expressive logics, which are able to reason about similar properties as discussed in this paper, but so far as we are aware, there is no tool support for them, while our focus is to make verification of concurrent programs practical. The difference between CAP and our approach is that we use a predicate as the resource invariant, rather than an arbitrary boxed formula. As a result, we can only use explicitly declared variables to specify a relation between the local state and the invariant. This is less elegant, but also prevents the problem of stability of boxed formulas that is caused by implicitly crossing the boundary between the shared and the local state. Essentially, iCAP enriches CAP with impredicative protocols and CaReSL introduces thread-locals to modularly reason about fine-grained data- structures. However, so far there is no tool support for these program logics. Moreover, these logics share the property that functional verification happens in parallel with the verification of the data race freedom. In contrast, using histories the functional verification happens separately. The logic TaDA has one feature that our logic does not (yet) have: it allows proving that a method behaves as if it atomically performs an action, while we can only axiomatize this. Closely related to our work, Jacobs and Piessens propose a technique to verify functional properties of lock-free data- structures involving atomic operations in VeriFast [14], which has recently been extended with support for Rely-Guarantee reasoning [15]. They also study the Michael-Scott queue as an example and their work is implemented in VeriFast. As far as data race freedom is concerned, their work and ours are identical in concept, but quite different in the organization of the specification language. For example, we write glue code in with and then blocks for every atomic method invocation. They declare several ways in which an atomic method can operate up front. For the functional properties, their method do not achieve the complete separation between local and global reasoning that is enabled by histories. Also, their notion of action is less general than ours, as theirs is limited to a single atomic operation, while ours can combine multiple atomic operations into a single action. Compared to the logics mentioned above, we use a simple form of invariant. Due to this simplicity, our invariants are easy to verify by encoding them in existing tool supported languages. Using thread local variables in a systematic way, our notion is powerful enough to prove data race freedom. Rather than designing extra features for functional verification into the invariant mechanism, we use a separate mechanism which offers a better separation of concerns. The claim made about IRIS [24] that invariants and monoids are all that one needs to reason about concurrent software is in spirit identical to the claim we make in this paper. Invariants in our approach are similar to IRIS’s invariants, but, while our process algebra is a monoid, the mechanism for executing actions has no equivalent in IRIS. Each action block consists of a number of atomic steps that are independent of any other step that it may be interleaved with. Our logic also satisfies the requirements put forth by Da Rocha Pinto et al. [25]: Our thread-local state is auxiliary state, histories provide interference abstraction, we have resource ownership through separation logic, and we get atomicity through the use of atomic methods and blocks. Our approach is also in line with the works of Jones et al. [26], [27], which propose a limit to the expressive power of specification formalisms in order to keep specifications analyzable and warn of not using auxiliary variables beyond the point where they are appropriate. We have used thread-local specification patterns in our earlier work on atomic operations [28], OpenCL kernel pro- grams [29], and Parallel Loops [30]. The encodings used to implement the latter two are similar in style to the ones introduced in this paper: they translate the proof requirements into a method that must be checked and modify code by inserting exhale and inhale instructions. Rely-Guarantee reasoning [31] is a reasoning style that is intuitive and often elegant. We believe it is possible to encode this style into layer 2 at the price of a large amount of (automatically) added annotations. It is much easier to employ rely-guarantee reasoning at layer 3: we can put the properties on which an action relies as its pre-condition and put the properties it guarantees as its post-condition. VII. CONCLUSION In this paper, we have shown how a layered combination of CSL-based verification approaches for concurrent programs can be used to make mechanical verification feasible and practical. Each layer focuses on a particular class of properties, and reuses the results of the lower layers. The layered approach enables a compositional encoding into a simple verification language, Silicon, with appropriate tool support. Because the encoding focuses on a simple aspect of the verification, it is easier to become convinced of the correctness of the encoding. We also illustrate how verification can take advantage of the layered approach. In particular, at layer 3, we verify a functional property of a lock-free queue, for which we have already shown data race freedom at the lower layer 1. Moreover, in layer 2, we verify correctness of a standard reentrant lock implementation with respect to its contracts mainly specifying its reentrancy properties [20]. As future work, we consider several directions. It might be possible to add other layers to the stack (or have a branching structure of verification techniques) to enable verification of other classes of properties. We also see that verification at the moment requires a large amount of annotations, and we plan to investigate if some of these can be generated automatically. Finally, we need to do large verification case studies, to show how well the mechanical verification scales. Especially, in layer 2, we are interested in case studies with richer concurrency protocols. ACKNOWLEDGMENT The work presented in this paper is supported by ERC grant 258405 for the VerCors project. REFERENCES
{"Source-Url": "http://wwwhome.ewi.utwente.nl/~marieke/pdp2016.pdf", "len_cl100k_base": 9606, "olmocr-version": "0.1.50", "pdf-total-pages": 9, "total-fallback-pages": 0, "total-input-tokens": 34388, "total-output-tokens": 12040, "length": "2e13", "weborganizer": {"__label__adult": 0.0003838539123535156, "__label__art_design": 0.00027561187744140625, "__label__crime_law": 0.0003845691680908203, "__label__education_jobs": 0.0003981590270996094, "__label__entertainment": 5.739927291870117e-05, "__label__fashion_beauty": 0.00014865398406982422, "__label__finance_business": 0.00015735626220703125, "__label__food_dining": 0.0003764629364013672, "__label__games": 0.0005960464477539062, "__label__hardware": 0.0008006095886230469, "__label__health": 0.0005488395690917969, "__label__history": 0.0002276897430419922, "__label__home_hobbies": 8.052587509155273e-05, "__label__industrial": 0.00039315223693847656, "__label__literature": 0.00024306774139404297, "__label__politics": 0.0003097057342529297, "__label__religion": 0.000553131103515625, "__label__science_tech": 0.0156707763671875, "__label__social_life": 8.231401443481445e-05, "__label__software": 0.004093170166015625, "__label__software_dev": 0.97314453125, "__label__sports_fitness": 0.0003838539123535156, "__label__transportation": 0.0006113052368164062, "__label__travel": 0.00022017955780029297}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 48906, 0.01011]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 48906, 0.62058]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 48906, 0.8855]], "google_gemma-3-12b-it_contains_pii": [[0, 5537, false], [5537, 11160, null], [11160, 17106, null], [17106, 22588, null], [22588, 27438, null], [27438, 33092, null], [33092, 37645, null], [37645, 44050, null], [44050, 48906, null]], "google_gemma-3-12b-it_is_public_document": [[0, 5537, true], [5537, 11160, null], [11160, 17106, null], [17106, 22588, null], [22588, 27438, null], [27438, 33092, null], [33092, 37645, null], [37645, 44050, null], [44050, 48906, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 48906, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 48906, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 48906, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 48906, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 48906, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 48906, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 48906, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 48906, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 48906, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 48906, null]], "pdf_page_numbers": [[0, 5537, 1], [5537, 11160, 2], [11160, 17106, 3], [17106, 22588, 4], [22588, 27438, 5], [27438, 33092, 6], [33092, 37645, 7], [37645, 44050, 8], [44050, 48906, 9]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 48906, 0.0]]}
olmocr_science_pdfs
2024-12-02
2024-12-02
45417525dfac1dd23daa5831009f05774cee1b7b
The design and implementation of an input/output subsystem for a Farsi language search engine Ronald L Young University of Nevada, Las Vegas Follow this and additional works at: https://digitalscholarship.unlv.edu/rtds Repository Citation Young, Ronald L, "The design and implementation of an input/output subsystem for a Farsi language search engine" (2003). UNLV Retrospective Theses & Dissertations. 1572. https://digitalscholarship.unlv.edu/rtds/1572 This Thesis is brought to you for free and open access by Digital Scholarship@UNLV. It has been accepted for inclusion in UNLV Retrospective Theses & Dissertations by an authorized administrator of Digital Scholarship@UNLV. For more information, please contact digitalscholarship@unlv.edu. THE DESIGN AND IMPLEMENTATION OF AN INPUT/OUTPUT SUBSYSTEM FOR A FARSI LANGUAGE SEARCH ENGINE by Ronald L. Young Bachelor of Science University of Nevada, Las Vegas 1981 A thesis submitted in partial fulfillment of the requirements for the Master of Science Degree in Computer Science School of Computer Science Howard R. Hughes College of Engineering Graduate College University of Nevada, Las Vegas December 2003 INFORMATION TO USERS The quality of this reproduction is dependent upon the quality of the copy submitted. Broken or indistinct print, colored or poor quality illustrations and photographs, print bleed-through, substandard margins, and improper alignment can adversely affect reproduction. In the unlikely event that the author did not send a complete manuscript and there are missing pages, these will be noted. Also, if unauthorized copyright material had to be removed, a note will indicate the deletion. The Thesis prepared by RONALD L. YOUNG Entitled THE DESIGN AND IMPLEMENTATION OF AN INPUT/OUTPUT SUBSYSTEM FOR A Farsi Language Search Engine is approved in partial fulfillment of the requirements for the degree of MASTER OF SCIENCE IN COMPUTER SCIENCE Examination Committee Chair Dean of the Graduate College Graduate College Faculty Representative ABSTRACT The Design and Implementation of an Input/Output Subsystem for a Farsi Language Search Engine by Ronald L. Young Dr. Kazem Taghva, Examination Committee Chair Professor of Computer Science University of Las Vegas, Nevada The question posed in this thesis is whether it is feasible to use commonly available computer hardware and software equipment found in the United States for querying a web-based native Farsi language search engine. A document conversion utility consisting of a C program called html2unicode was constructed to convert the native language web pages into a common format. A Javascript keyboard application and corresponding embeddable web server was developed to make native Farsi language input and output accessible to a search engine. Although there are some issues inherent in the conversion of Farsi web pages into a format suitable for searching, it is possible to use common hardware and software to retrieve Farsi documents. # TABLE OF CONTENTS ABSTRACT ................................................................................................................ iii ACKNOWLEDGEMENTS ....................................................................................... v CHAPTER 1 INTRODUCTION .......................................................................... 1 CHAPTER 2 A STANDARDIZED DOCUMENT ENCODING MECHANISM 3 Example English Language Encoding ........................................................... 4 Example Farsi Language Encoding ............................................................. 5 UNICODE Encoding ....................................................................................... 6 Two HTML Web Page Encoding Schemes ................................................... 7 CHAPTER 3 Farsi LANGUAGE ISSUES ........................................................ 9 Logical versus Presentation Order ............................................................. 9 Character Normalization ............................................................................ 10 Character Layout and Shaping .................................................................. 11 CHAPTER 4 SOLUTIONS .................................................................................... 15 Input Document Processing Utilities ....................................................... 15 Output Document Processing Utilities .................................................... 17 Type Foundry ............................................................................................... 19 Keyboard Applet ......................................................................................... 20 Embedded HTTP Server Interface Module ............................................. 23 CHAPTER 5 CONCLUSION AND FURTHER RESEARCH ........................ 29 BIBLIOGRAPHY .............................................................................................. 33 VITA .................................................................................................................. 35 ACKNOWLEDGEMENTS Thanks to my wife Cindy, for her love and support. I would like to thank all of the staff at the Information Science Research Institute for their discussions about this work as it progressed. I especially wish to thank Dr. Tom Nartker for introducing me to the world of Optical Character Recognition accuracy analysis during my time at ISRI, and most of all to Dr. Kazem Taghva for introducing me to the field of information retrieval. CHAPTER 1 INTRODUCTION This thesis describes the design and implementation of an input/output subsystem for a Farsi language search engine. The Information Science Research Institute (ISRI) is developing this Farsi language search capability as part of its research into cross-language information retrieval. The Farsi language was also chosen due to its relevance in the present day geopolitical climate. Additionally, Farsi also presents several interesting issues associated with the conversion and processing of documents using standard English language equipment and software tools. Farsi is the official language of Iran and one of the two official languages in Afghanistan (Pashto is the other). In addition, Farsi is spoken in Tajikistan and parts of Uzbekistan [13]. There are more than two million Iranians living in the United States, and the Farsi language is taught at many universities and institutions in North America and Europe [21]. Farsi is written using an expanded form of the Arabic script and is a member of the Indo-Iranian family of languages [10]. Other languages which use variants of the Arabic script include: Dari, Urdu, Pashto, and Arabic to name a few. Since these languages are all written using variations of the same script, many of the issues (and their solutions) that are discussed in later chapters can easily be expanded to include these languages. Languages using the Arabic script share the following characteristics: they are entered from a keyboard in left-to-right order (logical order) but are displayed on output devices in right-to-left order (presentation order). The script is written in a cursive manner such that the characters are joined together. Each character may be written as one of four possible presentation forms ("isolated", "initial", "medial" or "final") depending on its position in a word. Characters may be combined with certain modifiers called "harekats", which behave similarly to the diacritical modifiers found in Latin based languages like French and Spanish. This thesis describes these issues in the following four chapters: Chapter 2 provides an introduction to the concept of a standardized document encoding mechanism called Unicode [2] and how it can be applied to a Farsi language document collection. A major issue when dealing with web-based Farsi language documents is the lack of standardized character set encoding. Without a standard encoding method, search and retrieval of Farsi language documents becomes very unreliable. Chapter 3 explains the issues that are specific to the conversion and processing of Farsi language documents. These issues include conversion between the logical and presentation text layouts into a common form, font encoding standardization (conversion of different character presentation forms into a single Unicode encoding). Farsi also imposes some language specific rules regarding how certain character combinations should be displayed, care must be taken during the input conversion process to include an indication to the output processor informing it of the special display requirements. Chapter 4 describes the methods that were developed to address Farsi language issues and to allow the input and output of native Farsi words using Latin character based computer equipment and software. A web browser keyboard applet was developed to allow the entry of Farsi words using either the mouse or the computer keyboard. A "type foundry" utility was developed to generate bitmap images of Farsi letters, words or lines for display on computers that would not otherwise be capable of displaying the Farsi text. A third mechanism was developed that accepts the keyboard applet text and converts it into a form suitable for processing by a search engine's query processor. Finally, Chapter 5 presents the overall results regarding the feasibility of this approach in processing Farsi documents and query text. It states the conclusion of this study and offers possible areas for further research. CHAPTER 2 A STANDARDIZED DOCUMENT ENCODING MECHANISM Digital computers internally represent information as a collection of binary digits (bits), zero and one values. The number of bits and operations that the computer uses when accessing a data value determines the value's valid contents and type. Probably the most common data type in use is the “byte”. Although, the size of a byte may be arbitrary, on modern computers it is normally 8 bits. An 8 bit byte can contain a single value in the range between zero and 255. The meaning of a byte is determined by the encoding scheme used to associate information with each integer value. In terms of textual information, the information that we are mapping onto the integer values is the alphabet of the language that the text is written in. The complete alphabet is known as a “character set” and the integer values for the letters are known as “code points”. Historically, each computer manufacturer defined their own byte sizes and character sets. For example, Control Data Corporation mainframes used a 6-bit character size with the display code character set, Digital Equipment Corporation mainframes used a byte size of 8 or 9 bits with an encoding called “American Standard Code for Information Interchange” (ASCII) [7], and IBM used an 8-bit byte with the “Extended Binary Coded Decimal Interchange Code” (EBCDIC) [8]. In order to exchange information between computer systems of different manufacturers, it is therefore necessary to know what byte size and character set were used to encode the text. With the invention and widespread adoption of the personal computer, the encoding schemes used for English language text documents has standardized into USASCII, an updated version of the original ASCII standard [9]. Throughout the rest of this document, the term ASCII will be used in referring to both ASCII or USASCII. EBCDIC is still widely used by IBM mainframes to allow for compatibility with legacy software applications. Example English Language Encoding To illustrate the effect of different encodings on the same text, consider the text phrase “Information Retrieval”. Encoding it in ASCII and EBCDIC results in: <table> <thead> <tr> <th>ASCII</th> <th>73 110 102 111 114 109 97 116 105 111 110 32</th> </tr> </thead> <tbody> <tr> <td></td> <td>82 101 116 114 105 101 118 97 108</td> </tr> <tr> <td>EBCDIC</td> <td>201 213 198 214 216 212 193 227 201 214 213 64</td> </tr> <tr> <td></td> <td>217 133 163 153 137 133 165 129 147</td> </tr> </tbody> </table> Table 2.1: ASCII and EBCDIC CHARACTER ENCODING As is obvious from this example, even though these two sequences represent the same phrase, the computer system will not recognize them as such, since the numeric sequences are not equal. The ability to determine if two words are equal, is of fundamental importance when searching and retrieving documents. The techniques necessary to prepare English language documents so they are suitable for retrieval have been well studied by Salton [14], Frakes[4] and others. While the specific methods used are beyond the scope of this thesis, they include case folding (converting all alphabetic characters to the same case) and stemming (identifying the root of a word). ASCII fully represents the characters used when writing English language text, but as computer use spread to other non-English language countries, national extensions to the ASCII character set were developed. Since ASCII only uses the lower 128 code points, these national extensions usually involved assigning the new letters to the code points between 128 and 255. The various 256 character encodings are commonly referred to as “code pages”. With the advent of the World-Wide Web, the process repeated itself. The technology used to access the web was developed around the ASCII character set with the ability to substitute different code pages by adding a special “<FONT FACE>” tag into the web content. By using this technique, the web user who wished to view the encoded page, had to make sure that the font file covering the code page was loaded onto their computer, and if someone wanted to create a web page using the encoding, they would also need to know the code point assignments. Example Farsi Language Encoding Consider the Farsi phrase: “آیت الله خامنه‌ای” (Translation: Ayatollah Khameni - the person who currently holds the office of Supreme Ruler of Iran). Table 2.2 shows the results of encoding the phrase using two of the common character sets encountered in the study. These two character sets are known as CP1256 (Microsoft Windows Arabic code page) and Persian Nimrooz (a proprietary encoding used by the Hamashari Newspaper web site). These encodings are discussed in more detail in the next chapter. <table> <thead> <tr> <th></th> <th>Microsoft</th> <th>CP1256</th> <th>Persian</th> <th>Nimrooz</th> </tr> </thead> <tbody> <tr> <td></td> <td>194 237 202 199 225 229 32</td> <td>206 199 227 228 228 199 236</td> <td>141 254 150 144 243 243 249 255</td> <td>160 145 245 247 249 144 253</td> </tr> </tbody> </table> Table 2.2: CP1256 and PERSIAN NIMROOZ ENCODING Documents written using the Arabic script presents two problems with extracting text that are not found in English language documents. The shapes of Arabic letters can be different depending on their location in the word and not all of the shapes can fit in the upper 128 code points of a 256 letter font. UNICODE Encoding The genesis of the Unicode Consortium began in 1987 with informal discussions between staff members of Xerox Corporation and Apple Computer. These discussions were the result of difficulties encountered when converting software applications to support non-English languages, particularly Japanese. The result of these talks was the Unicode Standard. Unicode basically started with the ASCII code points and expanded them to include code points for most of the languages in use worldwide. The most frequently used subset of the Unicode standard provides a 16-bit encoding for these characters. By using a 16-bit encoding allows for the possibilities of 65536 different code points. This encoding is commonly divided into 256 character code pages for various languages. For this research study, we are interested in the U+0600-06FF (Arabic), U+FB50-FDFF (Arabic Presentation Forms-A), and U+FE70-FEFF (Arabic Presentation Forms-B) code pages. The notation “U+####” signifies the hexadecimal range of Unicode code points. For example: U+067E (1662 in decimal) is the code point assigned to the isolated presentation form of the Farsi letter PE (¶). The U+0600-06FF range contains the base letters for languages that use the Arabic script. For our purposes, all of the letters that are processed as input data will be converted to a code point inside of this range. The other two ranges, contain the code points for the other presentation formats of the Arabic letters. Another result of the work by the consortium members was the incorporation of Unicode support into the TrueType/Opentype glyph rendering standard. This was important because while Unicode provides a standardized method of manipulating code points, it does not address how to display them on output devices. TrueType/Opentype provides the information necessary to render the glyph images correctly on the output device. Two HTML Web Page Encoding Schemes Unlike ASCII text, Unicode encoded strings should not be used by software tools that are not Unicode aware. To do so can result in data corruption. To allow ASCII based tools to be used, several schemes were developed to encode Unicode code points so they can pass through ASCII-based tools unchanged. The two representations that are of interest are: HTML escape encoding, and UTF-8. The HTML escape encoding scheme is very simple: convert the code point value into a character string containing the decimal representation of the code point, prefix the string with "&" (an ampersand) and suffix the string with a semi-colon. So the code point U+067E would be represented as "&1662;". This encoding scheme has the advantage of being very simple to implement, but at the possible cost of expanding the size of a document up to 350% (from 16 bits per Unicode character to 56 bits (7 ASCII characters)). To minimize the amount of overhead required, another encoding scheme called the “Unicode Transformation Format-8” (UTF-8) [22] was developed. UTF-8 is an “8-bit clean”, lossless encoding of Unicode characters. This allows the encoded characters to pass through programs that assume all character data is made up of 8-bit values. ``` | U+0000 - U+007F | 0xxxxxxx | | U+0080 - U+07FF | 110xxxx 10xxxxxx | | U+0800 - U+FFFF | 1110xxx 10xxxxxx 10xxxxxx | ``` Table 2.3: 16-BIT UNICODE UTF-8 ENCODING [5] The part of the encoding scheme of interest is shown in Table 2.3. Where the xxx bit positions are filled with the bits of the character code point value in binary representation. For example, the Unicode character PE (پ, U+067E) has a binary representation of 00000110 01111110. Converted into UTF-8 results in the two 8-bit patterns: 11011001 10111110. The resulting bit values can pass through ASCII only applications unchanged. CHAPTER 3 FARSI LANGUAGE ISSUES In addition to the character set encoding issues described in the previous chapter, there are several other issues that are related to documents written in Farsi (and Arabic script in general). These issues include, logical versus presentation order, character normalization, and character layout & shaping. Logical versus Presentation Order Logical order is the order that a person would enter characters on the keyboard. Presentation order, also known as reading order, is the order in which those characters are displayed on an output device. For English language documents, the logical and presentation orders are the same, left-to-right. For Farsi documents, the logical order is left-to-right while the presentation order is right-to-left. While handling the difference in logical versus presentation order is straightforward for characters entered by the keyboard, it may be difficult to automatically determine the presentation ordering for HTML pages included in the document collection. This is due to the fact that depending on the software used to create the web page, the transformation of the logical ordering may or may not have already been done. In processing the pages for the Farsi-1 collection, two kinds of pages were encountered: the unicode encoded pages used the expected left-to-right ordering, and the proprietary encoded Persian Nimrooz pages contained text with right-to-left ordering. Character Normalization During processing of input document text, “combined” characters may be encountered. A combined character is a base character from the Unicode Arabic code page that has been modified by the addition of one or more harekats. Harekats are used to indicate the presence of vowels and/or repetition of consonants. Text written by native Farsi speakers normally only includes vowels when necessary to prevent ambiguity. Because of the possibility that harekats may be present on a query term entered from the keyboard, but not in the collection’s document text, it is important that the deconstruction of a combined character into its individual components be performed in a consistent manner. For this study, the unicode conventions of processing combined characters will be used. This convention is that the base character will appear first in the text’s logical order, followed any harekat modifiers. The keyboard applet also enforces this behavior for text entered manually. This convention simplifies the term matching routines used by the search engine. When comparing two terms, the routines will match the harekats only if they appear in both, and will ignore them otherwise. An additional issue related to character normalization, is in recognizing that the different presentation forms of a letter are equivalent for comparison purposes. To address this issue, all of the presentation forms for a letter will be mapped to the letter’s isolated code point in the U+0600 unicode code page. It is during this mapping, that some Farsi specific hints on which presentation form should be used for display may also be inserted. These hints, known as zero-width joining (ZWJ, U+200D) and zero-width non-joining (ZWNJ, U+200C) characters are discussed further in the next section. The final issue uncovered in this study, is that there are two code points that may be represented by the same glyph. The alef maksura (U+0649) and the Farsi Ye (U+06CC) share the same glyph (ٖ). This is addressed by mapping the Farsi Ye to the U+0649 code point. Character Layout and Shaping Character layout and shaping prepare the Unicode text strings so they can be displayed on an output device. They can be thought of as the inverse of the logical & presentation ordering and character normalization operations for input text. There are three major steps involved in preparing Farsi text for display on an output device: - Conversion from logical to presentation order. - Construction of combined characters from their normalized components. Also, substitute ligatures for common letter sequences where possible (i.e. lam (ل) followed by alef (ا) becomes the ligature (ی)). - Selection of the correct presentation form for each character. The Unicode Standard[2] provides generalized mechanisms to accomplish each of these steps. Unicode provides a bidirectional algorithm to correctly layout text. The bidirectional algorithm provides the ability to layout intermixed left-to-right and right-to-left ordered text. Since this study's purpose is to provide input and output for a Farsi language search engine, we can simply reverse the ordering of the characters instead of using the full bidirectional algorithm. Similarly, we can simplify the mechanism used to select the presentation form for each letter. Since we are only working with the Arabic script, we can use a variation of a simple table lookup described by Shaikh [16] instead of using the more involved method provided by the Unicode standard. The modifications that were made to Shaikh's algorithm was the addition of letters specific to Farsi and the ability to override the default shaping behavior with the use of zero-width joiner (ZWJ, U+200D) and zero-width non-joiner (ZWNJ, U+200C) characters. The ZWJ and ZWNJ unicode code points do not have widths, and therefore do not have a glyph, assigned to them. Their purpose is to override the default shaping behavior between two characters. If two characters normally would be joined, the insertion of the ZWNJ character between them will disable this joining. The first character will be converted into a final presentation form and the second character will be converted to an isolated or initial form. The insertion of a ZWJ character between two normally joining characters will have no effect. If two characters normally would not be joined, the insertion of the ZWJ character between them will force a joining. The first character will be converted from an isolated/initial form to an initial/medial form, and the second character will be converted from an initial/medial to a medial/final form. The insertion of a ZWNJ character between two normally non-joining characters will have no effect. The algorithm uses the Farsi character tables shown in tables 3.1 and 3.2 to select the presentation form for a letter, or the base character for a combined letter, based on the value of the letter and the presence or absence of letters before (prev) and after (next) the character being shaped. If prev and next would fall outside of the bounds of the text string, they are set to reflect no character present. - if both prev and next reflect no character present, select the isolated form. - if prev is present and next is not present, tentatively select the final form. - if prev is not present and next is present, tentatively select the initial form. - if both prev and next are present, tentatively select the medial form. - if there is not an entry in the table for the tentatively selected form, select the isolated form instead. Additional checking is performed to substitute ligature characters for common character sequences. <table> <thead> <tr> <th>Letter</th> <th>Presentation Form</th> </tr> </thead> <tbody> <tr> <td>sadda</td> <td>harekat / repetition</td> </tr> <tr> <td>ze.bar</td> <td>harekat</td> </tr> <tr> <td>zer</td> <td>harekat</td> </tr> <tr> <td>pesh</td> <td>harekat</td> </tr> <tr> <td>alef w/ madd</td> <td>̄, ̄</td> </tr> <tr> <td>alef</td> <td>̄, ̄</td> </tr> <tr> <td>vav</td> <td>̄, ̄</td> </tr> <tr> <td>ye</td> <td>̄, ̄</td> </tr> </tbody> </table> Table 3.1: Farsi Letters (Vowels and Harekats) <table> <thead> <tr> <th>Letter</th> <th>Presentation Form</th> <th>Presentation Form</th> </tr> </thead> <tbody> <tr> <td>be</td> <td>ب</td> <td>ض</td> </tr> <tr> <td>pe</td> <td>ب</td> <td>ط</td> </tr> <tr> <td>te</td> <td>ت</td> <td>ظ</td> </tr> <tr> <td>se</td> <td>ث</td> <td>ع</td> </tr> <tr> <td>jem</td> <td>ج</td> <td>غ</td> </tr> <tr> <td>che</td> <td>ح</td> <td>ف</td> </tr> <tr> <td>he</td> <td>خ</td> <td>ق</td> </tr> <tr> <td>khe</td> <td>خ</td> <td>ك</td> </tr> <tr> <td>dal</td> <td>د</td> <td>ل</td> </tr> <tr> <td>zal</td> <td>ذ</td> <td>ل</td> </tr> <tr> <td>re</td> <td>ر</td> <td>لا</td> </tr> <tr> <td>ze</td> <td>ز</td> <td>م</td> </tr> <tr> <td>zhe</td> <td>ز</td> <td>ن</td> </tr> <tr> <td>sen</td> <td>س</td> <td>و</td> </tr> <tr> <td>shen</td> <td>ش</td> <td>ه</td> </tr> <tr> <td>sad</td> <td>ص</td> <td>يا</td> </tr> </tbody> </table> Table 3.2: Farsi Letters (Consonants) CHAPTER 4 SOLUTIONS This chapter describes the program solutions that were implemented to provide Farsi language capabilities for document and keyboard input/output. The following portions of the input/output subsystem are described: utilities for both document input and output processing, character/word image generation (the “type foundry”), a keyboard input/output applet, and an embedded HTTP server interface module for inclusion into a search engine. Since the initial test collection consists only of HTML documents, all of the processing utilities developed in this study only process documents in this format. However, the processing methods can easily be extended to support additional formats like PDF, optical character recognition software output files, or Microsoft Word document formats using techniques similar to those described below. The only requirement is that the output format conform to the standard format described in the next section. Input Document Processing Utilities The input document processing utilities are a set of stand-alone programs that accept documents in a variety of formats and converts them to a standard format that can be processed by the search engine. The prototype I/O system utilities produces files containing a unicode byte-order-marker (BOM, u+FEFF) followed by zero or more 16-bit unicode code points. The unicode BOM and its counterpart u+FFFE identifies the byte ordering of the code points contained in the file. The u+FEFF will be read as the first unicode character if the host computer system stores binary data in “big-endian” (most significant byte first) order. If the host reads the BOM as u+FFFE, it stores binary data in “little-endian” (least significant byte first) and indicates that the two bytes of each character needs to be swapped before processing the data. Using the BOM, allows data files to be portable across different computer systems. For example, during the development of the document utilities, two different computer systems were used for testing, an IBM-PC clone (Intel Pentium 4 - little endian) and a Sun Microsystems Blade 2000 (Ultra SPARC - big endian). Because of the presence of the byte order marker, processed document files could be transferred between the systems without having to worry about the byte order. An input utility was developed, html2unicode that converts input HTML documents into the standard unicode file format described above. The html2unicode utility is executed in the following manner: ``` html2unicode <URI> [ reverse ] ``` Where <URI> is a uniform resource identifier (URI) identifying the location of the input document to be converted. By using a URI to specify the input document, both web-based text (i.e. http://www.hamashari.org) and disk based text files (file:///home/isri/ron/test.html) can be processed without having to modify the utility. The optional parameter reverse controls whether html2unicode will reverse the order of the input text to correct the documents presentation ordering. The converted document is written to the standard output. The document processing utilities use the LIBwww[23] library routines to parse the HTML documents and to process URI arguments. LIBwww allows a program to register a set of callback routines for processing of each syntactic element found in the HTML document. Callbacks can be invoked for the start and end of each HTML tag, for each text element, and for the start and end of a document. The callback functions for the *html2unicode* utility are defined as follows: - For each HTML tag, except for `<FONT FACE=name>`, no action is taken or output produced. - For each HTML `<FONT FACE=name>` tag, the font name is placed on a stack, with the topmost element on the stack becoming the active font face. - For each HTML `</FONT>` tag, the stack is popped, and the new topmost element on the stack becomes the active font face. - For each text string, each individual code point is mapped from the input font into unicode by the use of a translation table identified by the active font face. After this translation, the unicode code points are written (in binary) to the standard output. - For the start and end of document callbacks, no actions are taken and no output produced. Output Document Processing Utilities In addition to the input document processing utilities, two other utilities were developed, *html2unihtml* and *html2imghtml*. They are executed in the same manner as *html2unicode* above. The callbacks for the *html2unihtml* utility are defined similar to those for *html2unicode*, except that the callback for HTML tags is modified to write the tag to the standard output. This allows for the conversion of document text while retaining the HTML mark-up directives. The converted document can then be displayed with the same presentation format as the original document but using unicode fonts instead of the originally encoded proprietary font. The *html2imghtml* utility is one of the key parts of this study. It provides the same translation capabilities as the other utilities, but instead of outputting Unicode code points, it renders the text into graphic images with a corresponding HTML file to display them. This allows a computer with a web browser but no Unicode support to display Unicode documents. Because of the image rendering, the input text is converted into lines of Unicode and then a separate image file is created for each text line. The type foundry (described in the next section) is used to create the images. The callback functions for the *html2imghtml* utility are defined as follows: - For each HTML `<FONT FACE=\textit{name}>` tag, the font name is placed on a stack, with the topmost element on the stack becoming the active font face. - For each HTML `</\textit{FONT}>` tag, the stack is popped, and the new topmost element on the stack becoming the active font face. - For each HTML `<\textit{BR}>` (break) tag, the current line buffer is inserted into a linked list for later processing. The line buffer is then emptied. - For each HTML `<\textit{P}>` (paragraph) tag, the current line buffer followed by a blank line is inserted into the linked list. The line buffer is then emptied. - For all of the other HTML tags, no action is taken or output produced. - For each text string, each individual code point is mapped from the input font into Unicode by the use of a translation table identified by the active font face. After this translation, the Unicode code points are stored in a buffer containing the current line. - For the start document callback, no action is taken or output produced. • For the end document callback, each entry in the linked list of text lines is sent to the type foundry for rendering and the resulting graphic image is written to a unique filename. A HTML file is written containing an <IMG SRC=filename> tag such that when the HTML document is displayed in a web browser, the images of the lines will appear. Type Foundry The type foundry library consists of a set of application callable functions that create graphic bitmaps of unicode character strings. There is also a stand-alone application program called rendermain that can be called directly from a command shell to generate bitmap images. These routines are used by the keyboard applet to generate individual Farsi letters for display and by the utility html2imghtml to render HTML documents for display on non-unicode capable browsers. Two external libraries are used: Freetype[12] which renders strings using TrueType[3] font files into memory-based bitmap images, and libpng[15] which writes memory-based bitmap images into a disk file in the “Portable Network Graphics” (PNG) format. The process used to generate the images from unicode strings is briefly described as follows: • A unicode encoded string is stored in memory. When using the stand-alone application this string is retrieved from the command line arguments when the program is executed. When using the library, the unicode string is typically retrieved from the HTML web form (keyboard applet) or from a parsed HTML file (html2imghtml). • A glyph is assigned to each character code point in the string. This is accomplished by calling the Freetype routine TT_Char_Index (returns an index entry for the character code point inside of the font) and the type foundry routine assign_glyphs() (using the font index, selects the glyph for the code point). The type foundry function ShapeLetters() is called to select the correct presentation form for the characters in the string. This is implemented using the shaping algorithm described in the previous chapter. The type foundry function exe_render_common() is called with the shaped string and a name of the image file where the PNG image will be stored. The purpose of this function is to render the glyph images of each character in the proper presentation order while taking care to insure that each character is aligned and joined correctly. The type foundry routines are most commonly called from the keyboard applet to generate the images for combined characters as they are entered by the user. Keyboard Applet The capability specifications for the user input module of this study required that Farsi language input be able to be entered by the user using either a normal ASCII keyboard and/or the mouse into a web browser. This a secondary goal was to accomplish this without requiring the user to manually load additional software or font files onto the system. Two different approaches were tried to address the issue of accepting Farsi language input from the user. The first approach was to develop a Java Language applet. While this approach was successful, it suffered from two major shortcomings: not all of the web browsers used in this study support Java (and those that did supported different versions, mostly Java 1.1). While Java uses Unicode encoded strings internally, only recent versions fully support Arabic script strings. The major problem was that Java did not completely handle Arabic script rendering until version 1.4.2. To provide a consistent Java environment, would require the user to download and install the newer Java runtime environment. Another shortcoming was the amount of time required to download the code files for the actual applet and fonts whenever the input web page was initially loaded. These two issues were judged to be sufficiently severe such that the Java language approach was abandoned. The second approach was to develop a set of browser independent javascript functions coupled with some server based support capabilities to provide Farsi language input. This approach solved the shortcomings presented by the Java applet, but presented different issues that needed to be resolved. The Javascript issues were mainly caused by differences in the event handling models implemented by the two main browsers used: Microsoft's Internet Explorer and the Netscape/Mozilla family. Web browsers allow Javascript functions to interact with the browser’s input/output capabilities by implementing the concept of “events”. Events are similar to interrupts in other computer hardware and software. The events that we are interested in are: MOUSEDOWN, KEYPRESS, and KEYDOWN. There are other events available, but these are the ones of interest. Each of the events can have a Javascript function attached to them instead of the default behavior provided by the browser. In order to capture characters typed on the keyboard, it is necessary to attach a function to the KEYPRESS event for the current document being displayed on the browser. The mechanism to accomplish this is similar to the following javascript code fragment: ```javascript function ReadKey(e) { whKey = event.which; Type(far[whKey]); return false; } ``` Where `event.which` returns the code that was pressed on the keyboard. `Type(far[whKey])` maps the key code into the Farsi character set and calls the `Type()` function to actually process the Farsi character. The `ReadKey` function is associated with the KEYPRESS event using something like: ```javascript document.captureEvents(Event.KEYPRESS); document.onkeypress = ReadKey; ``` This works as expected in the Netscape and Mozilla family of browsers. They correctly accept all of the keyboard characters including control characters. It does not work with the Internet Explorer browsers. While the above code fragment will capture normal (printing) keyboard characters with slight modifications, not all of the control characters are returned to the `ReadKey` function. This is problematic since the backspace key is normally used in text input functions as a character delete key, but is interpreted by Internet Explorer as the “back page” function to have the browser display the previously viewed page. Internet Explorer processes the browser control characters before calling the KEYPRESS event handler, so the `ReadKey` function is never called for the backspace character. This problem can be overcome by assigning another event handler for the KEYDOWN event when Internet Explorer is used. The KEYDOWN event processes the backspace character (by calling the Type function directly) and ignores any other characters. With the exception of the above event handler differences, the rest of the Javascript code is the same regardless of the type of browser being used. This is different than most other web applications where common practice is to code for a single browser (Internet Explorer). The remainder of the keyboard code implements a simplified version of the type foundry functionality. The major difference, in addition to including normal text editing functions, is that the images used to display the Farsi letters are previously generated and stored on the server. The character images are loaded into the browser when the Javascript code is initially loaded and then used for displaying the shaped Farsi characters. Only base characters are cached in this manner, combined characters are still generated by the server and downloaded as needed. The keyboard applet tries to conform to the defined standards for Farsi keyboards. These standards are maintained by the Institute of Standard and Industrial Research of Iran (ISIRI). The relevant standard for keyboards is ISIRI 2901 first developed in 1988 and revised in 1994. The original document is written in Farsi, so information that was extracted and translated in an electronic mail message by Pournader[11] was used instead. This information consisted of the keyboard layout and placement of the ZWJ and NZWJ characters. Figure 4.1 shows the keyboard applet as it is used by the Farsi-1 collection relevancy question data entry application. Note: the Farsi text being displayed in the lower part of the figure are actually graphic images that were rendered by the type foundry utilities described in the previous section. Embedded HTTP Server Interface Module This section describes the mechanism that is used by the retrieval engine server component for communication with the client browser. From a design standpoint, there are two basic ways to accomplish this communication: using a stand-alone web server with a set of Common Gateway Interface (CGI) programs, or by using a web service directly embedded into the retrieval engine. Either method could be used to perform the server side processing required. For the purposes of this study, the embedded approach was chosen for the following reasons: - Ease of integration. By using an embedded server it is very easy to allow access to server functionality from the client by simply attaching a processing routine to a specific uniform resource identifier (URI). The only requirement for the event handling routine is to produce a valid HTML document as output. • Ease of support. With an embedded server, the issues of installation, operation, and security of stand-alone web server and CGI programs are avoided. Development resources can remain focused on the development of the retrieval application instead. • Allows the retrieval engine to be completely self-contained and easily ported to different host platforms. Since the application doesn’t rely on an external web server, it is unaffected by external configuration changes. As long as the host system is operational and network connections are accepted, the application should function correctly. Also, by choosing an embedded server, the application can be easily ported to any platform that has a standard C language compiler and networking based on the Berkeley Unix “sockets” model (practically all modern operating systems provide networking capabilities sufficient to allow the operation of the software produced in this study). The I/O subsystem described in this study was designed to be activated on demand by entering a “httpserver” statement to the retrieval engine’s interactive command line interface. Because of its modular nature, the I/O subsystem may also be activated directly from within a customized retrieval engine. The embedded web server that was selected for use is called libHTTP and was developed by Hughes Technologies[6]. By using a small set of API routines, libHTTP allows an application to accept and terminate HTTP connections, define valid URI’s and their actions, and retrieve values from the client browser. Assuming that the retrieval engine accepts http connections on the local computer system using port 1234, the following URI’s are defined: • http://localhost:1234. This URI causes the embedded server to display the retrieval engine’s “home page”. This page is intended to have introductory text describing the function of this particular search engine as well as hyperlinks to other URI’s that control the retrieval engine. - **http://localhost:1234/command.** Browser supplied values: ``` command=<engine command> query=text string ``` Accept a command line request to be processed by the retrieval engine from the client's web browser. This is done by injecting the entered command line into the command line processor's standard input and capturing the standard output and standard error files produced when the request has been processed by the retrieval engine. Note: while one of the parameters passed by the browser is named `query`, it is not intended for the `command` URI to be used to perform normal retrieval queries. The `query` and `process_query` URIs (described below) should be used instead. The intended use for this URI with the query value is to allow for special processing like reporting term co-occurrence and frequency information. - **http://localhost:1234/exit.** Terminate the HTTP connection, cleanup any rendered text and letter images, and exit the embedded web server. When the web server exits, control is returned to either the interactive command line processor (for the research prototype engine) or to the calling function (for a customized retrieval engine). - **http://localhost:1234/display.** Browser supplied value: ``` docid=<document id> ``` Requests that the retrieval engine display the requested document on the browser. At the current time this URI's action routine is a simple debugging stub. However, since this is a single routine, its functionality can be overridden by the retrieval engine to provide capabilities such as term highlighting, attaching hyperlinks to words, word substitution, etc. • http://localhost:1234/renderletter. Browser supplied value: farsi=<code points> OutStr=<code points> s=<point size> The renderletter URI requests that the unicode string encoded as hexadecimal digits contained in the farsi and/or OutStr variables be rendered as an image for display. The farsi variable contains the Farsi text encoded without any code point substitutions that reflect shaping. The OutStr variable contains these substitutions. The s variable contains the requested point size value to be used when rendering the letters. The output for this URI is the actual PNG image, making it suitable for use as source targets in html <IMG> statements. • http://localhost:1234/tmp/<filename>. The tmp URI provides access to a temporary store of images for use by HTML pages generated by the retrieval engine. For example, if the keyboard applet requests the rendering of a compound character, by using the renderletter URI, the generated image will assigned a unique name and placed in the temporary store. This name is also added to an internal list structure for use by the exit URI to cleanup these temporary data files. • http://localhost:1234/kbd. This URI is intended to allow the user to manually enter Farsi text for submission to the retrieval engine. It is tied to a filesystem directory located in the web server's document tree. This directory contains a html page that loads the keyboard applet and a results page into separate frames. It is configured to submit textual information to the process_query URI. • http://localhost:1234/kbd/js/<filename>. Allows the keyboard applet loaded in the client’s web browser to load the keyboard layout and pregenerated basic letter images from the server. For example the html statement: `<img src="http://localhost:1234/kbd/js/keyboard.png">` will cause the graphic image for the Farsi keyboard to be display on the browser. • http://localhost:1234/query. This URI causes the embedded server to display the retrieval engine’s “query page”. This page is intended to allow the user to enter Farsi search terms by using the keyboard applet. This page uses the kbd URI to activate the keyboard applet such that the entered text will be directed to the process_query URI when the submit button is pressed. • http://localhost:1234/process_query. Browser supplied value: farsi=<code points> OutStr=<code points> s=<point size> The process_query URI requests that the retrieval engine process the contents of the farsi variable as search terms against the current document collection. This processing consists of the normal information retrieval type tasks, the resulting html page should be a list of ranked documents that are relevant to the query terms. The OutStr and s variables are made available for use to the retrieval engine to possibly aid in rendering Farsi text displayed in the result page. Click on the "Query number" or "Add New Query" to enable the keyboard above. To delete a query, click on its number and click on 'clear' then accept (enter an empty string). To edit a query click on its number, then click on the desired edit mode (Replace mode, Insert mode, or Delete mode) once you have selected the edit mode, click on the desired letter in the edit box. Figure 4.1: Example use of the keyboard applet[17] CHAPTER 5 CONCLUSION AND FURTHER RESEARCH The software described in this study has been included in a research prototype Farsi language search engine developed and implemented by staff members of the UNLV Information Science Research Institute (see figure 5.1 for a functional block diagram of the prototype system)[19][18][20]. Based on the preliminary evaluation of the system, we can conclude that it is indeed feasible to use this software to provide Farsi text input and output capabilities without the need for language specific hardware or operating system support. The evaluation of the prototype system also provides several areas for improvement and further research: - Multiple script keyboard support. While testing the Farsi language keyboard applet, it became clear that using this mechanism of text input to a search engine would be even more useful if keyboard support for additional languages and scripts could be incorporated. The current design of the I/O subsystem could be extended for additional keyboards by a slight modification applied to the \textit{kbd} URI described in the previous chapter. Probably the easiest way to add this capability is to replace the single \textit{kbd} URI with one for each of the desired languages, i.e. \textit{farsikbd} for Farsi, \textit{arabickbd} for Arabic, and \textit{pashtokbd} for Pashto. Like the current \textit{kbd}, they would map to a specific directory located in the document root of the embedded web server. The main advantage of this method is that it is simple to add the additional keyboard support. The main disadvantage is that each language would then have its own separate set of applet code, Figure 5.1: Prototypical system architecture[17] layout images, and letter images. Another method would be to add an argument specifying which language the applet should process. The advantage to this method is that there is a single set of code and images. The disadvantage is that depending on how different the processing requirements of the supported languages, the complexity and size of the applet code may grow larger. This would not pose a problem if the system running the client browser is fast enough, but on older systems the additional processing and memory requirements may cause a delay in response time from the keyboard applet. • Improved response time to display documents. The major shortcoming uncovered during the prototype development was that there was a significant amount of time required to display a rendered document in the browser. This is caused by two main factors: each document is completely rendered before being displayed and entire lines are rendered into each image, so the amount of data required to be sent to the browser can take several seconds particularly on low-speed dial-up lines. A test was performed during the development of the software, instead of rendering entire lines, individual words were used instead. By using words, the time required to download the rendered document was reduced, but the text could be displayed incorrectly. The incorrect display appears to be caused by the differences in word wrapping of text between the English language default for the browser, left-to-right, and the Farsi language requirement of right-to-left. A compromise approach was adopted for this study, each document would be rendered into line images as part of creating the collection. This would eliminate the time delay required by rendering the document, but did not address the download time issue. • Allow the creation of stand-alone CD-ROM based collections. The design of the I/O subsystem doesn’t place any requirements on accessing collections through the network. By simply using the network loopback interface supplied by the host operating system, the I/O subsystem should be able to run using a local CD-ROM based collection. This assumes, however, that the host operating system is capable of running the search engine application and supporting libraries. • Decrease the time required to process search queries. The current I/O subsystem and search engine prototype is currently single threaded. It is possible to improve response time for searches as well as I/O processing by adopting some combination of concurrent processing, i.e. begin rendering of the top ranked documents while continuing to process the search query. Another possible approach is to have multiple threads or processes rendering the document images in parallel. BIBLIOGRAPHY 33 Reproduced with permission of the copyright owner. Further reproduction prohibited without permission. VITA Graduate College University of Nevada, Las Vegas Ronald L. Young Local Address: 8507 Shelly Rd. Las Vegas, NV 89123 Degrees: Bachelor of Science, Computer Science, 1981 University of Nevada, Las Vegas Publications: Thesis Title: The Design and Implementation of an Input/Output Subsystem for a Farsi Language Search Engine Thesis Examination Committee: Chairperson, Kazem Taghva, Ph. D. Committee Member, Dr. Thomas Nartker, Ph. D. Committee Member, Dr. Wolfgang Bein, Ph. D. Graduate Faculty Representative, Dr. Emma Regentova, Ph. D.
{"Source-Url": "https://digitalscholarship.unlv.edu/cgi/viewcontent.cgi?article=2571&context=rtds", "len_cl100k_base": 11482, "olmocr-version": "0.1.50", "pdf-total-pages": 43, "total-fallback-pages": 0, "total-input-tokens": 72676, "total-output-tokens": 14329, "length": "2e13", "weborganizer": {"__label__adult": 0.0004935264587402344, "__label__art_design": 0.0019483566284179688, "__label__crime_law": 0.0004274845123291016, "__label__education_jobs": 0.0177154541015625, "__label__entertainment": 0.0003173351287841797, "__label__fashion_beauty": 0.0002923011779785156, "__label__finance_business": 0.0005135536193847656, "__label__food_dining": 0.0003695487976074219, "__label__games": 0.0009636878967285156, "__label__hardware": 0.0023975372314453125, "__label__health": 0.0004363059997558594, "__label__history": 0.0011987686157226562, "__label__home_hobbies": 0.00013577938079833984, "__label__industrial": 0.00044918060302734375, "__label__literature": 0.0029201507568359375, "__label__politics": 0.0004379749298095703, "__label__religion": 0.0008711814880371094, "__label__science_tech": 0.1474609375, "__label__social_life": 0.0002341270446777344, "__label__software": 0.05267333984375, "__label__software_dev": 0.7666015625, "__label__sports_fitness": 0.00022614002227783203, "__label__transportation": 0.000553131103515625, "__label__travel": 0.00023829936981201172}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 58475, 0.03203]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 58475, 0.68031]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 58475, 0.87628]], "google_gemma-3-12b-it_contains_pii": [[0, 752, false], [752, 1173, null], [1173, 1683, null], [1683, 1683, null], [1683, 2041, null], [2041, 3008, null], [3008, 5142, null], [5142, 5597, null], [5597, 7452, null], [7452, 9617, null], [9617, 11263, null], [11263, 12998, null], [12998, 14658, null], [14658, 16626, null], [16626, 18313, null], [18313, 18745, null], [18745, 20196, null], [20196, 22265, null], [22265, 24172, null], [24172, 25873, null], [25873, 26294, null], [26294, 26741, null], [26741, 28451, null], [28451, 30220, null], [30220, 31698, null], [31698, 33390, null], [33390, 35211, null], [35211, 37259, null], [37259, 38596, null], [38596, 40576, null], [40576, 42596, null], [42596, 44568, null], [44568, 46232, null], [46232, 47768, null], [47768, 49103, null], [49103, 49529, null], [49529, 51208, null], [51208, 51855, null], [51855, 53529, null], [53529, 54009, null], [54009, 55837, null], [55837, 57702, null], [57702, 58475, null]], "google_gemma-3-12b-it_is_public_document": [[0, 752, true], [752, 1173, null], [1173, 1683, null], [1683, 1683, null], [1683, 2041, null], [2041, 3008, null], [3008, 5142, null], [5142, 5597, null], [5597, 7452, null], [7452, 9617, null], [9617, 11263, null], [11263, 12998, null], [12998, 14658, null], [14658, 16626, null], [16626, 18313, null], [18313, 18745, null], [18745, 20196, null], [20196, 22265, null], [22265, 24172, null], [24172, 25873, null], [25873, 26294, null], [26294, 26741, null], [26741, 28451, null], [28451, 30220, null], [30220, 31698, null], [31698, 33390, null], [33390, 35211, null], [35211, 37259, null], [37259, 38596, null], [38596, 40576, null], [40576, 42596, null], [42596, 44568, null], [44568, 46232, null], [46232, 47768, null], [47768, 49103, null], [49103, 49529, null], [49529, 51208, null], [51208, 51855, null], [51855, 53529, null], [53529, 54009, null], [54009, 55837, null], [55837, 57702, null], [57702, 58475, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 58475, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 58475, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 58475, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 58475, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 58475, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 58475, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 58475, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 58475, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 58475, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 58475, null]], "pdf_page_numbers": [[0, 752, 1], [752, 1173, 2], [1173, 1683, 3], [1683, 1683, 4], [1683, 2041, 5], [2041, 3008, 6], [3008, 5142, 7], [5142, 5597, 8], [5597, 7452, 9], [7452, 9617, 10], [9617, 11263, 11], [11263, 12998, 12], [12998, 14658, 13], [14658, 16626, 14], [16626, 18313, 15], [18313, 18745, 16], [18745, 20196, 17], [20196, 22265, 18], [22265, 24172, 19], [24172, 25873, 20], [25873, 26294, 21], [26294, 26741, 22], [26741, 28451, 23], [28451, 30220, 24], [30220, 31698, 25], [31698, 33390, 26], [33390, 35211, 27], [35211, 37259, 28], [37259, 38596, 29], [38596, 40576, 30], [40576, 42596, 31], [42596, 44568, 32], [44568, 46232, 33], [46232, 47768, 34], [47768, 49103, 35], [49103, 49529, 36], [49529, 51208, 37], [51208, 51855, 38], [51855, 53529, 39], [53529, 54009, 40], [54009, 55837, 41], [55837, 57702, 42], [57702, 58475, 43]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 58475, 0.10924]]}
olmocr_science_pdfs
2024-11-28
2024-11-28
316b14beb2913232e195bb85160ff818d8d0d4d0
Abstract—Application Programming Interfaces (APIs) are means of communication between applications, hence they can be seen as user interfaces, just with different kind of users, i.e., software or computers. However, the very first consumers of the APIs are humans, namely programmers. Based on the available documentation and the “ease of use” perception (sometimes led by corporate decisions and/or restrictions) they decide to use or not a specific API. In this paper, we propose a data-driven approach to measure web API usability, expressed through the predicted error rate. Following the reviewed state of the art in API usability, we identify a set of usability attributes, and for each of them we propose indicators that web API providers should refer to when developing usable web APIs. Our focus in this paper is on those indicators that can be quantified using the API logs, which indeed reflect the actual behaviour of programmers. Next, we define metrics for the aforementioned indicators, and exemplify them in our use case, applying them on the logs from the web API of District Health Information System (DHIS2) used at World Health Organization (WHO). Using these metrics as features, we build a classifier model to predict the error rate of API endpoints. Besides finding usability issues, we also drill down into the usage logs and investigate the potential causes of these errors. Index Terms—API usability, API logs, log mining, web API. I. INTRODUCTION Application programming interfaces (APIs) represent the abstraction layer built upon sets of low-level methods and functions, in order to make them easily reused by third parties [6]. They are a means of communication between applications. Thus, we can say that APIs are user interfaces, just with different users in mind, meaning software or computers [22]. But we should not exclude from API users the human dimension. Actually, the very first consumers of the APIs are humans, namely programmers. They are the ones who decide to use or not a specific API in their applications (sometimes under some corporate decisions and restrictions, e.g., pricing). If developers want to build a mobile application, and one of the features that they want to add to their application is the user location, usually it is up to them which location API to choose: Google Map API, OpenStreetMap API, Bing Maps API, Foursquare API, etc. Usually, API consumers decide to use an API by reading its documentation and by trying to perform different small tasks with it [22]. So, if API providers want to increase their consumer outreach or the number of users of their API, they should focus on improving the API documentation and its easy-to-use interface. In this paper, we propose a data driven approach to measure API usability, based on how API consumers perceive and use APIs. Throughout our work we focus on web APIs, which differ from the traditional ones (statically linked APIs) mostly in the way providers and consumers are connected (via internet, typically by HTTP protocol) or how consumers adapt when APIs change (if web API providers decide to disconnect an older version of web API, its consumers are forced to upgrade to the newer versions) [19], [25]. We use the API usability taxonomy proposed by Mosquera-Rey et al. [4], which is based on the work of Alonso-Rios et al. [3]. We adopt this taxonomy to describe the usability of web APIs. As we explain in more detail in Section III, there are some usability sub-attributes, which can not be investigated from the logs (they are related to the API source code and not to the interface). Therefore, for (almost) each of the usability sub-attributes, we propose some indicators that API providers should refer to. Based on these indicators, we define some metrics to measure each of the attributes. Then, we assess the relevance of these metrics in evaluating the usability of web API (reflected in the error rate of API endpoints), by building a classifier model that predicts the kind of error rate of endpoints based on the computed metrics. We aim to not only find usability issues, but also to investigate about their root causes by drilling down into the usage logs. Consumers’ behaviour is imprinted in these logs, so their monitoring and analysis is crucial as they can play an important role in revealing usability issues. Since log data are semi structured and often noisy, we explain how to perform the pre-processing step before doing the analysis. We introduce and further use the following concepts: - API resources - the data that API provides. - API endpoints - the location where the resources can be found. - API elements - resources, parameters, schema attributes. Here we focus only on the interface level of the APIs. In other words, we evaluate API usability abstracting from the implementation code and the functionalities that API offers. Putting all together, our study is driven by the following research questions: **RQ1:** Which are the usability sub-attributes that mostly influence the API consumers experience? **RQ2:** Can we find issues impacting these usability sub-attributes by analyzing the API usage logs? **RQ3:** Can the usability issues found in the API usage logs be measured in a meaningful way from the API consumer point of view? RQ3.1: How to carry out the pre-processing of API log data before performing usability analysis? The main contributions of the paper are as follows: • We perform an empirical study in measuring the web API usability, by monitoring and analyzing the API usage data. • We define and adapt a set of measurable indicators for web API usability attributes, and quantify in terms of API usage log traceability the indicators of one of the usability attributes, knowability. • We perform an experimental validation of the importance of these metrics, by applying our approach in a real-world case study. The remaining of this paper is organized as follows: in Section II we present the related work on API usability evaluation. In Section III we frame our approach. We describe the API log data pre-processing phase in Section IV and present our case study in Section V. We discuss our findings in section VI, and conclusions and future work in Section VII. II. RELATED WORK The evaluation of APIs usability has gained a lot of attention in the recent years [2], [14]. Based on the methods used, we can see two main categories: works that analyze the APIs design and their structural metrics, not taking into account how the API is being used (analytic methods [5], [9], [10]), and works that study how the API users are using the API (empirical methods [1], [13], [7]). We give a general overview of these works here, while the relevant usability attributes that we use in our study are explained in Section III. Rama et al. [5] presented a set of structural metrics that can be evaluated on the API interface, or on the API implementation source code. Scheller and Kühn [9] also provided several metrics to measure the usability of APIs. They conducted a literature review to identify factors that affect API usability, and investigated more in depth few of these factors. De Souza and Bentolila [10] provided visual representation of APIs complexity based on complexity metrics of Bandi et al. [15]. Gerken et al. [1] on the other hand, used the concept map method to study and evaluate API usability. But, their longitudinal approach can only be applied on long time segments. McLellan et al. [11] used the think aloud protocol. They gave API code examples to four programmers and asked them to analyze and understand. They found usability testing very effective, based on the usability issues identifies by the participants. Thus, they suggested iterative API redesign and testing phases. Piccioni et al. [7] designed an empirical usability study by interviewing 25 programmers, and giving them a concrete task to accomplish using the API under study, in order to compare the participants’ expectations with their actual performance. Grill et al. [13] evaluated API usability by applying a methodology of three phases: a heuristic evaluation (based on Zibran et al. [21]), a developer workshop and interviews, following this way both analytic and empirical methods. Actually, as Rauf et al. [2] stated in their work on systematic mapping of API usability studies, the most used methods to evaluate APIs usability were empirical ones: usability tests, controlled experiments, surveys, etc. In fact, these methods are the most consolidated in software usability or human computer interaction (HCI) studies. As APIs differ from regular traditional software (can be used in scenarios that even API designers have not thought before, are prone to frequent changes, etc.), their usability evaluation requires more automated, scalable and time-efficient methods [2]. Few studies focus on mining repositories. Zibran et al. [21] studied five different bug repositories to identify the most reported API usability issues (by the API consumers). More than one third (37.14%) of the bug-reports in their study were related to API usability. From these, the most frequent ones were about missing features, correctness, and documentation. Macvean et al. [8] analyzed specifically the usability of web APIs. They took data from Google API Explorer to identify APIs, with which developers struggle more and spend more time and effort in learning and using. The metric they used to measure API usability was API request error rate (client side erroneous requests (4XX) per total requests to the API). Nonetheless, they recognized that other metrics can also be considered to better evaluate the usability, like API consumer satisfaction measured by API surveys or the number of erroneous requests consumers make until they achieve a successful call (known also as time to first hello world or ah ha moment [17]). Although their results were still preliminary and, as they stated, early in nature, the methodology used seems promising and opens a lot of areas for future research. Murphy-Hill et al. [12] developed a tool that analyzed consecutive snapshots saved by developers to derive problems of the API. They checked the API methods that developers changed between snapshots, but more than the ‘worst’ usability problems, these changes reflected the most used API. They suggested the use of other heuristics, like analyzing consumers experience, comparing the experience of novice API consumers with the more familiar ones, etc. Mosqueira-Rey et al. [4] used both analytic and empirical methods. They adopted a general usability framework from Alonso-Rios et al. [3]. They derived from it a set of heuristics and guidelines for traditional APIs, and used these to evaluate the usability of a given API. Nevertheless, they pointed out the need to expand their work towards web API. Indeed, we use and follow their taxonomy that comprises six top-level attributes, refined into 21 more specific sub-attributes, to give and define a set of indicators that web API provider should use to offer usable web APIs. As Wittern et al. [19] stated in their work, there is still a lack of research on the consumption of web API (strongly related to the usability). As already annotated, web APIs differ from the traditional ones, hence, new methods need to be used in evaluating their usability, as well as other assumptions need to be taken into account. To understand and analyze the web API consumers behaviour, we do not conduct observational or controlled experiments, but instead monitor and analyze the web API log data, which indeed contain the interaction between API and its consumers. <table> <thead> <tr> <th>Usability Attributes</th> <th>Sub-attributes</th> <th>Indicators</th> <th>Traceability in the logs</th> </tr> </thead> <tbody> <tr> <td>1. Know-ability</td> <td></td> <td></td> <td></td> </tr> <tr> <td>1.a Clarity</td> <td>API elements’ name clearness, descriptiveness, unambiguity, similarity [21], [12], [9], [5], [7]</td> <td>✓</td> <td></td> </tr> <tr> <td>1.b Consistency</td> <td>Uniformity in naming API elements [21]</td> <td>✓</td> <td></td> </tr> <tr> <td>1.c Memorability</td> <td>The number of API endpoints’ parameters [21], [5], [9], [15]</td> <td>✓</td> <td></td> </tr> <tr> <td>1.d Helpfulness</td> <td>The use of different status codes for different situations [21], [5]</td> <td>✓</td> <td></td> </tr> <tr> <td>2. Operability</td> <td></td> <td></td> <td></td> </tr> <tr> <td>2.a Completeness</td> <td>Consumers workaround solutions for the missing features [23]</td> <td>✓</td> <td></td> </tr> <tr> <td>2.b Precision</td> <td>Proper data types to avoid loss of precision and unnecessary type-casting [3], [21], [13], [5], [9]</td> <td>✓</td> <td></td> </tr> <tr> <td>2.c Universality</td> <td>The use of universally recognized names, formats, etc., for API elements [4]</td> <td>✓</td> <td></td> </tr> <tr> <td>2.d Flexibility</td> <td>Multiple ways to do the same thing [21], [17]</td> <td>✓</td> <td></td> </tr> <tr> <td>3. Efficiency</td> <td></td> <td></td> <td></td> </tr> <tr> <td>3.a In human effort</td> <td>The balance between the flexibility of having different ways of doing a task and the complexity of having too many options [7]</td> <td>✓</td> <td></td> </tr> <tr> <td>3.b In task execution</td> <td>API response time [17]</td> <td>✓</td> <td></td> </tr> <tr> <td>3.c In tied up resources</td> <td>The excessive use of shared resources made by API [4], [21]</td> <td>✓</td> <td></td> </tr> <tr> <td>3.d To economic costs</td> <td>The excessive costs required for the API use [4]</td> <td>✓</td> <td></td> </tr> <tr> <td>4. Robustness</td> <td></td> <td></td> <td></td> </tr> <tr> <td>4.a To internal error</td> <td>The proper handling of internal errors [9], [21]</td> <td>✓</td> <td></td> </tr> <tr> <td>4.b To improper use</td> <td>The proper handling of consumers errors [9], [21]</td> <td>✓</td> <td></td> </tr> <tr> <td>4.c To third party abuse</td> <td>The handling and mitigation of abusive behaviour of third party</td> <td>✓</td> <td></td> </tr> <tr> <td>4.d To environment problems</td> <td>The handling of errors coming from environment problems</td> <td>✓</td> <td></td> </tr> <tr> <td>5. Safety</td> <td></td> <td></td> <td></td> </tr> <tr> <td>5.a User safety</td> <td>The use of safe HTTP methods to change resources</td> <td>✓</td> <td></td> </tr> <tr> <td>5.b Third party safety</td> <td>The confidentiality protection of the users’ personal information [4]</td> <td>✓</td> <td></td> </tr> <tr> <td>5.c Environment safety</td> <td>The security of the users’ assets [4]</td> <td>✓</td> <td></td> </tr> <tr> <td>6. Subjective satisfaction</td> <td></td> <td></td> <td></td> </tr> <tr> <td>6.a Interest</td> <td>The trend of API users over time (API new consumers, API churn rate) [17]</td> <td>✓</td> <td></td> </tr> <tr> <td>6.b Aesthetic</td> <td>The aesthetic of API elements’ name (no weird names or special characters used in an inappropriate way) [4]</td> <td>✓</td> <td></td> </tr> </tbody> </table> III. THE PROPOSED APPROACH In this section we describe the key elements of our approach. We start with explaining the different types of API logs and which usability attributes can be evaluated using each of them. Then we introduce the usability attributes, sub-attributes and the indicators inferred and adapted from the literature review. Lastly, we interpret these indicators in terms of API usage log traceability, where possible. A. Measuring web API usability in web API logs Web API usage logs can be collected at the provider side, at the consumer side, or at proxy servers [20], [26]. The usage data collected at each case reflect different aspects of the API usage. Data collected from the consumer side have all the requests made to the API, but only from that consumer. Log data from different consumers should be gathered to have more generalizable results from the analysis. On the other hand, the data logged at the API provider side contain information about all the consumers of the API, but if consumers have adopted API response caching, they do not record the requests for which the responses are cached. Moreover, development logs cannot be distinguished from production logs [8]. Nevertheless, the information transmitted through development logs differs from those in production logs. The former are created while the developers are creating and testing their applications. We can see the developers learning curve as well as their difficulties while using the APIs, only on development logs [8]. On the other hand, production logs are created during the post-development phase of the applications, after the applications are launched and used by their end users. The analysis of these logs can give us insights about API new usage scenarios, not evident even to API providers. Here we can address issues related to all the other usability aspects. All in all, we cannot evaluate all the usability attributes in one type of API logs: different API logs are needed to evaluate different attributes. For example, we cannot measure the completeness of an API, if we have development logs from one API consumer. We need production logs from different API consumers to conclude if the API in study lacks in some features, forcing this way its consumers to come up with different workarounds. B. API usability aspects API usability represents a qualitative characteristic [2]. As such, there exist different interpretations, different terminologies, and different definitions [2], [3]. After choosing the usability taxonomy to expand for web APIs, we performed a literature review in order to quantify each of the sub-attributes into indicators. Initially, we searched for works on API usability assessment, for both traditional and web APIs. As in our study we measure the usability based on the API interface, we filtered out the works that focused their analysis in the API implementation code. Next, we consolidated into indicators for each sub-attribute, all the information gathered. Then, considering that most of the information was for traditional APIs, we adapted it for web APIs. For example, Rama et al. [5] mentioned in their work as structural metric the one related to exception classes “Using exception throwing classes that are too general with respect to the error conditions that result in exceptions”. We link this with the status codes returned, and give as indicator the use of different status codes in different situations, so that web API consumers would know the exact error that happened. We classify this as an indicator for the helpfulness of the API. Finally, there were some sub-attributes for which we could not find any pertinent information in the literature review, thus we extend the current state of the art with additional indicators. Table I summarizes our findings and reports main usability attributes with their sub-attributes, their indicators, and points out if such indicators can be traced in API logs. C. Usability issues detected in API usage logs As already stated, we evaluate API usability by analyzing API usage logs. Due to different server setting parameters, logs may comply to different formats, but typically each log entry has information about the client’s IP address, the request time, the request method (GET, POST, etc.), the request body, the protocol, the time needed to respond to the request, the status code, and the size of the object returned. We evaluate from the API logs those attributes and sub-attributes that can be mapped to the information in the log entries (see Table I). Thus, we focus on indicators consisting of the information about the interface of the API (naming of API elements, number of parameters) and indicators about the interaction consumer - API (status codes, duration, request sequences). As a matter of fact, not all the usability sub-attributes of the taxonomy can be evaluated based on the information in the logs. For example, the precision of the API, an operability sub-attribute, is mostly related to the precision of the data types used. Data types selection is seen as too critical. API consumers should not perform type casting when it is not necessary, as this will not only increase their effort but also affect the precision [3], [21], [13], [5], [9]. However, in the log entry, requests are just strings, so we cannot analyze the parameters’ data types (part of the implementation code of the functions and methods under the APIs). Know-ability implies the ease of understanding, learning and remembering the API. Among others, this attribute is mainly related to the naming of the API elements. To properly evaluate the naming, it is essential to take into account the purpose and the functions of the API elements, and then to perform semantic analysis of their names. In automated solutions this is almost infeasible [9]. Hence, the controls that we perform for clarity, consistency, and memorability sub-attributes are channeled in names’ similarity, the style of naming, path/query length, query complexity features, etc. On the other hand, helpfulness is related mostly to accurate documentation and detailed error messages. In the logs this can be manifested in the erroneous repeated requests. Operability is mostly associated to the API consumers’ needs fulfillment. Tracking workarounds built by consumers when API is not offering them a direct solution, is quite difficult. Anyway, consumers interaction with the API is imprinted in the API logs, so from there we can infer behaviours that address this issue. Part of operability is also universality, which implies the use of universal names and symbols. Next, flexibility is a double-edged sword: for experienced programmers, it is considered beneficial, but for novice ones, it increase the complexity of APIs (as explained below). Efficiency can be evaluated in terms of human effort, time and resources spent while using the API. Regarding human effort, usually, the more complex the API is, the more effort is spent from the consumers’ side. Complexity is a very general concept, and comprises several usability attributes. As having several ways to do the same thing sometimes confuses the programmers [7], we consider this as an indicator in evaluating efficiency according to human effort. Efficiency in task execution is reflected in the time that an API needs to respond to a request, which in the logs is stored as duration. For the costs of using the API, we look at the API endpoints, that can be optimized regarding number of calls. Consumers have to pay for number of calls for non-free APIs. So, if there are endpoints that are always called one after the other, their merging can reduce the consumers’ expenses. We do not have a log-based indicator for the efficiency in tied up resources sub-attributes, as this is not related to the API interface, and is not reflected in any log entry fields. Robustness, defined as the property of an API to handle errors and adverse situations, it is strongly related to the status codes that APIs send to their consumers. Even thought applications that consume the API should also be robust and treat properly the error situations, APIs should not fail in front of incorrect or even improper use. Therefore, APIs have to handle both the errors that come from their side (5xx errors), and the errors from the consumers’ side (4xx errors). Safety deals with the challenge of mitigating risks or damage while the consumers are using the API. Consumers typically access web APIs using HTTP requests. APIs should not allow the consumers to change resources using safe HTTP methods (methods that do not modify resources, e.g. GET). The safety of the APIs is also associated with the third party safety, as well as API environment safety. For the last one, we do not have a log-based indicator. Subjective satisfaction is the capacity of the API to engage their users and preserve their interest. API providers can evaluate this by monitoring the trend of new API consumers. Additionally, the aesthetic of API is related to the aesthetic of API elements’ name. IV. API LOG DATA PRE-PROCESSING An API log file contains the requests made to the API. This information is raw, so before applying any analysis technique, the data should undergo a pre-processing phase (see Figure 1), typically counted as the most difficult task in the Usage Mining process [18], [20]. While it usually consists of three steps, namely data fusion, data cleaning, and data structuring, we include a fourth step, data generalization [18]. See the final steps in Figure 1. Data fusion. We already explained part of the data fusion step discussing different types of API log data (see Section III-A). Based on where we collect the data (consumers’ or providers’ side), we extract the log files and merge them (if they are in different servers). Before proceeding with the pre-processing steps, the data might be anonymized, because log files might contain information considered sensitive (identifiable personal information). One way of handling this concern is by masking the sensitive data (i.e., IDs, or IP addresses) with surrogate identifiers and then proceed with the next steps [18]. Data cleaning. This step mainly consists of removing irrelevant and noisy data from the files, and correcting the data by means of adding or completing missing values. When fusing data from several sources, the logs from different sources can have different formats. Thus, when merging them, we may need to adapt their formats: adding/removing certain fields, dealing with quoted/unquoted fields, etc. On the other hand, whether to keep or remove certain log entries depends much on the purpose of the further analysis [18]. For example, if one wants to discover user session profiles in web log data, he/she should filter out: (i) the log entries that result in errors, (ii) the log entries that have a request method different from GET, and (iii) the ones that accesses image files [16]. If the purpose of the analysis is to support caching or pre-fetching, then log entries for accessing images should not be excluded from the analysis [18]. Since we aim to measure the usability of the APIs, the status code is one of the most valuable fields in the log entries. The error rate of each API endpoint can reveal usability issues that can highly affect API consumers. Therefore, for purpose of measuring the usability of the APIs, we keep the erroneous requests, and filter out from the file, the log entries that are not API requests, and the ones that do not imply API resources manipulation. These are some typical examples, but we certainly do not exclude the possibility of having to remove other log entries, depending on how the information is logged. After this step, the number of log entries will be highly reduced [24], [18], [20]. Data structuring. This step includes user and session identification. By users here we mean the applications that are consuming the API, so this step should be performed when working with API logs from the provider side. Ideally, when an application uses an API, the logs generated should have an ID that identifies their pathway with the API. Usually, the log file contains only the device’s address (i.e., IP) and the user agent (i.e., software agent like a browser or an email reader). When applications’ identifiers are not in the API logs, each IP might be counted as a user [18]. On the other hand, log data are usually not completed with the session ID, and session identification results also specially challenging, due to several reasons (i.e., caching, proxy servers, same device used by several users, etc.) [18]. Thus, session must be inferred combining available user identification and approximate time-out simulating the time spent by a single user using the API. Data generalization. This step is considered an advanced pre-processing step, comprising one of the most complex tasks in API log data analysis [19], [24]. It consists of extracting general API specifications from the requests in the log files. For instance, if we have "https://.../api/country/Spain/regions", the challenge would be to detect "/country/" and "regions/" as resources’ name (fixed part of the path) and "/Spain/" as a parameter value (dynamic part of the path). Synthesising general API description from API usage is a hard problem, and existing solution are hampered by API logs nature (noisy, incomplete) and also API design and implementation problems [24], [19]. V. CASE STUDY DESIGN A. DHIS2 Web API We analyzed the log data of the District Health Information Software 2 (DHIS2) web API. DHIS2 is an open source, web-based health management information system platform used worldwide for data entry, data quality checks and reporting. It has an open REST API, used by more than 60 native applications. External software can make use of the open API, by connecting directly to it or through an interoperability layer. DHIS2 is as well instantiated as WHO Integrated Data Platform1 (WIDP) at World Health Organization (WHO), and is used by several departments for routine disease surveillance and country reporting. For the analysis, we use API log data from the development instance of WIDP, with more than 50 applications installed, core or built in-house. The logs date from September 2018 to November 2019. B. Data pre-processing We instantiate the data pre-processing workflow previously introduced in Section IV, and further discuss the challenges encountered in different steps of the process. Data fusion. As previously mentioned, we had the log data from WIDP, which is a DHIS2 API consumer. But as several applications are installed on this platform, it partly behaves as provider. The logs were recorded using a customized Apache log format, which contained the following information: client IP, request long date (date, time, timezone), duration (time needed to send the response), keepalive, request (method + resources URL + protocol), response code, the size of the object returned and the user agent. Data cleaning. We discarded the log entries with request method HEAD or OPTIONS, as they do not imply any resource manipulation or resource retrieval [24]. We filtered out also the log entries that were not related to APIs, thus --- not containing the “/api/” entry point, predefined to be in the API request. These are usually log entries for loading of style files, fonts, or graphics. But at the same time we were careful not to remove key log entries (i.e., log entries about the login, logout and applications’ first access) that, even though did not contain the “/api/” entry point, played an important role in data structuring. After data cleaning, our log file contained 2,268,291 log entries (i.e., requests), out of 5,936,203 that it had initially. **Data structuring.** For user identification, we used the information under “client IP” in the log entry to identify different API consumers (i.e., users). We considered as a session all the requests made by one user (client IP), with time difference no more than 15 minutes. We assigned incrementally a number to each session as an identifier, ending up with 40,067 sessions, from 849 users. As we were analyzing the know-ability of the API, our focus was not on the applications that were using the API (i.e., the real consumers of API), but on the programmers (i.e., the first consumers of the API). However, if measuring, for example, the completeness (investigate about workarounds) of an API, one should identify which application submitted each request, in order to be able to build an exact sequence of the requests for each application. As already mentioned, in our case, the log files contained log entries from each of the applications installed in the platform. But the log entries did not have information about which application submitted each requests. The only information we had was the log entry specifying the opening of any application: “GET /dhis2-dev/{nameOfTheApplication}/index.action”. But the same user could open several applications at the same time. So, from the moment the same user (ClientIP1) opened more than one application, we could not be sure about the origin of the next log entries: - ClientIP1 "GET /{App1}/index.action" - ClientIP1 "requests from App1" - ClientIP1 "GET /{App2}/index.action" - ClientIP1 "requests from App1 or App2" In these analysis scenarios, we might need to make approximations and combine IP information, current app(s) opened and the timeout. The lack of applications’ identifiers can impede not only the user identification, but also hinder the data cleaning. Apart from user and session identification, we performed also “target endpoint” identification. In order to be able to aggregate statistical information for each endpoint (total number of requests, requests with client side error, etc.) we assigned a “target endpoint” to each request that got a client side error response code. For example, if we want to compute statistical metrics for the endpoint “/api/organizationUnitGroupSets”, then we should somehow match it with the endpoints: “/api/organization-unit-group-sets” or “/api/organizationsUnitsGroupsSets”, which have a wrong syntax, but the programmer intent was the first endpoint. We started by extracting all the requests that got a status code not related with syntax errors. Using the Levenshtein distance algorithm [27], we computed the similarity of these endpoints with each real endpoint in the requests body, and grouped together the most similar ones. **Data generalization.** During this step we had to define which parts of paths were fixed (i.e., resources) and which were dynamic (i.e., parameter values). That is, for several endpoints with path body like “api/userGroups/uNJOBaIw/users/H4atNsEr”, or “api/userGroups/BzbYRSpk/users/D78WJM8J”, we inferred from them a general one, with generic API specifications “api/userGroups/ID/users/ID”. We applied some ad hoc procedures, and masked all the parameter values with the same string “ID”. **C. Data Analysis** We assumed that an API that suffers from poor know-ability, will have a high error rate. For each sub-attribute, based on the defined indicators, we computed the below metrics and created a model to predict the kind of error rate. - **Clarity:** We analyzed the endpoints’ names and the similarity between them, assuming that similar names confuse users and increase the chances of making errors. We expect that endpoints with higher similarity will have more client side errors response codes. We split each “target endpoint” into its elements. For each of them, we found the most similar one, by computing their similarity. For example, the account resource had the highest similarity of 0.71 with count, constants 0.82 with constraints, and so on. Using this information, we then computed two metrics for each endpoint: the average similarity and the maximum similarity. For example, userDataS-tore/gridColumns/eventCaptureGridColumns has three elements, userDataStore with similarity 0.69, gridColumns with similarity 0.48, and eventCaptureGridColumns with similarity 0.72. So the endpoint average similarity coefficient will be 0.63, while the maximum similarity will be 0.72, coming from eventCaptureGridColumns. - **Consistency:** We focus on the syntactical aspects of naming to evaluate the consistency. Thus, we analyzed the naming style of endpoints (names that contain only lower case or numbers, upper cases, underscores, hyphens, special characters, or more than one of these “styles”). Actually, we do not expect a specific naming style to be the cause of errors from client side. We will investigate the impact that the existence of several naming styles, can have on API consumers. Clearly, the semantic aspects (use of synonyms, homonyms, etc.) are also very important when we analyse the consistency of an API and can be evaluated using different tools for natural language processing. We will include this in our future work. - **Memorability:** We analyzed the path part as well as the query part of the requests. First we computed the path length as the overall number of characters; and stored under path elements the information about the number of elements in the path (e.g., “analytics/events/aggregate/ID” has three elements in the path body). Then, we examined the query part to quantify its complexity. We measure the query length as the number of characters; we analyze the query syntax and impute the transformation metric as the number or transformation functions in the query; we represent the logical operators as the number of logical operators used; we defined the query depth as the number of nested objects, giving to each nested object the same weight, despite the number of fields it contains, as we are analyzing the complexity of the query part from the programmer point of view (amount of code to be written) and not the machine point of view (amount of time to compute the results of the query); we counted the query parameters; and also the schema attributes used in each request. Both are part of the query length, commonly used to evaluate query complexity, but as they represent different ways of reducing the result size, we choose to count them separately. As we realized that consumers often use the same query parameter or schema attribute several times in a single request, we decided to reflect this also in different metrics: unique query parameters and unique schema attributes. - **Helpfulness:** To measure this sub-attribute, we analyzed the endpoints that got repeated client side error codes from the same user. We assume that the lack of details in the error messages and the lack of examples in the documentation can lead consumers to repeat the same mistakes. Therefore, we grouped all the requests with the same “target endpoint”, from the same client IP, and analyzed those that had 2 or more client side error. We imputed the error repetition rate as the number of error per total number of request for the same endpoint for each programmer. Besides the metrics per each request, we computed the error rate as the number of erroneous requests per all requests. We first selected only those endpoints that were in requests with error rate greater than zero and divided them in two classes: endpoints with error rate higher than 0.3 were considered with poor usability, and the ones with error rate lower than 0.3 with no usability issues. There were 1128 endpoints with certain values of the metrics. In order to balance the classes distribution to 40% for poor usability and 60% for no usability issues, we randomly extracted endpoints with error rate zero to obtain the desired proportion. First, in order to reduce over-fitting and facilitate interpretability of results, we performed attribute (i.e., metrics) selection, keeping only those metrics that were more relevant for predicting the class. We run the CorrelationAttributeEval with Rank method on WEKA\(^2\), which ranks the attributes by measuring the correlation between them and the class. From all the aforementioned metrics, maximum and average similarity, query depth, logical operators, and path length were the more relevant ones. Then, to see if we could predict the class based on these metrics, we built a decision tree using WEKA implementation of J48, with the default parameterization and 10-fold cross-validation. We used a classification model because we were interested in finding if the API had or not usability issues, more than predicting the exact error rate (as a regression model would imply). Thus, using the selected attributes from the information in the logs, we obtained a model able to predict the class of the endpoints with an accuracy of 72.25%. Considering that in our analysis we do not take into account other factors in APIs usability like: APIs functionality, semantic of API names, API programmers experience, etc., we aimed at a high precision, more than at a high recall. But, even though we were not aiming to find all the endpoints with usability problems only from the data in the API logs, our model performed quite good with a recall of 0.722 (Table II, III). Then, to see if we could predict the class based on these metrics, we built a decision tree using WEKA implementation of J48, with the default parameterization and 10-fold cross-validation. We used a classification model because we were interested in finding if the API had or not usability issues, more than predicting the exact error rate (as a regression model would imply). Thus, using the selected attributes from the information in the logs, we obtained a model able to predict the class of the endpoints with an accuracy of 72.25%. Considering that in our analysis we do not take into account other factors in APIs usability like: APIs functionality, semantic of API names, API programmers experience, etc., we aimed at a high precision, more than at a high recall. But, even though we were not aiming to find all the endpoints with usability problems only from the data in the API logs, our model performed quite good with a recall of 0.722 (Table II, III). <table> <thead> <tr> <th>TABLE II</th> <th>TABLE III</th> </tr> </thead> <tbody> <tr> <td><strong>CONCLUSION MATRIX</strong></td> <td><strong>J48 RESULTS</strong></td> </tr> <tr> <td></td> <td></td> </tr> <tr> <td>a</td> <td>272</td> </tr> <tr> <td>b</td> <td>725</td> </tr> <tr> <td><strong>Correctly Classified</strong></td> <td>72.25%</td> </tr> <tr> <td><strong>Incorrectly Classified</strong></td> <td>27.75%</td> </tr> <tr> <td><strong>Kappa statistic</strong></td> <td>0.389</td> </tr> <tr> <td><strong>Mean absolute error</strong></td> <td>0.399</td> </tr> <tr> <td><strong>Weighted Avg Recall</strong></td> <td>0.722</td> </tr> <tr> <td><strong>Weighted Avg Precision</strong></td> <td>0.723</td> </tr> </tbody> </table> VI. DISCUSSION To get finer insights for the classified gain, we analyzed in more detail the branches of the decision tree. We found that requests that did not have a query part tend to have lower error rate, even when the path had an average similarity higher than 0.61. The error rate was also low for those endpoints with both average and maximum similarity low, respectively lower than 0.61 and 0.75. On the other hand, the error rate was high for those endpoints that even though had low average similarity, they had at least one element in their path with very high similarity. Endpoints with high average similarity and a query part, had also high error rate. Additionally, we examined closer the endpoints with higher error rate, to see which were the most common mistakes done by the programmers. We point out the following issues: - Consumers try different name styles until they find the right one. The fact that in the same API, different resources are named using different styles, confuses them. For example, before typing userRoles/ID, one of the consumers tried with userrole/ID and user-roles/ID. - We encountered another consistency issue in the naming of API, plural and singular form of resources’ name. As some of the resources’ name were in plural, and others in singular, consumers tried their different forms. For objects with composed names (i.e., multi-word names), the error rate increased. For example, before typing organisationUnitGroups, one consumer tried three different versions: organisationUnitGroup, organisationUnitsGroups and organisationUnits-Group. The lack of consistency in naming resources decreases the memorability of the API. Different naming conventions (pascal or camel case, underscore, etc.) and \(^2\)https://www.cs.waikato.ac.nz/ml/weka the semantic nature of the analysis needed were the main reasons why these two aspects (plural/singular form and multi-word names), were not reflected in any of the metrics. - When analyzing the repeated errors for the same endpoints from the same consumers, to measure the helpfulness, we noticed low memorability perception from consumers. From 1,283 cases of repeated client side errors, 659 of them had a non client side error response code for the first request. This implies that even after understanding the API and submitting correct requests, consumers fall in mistakes. **Threats to validity.** The main threat to construct validity involve the arbitrary chosen threshold of 0.3 for the error rate class. To mitigate this, we plan to re-define the threshold by conducting other use cases (i.e., independent datasets). This way, we will also minimize the external validity threat, whose main concern is related to the one API we have as use case. **VII. CONCLUSION AND FUTURE WORK** We reviewed the current state of the art in API usability evaluation in order to identify those usability attributes that mostly affect the programmers experience in using the APIs. We combined the gathered information and for each usability attribute, we specified an indicator that web API providers should use to provide usable web APIs. We embodied the indicators for the know-ability attribute into several metrics, which we later computed using the web API usage data from our case study. In order to assess the significance of these metrics, we built a classifier to predict the kind of error rate based on the endpoints’ specifications. Know-ability issues that more influenced the API consumers experience were more related to similar API elements’ names, multi-word names, and lack of consistency in naming convention. As future work, we plan to define more metrics for the attributes under study and expand our analysis to other usability attributes. In order to re-define the threshold and the generalizability of our model, we will take under study other use cases. On the other hand, to evaluate the analysis results we plan to conduct a supplementary empirical analysis, directly asking the API users for their opinion on whether they encountered usability issues while using the API or no. **ACKNOWLEDGMENT** This work is supported by GENESIS project, funded by the Spanish Ministerio de Ciencia e Innovación under project TIN2016-79269-R. We especially thank Dr. Lise Grout and Dr. Pedro Albajar-Viñas from the Neglected Tropical Diseases (NTD) department at WHO, for providing the use case. **REFERENCES**
{"Source-Url": "https://upcommons.upc.edu/bitstream/handle/2117/341629/A%20Data-Driven%20Approach%20to%20Measure%20the%20Usability%20of%20Web%20APIs.pdf;jsessionid=68B82B4A8C43B65561956B31ADC2409D?sequence=3", "len_cl100k_base": 9987, "olmocr-version": "0.1.53", "pdf-total-pages": 8, "total-fallback-pages": 0, "total-input-tokens": 25738, "total-output-tokens": 11479, "length": "2e13", "weborganizer": {"__label__adult": 0.0002751350402832031, "__label__art_design": 0.0003638267517089844, "__label__crime_law": 0.00020122528076171875, "__label__education_jobs": 0.0008950233459472656, "__label__entertainment": 4.8160552978515625e-05, "__label__fashion_beauty": 0.00010913610458374023, "__label__finance_business": 0.00014543533325195312, "__label__food_dining": 0.0002225637435913086, "__label__games": 0.00040793418884277344, "__label__hardware": 0.0005297660827636719, "__label__health": 0.00034165382385253906, "__label__history": 0.00019788742065429688, "__label__home_hobbies": 5.84721565246582e-05, "__label__industrial": 0.0001862049102783203, "__label__literature": 0.00025153160095214844, "__label__politics": 0.00012934207916259766, "__label__religion": 0.00032210350036621094, "__label__science_tech": 0.0097808837890625, "__label__social_life": 7.468461990356445e-05, "__label__software": 0.00995635986328125, "__label__software_dev": 0.97509765625, "__label__sports_fitness": 0.00016641616821289062, "__label__transportation": 0.00023603439331054688, "__label__travel": 0.00015234947204589844}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 50758, 0.02379]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 50758, 0.2172]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 50758, 0.90728]], "google_gemma-3-12b-it_contains_pii": [[0, 5308, false], [5308, 11687, null], [11687, 18254, null], [18254, 24516, null], [24516, 30037, null], [30037, 35939, null], [35939, 43111, null], [43111, 50758, null]], "google_gemma-3-12b-it_is_public_document": [[0, 5308, true], [5308, 11687, null], [11687, 18254, null], [18254, 24516, null], [24516, 30037, null], [30037, 35939, null], [35939, 43111, null], [43111, 50758, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 50758, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 50758, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 50758, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 50758, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 50758, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 50758, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 50758, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 50758, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 50758, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 50758, null]], "pdf_page_numbers": [[0, 5308, 1], [5308, 11687, 2], [11687, 18254, 3], [18254, 24516, 4], [24516, 30037, 5], [30037, 35939, 6], [35939, 43111, 7], [43111, 50758, 8]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 50758, 0.24551]]}
olmocr_science_pdfs
2024-12-09
2024-12-09
70650e60b806b510383f181a791e6aa60892bcf2
A Principled Approach to Open Design Questions for Contracts Abstract SG21 has made significant progress toward producing a complete design for a Contracts facility MVP. As work proceeds for completing this feature proposal, open questions must be considered and answered such that the feature will eventually have widespread adoption throughout the entire C++ ecosystem. Fundamental design principles that help guide such decisions for the Contracts facility are presented in this paper as are proposals that address most (if not all) of the open questions affecting the design of the Contracts facility MVP. Contents 1 Introduction 2 2 Principles 2 2.1 CCAs Check Plain-Language Contracts 3 2.2 Program Semantics Are Independent of Chosen CCA Semantic 3 2.3 Zero Overhead 4 2.4 Choose Ill-Formed to Enable Flexible Evolution 5 3 Proposals 6 3.1 Trivial Special Member Functions 6 3.2 Implicit Lambda Captures 9 3.3 Compile-Time Evaluation 11 3.4 Virtual Functions 16 3.5 Coroutines 18 3.6 Contracts on First Declarations 19 4 Conclusion 21 5 Acknowledgments 22 Revision History Revision 0 (September 2023 mailing) - Original version of the paper for discussion during an SG21 telecon 1 Introduction The Contracts MVP being developed by SG21\(^1\) is progressing smoothly toward a complete proposal according to the agreed-upon schedule.\(^2\) SG21 has reviewed several papers and has reached a general consensus on what will happen when a contract-checking annotation (CCA) is evaluated. - [P2751R1], “Evaluation of Checked Contract-Checking Annotations,” clarified what content will be allowed in the predicate of a CCA and how the results of that evaluation will be interpreted. - [P2811R7], “Contract-Violation Handlers,” described a link-time replaceable contract-violation handler to allow for customized handling of contract violations at run time. - [P2834R1], “Semantic Stability Across Contract-Checking Build Modes,” established that having preconditions and postconditions evaluated outside the `noexcept` guarantee of a function that is marked `noexcept` should not be considered. - [P2877R0], “Contract Build Modes, Semantics, and Implementation Strategies,” made the choice of semantics for a CCA implementation defined and, in particular, showed that such a choice might vary between evaluations and is thus not a compile-time property of a CCA. Taking the above resolutions together, on top of the existing core MVP proposal, produces an almost complete specification for Contracts as a C++ language feature.\(^3\) Some edge cases and other design points, however, still need to be addressed.\(^4\) To motivate the choices we intend to make when suggesting answers to these design questions, we will begin by identifying fundamental principles that will codify our design intentions for the C++ Contracts facility. These principles start with basic goals and build up to concrete requirements that all proposals should meet (or maximize) when making engineering decisions for what should become part of C++. 2 Principles Each principle proposed in this paper comes from the author’s experience, follows from SG21’s earlier principles, or aims to maximize some aspect of the quality of the Contracts facility that eventually becomes adopted by the C++ Standard. \(^{1}\)See [P2521R4] and the forthcoming [P2900R0]. \(^{2}\)See [P2695R1]. \(^{3}\)I.e., barring an actual syntax for the feature, which is the subject of a separate, ongoing series of discussions orthogonal to the issues in this paper. For this paper, we will be using the C++20 attribute-like syntax (see [P0542R0]). \(^{4}\)See [P2834R1] for the initial explorations of some of these solutions based on the principles described by that paper. See also [P2896R0], which enumerates the open design questions addressed by this paper. 2.1 CCAs Check Plain-Language Contracts When programmers of any language set out to write a subroutine (or function), they have in mind some notion of what will happen when the subroutine is invoked (for a given subset of syntactically valid inputs). The part of that notion to which the programmer is willing to commit as unchanging with changes to the implementation is what we generally refer to as the function’s contract. Hence, for any function that can be relied upon by clients, a contract must exist between the callers of that function and its implementers. This contract, which we call the plain-language contract, exists as a combination of the explicit (through documentation) and implicit (through choice of programming language, coding style, local conventions, etc) agreements to which both parties agree. A plain-language contract can capture a boundless variety of different conditions, requirements, and promises that might exist between callers and callees. Some of these are prone to being validated with a simple C++ expression, such as \( x > 0 \), while others are completely beyond the scope of the C++ abstract machine, such as “clients of this function have paid their bills recently.” A contract-checking annotation encodes in C++ an algorithm that can detect when a plain-language contract has been violated. When writing a CCA, that new annotation must be checking some aspect of a plain-language contract to detect violations of the agreement that exists between the caller and callee of the function. Any CCA that identifies a condition as a defect that is not related to its associated plain-language contract is clearly doing something above and beyond checking the requirements of that plain-language contract. If, for any kind or placement of CCA, there are ways in which that CCA might be evaluated where the predicate might indicate a violation when the CCA’s associated plain-language contract is not violated or not relevant, then a false-positive bug will have been diagnosed, which would be a defect in the structure of the Contracts facility itself. Therefore, a CCA, when introduced anywhere, must always evaluate in ways that validate its associated plain-language contract. <table> <thead> <tr> <th>Principle 1: CCAs Check a Plain-Language Contract</th> </tr> </thead> <tbody> <tr> <td>Each contract-checking annotation placed on the declaration of a function must, when it is evaluated, identify violations of the plain-language contract of that function.</td> </tr> </tbody> </table> 2.2 Program Semantics Are Independent of Chosen CCA Semantic The fundamental conceit of a contract-checking facility is that running a program with CCAs checked at run time should tell us something meaningful about what happens when the same source code is evaluated with the CCA not checked at run time. If a design choice made by the contract-checking facility leads to the inability to detect bugs in an unchecked build when enabling checking, then the facility will have failed on a fundamental level. The ramifications of allowing the choice of semantic (i.e., checked or unchecked) to impact the results of the noexcept operator were thoroughly explored in [P2834R1]. This paper clearly showed that the seemingly innocuous decision to allow enabled checking to impact the results of the noexcept operator could easily lead to situations in which a small bug remains entirely undetectable by the contract-checking facility because the act of enabling contract checks at run time alters higher-level control flow to avoid the bug entirely. The adoption of [P2877R0], which allows the selection of CCA semantics to potentially occur at run time, renders compile-time consideration of the semantic of a CCA moot. Still, all design decisions related to runtime-evaluated CCAs must nonetheless conform to this important stability principle, whereby the current semantic has no impact (apart from evaluating the predicate itself) on any aspect of the behavior of the program itself. On the other hand, compile-time evaluation might still occur and might differ based on implementation-defined build options. Such variance at compile time would again open up the same risks for a Contracts design to fail to satisfy its most fundamental purpose. Therefore, the fundamental principle of [P2834R1] still stands as one that must guide all behaviors of CCAs within any C++ contract-checking facility. 2.3 Zero Overhead While the first major risk to Contracts being a viable contract-checking facility is failing to detect bugs, the second major risk is failure to be adopted. If projects and enterprises commonly disallow the use of Contracts due to fundamental design flaws, such as unavoidable costs introduced even when building with all CCAs ignored, then all SG21’s effort to design a product will have been for naught. The mere rumor that adding a CCA might increase runtime overhead would be a huge headwind against rapid adoption of the facility. A natural consequence would be that developers think they have compelling reasons to continue using macro-based contract-checking facilities indefinitely. Macros (such as assert) that expand to nothing when the facility is disabled are inherent to most macro-based contract-checking facilities. This characteristic results in there being no tangible runtime overhead to having CCAs in a program’s source code, thus minimizing the factors that might discourage ubiquitous use of Contracts. Expanding to absolutely nothing does bring with it a fundamental problem that experience has taught us we should strive to avoid with the Contracts facility: bit rot. When an unchecked build ignores CCA predicates completely (i.e., it treats them as arbitrary token soup), failing to maintain CCA predicates when changes are made to the APIs they use can become commonplace. Teams that do not regularly compile their software with Contracts checked can quickly find themselves unable to compile checked builds because of the invalidity of poorly maintained CCA predicates. To avoid bit rot, a highly prudent practice is to continue to syntactically check CCA predicates, which invariably brings with it compile-time side effects, such as template instantiations, and some amount of constant evaluation to validate the predicate’s semantic correctness. Other than those compile-time effects of validating a predicate, no other inherent runtime overhead is associated with having a CCA in source code. This property leads to our next fundamental principle. **Principle 3: Zero Overhead for Ignored Predicates** The behavior of code *proximate* to a CCA is *as if* the CCA had been commented out, i.e., removed from the source entirely. By following this principle, we also reduce (to nothing, we hope) the possibility of users wrapping CCA usage in macros that remove them entirely in some builds, thus reducing the chance of having non-ABI-compatible builds when mixing checked and unchecked code in the same application. This benefit hinges on one of the major gains achieved by adopting [P2877R0]: Mixed-semantic builds are, when supported, required to be valid and cannot be ODR violations, thus greatly increasing the ability to manage contract enablement at various granularities. ### 2.4 Choose Ill-Formed to Enable Flexible Evolution Early in the process of identifying a path for bringing Contracts back into the C++ draft Standard, SG21 solicited and amassed a wide array of use cases for guiding the scope of our next attempt at a viable MVP for a C++ Contracts facility. Despite valiant efforts to refine the semantics and functionality addressed by the MVP, a large number of these use cases will remain unsupported until more work is done and further consensus has been achieved. When standardizing a solution, we would be wise to leave room for satisfying the use cases that SG21 will address after an initial feature is integrated into C++. To facilitate that evolution, decisions made today must not prevent migration to a more broadly applicable feature in future revisions. When deciding how to provide this essential freedom, a few *specification tools* are available to us. - One choice, which was made for quite a few aspects of the C++20 Contracts facility, is to leave the behavior that is not finalized as undefined behavior. This option has the advantage of allowing implementations the flexibility to experiment with various possible solutions along with the severe disadvantage of all those solutions being nonportable and possibly conflicting. SG21 had early consensus to refrain from using undefined behavior in this fashion because doing so is generally perceived to be a source of reduced safety, not increased flexibility or correctness. - A middle ground rarely chosen is to simply make certain behaviors *implementation defined*. While generally appearing safer than *undefined behavior*, this approach still results in code that is nonportable when different platforms define distinct and incompatible behaviors for the same constructs. - Another specification tool available to us is to make what we are unsure of ill-formed. That is, given two or more plausible solutions whose behaviors largely but incompletely overlap, rather than making all of that behavior undefined or even implementation defined, we might --- 5 See [P1995R1]. choose to define the overlapping behavior and (to strongly discourage inconsistency) to leave the remaining, nonoverlapping behavior ill-formed. - Finally, when we have consensus on a solution but are unclear whether the solution in question will be implementable on all platforms, we might choose to specify the full solution and make it conditionally supported. Using this approach, however, effectively introduces multiple dialects of the language on different platforms, which is often an approach the WG21 community has avoided. In general, given the history of SG21’s consensus to focus on the safety and portability of the Contracts feature being developed, the preferable option is to leave room for evolution by making the available design space ill-formed in the current implementation. <table> <thead> <tr> <th>Principle 4: Make Undecided Behaviors Ill-Formed</th> </tr> </thead> <tbody> <tr> <td>To accommodate use cases that are not yet supported by the current contracts proposal, prefer to keep extensibility flexible by declaring unresolved behavior ill-formed, rather than either undefined (“unsafe”) or implementation defined (nonportable).</td> </tr> </tbody> </table> 3 Proposals Each subsection within this section discusses a distinct open question in the specification of the Contracts MVP and provides a proposed resolution based on the principles we have introduced above. Some proposals are made of multiple constituent parts. The individual parts throughout a section are not numbered, and a final complete, numbered proposal will be made near the end of each section. 3.1 Trivial Special Member Functions A trivial operation — constructor, destructor, or assignment operator — is one that (1) is generated entirely by the compiler and (2) invokes no user-provided code. The copy and move operations, when trivial, become bitwise copyable (and thus may be replaced by, e.g., memmove). The default constructor and destructor, when trivial, do nothing.\(^6\) Providing a body — even an empty one — for a special member function results in that function never being trivial. Defaulting a user-declared special member function (via = default on the first declaration) will result in it being trivial as long as it doesn’t need to invoke any user-provided code for a base-class or member object. The definition of the trivially copyable trait has evolved over the years, but the main point is that all the default-generated copy and move constructors and copy and move assignment operators are trivial (and hence, can treat the object as pure data) as long as at least one of them is not deleted. For a type to be trivially copyable, it must also be trivially destructible; i.e., the compiler-generated destructor is a no-op. \(^6\)See also the mention of this issue in [P2521R4], Section 4.4, “Annotations on trivial ops.,” {con.trv}. 6 Now consider that, to minimize runtime overhead and still get substantial coverage, common practice allows for any type that happens to have one or more (programmatically verifiable) class (object) invariants to assert them in the one place where the flow of control must pass for every constructed object: the destructor. This defensive-checking strategy is particularly effective at catching memory overwrites.\(^7\) Now imagine we have a trivially copyable value type, such as this heavily elided `Date` class: ```cpp class Date { int d_year; // [ 1 .. 9999 ] int d_month; // [ 1 .. 12 ] int d_day; // [ 1 .. 31 ] public: static bool isValidYMD(int year, int month, int day); // Return true if year/month/day represents a valid date. Date(int year, int month, int day) [[ pre: isValidYMD(year, month, day) ]]; // Create a Date object having a valid date. int year() const { return d_year; } // ... }; ``` In the `Date` class above, the user-declared value constructor creates a valid `Date` object set to the specified `year`, `month`, and `day`, and in a `checked` build, its precondition check invokes the class member function `isValid` to ensure (or perhaps just to observe) that the date is, in fact, valid. From then on, the only way to change the value of this object is through the use of its compiler-generated assignment operations.\(^8\) As previously stated, the `Date` class above is trivially copyable, but let’s now add a defaulted destructor having a precondition check that validates its invariants: ```cpp ~Date() = default [[ pre: isValidYMD(d_year, d_month, d_day) ]]; // Destroy this object. ``` Notice that the precondition itself applies the public class member function, `isValidYMD`, to the private data members, e.g., `d_year`, of the class. The Committee has long since agreed\(^9\) that all CCAs are part of a function’s implementation; hence, a CCA that is associated with a member function fairly deserves private access to the data members of the class. --- \(^7\)Feel free to ask the author for stories about the pain that comes from developers who decide to implement types that overwrite their own members by calling `memset(this,0,sizeof(this))` in their constructor bodies, under some misguided belief that doing so improved performance and correctness. In particular, if such a class has any member, such as `std::string`, that has a nontrivial default constructor that does more than just zero-initialize, this ill-fated choice leads to painful-to-diagnose problems that such invariant checking can often readily detect. \(^8\)Recall that, just by declaring any non-special-member constructor, we suppress even the declaration of the default constructor. All five remaining special member functions, however, are generated as usual. \(^9\)During a Standards Committee meeting in 2015 that involved CCAs, Bjarne Stroustrup expressed the need for a CCA on a member function to have private access to the implementation of the function’s class so that the CCA could write efficient preconditions without having to expose extra functions in a public API that were not directly relevant to clients. This discussion led to a paper, [P1289R1], which was considered and achieved consensus in November 2018. This result has remained the SG21 consensus, as indicated in Section 4.3 of [P2521R4]. If CCAs are ignored, the destructor does nothing, and because no user-supplied definition is available, one might reasonably presume that this special member function remains trivial. In a checked build, however, code provided by the user is expected to run when an object of this type is destroyed. In some sense, this Date type is almost\(^{10}\) trivially destructible and thus, at least notionally, trivially copyable. Following Principle 2, i.e., we cannot change the semantics of code based on which semantic CCAs are evaluated with, means that we cannot take the approach of treating this Date class as if it were trivially destructible and trivially copyable in an unchecked build but not in a checked build. Once again, we are left with two alternatives. 1. Specify that defaulted special member functions that have associated CCAs are never trivial in any build mode. The implication is that merely having an inactive precondition could substantially impact performance,\(^ {11}\) even in an unchecked (e.g., ignored) build. 2. Treat contract checks on trivial functions as skippable without notice. That is, if the function itself is considered trivial in an unchecked build mode, it will report so in every build mode. Libraries may circumvent the execution of these special member functions, even in checked build modes. (Note that we are skipping the check itself, not just any side effects that executing the check might have produced.) If, however, the compiler would be eliding invocation of the trivial function, it might nonetheless choose to evaluate the CCAs, followed by the trivial operation, depending on the user’s chosen build mode and optimization level. In the case of the first alternative above, the potential loss in runtime performance from not doing the memmove invocation could be substantial, perhaps even dramatic, and would introduce a strong disincentive to adding such defensive checks to otherwise trivial functions, thus violating Principle 3. Hence, we consider the first alternative to be nonviable. The second alternative is much more consistent with our conclusion with respect to the noexcept specifier in that it keeps the two language features — namely triviality and contract checking — maximally orthogonal. This latter approach does come with the risk of perhaps omitting checks that an uninitiated author might have intended the client to run in every case — i.e., including even those cases in which use of an equivalent memmove would be substantially more runtime performant. Fortunately, the duly informed author of a CCA for a special member function can always easily opt into this other slower but safer behavior: ```cpp ~Date() [[ pre: isValid(d_year, d_month, d_day) ]] { } // empty body // Destroy this object. ``` \(^{10}\)See [lakos21], Section 2.1.“Generalized Pods,” “Use Cases,” “Skippable destructors (notionally trivially destructible),” pp. 464–470, especially pp. 469–470. \(^{11}\)Although a special member function that has an empty body supplied by the user will provide no code and therefore would seem to be no different than the empty body supplied by the compiler, the copy constructor being trivial gives the compiler special permission to bypass calling that copy constructor entirely. This optimization is particularly effective for contiguous sequences of such objects — e.g., `std::vector<my_trivially_copyable_type>` — since repeated calls to the copy constructor can be replaced by a single call to memmove. For an object to be considered trivially copyable, however, it must have a trivial destructor. Note that the compiler’s ability to see that the body of a user-supplied destructor is empty doesn’t make that destructor trivial, nor does such compiler ability give license to the library to use memmove for a type that would otherwise be trivially copyable but for its almost trivial destructor. Simply by providing an empty function body (see the example above), a function that was otherwise trivial can easily be made nontrivial in every build mode, thus removing the permission for libraries or the compiler to skip the invocation of this destructor and the evaluation of its associated checks. Consider that the checks are on the destructor, so there’s nothing to skip on the copy constructor, and the compiler could easily run the checks on destruction in a checked build even though no code had to run to destroy the object. If the author of the class fails to realize the triviality of the function and, as a result, some check isn’t run, no affirmative harm is done since the check was defensive (redundant) anyway and therefore entirely useless in every correctly written program. Finally, we note that all contract checks are presumed to be purely defensive and thus entirely redundant in a defect-free program. Turning off runtime contract checking on otherwise trivial functions is, in effect, just one more way for developers to control if and to what extent their programs are checked at run time. Hence, as long as the presence of a CCA doesn’t affect the compile-time result of evaluating a trait on a type, we might imagine giving the compiler explicit (e.g., via a compiler switch) freedom to sometimes refrain from invoking such runtime checks on trivial types, perhaps in collaboration with the totality of the (e.g., optimization) build modes. Putting these suggestions together, we arrive at one proposal regarding the triviality of special member functions with contract-checking annotations. ### Proposal 1: CCAs Do Not Affect Triviality A (defaulted) special member function having preconditions or postconditions may still be trivial. Note that trivial special member functions might be replaced (by the language or a library) by bitwise copies or even elided completely, both of which would skip evaluation of any CCAs associated with that function. ### 3.2 Implicit Lambda Captures As with any other function that may be defined in C++, functions defined using a lambda expression must be annotatable with precondition and postcondition CCAs and must contain assertion CCAs within their bodies. Any issues related to name resolution or appurtenance, such as those raised for trailing return types by [P2036R3], must be resolved by the syntax adopted for Contracts, such as is done in [P2935R0]. ### Proposal 2.1: CCAs Allowed on Lambdas Precondition and postcondition CCAs may be placed on a lambda expression such that they appertain to the closure object’s call operator. Assertion CCAs may appear within the body of a lambda expression. Similar to affecting the triviality of a special member function, another area in which a CCA might be capable of having an impact on program behavior occurs when the predicate of a CCA within a lambda ODR-uses a local entity. In such cases, that entity might be implicitly captured as part of the generated closure object, thus affecting its size and possibly incurring a large cost to initialize it when that capture is by-value. In some sense, not capturing at all when a CCA will be ignored and capturing only when a CCA would have other semantics might be possible. With the adoption of [P2877R0], no mechanism is available to have such properties as what is captured be based on the semantic that a CCA will have when evaluated. Additionally, having such a fundamental property of the closure object as the list of members it contains (and thus its size) be dependent on the chosen semantic of a CCA would be a violation of Principle 2 and thus should not be considered. While simply allowing a capture might seem like a minimal violation of the zero-overhead principle (Principle 3), consider that the object referenced might far exceed the cost and scope of the lambda itself: ```cpp std::function<int()> foo(const std::vector<S>& v) { int ndx = pickIndexAtRandom(v); return [=]() { [[ pre : 0 <= ndx && ndx < v.size() ]] // needs to capture v { return ndx; // Obviously we intend this to capture ndx by value. }; } } ``` Because the full `v` object must be captured by-value due to referencing it to get its size in the precondition of the lambda, this simple constant-time function becomes linear in the size of `v` due to the capture. That is a subtle and significant performance hit due to the presence of a CCA. We are left with two options. 1. Allow the implicit capture from a CCA expression, which will happen regardless of the semantic with which the CCA is evaluated. 2. Make an implicit capture due to a CCA’s expression ill-formed, preventing subtle costs due to the presence of a CCA. Choosing the first alternative would violate Principle 3, ensuring that no runtime or object-size overhead is associated with any contract checks compared to simply not having such checks present in the program in the first place. The potentially significant and hidden cost of such captures might discourage the adoption of the Contracts facility in general. The second alternative — i.e., making ill-formed the ODR-use of a local entity that is not already ODR-used in the body of the lambda apart from any CCA — creates zero overhead when ignored, has no effect on object size, and yet clearly informs users when they are referencing a value that is not directly relevant to the body of the lambda. This approach is both consistent with Principle 3 and, if there is any doubt about whether it is the correct long-term direction, is also an application of Principle 4. The workaround, for those who want to capture that dubious value anyway, is simply to explicitly capture the variable in question or add the appropriate ODR-use directly within the body of the lambda: ```cpp std::function<int()> foo(const std::vector<S>& v) { int ndx = pickIndexAtRandom(v); }``` Of course, when thinking about the compilation error due to the lack of capture of \(v\), a developer will quickly realize that much better alternatives are available: assert that \(ndx\) is in the proper range prior to initializing the lambda or capture only \(v.size()\) for use in the lambda’s precondition. This reasoning all comes together into one additional proposal regarding lambdas. ```cpp return [=,v]() // capture v by value [[ pre : 0 <= ndx && ndx < v.size() ]] // needs to capture v { return ndx; // Obviously we intend this to capture ndx by value. }; ``` Proposal 2.2: CCA ODR-Use Does Not Implicitly Capture | Within the expression of a CCA that is attached to or within a lambda, the ODR-use of a local entity does not implicitly capture that entity. | The reference to the local entity from the CCA will still continue to attempt to name the member of the closure object instead of the local entity itself. Therefore, if no other factor creates that member of the closure (either an explicit capture or an ODR-use that is not in a CCA), a program will be ill-formed. In comparison to the proposal in [P2890R0], we have complete agreement on the need to support CCAs on lambda functions, and the only difference is whether the exception for captures of local entities from within CCAs should be made. ### 3.3 Compile-Time Evaluation The specifics of evaluating a CCA at compile time have not been thoroughly pinned down in the MVP and, more importantly, might violate some of our fundamental principles if no additional changes are made. Currently, after the adoption of [P2877R0], any evaluation of a CCA might or might not evaluate the predicate and detect a violation, and nothing about that proposal was specific to runtime evaluations. Therefore, even during compile-time evaluations, whether a CCA would be checked (i.e., have the observe or enforce semantic) or not (i.e., have the ignore semantic) is implementation defined. More importantly, the contract-violation handling process involves invoking the global, replaceable contract-violation handler, which clearly can’t be known when compiling an individual translation unit (TU). Egregious differences between the behavior of compile-time evaluation and runtime evaluation are ill advised, so we propose retaining the meanings of the potential semantics of CCA evaluation at compile time and simply changing the effects of violations in a way that has similar spirit but does not allow the same customizability; we change an attempt to invoke the contract-violation handler into one that simply emits a diagnostic, the mechanism we use for the compiler to emit information about a problem to the user. When a CCA being enforced is violated, we must also decide what happens when the implementation-defined program termination occurs, and again we have two potential choices. 1. Make the enclosing constant-evaluated expression ineligible to be a constant expression. This option is the typical specification tool used to say something cannot be done at compile time. 2. Make the program ill-formed, with no ability to choose a separate control flow path or to evaluate at run time instead. With Option 1, one can then decide, based on the evaluation semantic, what to do in other contexts, altering program semantics based on the chosen semantic; doing so would violate Principle 2, and thus we consider this option nonviable. We are thus obliged to choose Option 2, making any constant evaluation that violates a checked CCA ill-formed. Proposal: Compile-Time Contract Violations Emit Diagnostics When the contract-violation process is evaluated at compile time (i.e., a CCA is violated when being evaluated with the observe or enforce semantic), a diagnostic will be emitted. When the evaluation is performed with the enforce semantic, the program is ill-formed. The other major aspect of CCA evaluation that we must consider is the evaluation of the predicate itself and whether that must be eligible for compile-time evaluation. More importantly, can that predicate being ineligible for constant evaluation render the enclosing expression ineligible for being a constant expression? Recall from [P2877R0] that we can effectively consider the evaluation of a CCA with expression x to be of this form: ```c++ switch (__current_contract_semantic()) { case semantic::ignore: break; case semantic::observe: if (X) {} else { __invoke_violation_handler(contract_info, semantic::observe); } break; case semantic::enforce: if (X) {} else { __invoke_violation_handler(contract_info, semantic::enforce); __terminate_on_enforced_violation(); } break; } ``` The above proposal is equivalent to saying that the intrinsic `__current_contract_semantic()` is a valid core constant expression, and that `__current_contract_semantic` is constexpr or consteval. As described in [P2877R0], implementations have a wide range of flexibility in what this function may do. - An implementation that provides a single, global switch to choose the semantics for all CCAs might, for example, when that chosen semantic is enforced, install a version of semantic computation: ```c++ consteval semantic __current_contract_semantic() { return semantic::enforce; } ``` - A different configuration might choose to provide a mode in which the semantic computation function that is installed makes different decisions at compile or run time: ```c++ constexpr semantic __current_contract_semantic() { if consteval { // constant-evaluation semantic: return semantic::enforce; // or something else, based on compiler flags } else { // runtime semantic return semantic::ignore; // or something else, based on compiler flags } } ``` - Other implementations might inspect link-time properties to determine the runtime semantic, provide mechanisms to select the compile-time or runtime semantic based on the location of the CCA being evaluated, or do any number of other operations that produce the behavior such implementations have defined for the selection of CCA semantics. When determining if an expression containing a CCA can be evaluated at compile time, we will need to identify two things: 1. Is each individual evaluation within the process of evaluating a CCA eligible to be part of a constant expression? 2. If the expression is not eligible, what happens? The first question we have already answered above for the violation handler and termination: Neither can be performed at compile time, and it is ill-formed if the termination on enforced violation happens at compile time. The full expansion above, however, shows us we must answer questions about additional parts of this expansion as well. First, is the computation of the semantic, which is the implementation-defined manner in which a semantic is chosen for the evaluation of a CCA, eligible to be done as part of a constant expression? If we were to allow the answer to this question to be _no_, then doing contract checking at compile time would be impossible; the very act of determining the semantic for a CCA would make the enclosing expression no longer a constant expression. This decision would be highly unfortunate, effectively making the use of CCAs completely incompatible with compile-time programming. Therefore, we propose that the selection can be done at compile time. Proposal: Semantic May Be Selected At Compile Time The implementation-defined choice of semantic when evaluating a CCA may be evaluated as part of a core constant expression; i.e., selecting the semantic as part of evaluating a CCA does not make the expression containing the CCA ineligible to be a *core constant expression*. The other question is what happens when the expression, \(X\), is ineligible to be evaluated at compile time. Here we note that one chosen semantic — the *ignore* semantic — can always make the answer to this question irrelevant. When evaluating a CCA and given our previous proposal, if the *ignore* semantic is chosen, the rest of the evaluation will always be eligible to be part of a constant expression; no other evaluations will be performed. Therefore, because we are striving to maintain Principle 2 (program semantics are independent of chosen CCA semantics), the evaluation of the expression must be just as eligible to be part of a constant expression as the empty branch in the *ignore* case is. Therefore, if the evaluation of the predicate, \(X\), is *not* eligible to be part of a constant expression, we must make that ill-formed. Just as we do with contract violations, we should allow *observing* a CCA that fails to be evaluable at compile time to emit a diagnostic while *enforcing* such a CCA should be ill-formed. Proposal: Use of Nonconstant-Eligible Predicates When Constant Evaluation Is Required Is Ill-Formed In an expression that is a valid core constant expression, evaluation of a predicate that is not eligible to be a core constant expression emits a diagnostic. If the semantic of the corresponding CCA is *enforce*, the program is ill-formed. Note the importance of this situation being ill-formed when *enforced*, rather than the expression simply being ineligible to be a constant expression; some manifestly constant-evaluated contexts are also SFINAE contexts and thus would allow control flow to alter based on which semantic is selected for evaluating a CCA. Consider the following prototypical example of a function with a narrow contract, also a function one might consider beneficial to use at compile time: ```cpp constexpr double sqrt(double x) [[ pre : x >= 0 ]]; ``` Now, interestingly, we can make a concept check that could tell us whether a given expression is a valid Boolean constant expression: ```cpp #include <type_traits> // for std::bool_constant template <double x> concept can_constexpr_sqrt = requires { std::bool_constant<sqrt(x)>(); }; ``` Now, code could be written in terms of this concept that would have highly unintuitive behavior since it depends entirely on the chosen semantic of the precondition check on *sqrt* at compile time: ```cpp template <double x> void f() ``` 14 if constexpr (can_constexpr_sqrt<x>) { // #1 --- processing if x >= 0 or preconditions are disabled } else { // #2 } } The code block at #2 is reachable only if we were to allow the precondition check failure to be subject to SFINAE and thus let the concept check fail instead of making the program ill-formed when the attempt to form the result sqrt(-1.0) was made. With our proposals, the above code would be ill-formed if the precondition’s predicate is evaluated; otherwise, the code would always flow through to the block at #1. This behavior is the same as what we would observe in evaluating this code at run time with no attempt to use it at compile time. The same reasoning must be applied to potentially constant variables that are not constexpr — i.e., reference or non-volatile const-qualified variables of integral or enumeration types. These variables are usable in a constant expression if their initializers are core constant expressions, but they are also fine to initialize with noncore constant expressions (and thus dynamically initialize at run time). Here, following Principle 2 is again important as is keeping any well-formed behavior consistent with the behavior when CCAs are ignored. To determine this, an evaluation with all CCAs ignored must first be done to ascertain if the expression, without CCAs, is eligible to be a core constant expression. When this trial evaluation is not eligible for the initialization of a potentially constant variable, the CCAs should not matter; the initialization will happen as a dynamic initialization at run time, and any contract violations that might be detected will happen then. A trial evaluation that determines that a CCA is a core constant expression will cause the variable initialization to be a manifestly constant-evaluated context, and thus the rules above will apply. For such variables, we want to make ill-formed (and not SFINAE-able) any attempt to use them in a manifestly constant-evaluated context. ### Proposal: Nonconstant Eligible Initializers Evaluate CCAs at Run Time If the initializer of a nonconstexpr potentially-constant variable is not itself a core constant expression when all its CCAs are evaluated with the ignore semantic, then that initializer is not a core constant expression; hence, no attempt will be made to perform constant evaluation on the expression again with CCAs potentially having different semantics. We call out this last proposal because we should not aggressively enforce contracts at compile time that might never be evaluated at run time. All these proposals related to constant evaluation address individual aspects of the constant evaluation process and how it relates to CCA evaluation. Putting this all together produces one complete proposal that accomplishes all the above goals: Proposal 3: Evaluation of CCAs at Compile Time When determining whether an expression is a core constant expression, first determine if the expression is a core constant expression by evaluating it with all CCAs having the ignore semantic: - If it is a core constant expression or if it is not a core constant expression but is in a manifestly constant-evaluated context, re-evaluate the expression while evaluating the CCAs with semantics chosen in an implementation-defined manner. - If evaluating the resulting expression violates an observed CCA, emit a diagnostic. Constant evaluation continues as normal after the CCA. - If evaluating the result expression violates an enforced CCA, the program is ill-formed. Emit a diagnostic. - If the expression is not a core constant expression, the program is ill-formed. - Otherwise, the expression is not a core constant expression. In comparison to the proposal in [P2894R0], this proposal clarifies that contract violations (and contract predicates that are not evaluable at compile time) during constant evaluation must be hard errors, and the semantics for that proposed here is the result of extensive reflector discussion on the topic. Our understanding is that future revisions of [P2894R0] will propose very similar semantics. The primary difference is the support proposed here to enable a distinction between observed and enforced CCAs at compile time, where an observed CCA produces a diagnostic but is not a hard error. 3.4 Virtual Functions With the adoption of [P2954R0] by SG21, CCAs on virtual functions have the following behavior. - CCAs may be placed on virtual functions that do not override any other virtual functions. - A virtual function that overrides exactly one with CCAs inherits the CCAs of that overridden function. - Virtual functions that override multiple functions may do so only if none of those functions have CCAs. The problem is that inheritance of CCAs from a base class violates Principle 1. By introducing a CCA on a base-class virtual function, all derived class virtual functions implicitly get that same virtual function. The general case for well-defined object-oriented implementations might be okay with this, but in some cases that will misidentify defects in software that are not actually wrong. In particular, consider a derived class that has a wider contract on a function than its base class: ```cpp class Car { virtual void drive(int speed); // The behavior is undefined unless the specified speed // is less than 100. }; class FastCar { void drive(int speed) override; }; ``` The behavior is undefined unless the specified speed is less than 169. This FastCar is a completely fine derived class for Car and can be used anywhere Car can. Now consider adding a CCA to Car to validate the precondition of drive: ```cpp class Car { virtual void drive(int speed) [[ pre : speed < 100 ]]; }; ``` The default inheritance of this CCA in FastCar will cause all code that drives a FastCar fast to break — even code that knowingly has a FastCar and reasonably wants to take advantage of the fact that it has a FastCar in hand. This results in the following (partial) proposal to fix the current SG21 MVP behavior to adhere to our stated principles. --- **Proposal: CCAs Are Not Inherited** A virtual member function that has no precondition or postcondition CCAs on its declaration will have no precondition or postcondition CCAs (and will not inherit those of any functions it may be overriding). --- Properly allowing variance of CCAs across class hierarchies requires checking both the CCAs of the virtual function being invoked as well as those of the concrete implementation found through virtual dispatch. This solution might, however, not be ready for SG21 to adopt at this time. Consider a test function where we use a virtual function via dynamic dispatch through both base-class and derived-class references: ```cpp void testCars() { FastCar fc; Car& cr = fc; cr.drive(120); // CCAs of Car::drive and FastCar::drive should be checked. FastCar& fcr = fc; fcr.drive(120); // CCAs of FastCar::drive should be checked. } ``` With the current MVP, the CCAs of Car::drive and FastCar::drive are the same, so the behavior will be compatible with the above. The current MVP behavior without inherited CCAs does not give a clear answer as to what CCAs would be checked in the above calls. --- 12 After the initial MVP achieves consensus, the forthcoming [P2755R0] — or possibly other papers — will propose that the best approach here is to check both the CCAs that are visible based on the static type through which the function is being invoked as well as those of the specific concrete function selected by virtual dispatch, thus guaranteeing that all expectations of both caller and callee are satisfied. Without a more complete solution, we must then apply Principle 4 and remove the ability to put CCAs on virtual function declarations until that more complete solution is adopted: <table> <thead> <tr> <th>Proposal 4: No CCAs on Virtual Functions</th> </tr> </thead> <tbody> <tr> <td>It is ill-formed to place a <code>[[pre]]</code> or <code>[[post]]</code> CCA on a virtual function, i.e., a member function marked <code>virtual</code> or that overrides a virtual function in a base class.</td> </tr> </tbody> </table> ### 3.5 Coroutines When users begin to consider what `[[pre]]` and `[[post]]` might mean when applied to a coroutine, a few frequent misunderstandings and open questions would need to be resolved. - Do preconditions get applied if the body of the coroutine does not begin to execute for a coroutine that starts suspended? - Are the function parameters named in a precondition referring to the parameters of the function invocation or the copies made within the coroutine frame? What about parameters named by a postcondition? - Is a return value named by a postcondition a reference to the function’s returned value, to a value returned by `co_return`, or to something returned by `co_yield`? While perhaps clear answers could be provided, they all leave unsatisfied other obvious needs for providing contract checks on coroutines: `pre` and `post` alone do not provide anything like a complete solution for the contract checks on the interface of a coroutine. Some considerations must also be addressed. - For coroutine handle types that perhaps are not awaitable and cannot themselves be used with `co_await`, such as `std::generator`, whether a given function is a coroutine is unclear from a client perspective. In this context, `pre` and `post` have clear meanings in terms of the production of that initial returned object. Callers must be able to treat `pre` and `post` in the same fashion independently of whether the function being invoked is a coroutine or not. - For the implementer of a coroutine, however, many more entry and exit points are generally available between a coroutine and other code; each call to `co_return`, `co_yield`, and even `co_await` is a distinct part of the Promise–type-specific interface the coroutine has with the outside world. Any one of these boundaries might have requirements for correctness that would be beneficial for a user of the coroutine to know and thus could have meaning when placed on the coroutine’s declaration. - When invoking a coroutine, normally a return object is produced and returned to the caller, and little ambiguity arises about when a postcondition would get evaluated for that object. Invoking a coroutine within a `co_await` expression, however, is a fairly involved process, which may involve evaluation before and after suspension and resuming of the call-side coroutine, and when exactly postconditions should be evaluate or which specific options are even implementable becomes unclear. Should a `co_await` expression result in suspension, arbitrary amounts of other code might execute prior to resumption, any of which may invalidate a postcondition of the coroutine. Evaluation such as this would break the fundamental intuition many have that a postcondition hold in the code immediately following invocation of a function that had that postcondition. - Caller-side CCA checks would naturally be able to apply only to the actual function arguments, not the copies within the coroutine frame. This restriction can lead to subtle bugs if properties are checked that do not propagate through such copies. Possibly worse, forcing a coroutine parameter to be `const` by referring to it from a postcondition not only prevents modification of that parameter within the coroutine body (which is usually a manageable cost), but also causes the initialization of the copy (normally done with an xvalue referring to the original function parameter) to be done with a potentially much more expensive `copy` operation, not a `move` operation. In general, having preconditions and postconditions refer to objects that the body of the function can never actually see is a pitfall that must be considered very carefully. Currently, no concrete proposal covers the full breadth of the interface a coroutine has with its callers. Without this complete picture, we cannot yet know if `pre` and `post` will have a meaning that is correct and useful to those calling into or implementing coroutines. Possibly `pre` and `post` with their semantics applied caller-side are the optimal solution for coroutines, even with the potential risks. Additionally, coroutines might benefit more from having bespoke `kinds` of CCAs that have different, coroutine-specific semantics (which, due to callers generally being unaware if a function is coroutine, would need to be fully implemented in the coroutine definition) that avoid these pitfalls. Therefore, we apply Principle 4 to decide that we should disallow any CCAs on a coroutine until we have a more complete picture of what we intend to provide. <table> <thead> <tr> <th>Proposal 5: No CCAs on Coroutines</th> </tr> </thead> <tbody> <tr> <td>Specifying a precondition or postcondition on a function that is a coroutine is ill-formed. That is, a function that has a <code>co_return</code>, <code>co_yield</code>, or <code>co_await</code> expression in its definition and also has a <code>[[pre]]</code> or <code>[[post]]</code> CCA is ill-formed.</td> </tr> </tbody> </table> Note that Proposal 5 intentionally says nothing about assertions. Contract checks to identify defects can still be added to a coroutine (or within the function so defined by the Promise type); they must simply be manually put within the body and cannot have additional control points by which they can be automatically injected. In comparison to [P2957R0], this paper agrees completely on the treatment of assertion CCAs within a coroutine body. That paper, however, proposes semantics for precondition and postcondition CCAs on coroutines, which we propose disallowing until a more complete and intuitive picture can be provided for the interactions between coroutines and Contracts. ### 3.6 Contracts on First Declarations SG21 has agreed that, for the MVP, CCAs shall not be repeated on multiple declarations and must always be on the first declaration encountered for a function. This placement reduces the need for answering questions about behavior if, for instance, a function is invoked in one place without having seen the CCAs on that function yet and in another place after CCAs have been seen. Note the great benefit to insulating CCAs from either readers of a function’s primary declaration or from client translation units; i.e., long-term, allowing CCAs to be repeated on later declarations, omitted from the first declaration and repeated at a later point, or even partially declared on one declaration and then fully defined on a subsequent declaration will be necessary. None of these possibilities would circumvent the one approach being allowed by the MVP: to support CCAs on first declarations only. Therefore, SG21 has followed Principle 4 to leave flexibility for future evolution and must simply define the behavior of the minimal feature we are supporting. To fully define what we mean by restricting CCAs to be on first declarations only, we need to break down a few points. - **What is a first declaration?** - **If multiple first declarations can appear in the same program, when are such CCAs the same?** - **What happens if CCAs are not the same?** To allow for functions to be declared in multiple modules or in different header files, modern C++ would determine first based on reachability. In general, one declaration \(A\) is reachable from another \(B\) if \(A\) precedes \(B\) within the same TU or if \(A\) is declared in a module imported (directly or transitively) by the TU containing \(B\). A declaration \(D\) for an entity is a first declaration of that entity if no other declarations for \(D\) are reachable — i.e., if no such declaration occurs earlier in the same TU and no such declaration is exported or used by a module that has been imported. Given a clear definition of what is or is not a first declaration, we can restate the general rule in the MVP for CCAs being on first declarations only. **Proposal 6.1: CCAs on First Declarations Only** A function declaration that is not a first declaration shall not have \([\text{pre}]\) or \([\text{post}]\) CCAs attached to it. To define if CCAs are the same, we will want to use the one-definition rule (ODR). This rule, however, applies to definitions, not declarations. Using part of the approach taken in C++20 Contracts,\(^\text{13}\) we can define CCAs on different declarations for the same entity to be the same if they would be the same if placed in a function definition (at the same place where their declaration occurs), excluding potential renaming of function parameters, template parameters, or return value identifiers. \(^\text{13}\)See [N4820] for the draft Standard that included the C++20 Contracts proposal wording. Definition: CCA Sameness A CCA, \( c_1 \), on a function declaration, \( d_1 \), is the same as a CCA, \( c_2 \), on a function declaration, \( d_2 \), if their predicates, \( p_1 \) and \( p_2 \), would satisfy the one-definition rule if placed in function definitions on the declarations \( d_1 \) and \( d_2 \), respectively, except for the renaming of parameters, return value identifiers, and template parameters. With the ability to identify if two CCAs are the same, we can easily extend this definition to two lists of CCAs being the same if all corresponding elements of the lists are the same. Finally, the question of when to check that CCAs on a function are declared consistently across multiple first declarations must be addressed. Should the function declarations be in distinct TUs with no compile-time awareness of one another, we have little choice but to make a mismatch ill-formed, no diagnostic required (IFNDR). Whether CCAs match when there are multiple first declarations reachable from the same point could be checked in two situations: 1. When importing a module that contains a first declaration for a function that is already reachable 2. When invoking a function with multiple first declarations that are reachable Both options would require potentially large implementation difficulty, so we recommend leaving detection of mismatched CCAs as a quality of implementation decision; in practice, CCAs should mismatch only when declarations are being copied and pasted inappropriately instead of sourced from a header file with a single, canonical definition, so demanding extraordinary effort to detect such defects does not present as an incredibly high priority. Proposal 6.2: Function CCA Lists Must Be Consistent The list of CCAs on all first declarations (in all TUs) for a function shall be the same, no diagnostic required. Because nonfirst declarations may have no CCAs on them, nothing else needs to be said for the Contracts MVP. If CCAs on nonfirst declarations were allowed, they would generally be from different source locations, and validating that the redeclared CCA lists were the same as the original would be straightforward and needed, and mismatches would then be ill-formed, not IFNDR. 4 Conclusion SG21 has come a long way while finalizing a design for a Contracts MVP. Even with the small, focused scope of the MVP, open questions remain and must be addressed prior to having Contracts as an adopted feature in ISO C++. This paper has attempted to wrap up the remaining known edge cases that are essential to address to have a complete feature proposal ready to be integrated into the rich, powerful, and sometimes challenging language that C++ is. Should any further questions arise during the adoption of this proposal, we hope these same principles can guide remaining decisions to keep the Contracts facility’s design clear and consistent. As a foundation for reasoning about undecided features for the C++ Contracts facility, and the SG21 MVP in particular, we have presented four principles: - **Principle 1** — CCAs Check a Plain-Language Contract - **Principle 2** — Program Semantics Are Independent of Chosen CCA Semantics - **Principle 3** — Zero Overhead for Ignored Predicates - **Principle 4** — Make Undecided Behaviors Ill-Formed Based on these principles, the open questions for the Contracts MVP have been addressed by the following proposals. - **Proposal 1** — CCAs Do Not Effect Triviality - **Proposal 2.1** — CCAs Allowed on Lambdas - **Proposal 2.2** — CCA ODR-Use Does Not Implicitly Capture - **Proposal 3** — Evaluation of CCAs at Compile Time - **Proposal 4** — No CCAs on Virtual Functions - **Proposal 5** — No CCAs on Coroutines - **Proposal 6.1** — CCAs on First Declarations Only - **Proposal 6.2** — Function CCA Lists Must Be Consistent Finally, adoption of each of these reasoned proposals will serve two important objectives. 1. All outstanding design issues presented in [P2896R0] will be resolved. 2. The SG21 Contracts proposal will be a robust, initially useful, easy-to-evolve facility that integrates well with the whole of the C++ language and is ready to adopt and release in a timely fashion. ## 5 Acknowledgments Thanks to Lori Hughes, Jens Maurer, John Lakos, and Andrzej Krzemieński for reviewing this paper and providing feedback. ### Bibliography - [lakos21]: John Lakos, Vittorio Romeo, Rostislav Khlebnikov, and Alisdair Meredith, *Embracing Modern C++ Safety* (Boston: Addison-Wesley, 2021) <table> <thead> <tr> <th>Paper Reference</th> <th>Authors and Title</th> <th>Year</th> <th>URL</th> </tr> </thead> <tbody> <tr> <td>P2890R0</td> <td>Timur Doumler, “Contracts on lambdas”, 2023</td> <td>2023</td> <td><a href="http://wg21.link/P2890R0">http://wg21.link/P2890R0</a></td> </tr> <tr> <td>P2894R0</td> <td>Timur Doumler, “Constant evaluation of Contracts”, 2023</td> <td>2023</td> <td><a href="http://wg21.link/P2894R0">http://wg21.link/P2894R0</a></td> </tr> <tr> <td>P2896R0</td> <td>Timur Doumler, “Outstanding design questions for the Contracts MVP”, 2023</td> <td>2023</td> <td><a href="http://wg21.link/P2896R0">http://wg21.link/P2896R0</a></td> </tr> <tr> <td>P2900R0</td> <td>Joshua Berne, Timur Doumler, and Andrzej Krzemieński, “Contracts for C++”, 2023</td> <td>2023</td> <td></td> </tr> <tr> <td>P2954R0</td> <td>Ville Voutilainen, “Contracts and virtual functions for the Contracts MVP”, 2023</td> <td>2023</td> <td><a href="http://wg21.link/P2954R0">http://wg21.link/P2954R0</a></td> </tr> <tr> <td>P2957R0</td> <td>Andrzej Krzemieński and Iain Sandoe, “Contracts and coroutines”, 2023</td> <td>2023</td> <td><a href="http://wg21.link/P2957R0">http://wg21.link/P2957R0</a></td> </tr> </tbody> </table>
{"Source-Url": "https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2023/p2932r0.pdf", "len_cl100k_base": 13255, "olmocr-version": "0.1.50", "pdf-total-pages": 23, "total-fallback-pages": 0, "total-input-tokens": 52080, "total-output-tokens": 15281, "length": "2e13", "weborganizer": {"__label__adult": 0.0004448890686035156, "__label__art_design": 0.00040984153747558594, "__label__crime_law": 0.00035572052001953125, "__label__education_jobs": 0.00048661231994628906, "__label__entertainment": 4.374980926513672e-05, "__label__fashion_beauty": 0.0001506805419921875, "__label__finance_business": 0.00020754337310791016, "__label__food_dining": 0.0003466606140136719, "__label__games": 0.0005431175231933594, "__label__hardware": 0.0005517005920410156, "__label__health": 0.0003097057342529297, "__label__history": 0.0001798868179321289, "__label__home_hobbies": 8.386373519897461e-05, "__label__industrial": 0.0002713203430175781, "__label__literature": 0.00022733211517333984, "__label__politics": 0.0003063678741455078, "__label__religion": 0.00043129920959472656, "__label__science_tech": 0.0018434524536132812, "__label__social_life": 7.903575897216797e-05, "__label__software": 0.002674102783203125, "__label__software_dev": 0.98876953125, "__label__sports_fitness": 0.0003299713134765625, "__label__transportation": 0.0005464553833007812, "__label__travel": 0.0002359151840209961}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 63721, 0.02711]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 63721, 0.23487]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 63721, 0.91155]], "google_gemma-3-12b-it_contains_pii": [[0, 1081, false], [1081, 3845, null], [3845, 7254, null], [7254, 10149, null], [10149, 13179, null], [13179, 16020, null], [16020, 19403, null], [19403, 23297, null], [23297, 26411, null], [26411, 29215, null], [29215, 31917, null], [31917, 34414, null], [34414, 36657, null], [36657, 39443, null], [39443, 42266, null], [42266, 44877, null], [44877, 47141, null], [47141, 50148, null], [50148, 53400, null], [53400, 56128, null], [56128, 59035, null], [59035, 60980, null], [60980, 63721, null]], "google_gemma-3-12b-it_is_public_document": [[0, 1081, true], [1081, 3845, null], [3845, 7254, null], [7254, 10149, null], [10149, 13179, null], [13179, 16020, null], [16020, 19403, null], [19403, 23297, null], [23297, 26411, null], [26411, 29215, null], [29215, 31917, null], [31917, 34414, null], [34414, 36657, null], [36657, 39443, null], [39443, 42266, null], [42266, 44877, null], [44877, 47141, null], [47141, 50148, null], [50148, 53400, null], [53400, 56128, null], [56128, 59035, null], [59035, 60980, null], [60980, 63721, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 63721, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 63721, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 63721, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 63721, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 63721, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 63721, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 63721, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 63721, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 63721, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 63721, null]], "pdf_page_numbers": [[0, 1081, 1], [1081, 3845, 2], [3845, 7254, 3], [7254, 10149, 4], [10149, 13179, 5], [13179, 16020, 6], [16020, 19403, 7], [19403, 23297, 8], [23297, 26411, 9], [26411, 29215, 10], [29215, 31917, 11], [31917, 34414, 12], [34414, 36657, 13], [36657, 39443, 14], [39443, 42266, 15], [42266, 44877, 16], [44877, 47141, 17], [47141, 50148, 18], [50148, 53400, 19], [53400, 56128, 20], [56128, 59035, 21], [59035, 60980, 22], [60980, 63721, 23]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 63721, 0.07273]]}
olmocr_science_pdfs
2024-11-28
2024-11-28
d8b656b95433b6b191df004d9f37ccae9a39b88e
Advances in Parallel-Stage Decoupled Software Pipelining Leveraging Loop Distribution, Stream-Computing and the SSA Form Feng Li, Antoniu Pop, Albert Cohen To cite this version: Feng Li, Antoniu Pop, Albert Cohen. Advances in Parallel-Stage Decoupled Software Pipelining Leveraging Loop Distribution, Stream-Computing and the SSA Form. WIR 2011: Workshop on Intermediate Representations, Apr 2011, Chamonix, France. pp.29-36. hal-00744090 HAL Id: hal-00744090 https://hal-mines-paristech.archives-ouvertes.fr/hal-00744090 Submitted on 22 Oct 2012 HAL is a multi-disciplinary open access archive for the deposit and dissemination of scientific research documents, whether they are published or not. The documents may come from teaching and research institutions in France or abroad, or from public or private research centers. L’archive ouverte pluridisciplinaire HAL, est destinée au dépôt et à la diffusion de documents scientifiques de niveau recherche, publiés ou non, émanant des établissements d’enseignement et de recherche français ou étrangers, des laboratoires publics ou privés. Advances in Parallel-Stage Decoupled Software Pipelining Leveraging Loop Distribution, Stream-Computing and the SSA Form Feng Li INRIA feng.li@inria.fr Antoniu Pop Centre de recherche en informatique, MINES ParisTech antoniu.pop@mines-paristech.fr Albert Cohen INRIA albert.cohen@inria.fr Abstract Decoupled Software Pipelining (DSWP) is a program partitioning method enabling compilers to extract pipeline parallelism from sequential programs. Parallel Stage DSWP (PS-DSWP) is an extension that also exploits the data parallelism within pipeline filters. This paper presents the preliminary design of a new PS-DSWP method capable of handling arbitrary structured control flow, a slightly better algorithmic complexity, the natural exploitation of nested parallelism with communications across arbitrary levels, with a seamless integration with data-flow parallel programming environments. It is inspired by loop-distribution and supports nested/structured partitioning along with the hierarchy of control dependences. The method relies on a data-flow streaming extension of OpenMP. These advances are made possible thanks to progresses in compiler intermediate representation. We describe our usage of the Static Single Assignment (SSA) form, how we extend it to the context of concurrent streaming tasks, and we discuss the benefits and challenges for PS-DSWP. Categories and Subject Descriptors D.3.4 [Programming Languages]: Processors-Compilers, Optimization General Terms optimization Keywords automatic parallelization, stream-computing, loop distribution 1. Introduction In recent years, the CPU manufacturers have embraced chip multiprocessors because of technology, power consumption and thermal dissipation constraints, and because of diminishing returns in instruction-level parallelism. The amount of performance gained by the use of multicore processor depends highly on the software fraction that can be parallelized to run on multiple cores simultaneously. Multiprocessor programming leaves the burden to programmer who faces the extra complexity, heisenbugs, deadlocks and other problems associated with parallel programming. The situation is worse when dealing with the migration of legacy code. Decoupled Software Pipelining (DSWP) is an automatic thread partitioning method which could partition a sequential program to run on multiple cores, and Parallel-Stage DSWP (PS-DSWP) exposes data parallelism into task pipelines extracted by DSWP. These automatic thread partitioning methods free the programmer from manual parallelization. They also promise much wider flexibility than data-parallelism-centric methods for processors, aiming for the effective parallelization of general-purpose applications. In this paper, we provide another method to decouple control-flow regions of serial programs into concurrent tasks, exposing pipeline and data parallelism. The power and simplicity of the method rely on the restriction that all streams should retain a synchronous semantics [8]. It amounts to checking the sufficient condition that the source and target of any decoupled dependence are control-dependent on the same node in the control dependence tree (this assumes structured control flow). This restriction may appear as a severe one for experienced parallel programmers; but at the potential expense of adding extra levels of nested parallelism, it does not restrict the degree of pipeline parallelism. In fact, any pair of computational statements can be decoupled and assigned to different concurrent tasks. The partitioning algorithms also handle DOALL parallelization within task pipelines, and arbitrarily nested data-parallel pipelines following the control dependence tree of a structured control flow graph. Unlike existing DSWP algorithms, our method does not explicitly copy conditional expressions and can handle arbitrary backward data and control dependences. We are using two intermediate representations. - A conventional SSA-based representation, annotated with natural loop and control dependence trees (for structured control flow). - And a streaming data-flow extension of the latter representation as a backend for our partitioning algorithm, still in SSA form but with explicit task boundaries (for single-entry single-exit regions) and multi-producer multi-consumer streams to communicate across tasks. The backend representation streamlines the decoupling of multi-producer multi-consumer data flow through explicit, compiler-controlled sampling and merging stages. Multi-producer multi-consumer semantics is absolutely essential to handle general decoupling patterns where data-parallel stages feature an unbalance in the number of worker threads. Sampling is handled transparently by nesting tasks into enclosing control flow. Merging is captured by $\Phi$ functions at task boundaries, introducing a minor variant of the SSA form satisfying the so-called task-closed property that multiple incoming flows targeting the same use in a given task should be explicitly merged by a dedicated $\Phi$ function at the task entry point. Relying on SSA avoids building the complete program dependence graph: with the exception of the array dependence graph, our method only processes linear-size data structures, as opposed to the worst-case quadratic program dependence graph in DSWP. 2. Related Work The most closely related work to this paper is decoupled software pipelining and loop distribution. We recall the state-of-the-art in both and present the original finding at the source of this work: by extending loop distribution with pipelining and asserting a synchronous concurrency hypothesis, arbitrary data and control dependences can be decoupled very naturally with only minor changes to existing algorithms that have been proposed for loop distribution [10]. 2.1 Decoupled software pipelining Decoupled Software Pipelining (DSWP) [13] is one approach to automatically extract threads from loops. It partitions loops into long-running threads that communicate via inter-core queues. DSWP builds a Program Dependence Graph (PDG) [7], combining control and data dependences (scalar and memory). Then DSWP... introduces a load-balancing heuristic to partition the graph according to the number of cores, making sure no recurrence spans across multiple partitions. In contrast to DOALL and DOACROSS [4] methods which partition the iteration space into threads, DSWP partitions the loop body into several stages connected with pipelining to achieve parallelism. It exposes parallelism in cases where DOACROSS is limited by loop-carried dependences on the critical path. And generally speaking, DSWP partitioning algorithms handles uncounted loops, complex control flow and irregular pointer-based memory accesses. Parallel-Stage Decoupled Software Pipelining [16] (PS-DSWP) is an extension to combine pipeline parallelism with some stages executed in a DOALL, data-parallel fashion. For example, when there are no dependences between loop iterations of a DSWP stage, the incoming data can be distributed over multiple data-parallel worker threads dedicated to this stage, while the outgoing data can be merged to proceed with downstream pipeline stages. These techniques have a few caveats however. They offer limited support for decoupling along backward control and data dependences. They provide a complex code generation method to decouple dependences among source and target statements governed by different control flow, but despite its complexity, this method remains somewhat conservative. By building the PDG, DSWP also incurs a higher algorithmic complexity than typical SSA-based optimizations. Indeed, although traditional loop pipelining for ILP focuses on innermost loops of limited size, DSWP is aimed at processing large control flow graphs after aggressive inter-procedural analysis optimization. In addition, the loops in DSWP are handled by the standard algorithm as ordinary control flow, missing potential benefits of treating them as a special case. To address these caveats, we turned our analysis to the state of the art in loop distribution. 2.2 Loop distribution Loop distribution is a fundamental transformation in program restructuring systems designed to extract data parallelism for vector or SIMD architectures [10]. In its simplest form, loop distribution consists of breaking up a single loop into two or more consecutive loops. When aligning loop distribution to the strongly connected components of the data-dependence graph, one or more of the resulting loops expose iterations that can be run in parallel, exposing data parallelism. Barriers are inserted after the parallel loops to enforce precedence constraints with the rest of the program. An example is presented in Figure 1. ``` for (i = 1; i < N; i++) { S1 A[i] = B[i] + 1; S2 C[i] = A[i-1] + 1; <barriers inserted here> } ``` Figure 1. Barriers inserted after loop distribution. 3. OpenMP Extension for Stream-Computing as a Code Generation Target A recently proposed stream-computing extension to OpenMP [14] allows the expression of pipeline parallelism by making explicit the flow dependences, or producer-consumer patterns, between OpenMP tasks. It provides a simple way for explicitly building dynamic task graphs, where tasks are connected through streams that transparently privatize the data. The extension consists of two additional clauses, input and output to the task construct, that define the producer-consumer relationships between tasks. The OpenMP language, with this extension, is a natural fit as a target for our code generation. It provides for dynamic task creation and connection in the task graph, it handles arbitrary nesting of pipelined tasks in control-flow, and it allows the hierarchical nesting of tasks. The task construct is extended with input and output clauses as presented on Figure 2. Both clauses take a list of items, each of which describes a stream and its behavior w.r.t. the task to which the clause applies. In the abbreviated item form, stream, the stream can only be accessed one element at a time through the same variable a. In the second form, stream >> window, the programmer uses the C++ flavoured >> stream operators to connect a sliding window to a stream, gaining access, within the body of the task, to horizon elements in the stream. One of the main issues that needs to be addressed in order to distribute a PDG to the OpenMP stream-computing extension is that, in the latter, the data flow bypasses the control flow. In other words, when a task produces values on an output stream, these values will all reach the consumers of the stream, even if, in the serial semantics, the values would have been overwritten before reaching the consumers. This means that the only case where a direct annotation scheme will work is if all tasks are in the same control flow. There are multiple ways this issue can be handled, the most systematic one being to always ensure that every producer-consumer pair share the same control dependence. This is achieved by sinking all control flow surrounding the tasks, and not shared by both producer and consumer, in the tasks. To avoid the loss of parallelization opportunities, each task’s body can be further partitioned into nested pipelines. The GCC implementation of the OpenMP extension for stream-computing has been shown to be efficient to exploit mixed pipeline- and data-parallelism, even in dynamic task graphs [14]. It relies on compiler and runtime optimizations to improve cache locality and relies on a highly efficient lock-free and atomic operation-free synchronization algorithm for streams. 4. Observations It is quite intuitive that the typical synchronization barriers in between distributed data-parallel loops can be weakened, resulting into data-parallel pipelines. We aim to provide a comprehensive treatment of this transformation, generalizing PS-DSWP in the process. 4.1 Replacing loops and barriers with a task pipeline In the previous example, we could remove the barriers between two distributed loops with pipelining so that the two loops could run in parallel. ``` /* Initialize the stream, inserting a delay. */ void INIT_STREAM() { produce(stream, A[0]); } /* Decoupled producer and consumer. */ for (i = 1; i < N; i++) { S1 A[i] = B[i] + 1; produce(stream, A[i]); } /* Connect a sliding window to a stream, gaining access, within the body of the task, to horizon elements in the stream. */ for (i = N; i < horizon; i++) { S2 C[i] = A[i-1] + 1; consume(stream); } ``` Figure 3. Pipelining inserted between distributed loops. Initialize the stream (left), producer and consumer thread (right). Figure 3 shows that pipelined execution is possible: the INIT_STREAM function inserts one delay into a communication stream; the produce/consume primitives implement a FIFO, enforcing the precedence constraint of the data dependence on array \( A \) and communicating the value in case the hardware needs this information. When distributing loops, scalar and array expansion (privatization) is generally required to eliminate memory-based dependences. The conversion to a task pipeline avoids this complication through the usage of communication streams. This transformation can be seen as an optimized version of scalar/array expansion in bounded memory and with improved locality [15]. 4.2 Extending loop distribution to PS-DSWP The similarity between DSWP and distributed loops with data-parallel pipelines is striking. First, both of them partition the loop into multiple threads. Second, both of them avoid partitioning the loop iteration space: they partition the instructions of the loop body instead. But four arguments push in favor of refining DSWP in terms of loop distribution. 1. Loop distribution leverages the natural loop structure, where the granularity of thread partitioning can be easily controlled. Moreover, it is useful to have a loop control node to which to attach information about the iteration of the loop, including closed forms of induction variables; this node can also be used to represent the loop in additional transformations. 2. Using a combination of loop distribution and fusion, then replacing barriers with pipelining leads to an incremental path in compiler construction. This path leverages existing intermediate representations and loop nest optimizers, while DSWP relies on new algorithms and a program dependence graph. 3. Considering the handling of control dependences, a robust and general algorithm already exists for loop distribution. McKinley and Kennedy’s technique handles arbitrary control flow [10] and provides a comprehensive solution. The same methods could be applied for DSWP, transforming control dependences into data dependences, and storing boolean predicates into stream. After restructuring the code, updating the control dependence graph and data dependence graph, the code generation algorithm for PDGs [2, 5, 6] can be used to generate parallel code. This solution would handle all cases where the current DSWP algorithm fails to clone a control condition. 4. Since loop distribution does not partition the iteration space, it can also be applied to uncounted loops. Unfortunately, the termination condition needs to be propagated to downstream loops. This problem disappears through the usage of a conventional communication stream when building task pipelines. From this high-level analysis, it appears possible to extend loop distribution with pipelining to implement PS-DSWP and handle arbitrary control dependences. Yet the method still seems rather complex, especially the if-conversion of control dependences and the code generation step from the PDG. We go one step further and propose a new algorithm adapted from loop distribution but avoiding these complexities. 4.3 Motivating example Our method makes one more assumption to reduce complexity and limit risks of overhead. It amounts to enforcing the synchronous hypothesis on all communicating tasks in the partition [8]. A sufficient condition is to check if the source and target of any decoupled dependence is dependent on the same control node. Consider the example in Figure 4. S1 and S7 implement the loop control condition and induction variable, respectively. S2, S3 and S6 are control dependent on S1. S3 is a conditional node, S4, S5 and L1 are control dependent on it. In the inner loop, L2 and L3 are control dependent on L1. When we apply DSWP to the outer loop, the control dependences originating from S1 must be if-converted by creating several streams (the number of streams depends on the number of partitions). When decoupling along the control dependence originating from S3, a copy of the conditional node must be created as well as another stream. ``` S1 while (p != NULL) { S2 x = p->value; S3 if(c1) { S4 x = p->value/2; S5 ip1 = p->inner_loop; L1 while (ip1) { L2 do_something(ip1); L3 ip1 = ip1->next; } } S6 ... = x; S7 p = p->next; } ``` Figure 4. Uncounted nested loop before partitioning. ``` S1 while (p = q stav(p0, p2)) { S2 x1 = p1->value; S3 if(c1) { S4 x2 = p1->value/2; S5 ip2 = p1->inner_loop; L1 while (ip2 = q stav(ip1, ip3)) { L2 do_something(ip2); L3 ip3 = ip2->next; } } S6 ... = x2; S7 p2 = p1->next; } ``` Figure 5. Uncounted nested loop in SSA form. Among these, the same variable $x$ controls flow regions of both partitioning into tasks, so that task1_1 partition model is well suited for unbalanced loads, but the overhead construct; no ordering of tasks can be assumed. Such an execution top-down heuristics can be used. The nesting levels according to the load balancing and synchronization overhead will be executed first, and a pipeline will be created for the main task and its inner tasks three $\Phi$ and $x$ tasks. One may then check for data parallelism in the inner loops: if they do not carry any dependence, one may isolate them in additional data-parallel tasks, such as task1_3 in this example. In Figure 5, after building the control dependence tree, one may partition it into 3 tasks (task1_1, task1_2 and task1_3) at the root level, and for task1_2, one may further partition this task into nested tasks task2_1 and task2_2. One may then check for data parallelism in the inner loops: if they do not carry any dependence, one may isolate them in additional data-parallel tasks, such as task3_1 in this example. Figure 6 shows the task and stream-annotated code using an OpenMP syntax. Figure 7 shows the nested pipelining and data parallelization corresponding to the partitioned code. The main task will be executed first, and a pipeline will be created for the main task and its inner tasks three $\Phi$ and $x$ tasks. Among these, the same variable $x$ used to be defined in the control flow regions of both task1_1 and task1_2, to be used in task1_3. This output dependence must be eliminated prior to partitioning into tasks, so that task1_1 and task1_2 could be decoupled, while task1_3 may decide which value to use internally. Nested tasks are introduced to provide fine grained parallelism. It is of course possible to adapt the partition and the number of nesting levels according to the load balancing and synchronization overhead. The generated code will be well structured, and simple top-down heuristics can be used. In the execution model of OpenMP 3.0, a task instance is created whenever the execution flow of a thread encounters a task construct; no ordering of tasks can be assumed. Such an execution model is well suited for unbalanced loads, but the overhead of creating tasks is significantly more expensive than synchronizing persistent tasks. To improve performance, we use the persistent task model for pipelining, in which a single instance will handle the full iteration space, consuming data on the input stream and producing on the output stream [14]. In Figure 7, all the tasks except task3_1 use the persistent model to reduce the overhead of task creation; task3_1 is an ordinary task following the execution model of OpenMP 3.0 (instances will be spawned every time the control flow encounters the task directive). All these tasks will be scheduled by the OpenMP runtime. One problem with the partitioning algorithms is the fact that the def-use edges (scalar dependences) can become very large, sometimes quadratic with respect to the number of nodes [9]. Figure 8 (left) presents an example that illustrates this problem. Statements S1, S2 define the variable $x$. These definitions all reach the uses in the statements S3, S4 by passing through S5. Because each definition could reach every use, the number of definition-use edges is proportional to the square of the number of statements. These dependences constitute the majority of the edges in a PDG. SSA provide a solution to this problem. In SSA form, each assignment creates a different variable name and at point where control flow joins, a special operation is inserted to merge different incarnations of the same variable. The merge nodes are inserted just at the place where control flow joins. Figure 8 (right) is the original program under SSA form. A merge node ($\Phi$) is inserted at S5, and killed the definition of S1 and S2. We could see here, in the SSA form, we could reduce the definition-use edges from quadratic to linear. The systematic elimination of output dependences is also facilitated by the SSA form, with a $\Phi$ node in task3_1. Notice that the conditional expression from which this $\Phi$ node selects one or another input also needs to be communicated through a data stream. When modifying loop distribution to rely on tasks and pipelining rather than barriers, it is not necessary to distribute the loop control node and one may run it all in the master task, which in turn will activate tasks for the inner partitions. The statements inside each partition form a treegion whose root is the statement that is dependent on the loop control node. With pipelining inserted, distributed loops could be connected with pipelining when there are data dependences. One concern here is that loop distribution with task pipelines may not provide expressiveness to extract pipeline parallelism. This is not a problem however, since we may apply the same method to every conditional statement rooted treegion, with some special care to the nested tasks, we could get fine grained parallelism without explicitly decoupling the control dependences. Considering again the example in Figure 4, its control dependence tree is given in Figure 9. The root treegion includes all the nodes in the control dependence graph, treegion1_2 represents the treegion at conditional level 1 and its root is node 2, treegion1_3 is at conditional level 1 and includes nodes (S3,S4,S5,L1,L2,L3). treegion1_2 is in conditional level 2 and its root is node (L1), which is the loop control node of the inner loop. So following our approach, we may start from the treegion at conditional level 0, which is the whole loop, an implicit task will be created as the master task. For the treegions at level 1, we could create them as sub-tasks running at the context of the main task. If there are data dependences between the treegions at the same level and without recurrence, we will connect them with communication streams. If there is a dependence from the master task to one inner task, the value from the enclosing context can be forwarded to the inner task like in a lastprivate clause of OpenMP. Dependences from an inner task to the master task are also supported, although lastprivate is not natively supported for OpenMP3.0 tasks, it is a necessary component of our streaming task representation. lastprivate($x$) is associated with a synchronization point at the end of the task and makes the value of $x$ available to the enclosing context. The same algorithms could be recursively applied to the treegion at the next inner level. e.g. For treegion1_3 at level 1, the sub treegion at level 2 is In this section, we present our partitioning algorithm, based on the SSA and treegion representations. We define our model and the important constructs that will be used by our algorithm, then we present and describe our algorithm. 5.1 Definitions In this work, we are only targeting natural structured loops [3]. Such loops are single-entry single-exit CFG sub-graphs with one entry block and possibly several back edges leading to the header from inside of the loop. break and continue statements can be preprocessed to comply with this restriction, but we plan to lift it altogether in the future. Treegion The canonical definition of a treegion is a non-linear, single-entry multiple-exit region of code containing basic blocks that constitute a sub-graph of the CFG. We alter this definition to bear on the Control-Dependence Graph (CDG) instead, so we will be looking at single-entry multiple-exit sub-graphs of the CDG. Loop Control Node In the representation we employ later, we will use the loop control node to represent the loop. The loop control node include statements which will evaluate the loop control expression and determines the next iteration. Although control dependences in loops can be handled by the standard algorithm by converting them to a control flow graph, there are advantages in treating them as a special case with coalescing them in a single node (loop control node): not only the backward dependence is removed by building the loop control node so that the control dependence graph will form a tree, but also, this node can be used to represent the loop in all sort of transformations. Conditional Level The control dependence graph of the structured code is a tree after building the loop control node. The root of the tree is the loop control node at the loop’s outermost level. We define the conditional level for every node in the control dependence graph as the depth of the node in the tree. The root of the tree with depth 0 has conditional level 0. We define the conditional level for the treegion is the conditional level of the root node of the treegion (subtree). We define treegion\_M to identify a treegion where M is the conditional level of the treegion and M is the root node number of the treegion. 5.2 The algorithm The algorithm takes an SSA representation of a single function, and returns a concurrent representation annotated with tasks and communication streams. Step 1: Transform Conditional Statements to Conditional Variables To achieve fine-grained pipelining, conditional statements are split to conditional variables. As showed in Figure 10. Full conversion to three-address SSA form is also possible (as it is performed in GCC or LLVM, for example). ```c if (condition(i)) //is transformed to cl = condition(i) if (cl) ``` Figure 10. Split conditional statements to expose finer grained pipelining. Step 2: Build the Program Dependence Graph under SSA By building the program dependence graph, the control dependence graph, data dependence graph (through memory) and scalar dependence graph (through registers) are built together. The control dependence graph for the structured code is a tree, the root of the tree is the loop control node. The leaves of the tree are non-conditional statements and the other nodes inside the tree are the conditional statements or the loop control node of the inner loops. We start from building the control dependence graph, and evaluate the conditional level for each node in the graph. Every node inside the control dependence graph is an statement from the compiler’s intermediate representation of the loop except for the loop control node. The loop control node will be built by searching the strongly connect component started from the loop header node (at each loop nest level) in the program dependence graph. The data dependence graph could be built by the array dependence analysis [9] for the loop. We should analyse every pair of data dependences to mark the irreducible edges in a later step if there are recurrence. Step 3: Marking the Irreducible Edges A partition can preserve all dependences if and only if there exists no dependence cycle spanning more than one output loop [1, 12]. In our case, for the treegion at the same conditional level, if there are dependences that form a cycle, we mark the edges in between as irreducible. If we have statements in different conditional level, we promote the inner one to its ancestor until both of them are in the same treegion, mark the promoted root node and the other root node as irreducible. The algorithms is presented in Figure 11. Step 4: Structured Typed Fusion Before partitioning, to reveal data parallelism, we type every node in the dependences graph as parallel or !parallel. If there are loop-carried dependence inside this node, then it should be typed as !parallel, otherwise, typed as parallel. The parallel type nodes are candidates for data parallelization. The goal is to merge this type of nodes to create the largest parallel loop, reducing synchronization overhead and (generally) improving data locality. Further partitioning can happen in the following step, starting from this maximally type-fused configuration. Given a DAG with edges representing dependences and the vertices representing statements in the loop body, we want to produce an equivalent program with minimal number of parallel loops. We want it to be as large as possible to balance the synchronization. // input: PDG Graph PDG(V,E) PDG--Program Dependence Graph // input: CDG Graph CDG(V,E) CDG--Control Dependence Graph // output: irreducible_edge_set Irreducible_edge_set //SCCs = find_SCCs(PDG) // For each SCC in SCCs: // for each pair of node (Vx,Vy) in SCC: // CL represents for conditional level // in the Control dependence graph. // if they are in the same treegion, merge into one node. if Vy.CL <= Vy.CL: merge_to_one_nodes(Vx, Vy) // levels. And mark the edge between the nodes as irreducible. max_CL = Vx.CL <= Vy.CL? Vx.CL: Vy.CL Vy = up_n_level(CDG, max_CL - Vy.CL) //mark edge (Vx,Vy) irreducible Irreducible_edge_set.insert(edge(Vx,Vy)) Figure 11. Algorithm for marking the irreducible edges. Step 5: Structured Partitioning Algorithms Updating the CDG after typed fusion, start from the treeregion which has conditional level 0 for our partitioning algorithms, and for all of its child treeregions at conditional level 1, we should decide where to partition. The partition point could be any point between each of these treeregions at the same level except the irreducible edges that we have created in step 3. The algorithm may decide at every step if it is desirable to further partition any given task into several sub-tasks. Look at the example Figure 13: ``` for(1...) for (1...) x = work(i) BEGIN task1_1 if (c1) BEGIN task1_1 y = x + i; if (c1) BEGIN task1_2 x = work(i) END task1_1 if (c2) BEGIN task2_2 z = y*y; END task2_1 q = z - y; END task1_2 ``` Figure 13. Before partitioning (left), and After partitioning (right). Loop with control dependences. The code in Figure 13 (left) is partitioned into 2 tasks, and one task (task1_2) is partitioned further into 3 sub-tasks. 6. Code Generation After the partitioning algorithms, we have decided the partition point between the original treeregions, with the support of the stream extension of OpenMP. We ought to generate the code by inserting the input output directives. With the support of nested tasks, relying on the downstream, extended OpenMP compilation algorithm (called OpenMP expansion). But some challenges remain, especially in presence of multiple producers and consumers. We are using SSA form as an intermediate representation and generating the streaming code. 6.1 Decoupling dependences across tasks belonging to different treeregions Clearly if we decouple a dependence between tasks in the same treeregion, the appropriate input and output clauses can be naturally inserted. But what about the communication between tasks at different level? Considering the example in Figure 14, if we decide to partition the loop to 3 main tasks: task1_1 with S1, task1_2 with (S2,S3), and task1_3 with S4, task1_2 is further divided to task2_1 with S3. If we insert the produce and consume directly into the loop, unmatched production and consumption will result. ``` for (...) for (i = 0; i < N; i++) x = work(i) if (c1) begin x = consume(stream_x, x) y = x + i; end if (c1) begin x = consume(stream_x, x) end if (c1) begin x = consume(stream_y, y) end ``` Figure 14. Normal form of code (left) and using streams (right). The answer comes from following the synchronous hypothesis and slightly modifying the construction of the SSA form in presence of concurrent streaming tasks. 6.2 SSA representation We are using the Static Single Assignment (SSA) form as an intermediate representation for the source code. A program in SSA form if every variable used in the program appears a single time in the left hand side of an assignment. We are using the SSA form to eliminate the output dependences in the code, and to disambiguate the flow of data across tasks over multiple producer configurations. ```c /* Normal form of the code. */ /* Code under SSA form. */ S1: r1 = ... S2: if (condition) r1 = ... S3: r1 = ... S4: ... = r1 S5: r1_3 = phi(r1_1, r1_2) S6: ... = r1_3 Figure 15. Normal form of code (left) and SSA form of the code (right). ``` Considering the example in Figure 15, if we partition the statements into (S1), (S2,S3), (S4), we need to implement precedence constraints for the output dependence between partition (S1) and (S2,S3), which decreases the degree of parallelism and induces synchronization overhead. Eliminating the output dependences with the SSA form leads to the introduction of multiple streams in the partitioned code. In order to merge the information coming from different control flow branches, a $\Phi$ node is introduced in the SSA form. The $\Phi$ function is not normally implemented directly, after the optimizations are completed the SSA representation will be transformed back to ordinary one with additional copies inserted at incoming edges of (some) $\Phi$ functions. We need to handle the case where multiple producers in a given partition reach a single consumer in a different partition. When decoupling a dependence whose sink is a $\Phi$ node, the exact conditional control flow leading to the $\Phi$ node is not accessible for the out-of-SSA algorithm to generate ordinary code. **Task-closed $\Phi$ node** In SSA loop optimization, there is a concept called loop-closed $\Phi$ node, which implements the additional property that no SSA name is used outside of loop where it is defined. When enforcing this property, $\Phi$ nodes must be inserted at the loop exit node to catch the variables that will be used outside of the loop. Here we give a similar definition for task-closed $\Phi$ node: if multiple SSA variables are defined in one partition and used in another, a phi node will be created at the end of the partition for this variable. This is the place where we join/split the stream. We need to make sure that different definitions of the variable will be merged in this partition before it continues to a downstream one. This node will be removed when converting back from SSA. **Task-closed stream** Our partitioning algorithms generate nested pipelining code to guarantee that all communications follow the synchronous hypothesis. For each boundary, if there are one or more definitions of a variable coming through from different partitions, we insert a consumer at this boundary to merge the incoming data, and immediately insert a producer to forward the merged data at the rate of the downstream control flow. 1. When partitioning from a boundary, if inside the treegion, there are multiple definitions of a scalar and it will be used in other treegions which has the same conditional level, we create a $\Phi$ node at the end of this partition to merge all the definitions, and also update the SSA variable in later partitions. 2. If there is a $\Phi$ node at the end of a partition, insert a stream named with the left-hand side variable of the $\Phi$ node. 3. At the place where this variable is used, which is also a $\Phi$ node, add a special stream-$\Phi$ node to consume. 4. To generate code for the stream-$\Phi$, use the boolean condition associated with the conditional phi node it originates from. Let us consider the SSA-form example in Figure 15 where we partition the code into (S1,S2,S3) and (S4,S5). A $\Phi$ node will be inserted at the end of the first partition, $r1_4 = phi(r1_1, r1_2)$, the $\Phi$ node in a later partition should be updated from $r1_3 = \Phi(r1_1, r1_2)$ to $r1_5 = \Phi(r1_4)$. In the second step, we find out that in partition (S1,S2,S3), there is a $\Phi$ node at the end, so we insert a stream to produce there. And in partition (S4,S5), after the $\Phi$ node there is a use of the variable, so we insert a stream consume. The generated code will look like Figure 16. ```c /* Producer. */ /* Consumer. */ S1: r1_1 = ... S2: if (condition) r1_2 = ... S3: ... = r1 S4: r1_3 = phi(r1_1, r1_2) S5: ... = r1_3 S4: r1_6 = phi(r1_4) S5: ... = r1_6 produce(stream_r1_4, r1_4) Figure 16. Apply our algorithm to generate the parallel code. Producer thread (left) and consumer thread (right). ``` This example illustrates the generality of our method and shows how fine-grain pipelines can be built in presence of complex, multi-level control flow. If we decide to partition the statements into (S1), (S2,S3), (S4,S5), which is the case for multiple producers, the generated code will look like in Figure 17. ```c /* Producer 1. */ /* Consumer. */ S1: r1_1 = ... S2: if (condition) r1_2 = ... S3: ... = r1 S4: r1_6 = phi(r1_2, r1_4) produce(stream_r1_2, r1_2) r1_5 = consume(stream_r1_4, i) else S5: ... = r1_6 r1_3 = ... i++ r1_4 = phi(r1_3) produce(stream_r1_4, r1_4) Figure 17. Multiple producers with applied our algorithm, the generated code. ``` For multiple consumers, the stream extension of OpenMP will broadcast to its consumers, which is appropriate for our case. 7. Conclusion In this paper, we propose a method to decouple independent tasks in serial programs, to extract scalable pipelining and data-parallelism. Our method leverages a recent proposition of a stream-processing extension of OpenMP; with a persistent task semantics to eliminate the overhead of scheduled task instances each time a pair of tasks need to communicate. Our method is inspired by the synchronous hypothesis: communicating concurrent tasks share the same control flow. This hypothesis simplifies the coordination of communicating tasks over nested levels of parallelism. Synchrony also facilitates the definition of generalized, structured typed fusion and partition algorithms preserving the loop structure information. These algorithms have been proven to be essential to the adaptation of the grain of parallelism to the target and to the effectiveness of compile-time load balancing. These partitioning algorithms also handle DOALL parallelization inside a task pipeline. We are using a combination of SSA, control dependence tree and (non-scalar) dependence graph as an IR. With the support of SSA, our method eliminates the nested multiple producer and multiple consumer problems of PS-DSWP. SSA also provides additional applicability, elegance and complexity benefits. This work is currently under development in a development branch of GCC, the partitioning algorithms is partially developed. For the code generation part, we first need to migrate the existing OpenMP expansion pass of GCC to work under SSA form, which has been a long-running challenge. When this work is complete, our method will leverage the array data-flow analysis of the Graphite polyhedral compilation pass of GCC to provide more precise data dependence information in loop nests with regular control flow. **Acknowledgments** This work was partly funded by the European FP7 project TERAFLUX id. 240013, http://www.teraflux.eu References
{"Source-Url": "https://hal-mines-paristech.archives-ouvertes.fr/hal-00744090/file/A-462.pdf", "len_cl100k_base": 9098, "olmocr-version": "0.1.53", "pdf-total-pages": 9, "total-fallback-pages": 0, "total-input-tokens": 28798, "total-output-tokens": 10760, "length": "2e13", "weborganizer": {"__label__adult": 0.0003266334533691406, "__label__art_design": 0.0002753734588623047, "__label__crime_law": 0.00029206275939941406, "__label__education_jobs": 0.0003249645233154297, "__label__entertainment": 5.728006362915039e-05, "__label__fashion_beauty": 0.00013303756713867188, "__label__finance_business": 0.00015974044799804688, "__label__food_dining": 0.0003345012664794922, "__label__games": 0.0006012916564941406, "__label__hardware": 0.0012664794921875, "__label__health": 0.0003848075866699219, "__label__history": 0.00021719932556152344, "__label__home_hobbies": 7.76052474975586e-05, "__label__industrial": 0.0004284381866455078, "__label__literature": 0.00016176700592041016, "__label__politics": 0.00026154518127441406, "__label__religion": 0.0004799365997314453, "__label__science_tech": 0.01885986328125, "__label__social_life": 6.073713302612305e-05, "__label__software": 0.00496673583984375, "__label__software_dev": 0.96923828125, "__label__sports_fitness": 0.0003190040588378906, "__label__transportation": 0.0005536079406738281, "__label__travel": 0.00020563602447509768}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 44548, 0.04082]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 44548, 0.59204]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 44548, 0.87472]], "google_gemma-3-12b-it_contains_pii": [[0, 1093, false], [1093, 7269, null], [7269, 13955, null], [13955, 18621, null], [18621, 25294, null], [25294, 30781, null], [30781, 34134, null], [34134, 41474, null], [41474, 44548, null]], "google_gemma-3-12b-it_is_public_document": [[0, 1093, true], [1093, 7269, null], [7269, 13955, null], [13955, 18621, null], [18621, 25294, null], [25294, 30781, null], [30781, 34134, null], [34134, 41474, null], [41474, 44548, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 44548, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 44548, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 44548, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 44548, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 44548, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 44548, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 44548, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 44548, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 44548, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 44548, null]], "pdf_page_numbers": [[0, 1093, 1], [1093, 7269, 2], [7269, 13955, 3], [13955, 18621, 4], [18621, 25294, 5], [25294, 30781, 6], [30781, 34134, 7], [34134, 41474, 8], [41474, 44548, 9]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 44548, 0.0]]}
olmocr_science_pdfs
2024-12-07
2024-12-07
5f9c5110e6de988d38550e889f5cb8134c22d187
Advances in Parallel-Stage Decoupled Software Pipelining Leveraging Loop Distribution, Stream-Computing and the SSA Form Feng Li, Antoniu Pop, Albert Cohen To cite this version: HAL Id: hal-00744090 https://hal-mines-paristech.archives-ouvertes.fr/hal-00744090 Submitted on 22 Oct 2012 HAL is a multi-disciplinary open access archive for the deposit and dissemination of scientific research documents, whether they are published or not. The documents may come from teaching and research institutions in France or abroad, or from public or private research centers. L’archive ouverte pluridisciplinaire HAL, est destinée au dépôt et à la diffusion de documents scientifiques de niveau recherche, publiés ou non, émanant des établissements d’enseignement et de recherche français ou étrangers, des laboratoires publics ou privés. Advances in Parallel-Stage Decoupled Software Pipelining Leveraging Loop Distribution, Stream-Computing and the SSA Form Feng Li INRIA feng.li@inria.fr Antoniu Pop Centre de recherche en informatique, MINES ParisTech antoniu.pop@mines-paristech.fr Albert Cohen INRIA albert.cohen@inria.fr Abstract Decoupled Software Pipelining (DSWP) is a program partitioning method enabling compilers to extract pipeline parallelism from sequential programs. Parallel Stage DSWP (PS-DSWP) is an extension that also exploits the data parallelism within pipeline filters. This paper presents the preliminary design of a new PS-DSWP method capable of handling arbitrary structured control flow, a slightly better algorithmic complexity, the natural exploitation of nested parallelism with communications across arbitrary levels, with a seamless integration with data-flow parallel programming environments. It is inspired by loop-distribution and supports nested/structured partitioning along with the hierarchy of control dependences. The method relies on a data-flow streaming extension of OpenMP. These advances are made possible thanks to progresses in compiler intermediate representation. We describe our usage of the Static Single Assignment (SSA) form, how we extend it to the context of concurrent streaming tasks, and we discuss the benefits and challenges for PS-DSWP. Categories and Subject Descriptors D.3.4 [Programming Languages]: Processors-Compilers, Optimization General Terms optimization Keywords automatic parallelization, stream-computing, loop distribution 1. Introduction In recent years, the CPU manufacturers have embraced chip multiprocessors because of technology, power consumption and thermal dissipation constraints, and because of diminishing returns in instruction-level parallelism. The amount of performance gained by the use of multicore processor depends highly on the software fraction that can be parallelized to run on multiple cores simultaneously. Multiprocessor programming leaves the burden to programmer who faces the extra complexity, heisenbugs, deadlocks and other problems associated with parallel programming. The situation is worse when dealing with the migration of legacy code. Decoupled Software Pipelining (DSWP) is an automatic thread partitioning method which could partition a sequential program to run on multiple cores, and Parallel-Stage DSWP (PS-DSWP) exposes data parallelism into task pipelines extracted by DSWP. These automatic thread partitioning methods free the programmer from manual parallelization. They also promise much wider flexibility than data-parallelism-centric methods for processors, aiming for the effective parallelization of general-purpose applications. In this paper, we provide another method to decouple control-flow regions of serial programs into concurrent tasks, exposing pipeline and data parallelism. The power and simplicity of the method rely on the restriction that all streams should retain a synchronous semantics [8]. It amounts to checking the sufficient condition that the source and target of any decoupled dependence are control-dependent on the same node in the control dependence tree (this assumes structured control flow). This restriction may appear as a severe one for experienced parallel programmers; but at the potential expense of adding extra levels of nested parallelism, it does not restrict the degree of pipeline parallelism. In fact, any pair of computational statements can be decoupled and assigned to different concurrent tasks. The partitioning algorithms also handle DOALL parallelization within task pipelines, and arbitrarily nested data-parallel pipelines following the control dependence tree of a structured control flow graph. Unlike existing DSWP algorithms, our method does not explicitly copy conditional expressions and can handle arbitrary backward data and control dependences. We are using two intermediate representations. - A conventional SSA-based representation, annotated with natural loop and control dependence trees (for structured control flow). - And a streaming data-flow extension of the latter representation as a backend for our partitioning algorithm, still in SSA form but with explicit task boundaries (for single-entry single-exit regions) and multi-producer multi-consumer streams to communicate across tasks. The backend representation streamlines the decoupling of multi-producer multi-consumer data flow through explicit, compiler-controlled sampling and merging stages. Multi-producer multi-consumer semantics is absolutely essential to handle general decoupling patterns where data-parallel stages feature an unbalance in the number of worker threads. Sampling is handled transparently by nesting tasks into enclosing control flow. Merging is captured by Φ functions at task boundaries, introducing a minor variant of the SSA form satisfying the so-called task-closed property that multiple incoming flows targeting the same use in a given task should be explicitly merged by a dedicated Φ function at the task entry point. Relying on SSA avoids building the complete program dependence graph; with the exception of the array dependence graph, our method only processes linear-size data structures, as opposed to the worst-case quadratic program dependence graph in DSWP. 2. Related Work The most closely related work to this paper is decoupled software pipelining and loop distribution. We recall the state-of-the-art in both and present the original finding at the source of this work: by extending loop distribution with pipelining and asserting a synchronous concurrency hypothesis, arbitrary data and control dependences can be decoupled very naturally with only minor changes to existing algorithms that have been proposed for loop distribution [10]. 2.1 Decoupled software pipelining Decoupled Software Pipelining (DSWP) [13] is one approach to automatically extract threads from loops. It partitions loops into long-running threads that communicate via inter-core queues. DSWP builds a Program Dependence Graph (PDG) [7], combining control and data dependences (scalar and memory). Then DSWP... introduces a load-balancing heuristic to partition the graph according to the number of cores, making sure no recurrence spans across multiple partitions. In contrast to DOALL and DOACROSS [4] methods which partition the iteration space into threads, DSWP partitions the loop body into several stages connected with pipelining to achieve parallelism. It exposes parallelism in cases where DOACROSS is limited by loop-carried dependences on the critical path. And generally speaking, DSWP partitioning algorithms handles uncounted loops, complex control flow and irregular pointer-based memory accesses. Parallel-Stage Decoupled Software Pipelining [16] (PS-DSWP) is an extension to combine pipeline parallelism with some stages executed in a DOALL, data-parallel fashion. For example, when there are no dependences between loop iterations of a DSWP stage, the incoming data can be distributed over multiple data-parallel worker threads dedicated to this stage, while the outgoing data can be merged to proceed with downstream pipeline stages. These techniques have a few caveats however. They offer limited support for decoupling along backward control and data dependences. They provide a complex code generation method to decouple dependences among source and target statements governed by different control flow, but despite its complexity, this method remains somewhat conservative. By building the PDG, DSWP also incurs a higher algorithmic complexity than typical SSA-based optimizations. Indeed, although traditional loop pipelining for ILP focuses on innermost loops of limited size, DSWP is aimed at processing large control flow graphs after aggressive inter-procedural analysis optimization. In addition, the loops in DSWP are handled by the standard algorithm as ordinary control flow, missing potential benefits of treating them as a special case. To address these caveats, we turned our analysis to the state of the art in loop distribution. 2.2 Loop distribution Loop distribution is a fundamental transformation in program restructuring systems designed to extract data parallelism for vector or SIMD architectures [10]. In its simplest form, loop distribution consists of breaking up a single loop into two or more consecutive loops. When aligning loop distribution to the strongly connected components of the data-dependence graph, one or more of the resulting loops expose iterations that can be run in parallel, exposing data parallelism. Barriers are inserted after the parallel loops to enforce precedence constraints with the rest of the program. An example is presented in Figure 1. ``` for (i = 1; i < N; i++) { S1 A[i] = B[i] + 1; S2 C[i] = A[i-1] + 1; } ``` Figure 1. Barriers inserted after loop distribution. 3. OpenMP Extension for Stream-Computing as a Code Generation Target A recently proposed stream-computing extension to OpenMP [14] allows the expression of pipeline parallelism by making explicit the flow dependences, or producer-consumer patterns, between OpenMP tasks. It provides a simple way for explicitly building dynamic task graphs, where tasks are connected through streams that transparently privatize the data. The extension consists of two additional clauses, input and output to the task construct, that define the producer-consumer relationships between tasks. The OpenMP language, with this extension, is a natural fit as a target for our code generation. It provides for dynamic task creation and connection in the task graph, it handles arbitrary nesting of pipelined tasks in control-flow, and it allows the hierarchical nesting of tasks. The task construct is extended with input and output clauses as presented on Figure 2. Both clauses take a list of items, each of which describes a stream and its behavior w.r.t. the task to which the clause applies. In the abbreviated item form, stream, the stream can only be accessed one element a time through the same variable a. In the second form, stream >> window, the programmer uses the C++ flavoured >> stream operators to connect a sliding window to a stream, gaining access, within the body of the task, to horizon elements in the stream. Figure 2. Syntax for input and output clauses. One of the main issues that needs to be addressed in order to distribute a PDG to the OpenMP stream-computing extension is that, in the latter, the data flow bypasses the control flow. In other words, when a task produces values on an output stream, these values will all reach the consumers of the stream, even if, in the serial semantics, the values would have been overwritten before reaching the consumers. This means that the only case where a direct annotation scheme will work is if all tasks are in the same control flow. There are multiple ways this issue can be handled, the most systematic one being to always ensure that every producer-consumer pair share the same control dependence. This is achieved by sinking all control flow surrounding the tasks, and not shared by both producer and consumer, in the tasks. To avoid the loss of parallelization opportunities, each task’s body can be further partitioned into nested pipelines. The GCC implementation of the OpenMP extension for stream-computing has been shown to be efficient to exploit mixed pipeline-and data-parallelism, even in dynamic task graphs [14]. It relies on compiler and runtime optimizations to improve cache locality and relies on a highly efficient lock-free and atomic operation-free synchronization algorithm for streams. 4. Observations It is quite intuitive that the typical synchronization barriers in between distributed data-parallel loops can be weakened, resulting into data-parallel pipelines. We aim to provide a comprehensive treatment of this transformation, generalizing PS-DSWP in the process. 4.1 Replacing loops and barriers with a task pipeline In the previous example, we could remove the barriers between two distributed loops with pipelining so that the two loops could run in parallel. ``` // Initialize the stream, inserting a delay. */ void INIT_STREAM() { produce(stream, A[0]); } // Decoupled producer and consumer. */ for (i = 1; i < N; i++) { S1 A[i] = B[i] + 1; produce(stream, A[i]); } ``` Figure 3. Pipelining inserted between distributed loops. Initialize the stream (left), producer and consumer thread (right). Figure 3 shows that pipelined execution is possible: the INIT_STREAM function inserts one delay into a communication stream; the produce/consume primitives implement a FIFO, enforcing the precedence constraint of the data dependence on array \( A \) and communicating the value in case the hardware needs this information. When distributing loops, scalar and array expansion (privatization) is generally required to eliminate memory-based dependences. The conversion to a task pipeline avoids this complication through the usage of communication streams. This transformation can be seen as an optimized version of scalar/array expansion in bounded memory and with improved locality [15]. 4.2 Extending loop distribution to PS-DSWP The similarity between DSWP and distributed loops with data-parallel pipelines is striking. First, both of them partition the loop into multiple threads. Second, both of them avoid partitioning the loop iteration space: they partition the instructions of the loop body instead. But four arguments push in favor of refining DSWP in terms of loop distribution. 1. Loop distribution leverages the natural loop structure, where the granularity of thread partitioning can be easily controlled. Moreover, it is useful to have a loop control node to which to attach information about the iteration of the loop, including closed forms of induction variables; this node can also be used to represent the loop in additional transformations. 2. Using a combination of loop distribution and fusion, then replacing barriers with pipelining leads to an incremental path in compiler construction. This path leverages existing intermediate representations and loop nest optimizers, while DSWP relies on new algorithms and a program dependence graph. 3. Considering the handling of control dependences, a robust and general algorithm already exists for loop distribution. McKinley and Kennedy’s technique handles arbitrary control flow [10] and provides a comprehensive solution. The same methods could be applied for DSWP, transforming control dependences into data dependences, and storing boolean predicates into stream. After restructuring the code, updating the control dependence graph and data dependence graph, the code generation algorithm for PDGs [2, 5, 6] can be used to generate parallel code. This solution would handle all cases where the current DSWP algorithm fails to clone a control condition. 4. Since loop distribution does not partition the iteration space, it can also be applied to uncounted loops. Unfortunately, the termination condition needs to be propagated to downstream loops. This problem disappears through the usage of a conventional communication stream when building task pipelines. From this high-level analysis, it appears possible to extend loop distribution with pipelining to implement PS-DSWP and handle arbitrary control dependences. Yet the method still seems rather complex, especially the if-conversion of control dependences and the code generation step from the PDG. We go one step further and propose a new algorithm adapted from loop distribution but avoiding these complexities. 4.3 Motivating example Our method makes one more assumption to reduce complexity and limit risks of overhead. It amounts to enforcing the synchronous hypothesis on all communicating tasks in the partition [8]. A sufficient condition is to check if the source and target of any decoupled dependence is dependent on the same control node. Consider the example in Figure 4. S1 and S7 implement the loop control condition and induction variable, respectively. S2, S3 and S6 are control dependent on S1. S3 is a conditional node, S4, S5 and L1 are control dependent on it. In the inner loop, L2 and L3 are control dependent on L1. When we apply DSWP to the outer loop, the control dependences originating from S1 must be if-converted by creating several streams (the number of streams depends on the number of partitions). When decoupling along the control dependence originating from S3, a copy of the conditional node must be created as well as another stream. ![Figure 4. Uncounted nested loop before partitioning.](image) ![Figure 5. Uncounted nested loop in SSA form.](image) ![Figure 6. Loops after partitioning and annotated with OpenMP stream extension.](image) partitioning technique will build a stream to communicate this condition from its definition site to the cond-Φ node’s task. We build on the concept of treegion, a single-entry multiple-exit control-flow region induced by a sub-tree of the control dependence graph. In the following, we assume the control flow is structured, which guarantees that the control dependence graph forms a tree. Every sub-tree can be partitioned into concurrent tasks according to the control dependences originating from its root. Any data dependence connecting a pair of such tasks induces communication over a dedicated stream. We call taskM_1_h the h-th task at level M of the control flow tree. In Figure 5, after building the control dependence tree, one may partition it into 3 tasks (task1_1, task1_2 and task1_3) at the root level, and for task1_2, one may further partition this task into inner nested tasks task2_1 and task2_2. One may then check for data parallelism in the inner loops: if they do not carry any dependence, one may isolate them in additional data-parallel tasks, such as task3_1 in this example. Figure 6 shows the task and stream-annotated code using an OpenMP syntax. Figure 7 shows the nested pipelining and data parallelization corresponding to the partitioned code. The main task will be executed first, and a pipeline will be created for the main task and its inner tasks three task1_1, task1_2 and task1_3. Among these, the same variable x used to be defined in the control flow regions of both task1_1 and task1_2, to be used in task1_3. This output dependence must be eliminated prior to partitioning into tasks, so that task1_1 and task1_2 could be decoupled, while task1_3 may decide which value to use internally. Nested tasks are introduced to provide fine-grained parallelism. It is of course possible to adapt the partition and the number of nesting levels according to the load balancing and synchronization overhead. The generated code will be well structured, and simple top-down heuristics can be used. In the execution model of OpenMP 3.0, a task instance is created whenever the execution flow of a thread encounters a task construct; no ordering of tasks can be assumed. Such an execution model is well suited for unbalanced loads, but the overhead of creating tasks is significantly more expensive than synchronizing persistent tasks. To improve performance, we use the persistent task model for pipelining, in which a single instance will handle the full iteration space, consuming data on the input stream and providing results on the output stream. The systematic elimination of output dependences is also facilitated by the SSA form, with a Φ node in task3_1. Notice that the conditional expression from which this Φ node selects one or another input also needs to be communicated through a data stream. When modifying loop distribution to rely on tasks and pipelining rather than barriers, it is not necessary to distribute the loop control node and one may run it all in the master task, which in turn will activate tasks for the inner partitions. The statements inside each partition form a treegion whose root is the statement that is dependent on the loop control node. With pipelining inserted, distributed loops could be connected with pipelining when there are data dependences. One concern here is that loop distribution with task pipelines may not provide expressiveness to extract pipeline parallelism. This is not a problem however, since we may apply the same method to every conditional statement rooted treegion, with some special care to the nested tasks, we could get finer grained parallelism without explicitly decoupling the control dependences. Considering again the example in Figure 4, its control dependence tree is given in Figure 9. The root treegion includes all the nodes in the control dependence graph, treegion1_2 represents the treegion at conditional level 1 and its root is node 2, treegion1_3 is at conditional level 1 and includes nodes (S3, S4, S5, L1, L2, L3). treegion2_1 is in conditional level 2 and its root is node (L1), which is the loop control node of the inner loop. So following our approach, we may start from the treegion at conditional level 0, which is the whole loop, an implicit task will be created as the master task. For the treegions at level 1, we could create them as sub-tasks running at the context of the main task. If there are data dependencies between the treegions at the same level and without recurrence, we will connect them with communication streams. If there is a dependence from the master task to one inner task, the value from the enclosing context can be forwarded to the inner task like in a firstprivate clause of OpenMP. Dependences from an inner task to the master task are also supported, although lastprivate is not natively supported for OpenMP 3.0 tasks. It is a necessary component of our streaming task representation. lastprivate(x) is associated with a synchronization point at the end of the task and makes the value of x available to the enclosing context. The same algorithms could be recursively applied to the treegion at the next inner level. e.g. For treegion_3 at level 1, the sub treegion at level 2 is... ### 5. Partitioning Algorithm In this section, we present our partitioning algorithm, based on the SSA and treegion representations. We define our model and the important constructs that will be used by our algorithm, then we present and describe our algorithm. #### 5.1 Definitions In this work, we are only targeting natural structured loops [3]. Such loops are single-entry single-exit CFG sub-graphs with one entry block and possibly several back edges leading to the header from inside of the loop. break and continue statements can be preprocessed to comply with this restriction, but we plan to lift it altogether in the future. **Treegion** The canonical definition of a treegion is a non-linear, single-entry multiple-exit region of code containing basic blocks that constitute a sub-graph of the CFG. We alter this definition to bear on the Control-Dependence Graph (CDG) instead, so we will be looking at single-entry multiple-exit sub-graphs of the CDG. **Loop Control Node** In the representation we employ later, we will use the loop control node to represent the loop. The loop control node include statements which will evaluate the loop control expression and determines the next iteration. Although control dependences in loops can be handled by the standard algorithm by converting them to a control flow graph, there are advantages in treating them as a special case with coalescing them in a single node (loop control node): not only the backward dependence is removed by building the loop control node so that the control dependence graph will form a tree, but also, this node can be used to represent the loop in all sort of transformations. **Conditional Level** The control dependence graph of the structured code is a tree after building the loop control node. The root of the tree is the loop control node at the loop’s outermost level. We define the conditional level for every node in the control dependence graph as the depth of the node in the tree. The root of the tree with depth 0 has conditional level 0. We define the conditional level for the treetregion is the conditional level of the root node of the treetregion (subtree). We define treegion2_N to identify a treetregion where N is the conditional level of the treetregion and H is the root node number of the treetregion. #### 5.2 The algorithm The algorithm takes an SSA representation of a single function, and returns a concurrent representation annotated with tasks and communication streams. **Step 1: Transform Conditional Statements to Conditional Variables** To achieve fine-grained pipelining, conditional statements are split to conditional variables. As showed in Figure 10. Full conversion to three-address SSA form is also possible (as it is performed in GCC or LLVM, for example). ```plaintext if (condition(i)) //is transformed to cl = condition(i) if (cl) ``` **Step 2: Build the Program Dependence Graph under SSA** By building the program dependence graph, the control dependence graph, data dependence graph (through memory) and scalar dependence graph (through registers) are built together. The control dependence graph for the structured code is a tree, the root of the tree is the loop control node. The leaves of the tree are non-conditional statements and the other nodes inside the tree are the conditional statements or the loop control node of the inner loops. We start from building the control dependence graph, and evaluate the conditional level for each node in the graph. Every node inside the control dependence graph is an statement from the compiler’s intermediate representation of the loop except for the loop control node. The loop control node will be built by searching the strongly connect component started from the loop header node (at each loop nest level) in the program dependence graph. The data dependence graph could be built by the array dependence analysis [9] for the loop. We should analyse every pair of data dependences to mark the irreducible edges in a later step if there are recurrence. **Step 3: Marking the Irreducible Edges** A partition can preserve all dependences if and only if there exists no dependence cycle spanning more than one output loop [1, 12]. In our case, for the treegion at the same conditional level, if there are dependences that form a cycle, we mark the edges in between as irreducible. If we have statements in different conditional level, we promote the inner one to its ancestor until both of them are in the same treegion, mark the promoted root node and the other root node as irreducible. The algorithms is presented in Figure 11. **Step 4: Structured Typed Fusion** Before partitioning, to reveal data parallelism, we type every node in the dependences graph as parallel or !parallel. If there are loop-carried dependence inside this node, then it should be typed as !parallel, otherwise, typed as parallel. The parallel type nodes are candidates for data parallelization. The goal is to merge this type of nodes to create the largest parallel loop, reducing synchronization overhead and (generally) improving data locality. Further partitioning can happen in the following step, starting from this maximally type-fused configuration. Given a DAG with edges representing dependences and the vertices representing statements in the loop body, we want to produce an equivalent program with minimal number of parallel loops. We want it to be as large as possible to balance the synchronization... Step 5: Structured Partitioning Algorithms Updating the CDG after typed fusion, start from the treecregion which has conditional level 0 for our partitioning algorithms, and for all of its child treesregions at conditional level 1, we should decide where to partition. The partition point could be any point between each of these treesregions at the same level except the irreducible edges that we have created in step 3. The algorithm may decide at every step if it is desirable to further partition any given task into several sub-tasks. Look at the example Figure 13: for(1...) for (1...) \[ x = \text{work}(i) \] \[ x = \text{work}(i) \] BEGIN task1_1 BEGIN task1_2 \[ if \ (c1) \] \[ if \ (c1) \] \[ y = x + i; \] \[ y = x + i; \] BEGIN task2_1 END task2_1 \[ if \ (c2) \] \[ if \ (c2) \] \[ z = y*y; \] \[ z = y*y; \] BEGIN task2_2 END task2_2 \[ q = z - y; \] \[ q = z - y; \] BEGIN task2_3 END task2_3 END task1_2 Figure 13. Before partitioning (left), and After partitioning (right). Loop with control dependences. The code in Figure 13 (left) is partitioned into 2 tasks, and one task (task1_2) is partitioned further into 3 sub-tasks. 6. Code Generation After the partitioning algorithms, we have decided the partition point between the original treesregions, with the support of the stream extension of OpenMP. We ought to generate the code by inserting the input output directives. With the support of nested tasks, relying on the downstream, extended OpenMP compilation algorithm (called OpenMP expansion). But some challenges remain, especially in presence of multiple producers and consumers. We are using SSA form as an intermediate representation and generating the streaming code. 6.1 Decoupling dependences across tasks belonging to different treesregions Clearly if we decouple a dependence between tasks in the same treesregion, the appropriate input and output clauses can be naturally inserted. But what about the communication between tasks at different level? Considering the example in Figure 14, if we decide to partition the loop to 3 main tasks: task1_1 with S1, task1_2 with (S2,S3), and task1_3 with S4, task1_2 is further divided to task2_1 with S3. If we insert the produce and consume directly into the loop, unmatched production and consumption will result. for (i=0; i < N; i++) \[ S1 \ x = \text{work}(i) \] \[ S1 \ x = \text{work}(i) \] \[ \text{produce}(\text{stream}_x, x) \] \[ \text{produce}(\text{stream}_x, x) \] \[ \text{//task1_1 end} \] \[ \text{//task1_1 end} \] \[ S2 \ if \ (c1) \] \[ S2 \ if \ (c1) \] \[ S3 \ y = x + i; \] \[ S3 \ y = x + i; \] \[ \text{produce}(\text{stream}_x, y) \] \[ \text{produce}(\text{stream}_x, y) \] \[ \text{//task2_2 start} \] \[ \text{//task2_2 start} \] \[ \text{//task2_1 start} \] \[ \text{//task2_1 start} \] \[ \text{//task2_1 end} \] \[ \text{//task2_1 end} \] \[ \text{//task2_1 end} \] \[ \text{//task2_1 end} \] \[ \text{//task3 end} \] \[ \text{//task3 end} \] \[ \text{//task3 end} \] \[ \text{//task3 end} \] \[ S4 \ y = x + i; \] \[ S4 \ y = x + i; \] \[ \text{produce}(\text{stream}_y, y) \] \[ \text{produce}(\text{stream}_y, y) \] \[ \text{//task3_3 end} \] \[ \text{//task3_3 end} \] \[ \text{//task3_3 end} \] \[ \text{//task3_3 end} \] \[ \text{//task3_3 end} \] \[ \text{//task3_3 end} \] \[ \text{//task3_3 end} \] \[ \text{//task3_3 end} \] Figure 14. Normal form of code (left) and using streams (right). The answer comes from following the synchronous hypothesis and slightly modifying the construction of the SSA form in presence of concurrent streaming tasks. Figure 11. Algorithm for marking the irreducible edges. Figure 12. Structured typed fusion algorithm. 6.2 SSA representation We are using the Static Single Assignment (SSA) form as an intermediate representation for the source code. A program in SSA form if every variable used in the program appears a single time in the left-hand side of an assignment. We are using the SSA form to eliminate the output dependences in the code, and to disambiguate the flow of data across tasks over multiple producer configurations. ```c /* Normal form of the code. */ /* Code under SSA form. */ S1: r1 = ... S1: r1 = ... S2: if (condition) S2: if (condition) S2: r1 = ... S2: r1 = ... S3: ... = r1 S3: ... = r1 S4: ... = r1 S4: r1_3 = phi(r1_1, r1_2) S5: ... = r1_3 ``` Figure 15. Normal form of code (left) and SSA form of the code (right). Considering the example in Figure 15, if we partition the statements into (S1), (S2,S3), (S4), we need to implement precedence constraints for the output dependence between partition (S1) and (S2,S3), which decreases the degree of parallelism and induces synchronization overhead. Eliminating the output dependences with the SSA form leads to the introduction of multiple streams in the partitioned code. In order to merge the information coming from different control flow branches, a $\Phi$ node is introduced in the SSA form. The $\Phi$ function is not normally implemented directly, after the optimizations are completed the SSA representation will be transformed back to ordinary one with additional copies inserted at incoming edges of (some) $\Phi$ functions. We need to handle the case where multiple producers in a given partition reach a single consumer in a different partition. When decoupling a dependence whose sink is a $\Phi$ node, the exact conditional control flow leading to the $\Phi$ node is not accessible for the out-of-SSA algorithm to generate ordinary code. **Task-closed $\Phi$ node** In SSA loop optimization, there is a concept called loop-closed $\Phi$ node, which implements the additional property that no SSA name is used outside of loop where it is defined. When enforcing this property, $\Phi$ nodes must be inserted at the loop exit node to catch the variables that will be used outside of the loop. Here we give a similar definition for task-closed $\Phi$ node: if multiple SSA variables are defined in one partition and used in another, a phi node will be created at the end of the partition for this variable. This is the place where we join/split the stream. We need to make sure that different definitions of the variable will be merged in this partition before it continues to a downstream one. This node will be removed when converting back from SSA. **Task-closed stream** Our partitioning algorithms generate nested pipelining code to guarantee that all communications follow the synchronous hypothesis. For each boundary, if there are one or more definitions of a variable coming through from different partitions, we insert a consumer at this boundary to merge the incoming data, and immediately insert a producer to forward the merged data at the rate of the downstream control flow. 1. When partitioning from a boundary, if inside the treegion, there are multiple definitions of a scalar and it will be used in other treegions which has the same conditional level, we create a $\Phi$ node at the end of this partition to merge all the definitions, and also update the SSA variable in later partitions. 2. If there is a $\Phi$ node at the end of a partition, insert a stream named with the left-hand side variable of the $\Phi$ node. 3. At the place where this variable is used, which is also a $\Phi$ node, add a special stream-$\Phi$ node to consume. 4. To generate code for the stream-$\Phi$, use the boolean condition associated with the conditional phi node it originates from. Let us consider the SSA-form example in Figure 15 where we partition the code into (S1,S2,S3) and (S4,S5). A $\Phi$ node will be inserted at the end of the first partition, $r_1_4 = phi(r_1_1, r_1_2)$. The $\Phi$ node in a later partition should be updated from $r_1_3 = \Phi(r_1_1, r_1_2)$ to $r_1_5 = \Phi(r_1_4)$. In the second step, we find out that in partition (S1,S2,S3), there is a $\Phi$ node at the end, so we insert a stream to produce there. And in partition (S4,S5), after the $\Phi$ node there is a use of the variable, so we insert a stream consume. The generated code will look like Figure 16. ```c /* Producer. */ /* Consumer. */ S1: r1_1 = ... S4: r1_6 = phi(r1_4) S2: if (condition) r1_5 = consume(stream_r1_4, 1) S2: r1_2 = ... if (condition) S3: r1_4 = phi(r1_1, r1_2) S4: r1_5 = consume(stream_r1_4, 1) S5: ... = r1_6 produce(stream_r1_4, r1_4) ``` Figure 16. Apply our algorithm to generate the parallel code. Producer thread (left) and consumer thread (right). This example illustrates the generality of our method and shows how fine-grain pipelines can be built in presence of complex, multi-level control flow. If we decide to partition the statements into (S1), (S2,S3), (S4,S5), which is the case for multiple producers, the generated code will look like in Figure 17. ```c /* Producer */ /* Consumer */ S1: r1_1 = ... S4: r1_6 = phi(r1_4) S1: r1_2 = phi(r1_1) r1_5 = consume(stream_r1_4, 1) S2: if (condition) else S3: r1_4 = phi(r1_1, r1_2) S4: r1_5 = consume(stream_r1_4, 1) S5: ... = r1_6 produce(stream_r1_4, r1_4) ``` Figure 17. Multiple producers with applied our algorithm, the generated code. For multiple consumers, the stream extension of OpenMP will broadcast to its consumers, which is appropriate for our case. 7. Conclusion In this paper, we propose a method to decouple independent tasks in serial programs, to extract scalable pipelining and data-parallelism. Our method leverages a recent proposition of a stream-processing extension of OpenMP, with a persistent task semantics to eliminate the overhead of scheduling task instances each time a pair of tasks need to communicate. Our method is inspired by the synchronous hypothesis: communicating concurrent tasks share the same control flow. This hypothesis simplifies the coordination of communicating tasks over nested levels of parallelism. Synchrony also facilitates the definition of generalized, structured typed fusion and partition algorithms preserving the loop structure information. These algorithms have been proven to be essential to the adaptation of the grain of parallelism to the target and to the effectiveness of compile-time load balancing. These partitioning algorithms also handle DOALL parallelization inside a task pipeline. We are using a combination of SSA, control dependence tree and (non)-dependence dependence graph as an IR. With the support of SSA, our method eliminates the nested multiple producer and multiple consumer problems of PS-DSWP. SSA also provides additional applicability, elegance and complexity benefits. This work is currently under development in a development branch of GCC, the partitioning algorithms is partially developed. For the code generation part, we first need to migrate the existing OpenMP expansion pass of GCC to work under SSA form, which has been a long-running challenge. When this work is complete, our method will leverage the array data-flow analysis of the Graphite polyhedral compilation pass of GCC to provide more precise data dependence information in loop nests with regular control flow. Acknowledgments This work was partly funded by the European FP7 project TERAFLUX id. 249013, http://www.teraflux.eu References
{"Source-Url": "https://hal-mines-paristech.archives-ouvertes.fr/hal-00744090/file/A-462.pdf", "len_cl100k_base": 8813, "olmocr-version": "0.1.49", "pdf-total-pages": 9, "total-fallback-pages": 0, "total-input-tokens": 28870, "total-output-tokens": 10602, "length": "2e13", "weborganizer": {"__label__adult": 0.00033211708068847656, "__label__art_design": 0.00028228759765625, "__label__crime_law": 0.0002956390380859375, "__label__education_jobs": 0.0003590583801269531, "__label__entertainment": 5.894899368286133e-05, "__label__fashion_beauty": 0.00013756752014160156, "__label__finance_business": 0.0001748800277709961, "__label__food_dining": 0.0003352165222167969, "__label__games": 0.0006084442138671875, "__label__hardware": 0.0013742446899414062, "__label__health": 0.00039887428283691406, "__label__history": 0.00023162364959716797, "__label__home_hobbies": 8.374452590942383e-05, "__label__industrial": 0.0004754066467285156, "__label__literature": 0.00016736984252929688, "__label__politics": 0.0002696514129638672, "__label__religion": 0.0004911422729492188, "__label__science_tech": 0.0245361328125, "__label__social_life": 6.473064422607422e-05, "__label__software": 0.005306243896484375, "__label__software_dev": 0.962890625, "__label__sports_fitness": 0.000316619873046875, "__label__transportation": 0.0005931854248046875, "__label__travel": 0.00021004676818847656}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 43057, 0.04402]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 43057, 0.56379]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 43057, 0.86842]], "google_gemma-3-12b-it_contains_pii": [[0, 1154, false], [1154, 7332, null], [7332, 13822, null], [13822, 18016, null], [18016, 23264, null], [23264, 28762, null], [28762, 32498, null], [32498, 39956, null], [39956, 43057, null]], "google_gemma-3-12b-it_is_public_document": [[0, 1154, true], [1154, 7332, null], [7332, 13822, null], [13822, 18016, null], [18016, 23264, null], [23264, 28762, null], [28762, 32498, null], [32498, 39956, null], [39956, 43057, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 43057, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 43057, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 43057, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 43057, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 43057, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 43057, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 43057, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 43057, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 43057, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 43057, null]], "pdf_page_numbers": [[0, 1154, 1], [1154, 7332, 2], [7332, 13822, 3], [13822, 18016, 4], [18016, 23264, 5], [23264, 28762, 6], [28762, 32498, 7], [32498, 39956, 8], [39956, 43057, 9]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 43057, 0.0]]}
olmocr_science_pdfs
2024-11-24
2024-11-24
737e5071650046ff31f144087702cbe339359309
Open Source Solutions for Building IaaS Clouds Original Availability: This version is available at: 11583/2654067 since: 2016-10-24T11:34:12Z Publisher: Open Journal Systems 2.3.3.3 Published DOI:10.12694 Terms of use: openAccess This article is made available under terms and conditions as specified in the corresponding bibliographic description in the repository Publisher copyright (Article begins on next page) 05 December 2018 OPEN SOURCE SOLUTIONS FOR BUILDING IAAS CLOUDS AMINE BARKAT, ALYSSON DINIZ DOS SANTOS AND SONIA IKKEN Abstract. Cloud Computing is not only a pool of resources and services offered through the internet, but also a technology solution that allows optimization of resources use, costs minimization and energy consumption reduction. Enterprises moving towards cloud technologies have to choose between public cloud services, such as: Amazon Web Services, Microsoft Cloud and Google Cloud services, or private self built clouds. While the firsts are offered with affordable fees, the others provide more privacy and control. In this context, many open source softwares approach the building of private, public or hybrid clouds depending on the users need and on the available capabilities. To choose among the different open source solutions, an analysis is necessary in order to select the most suitable according with the enterprise’s goals and requirements. In this paper, we present a depth study and comparison of five open source frameworks that are gaining more attention recently and growing fast: CloudStack, OpenStack, Eucalyptus, OpenNebula and Nimbus. We present their architectures and discuss different properties, features, useful information and our own insights on these frameworks. Key words: Cloud Computing, IaaS, OpenStack, CloudStack, Eucalyptus, OpenNebula, Nimbus AMS subject classifications. 68M14 1. Introduction. Open source cloud platforms were born as a response to the necessity of Infrastructure as a Service (IaaS) solutions to provide privacy and control over virtualized environments. Therefore the open source cloud platforms were primely used to build private clouds. Eventually, these open source solutions can be used to set up public clouds, private clouds or a mix of them, i.e., hybrid clouds. With the emergence of different open source cloud solutions, the decision to choose the most suitable one becomes a confusing task, given the specific characteristics of each platform [18]. Moreover, since hybrid clouds are the most widely used nowadays, surveying open source middlewares that simplify cluster management is an important matter. In this context, several papers analyzed and compared different platform, trying to establish a starting point to look when deciding which open source cloud technology should be adopted. Diverse researches detail comparison among cloud solution platforms. Table 1.1 shows related studies that compare cloud solutions, highlighting the analyzed solutions and their main focus/limitation. Some studies are generalists on the approach and intend to provide a wide view on cloud solutions. Therefore they briefly present a higher number of solutions, with no comparison - the case in [33, 34] - or with a simple general feature comparison, as in [35]. More specific studies tend to deeper detail the analyzed solutions, considering a specific point of view. [11] focus on appearance design and novel features, while [32] focus on the scalability comparison of the platforms and [37] on placement policies, platform architecture and networking of the analyzed solutions. [13] details OpenStack and CloudStack solutions, but with deeper details only for OpenStack. [28] provide a comparison of Eucalyptus, OpenNebula and Nimbus systems. The authors describe the different features and design, accurately highlighting tendencies in the focus of each of these products. Nevertheless, the study is outdated and missing two important open source solutions that gained importance since the publication of the paper, OpenStack and CloudStack. In this context, this work is focused in IaaS open source cloud solutions. It presents in deep details the newest versions of OpenStack, CloudStack, OpenNebula, Eucalyptus and Nimbus and compare their general features and important properties, trying to provide useful information for users that need to choose an open source cloud software. This work is a continuation of the work done before [12], which compared only CloudStack and Openstack. The architecture is organized as follows: Sections 2, 3, 4, 5 and 6 describe respectively the architecture of OpenStack, CloudStack, Eucalyptus, OpenNebula and Nimbus and their important properties; Section 7 performs <table> <thead> <tr> <th>Study</th> <th>Analyzed platforms</th> <th>Main restriction</th> </tr> </thead> <tbody> <tr> <td>Voras et al. (2011) [33]</td> <td>OpenNebula, Eucalyptus, Ubuntu Enterprise Cloud, openQRM, Abiquo, Red Hat Cloud Foundations, OpenStack, Nimbus and mOSAIC</td> <td>Brief introduction on any solution, no comparison provided</td> </tr> <tr> <td>Zeng et al. (2012) [34]</td> <td>Amazon EC2, IBM smart cloud, Google App Engine, Windows Azure, Hadoop, Eucalyptus, OpenNebula and Nimbus</td> <td>Brief introduction on any solution, no comparison provided</td> </tr> <tr> <td>Endo et al. (2010) [35]</td> <td>XCP, Nimbus, OpenNebula, Eucalyptus, TPlatform, ECP (Enomalys Elastic Computing Platform) and Apaches VCL</td> <td>Brief introduction on any solution, brief comparison provided</td> </tr> <tr> <td>Amrani et al. (2012) [11]</td> <td>Eucalyptus, OpenNebula and Nimbus</td> <td>Restricted to appearance design and new features description</td> </tr> <tr> <td>Von Laszewski et al. (2012)</td> <td>Eucalyptus, OpenNebula, Nimbus and OpenStack</td> <td>Focus on scalability</td> </tr> <tr> <td>Cordeiro et al. (2010) [37]</td> <td>XCP, Eucalyptus and OpenNebula</td> <td>Focus on placement policies, platform architecture and networking</td> </tr> <tr> <td>Baset (2012) [13]</td> <td>OpenStack and CloudStack</td> <td>Further details only on OpenStack</td> </tr> <tr> <td>Sempolinsky and Thain (2010)</td> <td>Eucalyptus, OpenNebula and Nimbus</td> <td>Outdated, missing OpenStack and CloudStack</td> </tr> </tbody> </table> comparisons between the platforms in terms of generalities, functionalities and proprieties. Conclusions are detailed on Section 8. 2. OpenStack. OpenStack is a cloud software that offers capability to control large pools of compute, storage and networking resources. It also empowers users providing on-demand resources [29]. Starting from 2010, OpenStack was developed by Rackspace Hosting and NASA [6] aimed to provide open source cloud solution to build public or private clouds. The mission of OpenStack is to enable any organization to create and offer cloud computing services running on standard hardwares. Provisioned as open source solution, OpenStack is built keeping these core principles in mind: (i) open source: all code will be released under the Apache 2.0 license allowing the community to use it freely; (ii) open design: every 6 months the development community hold a design summit to gather requirements and write specifications for the upcoming releases; (iii) open development: maintains a publicly available source code repository through the entire development process; and (iv) open community: produces a engaged development and user community through an open and transparent process. The first version of OpenStack was entitled Austin and was released in October of 2010. Since then OpenStack adopts a policy of two major releases per year, totaling 11 releases so far (the next one, entitled Liberty, expected to October of 2015). The Austin release of OpenStack had only the object storage (Swift) and compute (Nova) components, and presented important restrictions, like the support of objects limited to 5GB. The support to large files was introduced in the second release, entitled Bexar, together with the image registry and delivery service (Glance). New modules were introduced only on the fifth release, entitled Essex, with the graphical user interface (Horizon) and the security component (Keystone). The sixth release, Folsom, introduced the network as a core OpenStack project (then code-named Quantum, actually Neutron) and the block storage component (Cinder). Folsom was then, the first release to embody the OpenStack three more important modules, Swift, Nova and Neutron. Since this version, all the existent modules were fixed and improved and new shared services were added, such as: metering (Ceilometer) and orchestration (Heat) on the eighth release, Havana; the database service (Trove) on the ninth release, Icehouse; the data processing (Sahara) on the tenth release, Juno; and the bare metal service (Ironic) on the newest version, Kilo. The following Section 2.1 details the components that compound the general architecture of OpenStack. 2.1. General Architecture. As in any cloud platform, the infrastructure underneath OpenStack is standard hardware, which can contain any pieces of physical devices such as servers, disks or network devices. In order to provide cloud services, OpenStack develops virtualization layers, promoting the abstract view of physical infrastructure to end users. These virtualization layers are built up in a multicomponent architecture. The OpenStack architecture consists of three main components: Compute (Nova), Network (Neutron) and Storage (Swift). Beside these three pillars, OpenStack has been developing many other services, each of those designed to work together to provide a complete IaaS solution. The integration of these services is facilitated through public application programming interfaces (APIs) offered by each service [6]. In the following, the detailed description of each component is provided. 2.1.1. Compute (Nova). The Compute component, codenamed Nova and written in Python, is the computing fabric controller responsible for managing large networks of virtual machines (VMs), and eventually to properly schedule VMs among available physical machines (PMs) [6]. Compute is a distributed application that consists of six components: Nova-api, Message Queue, Nova-Compute, Nova-Network, Nova-Volume and Nova-Scheduler. Nova supports the complete life-cycles of an instance in the cloud, starting from the request to initialize a VM until its termination. It follows this architecture: - **Nova-api:** accepts and responds to end user compute API calls. Beside providing its own OpenStack Compute API, Nova-api is compatible with Amazon EC2 API, offering the potential to integrate with Amazon cloud services. It has another special Admin API reserved for privileged users to perform administrative actions. This component also handles the orchestration activities, such as: running an instance and the enforcing policies (e.g. quota checks). - **Nova-compute:** is primarily a worker daemon that creates and terminates VM instances via hypervisor APIs. In order to do so, it accepts actions from the queue and performs system commands to fulfill them, while updating the database state accordingly. OpenStack supports several standard hypervisors (listed in Section 7) while keeping the openness that allows to interface other hypervisors through its standard library. - **Nova-volume:** manages the creation, attachment and detachment of persistent volumes to compute instances. There are two types of block devices supported by a VM instance: (1) Ephemeral storage, which is associated to a single unique instance. One ephemerally stored block device life-cycle is coupled with the instance life-cycle, i.e., when the instance is terminated, data on this storage will also be deleted; (2) Volume storage is persistent and independent from any particular instance. This storage can be used as external disk device where the data stored on it still remains even when the instance is terminated. - **Nova-network:** is a worker daemon that handles network-related tasks. It accepts and performs networking tasks from the queue. Task examples include setting up bridging interfaces or changing iptable rules. - **Nova-schedule:** handles the scheduling of VMs among PMs. While the scheduling algorithms can be defined by users, Nova-schedule supports by default three algorithms: (1) Simple: attempts to find least loaded host, (2) Chance: chooses random available host from service table, (3) Zone: picks random host from within an available zone. By allowing users to define their own scheduling algorithms, this component is important for building fault tolerant and load-balanced systems. - **Queue:** provides a central hub for passing messages between daemons. This is usually implemented with RabbitMQ, but can support any AMPQ message queue. - **Database:** stores most of the build-time and run-time state of a cloud infrastructure. For example, it provides information of the instances that are available for use or in use, networks availability or storage information. Theoretically, OpenStack Nova can support any SQL-based database but the most widely used databases currently are sqlite3, MySQL and PostgreSQL. All the components of the OpenStack architecture follow a shared-nothing and messaging-based policy. Shared-nothing means that each component or each group of components can be installed on any server, in a distributed manner; while the messaging-based policy ensures that the communication among all components is performed via Queue Server. 2.1.2. Network (Neutron). The Network component of any cloud platform has important attributions: (i) to offer accessibility to resources and services; (ii) to provide address binding between different services (essential to support multi-tier applications) and (iii) to automatically configure the network (fundamental in auto-scaling scenarios). The OpenStack Networking component gives operators the ability to leverage different network technologies to power their cloud networking. It does so through a rich set of APIs, multiple networking models (e.g., flat or private network) and flexible plug-in architecture. Especially, the plug-in architecture - with the plug-in agent - enables, not only the usage of various network technologies, but also the ability to handle user workloads. In OpenStack, at network level, developers can implement their own load balancing algorithms and plug it in the platform to achieve better workload control. The Network architecture consists of four distinct physical data center networks: - Management network: used for internal communication between OpenStack components. The IP addresses on this network should be reachable only within the data center. - Data network: used for VM data communication within the cloud deployment. The IP addressing requirements of this network depend on the OpenStack Networking plug-in in use. - External network: used to provide VMs with Internet access in the deployment scenarios. The IP addresses on this network should be reachable by anyone on the Internet. - API network: exposes all OpenStack APIs, including the OpenStack Networking API, to tenants. The IP addresses on this network should be reachable by anyone on the Internet. 2.1.3. Storage. The Storage component, one of three main pillars of OpenStack architecture, is used to manage stored resources. OpenStack has support for both Object Storage and Block Storage, with many deployment options for each, depending on the use case. Object Storage (codename Swift) is a scalable object storage system. It provides a fully distributed, API-accessible storage platform that can be integrated directly into applications or used for backup, archiving, and data retention [6]. In Object Storage, data are written to multiple hardware devices, with the OpenStack software responsible for ensuring data replication and integrity across clusters. Object storage clusters are scaled horizontally while adding new nodes. If a node fails, OpenStack replicates its content from other active nodes. Because OpenStack uses software logic to ensure data replication and distribution, inexpensive commodity hard drives and servers can be used instead of expensive equipments. Therefore, Object Storage is ideal for cost effective, scale-out storage [6]. Block Storage (codename Cinder) allows block devices to be exposed and connected to compute instances for expanded storage, better performance and integration with enterprise storage platforms, such as NetApp, Nexenta and SolidFire [6]. By managing the storage resources in blocks, Block Storage is appropriate for performance sensitive scenarios, such as: database storage, expandable file systems, or the provision of a server with access to raw block level storage. 2.1.4. User interface - Dashboard. The OpenStack dashboard is a graphical user interface, to both administrators and users, that controls compute, storage and networking resources. Through the dashboard, administrators can also manage users and set limits on resources access for each user. 2.1.5. Shared Services. OpenStack Shared services are a set of several services that span across three pillars of compute, storage and networking, facilitating the cloud management operations. These services include the identity, image, telemetry, orchestration and database services [6]: Identity Service (code-named Keystone) is the security service to protect resources access and usage. This service provides a central directory management, mapping users to OpenStack accessible services. It acts as a common authentication system across the cloud operating system. It also supports multiple forms of authentication including standard username and password credentials, token-based systems and AWS-style logins. Image Service (code-named Glance) is the repository for virtual disk and server images used by the VMs. In OpenStack, user can copy or snapshot a server image and immediately store it away. Stored images can be used as a template to get new servers up and running quickly and consistently. _Telemetry Service (code-named Ceilometer)_ aggregates resources usage and performance data of the services deployed in OpenStack cloud. This capability provides visibility into the usage of the cloud infrastructure and allows cloud operators to view metrics globally or individually. _Orchestration Service (code-named Heat)_ is a template-driven engine that allows application developers to describe and automate the deployment of the cloud infrastructure. It also enables detailed post-deployment activities of infrastructure, services and applications. _Database Service (code-named Trove)_ allows users to utilize the features of a relational database. Cloud users and database administrators can create and manage multiple database instances as needed. 2.2. Properties. Provisioned as IaaS, OpenStack is built following an open philosophy: to avoid technology lock-ins by not requiring specific technologies and to provide user freedom to choose the best slot that matches its needs [6]. In this section, we will analyze some important properties of OpenStack. - **Live migration:** OpenStack supports two types of live migration: shared storage based and block live migration. The former supports live migration scenarios where the source and destination hypervisors have access to the shared storage, while the latter does not require shared storage. - **Load balancing:** OpenStack supports load balancing at different scales. First of all, the supporting feature of live migration has enabled system administrators to distribute application workloads among physical servers by means of adjusting VM placement. Moreover, it is possible to control application workloads at VM level, service provided by OpenStack Network layer, controlled by Neutron component. This component, with a flexible plug-in architecture allows the development of run-time custom algorithms to distribute workloads among VMs. Indeed, OpenStack has an on-going project called Load Balancing as a Service (LBaaS) that is aimed to provide load balancing service to end users. This service has monitoring feature to determine whether the VMs are available to handle user requests and take routing decisions accordingly. Several routing policies are supported, such as: round robin (i.e., rotates requests evenly between multiple instances), source IP (i.e., requests from a unique source IP address are consistently directed to the same instance) and least connections (i.e., allocate requests to the instance with the least number of active connections). - **Fault tolerance:** Fault tolerance can also be handled at different levels, depending on the way the IaaS system is configured and deployed. At the VMs level, in order to prevent failures, users can develop scheduling algorithms (besides the three already supported algorithms by OpenStack) for placing the VMs that best fits to his use cases. Some scheduling algorithms have been designed at the present time, such as: group scheduling (i.e., VMs that provide the same functionalities are grouped and placed to separate PMs) and rescheduling (i.e., rescheduling of VMs from failed host to surviving hosts using live-migration). At storage or database level, fault tolerance is achieved by using replication and synchronization to ensure that a failure occurred at one device will not break the whole system. - **Availability:** In OpenStack, high availability can be achieved through different setups depending on services types, stateless or stateful services. Stateless services can provide answer to a request without requiring further information of other services or historical data. OpenStack stateless services include nova-api and nova-scheduler. For these services, high availability is achieved by providing redundant instances and load balancing them. In the opposite, stateful services are ones that require other information to answer a request, which difficult the high availability achievement. These services, e.g., database or storage, can be highly available by using replication, with the adequate synchronization between the main version and replicated versions in order to keep the system consistency [23]. - **Security:** OpenStack has a separated service (Identity service) which provides a central authentication management across the cloud operating system and users. The possibility to set up VPNs and firewalls is available. - **Compatibility:** OpenStack is compatible with Amazon EC2 and Amazon S3 and thus client applications written for Amazon Web Services can be used with OpenStack with minimal porting effort [6]. In terms of hypervisors, OpenStack supports multiple hypervisors, e.g., Xen, KVM, HyperV, VMWare, etc. Other hypervisors with existing standard drivers can also be interfaced with OpenStack through standard library, e.g. libvirt library. 3. CloudStack. CloudStack [4] is an open source software platform, written in Java, designed for development and management of cloud Infrastructure as a Service. It aggregates computing resources for building private, public or hybrid clouds. CloudStack brings together the "Stack" of features requested by companies and users, like data centers orchestration, management and administration of users and NaaS (Network as a Service). The start of CloudStack was with Cloud.com in 2008. In May 2010, it was open source under GNU General Public License. Citrix bought CloudStack in July 2011, then in April 2012, Citrix donated CloudStack to Apache Software Foundation (ASF) where it was relicensed under Apache 2.0 and accepted as an incubation project. Since March 2013, CloudStack became a Top Level Project of Apache. Many companies are basing on CloudStack for building and managing their cloud infrastructures. Among these companies, there are: Nokia, Orange, Apple, Disney and many others. The first major release of CloudStack since its graduation from the Apache Incubator is 4.1.0, major changes were realized on the platform with modifications in the codebase to make its development easier, Maven was used as a build tool, and for creating RPM/Debian packages a new structure was used. The second major release was 4.2, many features were born due to cooperations with different industries, including an integrated support of Cisco UCS compute chassis, SolidFire storage arrays, and the S3 storage protocol. Next CloudStack releases until the last one 4.5.1, mainly include new features, bug fixes and improvement of the interaction with different hypervisors. 3.1. General Architecture. In CloudStack, physical resources are organized and managed in a hierarchical structure. The lowest level contains the computational devices, i.e. hosts and primary storage. Different hosts accessing a shared storage form a cluster. Clusters combined by a layer 2 switch form a pod. Pods are grouped together with secondary storage by a layer 3 switch to form a zone. At the highest level, zones are grouped to create a region. All these resources are managed by a Management Server. In the following, we describe in details each component that forms the whole architecture. 3.1.1. The architectural levels. The architectural levels are the core of the CloudStack architecture. These levels are: the lowest level, clusters, pods, zones and regions. A host represents a physical computational machine that contains local storage. The physical hosts are virtualized by hypervisors. CloudStack supports many hypervisors for VMs management such as Xen, KVM, vSphere, Hyper-V, VMWare, etc. as well as bare metal provisioning. All hosts within a cluster must be homogeneous in terms of the hypervisor, with the possibility of having heterogeneous hypervisors in different clusters. Within a cluster, hosts are tied together into the same computational pool with the primary storage. In a cluster all hosts share the same IP subnet. The primary storage can be any kind of storage supported by the hypervisor and one cluster can have multiple primary storage devices. A pod is a collection of different clusters linked with a layer 2 switch. Hosts in the same pod are in the same subnet. A pod is not visible to the end user. A zone contains pods that are attached to the secondary storage using a layer 3 switch. Zones are visible to the end user and they can be private or public. Public zones are visible to all users in the cloud, while private zones are visible only to users from a particular domain. Zones main benefits are isolation and redundancy. Often, a zone corresponds to a data center; although if a data center is large enough, it can have multiple zones. A region is the largest organizational unit in CloudStack. A region contains multiple zones distributed in geographic locations close to each other. 3.1.2. Management Server. A Management Server is used to manage all resources in cloud infrastructure through APIs or UI. One management server can support around 10K hosts and can be deployed either on a physical server or on a VM. In case of the existence of more than one management server, user interaction to either of them will return the same result. This ensures high availability of CloudStack. A database is required for management servers to be persistent. In order to prevent single point of failure, we can have one primary database and several database replicas always synchronized with the primary copy. 3.1.3. Storage. In addition to the host local storage, CloudStack manages two main types of storage: primary storage and secondary storage. • **Primary storage:** is a storage associated with a cluster or a zone, with the possibility of a single cluster to deploy multiple primary storages. This kind of storage is basically used to run VMs and to store application data. Since this storage interacts directly with applications deployed in VMs, it can be expensive in terms of I/O operations, reason why it is placed physically near to the hosts. • **Secondary storage:** supports two different types, NFS and Object Storage. It is used to store ISO images, templates and snapshots. - ISO image: is used when user wants to create a VM. - Template: is the base operating system image that the user can choose when creating new instance. - It may also include additional configuration information such as installed applications. - Snapshot: is used as backup for data recovery service. CloudStack supports two types of snapshot: individual snapshot and recurring snapshot. The former is one-time full snapshot, while the latter is either one-time full snapshot or incremental snapshot. ### 3.1.4. Networking CloudStack supports the use of different physical networking devices (*e.g.* NetScaler, F5 BIG-IP, Juniper SRX, etc.). In CloudStack, users have the ability to choose between two types of network scenarios: basic and advanced. The basic scenario is for an AWS-style networking. It provides a single network where guest isolation is done through the layer 3 switch. The advanced scenario is more flexible in defining guest networks [4]. For example, the administrator can create multiple networks to be used by the guests. CloudStack provides many networking services. Examples include: • **Isolation:** CloudStack assures the isolation of networks, by allowing the access to the isolated network only by virtual machines of a single account. • **Load Balancing:** to balance the traffic in the cloud, the user can create a rule to control and distribute the traffic and apply it to a group of VMs. Within the defined rule, user can choose a load balancing algorithm among the supported ones. • **VPN:** to access a VM using a CloudStack account, users can create and configure VPNs. Each network has its own virtual router, so VPNs are not shared across different networks. Using VPN tunnels, hosts in different zones are allowed to access each other. • **Firewall:** one host can access others in the same zone without passing through the firewall. Users can use external firewalls. ### 3.2. Properties The main properties of CloudStack are [4]: • **Live migration:** A live migration of running VMs between hosts is allowed in CloudStack through the Dashboard. Depending on the VMs hypervisor, migration conditions can be different. For example, live migration using KVM hypervisor will not support the use of local disk storage, and source and destination hosts have to be in the same cluster; while Xen and VMWare support local disk storage and allow to migrate between different clusters [3]. • **Load balancing:** a load balancer is an optional component of CloudStack that allows traffic distribution among different management servers [5]. In addition to creating rules and using load balancing algorithms, CloudStack offers the possibility to integrate with external load balancers such as Citrix NetScaler [27]. • **Fault tolerance:** in CloudStack, fault tolerance is achieved at different scales, *e.g.* management, database and host levels. In order to prevent failures of management server, the server can be deployed in multi-node configuration. If one management node fail, other nodes can be used without affecting the functioning cloud. Failures at database level are handled by using one or more replication of the database linked to the management server. For host’s fail-over, CloudStack recovers the VM instances by taking the images from secondary storage and using application data in primary storage. • **Availability:** CloudStack ensures high availability of the system by using multiple management server nodes which may be deployed with load balancers. • **Security:** in addition to isolation using different accounts, VPNs and firewalls, CloudStack offers the isolation of traffic using the strategy of security groups. These are sets of VMs that filter the traffic on the basis of configuration rules. CloudStack provides a default security group with predefined rules, that can be modified if necessary. • **Compatibility:** the pluggable architecture of CloudStack allows one cloud to support different hypervisor implementations, including: Hyper-V, KVM, LXC, vSphere, Xenserver, Xen Project and also bare metal provisioning. Moreover, CloudStack is compatible with Amazon API and enables the integration of these two platforms. - Scalability: CloudStack can manage thousands of servers distributed in different data centers and different locations, thanks to the management server capability (one management server node can manage a big pool of physical resources), and the possibility of using multiple management servers for reducing VMs downtime. - API extensibility: The CloudStack APIs are very powerful and allow developers to create new command line tools and UIs, and to plug them into CloudStack architecture. If the developer wants to use a new hypervisor, new storage system or new networking service, he just needs to write a new plug-in in Java and integrate it. 4. Eucalyptus. Eucalyptus is a popular open source IaaS product, provided by Eucalyptus Systems [7]. It is used to implement, manage, and maintain private and hybrid clouds (but cannot build public clouds) with a main key design feature, which is Amazon Web Services (AWS) API compatibility. Many programming languages can be used to code Eucalyptus including: Java, C, Groovy, Shell, Perl, Python [7]. Originally it was designed at the University of California, Santa Barbara, as set of services that could emulate AWS on a different site apart from Amazon servers, with the aim of linking together AWS, supercomputer centers at National Science Foundation and several university sites [20]. It became a for-profit organization in 2009. In 2012, Eucalyptus started a partnership with AWS that allowed to develop more AWS-compatible environments, and to create hybrid clouds by facilitating movements of instances -created from stored Operating System Images- between an Eucalyptus private cloud and Amazon Elastic Compute Cloud (EC2). In September 2014 HP acquired Eucalyptus and lunch it under the Helion Eucalyptus name. Beside its high AWS compatibility that allows running an application on AWS and Eucalyptus without any modifications, Eucalyptus is characterized by its high availability configuration, easy installation and simple user interface. Its main clients include: AppDynamics, Nokia, NASA, Puma and others [7]. Eucalyptus since its first releases contains its main feature which is compatibility with Amazon Web Services. Many announced releases were just maintenance releases and do not contain new features. Eucalyptus Cloud User Console was included in the release 3.2.0 which enabled self-service provisioning of different resources for cloud users. Eucalyptus 3.3.0 introduced many important features such as auto-Scaling, Load Balancing, CloudWatch and new VM Types, and this make it one of the most important releases of Eucalyptus. Many things were changed in release 4.0.0, including changes in the whole architecture and how components are installed and registered, changes in storage architecture, changes in networking mode and a new administrator roles were set. The current release 4.1.1 (11/5/2015) is a maintenance release for 4.1.0 in which a support for CloudFormation was add with new Management Console features and new instance status checks. 4.1. General Architecture. Eucalyptus has a highly modular, hierarchical and distributed architecture [22]. Users familiar with AWS do not find any difficulties with Eucalyptus because it replicates the same interaction tools and interfaces used in AWS, such as: euca2ools - the command-line tool - or the Eucalyptus User Console - a GUI based tool. Eucalyptus architecture is characterized by five main components: Cloud Controller, Cluster Controller, Storage Controller, Node Controller and Scalable Object Storage, and one optional component: VMware Broker. These components are grouped in three different logical levels: Cloud Level, Cluster Level and Node Level [7]. In the following sections we describe each logical level and the associated components. The Cloud Controller (CLC) is a Java program that provides the interface to the cloud, and each cloud contains only one. CLC contains query interfaces and a EC2-compatible SOAP. It handles users requests and provides high level authentication, quota management, accounting and reporting. CLC does also meta-schedule and manages different cloud resources after collecting information provided by the Cluster Controller. The Scalable Object Storage (SOS) is an Eucalyptus service that allows the use of external (open source or commercial) storage solutions. SOS is equivalent to AWS Simple Storage Service (S3). In case of small deployments Eucalyptus has a basic storage implementation called Walrus that has two main functionalities: (i) storage of system files that could be accessible from different nodes (it may contain: VM images, volumes, snapshots, Linux kernel images, Root filesystem), and (ii) be used as Storage as a Service to store users data and applications. 4.1.2. Cluster Level. Each cluster is formed by a group of nodes linked with a LAN network. This level contains two main components: Cluster Controller and Storage Controller, and one optional: VMware Broker. Clusters are under subnets with a specific range of IP addresses, what compromises the flexibility and is a disadvantage of Eucalyptus. The Cluster Controller (CC) is a C program that collects information, manages the execution of the virtual instances and virtual network and verifies the respect of Service Level Agreement. Multiple Cluster Controller could exist within one cloud. It works as an intermediate between the Cloud Controller, the Storage Controller and the Node Controller. CC is equivalent to AWS availability zone. The Storage Controller (SC) is a Java program developed to have the same features as AWS Elastic Block Store (EBS). It manages the snapshots and volumes of a specific Cluster and controls the block-access network storage. The SC also communicates with different storage systems (NFS, iSCSI, SAN,...), with the Node Controller and the Cluster Controller. The VMware Broker (VB) is an optional component available only in Eucalyptus version with VMware support. It provides an AWS compatible interface for VMware environments that allows the deployment of VMs on VMware infrastructure elements. VB directly manages the communication between the CC and the VMware hypervisors (ESX/ESXi), or it is possible that it passes through VMware vCenter. 4.1.3. Node Level. This level is composed by a single component, the Node Controller (NC), a C program that hosts VMs and their associated services, and manages the endpoint of the virtual network. NC interacts with the hypervisor and the hosted operating system to control VMs life-cycle, their creation and termination. It collects and sends information about VMs and their associated physical resources to the Cluster Controller to make high level decisions, like when to proceed with the load balancing. 4.2. Properties. - Compatibility: it is the main feature of Eucalyptus. AWS APIs are built on top of Eucalyptus tools which simplifies intercommunication between both [25]. AWS APIs supported by Eucalyptus are: Elastic Compute Cloud (EC2), Elastic Block Storage (EBS), Amazon Machine Image (AMI), Simple Storage Service (S3), Identity and Access Management (IAM), Auto Scaling, Elastic Load Balancing, CloudWatch and CloudFormation. - Live migration: one of the weak points of Eucalyptus is the absence of a live migration feature. Nevertheless many external approaches was proposed to add this feature, like the one described in [19]. - Load balancing and Fault tolerance: Eucalyptus does not contains an implicit load balancing mechanism for the low level of VMs, nor for the high level of user requests, but it could be achieved using Elastic Load Balancing of AWS. Elastic Load Balancing is a service that provides fault tolerance by distributing the incoming service requests and users traffic among different Eucalyptus instances. It automatically detects overloaded instances, and redirects the traffic to more available ones. Load balancers are the core of Elastic Load Balancing, they are special Eucalyptus instances created from specific Eucalyptus VMs images. If there is a problem in one of the instances or if it is removed due an internal error, the system stops rerouting traffic to that instance until it is restored or a new one is created. Load balancing could be managed within the same or among different clusters depending on the users need. Elastic Load Balancing contains also a health check system that routinely sends check requests to instances. It uses latency, RequestCount and HTTP response code counts to verify if the instance is responding in time to users requests. - Scalability: as mentioned before, Eucalyptus is by nature distributed, what makes it highly scalable. There is also an auto scaling feature that allows to add and remove instances and VMs depending on traffic increase, the available resources and with respect to the Service Level Agreement. Using this feature developers can scale resources up or down depending on the need. There are three main component in Auto Scaling which are: - Auto Scaling group: is the main component of Auto Scaling, it defines for each user the minimum and the maximum number of scaling instances, and the related parameters. In case the user did not select any specifications, it chooses the default parameters, which are equal to the minimum number of instances to use. - Launch configuration: it contains the information needed to make the scaling, including instance type, VM image ID, security groups, and many others. - Scaling plan (policy): it defines the manner of doing the auto scaling. It could be manually or automatically, responding to CloudWatch alarms. • Cloud Watch: is an Eucalyptus service that collects raw data from different cloud resources (instances, elastic block store volumes, auto scaling instances and load balancers) and generates and records performance metrics. This allows users to make operational business decisions based on the historical records. Cloud Watch also configures alarms based on data from user filled metrics. • Availability: Eucalyptus contains high availability as a feature since version 3. If an individual node or even a rack fails, Eucalyptus put other nodes into use immediately or moves to another rack in case of rack failure. This is achieved through a service that is running concurrently on physical machines which is "hot spare". The information failure is quickly diffused internally, without any signs to the users, and the failure is recovered with respect to SLA (service level agreement). In [30] an evaluation tool was proposed for testing availability in IaaS platforms. This tool was tested on Eucalyptus by faults injections in an Eucalyptus cloud testbed. This paper shows that software repairs were more often than hardware repairs. • Security: Eucalyptus manages the access to the cloud using policies related to users, groups and accounts. A group is a set of users within an account, which have the authorization to access to a specified pool of resources. A user can belong to different groups. Security groups are also used by defining firewalls that should be applied to the set of VMs within a group. The security policies could be managed by users using the command line Euca2ools. 5. OpenNebula. OpenNebula [2] is an open source cloud platform developed by Universidad Complutense of Madrid UCM (Under the Apache 2.0 License) that delivers a simple, but feature rich, solution to build enterprise clouds and virtualized data centers. OpenNebula provides a complete toolkit to centrally manage heterogeneous virtual infrastructure, which is compatible with conventional hypervisors: VMware, Xen, KVM. It operates as a scheduler of storage layers, network, supervision and security. It is an appropriate solution for the conversion of a virtual infrastructure to IaaS platform. The centralized orchestration of hybrid environments is the heart of the tool. OpenNebula also utilizes Cloud Computing Interface (OCCI) and support to Amazon Elastic Cloud Compute (EC2) in order to expand the resources connected to it in order to form a hybrid cloud [2]. OpenNebula project started in 2005, has delivered its first version in 2008 and remains active since. Many releases have achieved today significant functional changes on the support of the storage nodes, high availability environments and ergonomics of the administrative interfaces. OpenNebula has also a wide user base that includes leading companies in banking, technology, telecommunications, and research and supercomputing centers. At present, it has more than 4000 downloads per month and many research institutes and enterprises use it to build their own cloud. One major release of OpenNebula is launched approximately every year, with two or three minor releases to each version. The first major release was in July 2008; it supported Xen and KVM virtualization platforms to provide efficient resource management and fault tolerant design. OpenNebula 2.0 (25/10/2010) brought a significant amount of changes and new features, including: the image repository, MySQL support, authorization and authentication drivers. The next major release of OpenNebula was 3.0 (3/10/2011) and introduced many new components and features for the core and libraries, providing support to: groups users management, flexible access control list system, DB versioning and schema. Currently, the stable version of OpenNebula is 4.12.1 (8/04/2015) and presents several improvements in resource management with virtual data-centers and the exclusion of the term resource provider. Networking has been vastly improved in 4.12 (03/11/2015), with the addition of security groups, allowing administrators to define the firewall rules and apply them to the Virtual Machines. 5.1. General Architecture. A key feature of OpenNebula architecture is its highly modular design and flexibility, which facilitates integration with any virtualization platform and third-party component in the cloud ecosystem. The main components of OpenNebula architecture are: the Driver, the Core and the Tools. The Driver is responsible for direct communication with the underlying operating system and for the encapsulation of the underlying infrastructure as an abstract service (e.g. virtualization hypervisor, transfer mechanisms or information services). It is designed to plug-in different virtualization, storage and monitoring technologies and cloud services into the core. These pluggable drivers are responsible for the creation, startup and shutdown of virtual machines, allocating storage for VMs and monitoring the operational status of physical machines and VMs. The roles of each service are: - The transfer driver manages the VMs disk images on different kind of storage systems, a shared one: Network File System (NSF) or Internet Small Computer System Interface (iSCSI), or a non-shared one, such as a simple copy over Secure Shell (SSH). - The VM driver is considered a set of hypervisor-specific drivers used to manage VMs instances on different hosts. - The information driver is also considered a set of hypervisor-specific drivers used to monitor and retrieve the current status hosts and VMs instances through SSH. The Core reflects a centralized layer that controls and monitors VM full life cycles, virtual networks (VN), storage and hosts. These components are implemented in this layer by invoking a suitable driver. The features of such component are: (i) VM manager allocates resources required by VMs to operate, implementing VMs deployment policies; (ii) VN manager interconnects VMs, and generates MAC and IP address for a VM; (iii) host manager manages a VM storage and allocates a VM disk; (iv) SQL Pool is a database (SQLite or MySQL) that stores configuration data and current status of hosts and VMs instances; and (v) request manager (XML-RPC) accesses the application programming interface directly. The Tools contains tools distributed with OpenNebula. First, it includes Scheduler that manages the functionality provided by the core layer. Scheduler component makes VM placement decisions. These VMs are deployed on host nodes following specific user requirements and resource-aware policies, such as packing, striping, or load-aware. Secondly, Command line interface-CLI and Libvirt API [1], an open interface for VM management and communicating with users. Additionally, third party tools that can be easily created using the XML-RPC interface or the OpenNebula Client API. External users are capable of sharing these functionalities through a cloud interface which is provided by the Tools layer. 5.2. Properties. - Live migration: is one of the advantages of OpenNebula. It is supported through shared storage, but it could demand a high-performance SAN (Storage Area Network) [18]. OpenNebula uses the libvirt TCP protocol to provide migration capabilities. - Load balancing: is provided across NGINX [34], which is an open-source, high-performance web server. It is capable of handling large numbers of concurrent connections and represents a centralized manager to balance the workload. In order to distribute efficiently the I/O of the VMs across different disks, LUNs or several storage back-ends, OpenNebula is able to define multiple system datastores per cluster. Scheduling algorithms (used by load balancers) take into account disk requirements of a particular VM, so OpenNebula is able to pick the best execution host based on capacity and storage metrics [9]. - Fault tolerance: OpenNebula provides VM migration for those not running VMs. However, OpenNebula can only detect problems on VM level. If a service or an application corrupts unexpectedly, simply rebooting the VM on another node may break the continuity of the service and result in loss. This service is maintained by database back-end (registers VM information) to store host and VM information. - High availability: OpenNebula delivers the availability required by most applications running in VMs. OpenNebula ensures high availability of the system by using multiple persistent databases back-end in a pools cluster of hosts that share datastores and VNs. It provides information in order to prepare for failures in the VMs or physical nodes, and recover from them. These failures are categorized depending on whether they come from the physical infrastructure (Host failures) or from the virtualized infrastructure (VM crashes). In both scenarios, OpenNebula provides a cost-effective fail-over solution to minimize downtime from server and OS failures, and supports high availability configurations [15]. • Security: OpenNebula takes many measures to ensure the security. The infrastructure administrator manages a secure and efficient Users and Groups Subsystem for pluggable authentication and authorization based on passwords, SSH and RSA key pairs, X.509 certificates or LDAP. OpenNebula also uses Firewall to configure the VMs, in order to shutdown TCP and UDP ports, filter some unwanted packets and defines a policy for ICMP connections. In addition, OpenNebula uses ACL (Access Control List) which is a collection of permit and deny conditions (ACL rules), allowing different role management with fine grain permission granting over any resource managed by OpenNebula, support for isolation at different levels. Since version 4.4 OpenNebula has special authentication mechanisms for SunStone (OpenNebula GUI) and the Cloud Services (EC2 and OCCI). • Compatibility: OpenNebula can be deployed to existing infrastructures and integrated with various cloud services and multi-platform. OpenNebula currently includes an EC2 driver, which can submit requests to Amazon EC2 and Eucalyptus, as well as an ElasticHosts driver. OpenNebula supports different access interfaces including REST-based interfaces (e.g., EC2-Query API), OGF OCCI service interfaces, the OpenNebula Cloud API (OCA), and APIs for native drivers, for example, to connect with AWS. • Scalability: OpenNebula has been tested in the management of medium scale infrastructures with hundreds of servers and VMs [15]. By a cloud federation, OpenNebula provides scalability, isolation, and multiple-site support to interface with external clouds. This allows complementing the local infrastructure with computing capacity from public clouds to meet peak demands. Thus, a single access point and centralized management system can be used to control multiple deployment on OpenNebula. In OpenNebula highly scalability can be achieved through database back-end with support for MySQL and SQLite, and virtualization drivers can be adjusted to achieve maximum scalability. • Flexibility and extensibility: OpenNebula provides extension and integration to fit into any existing data center, and flexible architecture, interfaces and components, allowing its integration with any product or tool. OpenNebula offers different means to easily extend and adjust behavior of the cloud management instance to the requirements of the environment and use cases, e.g. new drivers can be easily written in any language for the main subsystems to easily leverage existing IT infrastructure and system management product [9]. 6. Nimbus. Nimbus is an open source solution (licensed under the terms of the Apache License) for using cloud computing in the context of scientific applications. Although the focus on the scientific community, Nimbus approaches three goals targeting three different communities: (1) Enable resource owners to provide their resources as an infrastructure cloud; (2) Enable cloud users to access infrastructure cloud resources more easily, and (3) Enable scientists and developers to extend and experiment with both sets of capabilities. These goals are related with the architecture of Nimbus. Its main architecture can be divided in two components, each one responsible for attending one of the goals. The first goal is realized by the Nimbus Infrastructure and the second by the Nimbus Platform. The third goal is realized by the strong support of open source development practices via modular, extensible code and engagement with open source developers [8]. Released in 2005, to solution is kept on GitHub since 2009 and its updates are revised by an international researchers committee. Nevertheless, recently, Nimbus is missing regular updates. The last release is 2.10.1 (release date: 27/02/2013) and the last github update is the cloud client version 022 (release date: 27/10/2013). Although some new features have been introduced, like the multi-cloud VM image generator for FutureGrid users (release date: 04/06/2014) and some additions on the Phantom component (release date: 15/07/2014), the focus of the Nimbus team seems to be more on collaborating with another research groups than on developing the Nimbus. 6.1. General Architecture. This section presents further details on the components Nimbus Platform and Nimbus Infrastructure. 6.1.1. Nimbus Platform. This is an integrated set of open source tools that allows users to easily leverage Infrastructure-as-a-Service (IaaS) cloud computing systems. This includes application instantiation, configuration, monitoring, and repair [8]. The Nimbus platform is divided in three modules: the context broker, the elastic scaling tools and the deployment coordination. The context broker is a service that allows clients to coordinate large virtual cluster launches automatically and repeatably. The context broker requires that each VM runs a lightweight script at boot time called the context agent. This context agent depends only on Python and on the ubiquitous curl program, that securely contacts the context broker using a secret key. To enforce security the context broker uses contextualization, e.g., the key is created on the fly and seeded inside the instance. This agent gets information concerning the cluster from the context broker and then causes last minute changes inside the image to adapt to the environment [8]. The elastic scaling tools on Nimbus are called EPU. The EPU system is used with IaaS systems to control highly available services. On these kind of services any failures are compensated with replacements. EPU is also useful with services that can be configured to be elastic; it responds to monitoring signals with adjustments of the amount of instances that composes a service. If the service cannot handle instances being added and dropped on the fly (many services have static node-number configurations), EPU still provides automatic launch, monitoring, and failure replacement capabilities [8]. 6.1.2. Nimbus Infrastructure. This is a set of tools that provides the IaaS at the Nimbus cloud computing solution. The Nimbus infrastructure is divided in Workspace service and Cumulus. The Nimbus workspace service is a standalone site VM manager that can be invoked by different remote protocol front-ends [8]. The workspace service is web services based and provides security with the GSI authentication and authorization. Currently, Nimbus supports two front-ends: Amazon EC2 and WSRF. The structure of the workspace service is composed by three modules: workspace control, workspace resource manager and workspace pilot. - Workspace control: controls VM instances, manages and reconstructs images, integrates a VM to the network and assigns IP and MAC addresses. The workspace control tools operate with the Xen hypervisor and can also operate with KVM. Implemented in Python in order to be portable and easy to install [35, 8]. - Workspace resource manager: is an open source solution to manage different VMs, but can be replaced by other technologies such as OpenNebula [35, 8]. - Workspace pilot: is responsible for providing virtualization with few changes in cluster operation. This component handles signals and integrates administration tools [35, 8]. The Nimbus Cumulus is an open source implementation of the Amazon S3 REST API. It provides an implementation of a quota-based storage cloud. In order to boot an image on a given Nimbus cloud, that image must first be put into that same clouds Cumulus repository, although advanced use cases can by pass this restriction. In practice, it is used as the Nimbus repository solution but can also be installed standalone. Cumulus is designed for scalability and allows providers to configure multiple storage cloud implementations [8]. 6.2. Properties. - Live migration: Nimbus has no in built support to live migration. It is possible to migrate virtual machines only at hypervisor interface level [26]. The Nimbus team recently participated in a research that addresses network contention between the migration traffic and the Virtual Machine application traffic for the live migration of co-located Virtual Machines, and the live migration support is on the map of next improvements of the solution [16]. - Load balancing: At VM level, Nimbus features a system of Nagios plugins that can give information on the status and availability of the Nimbus head node and worker nodes, including changes of the virtual machines running on the worker node [24]. Specifically from the cloud provider’s point of view Nimbus does the back-filling of partially used physical nodes, allowing also preemptable virtual machines. On the platform level, the cloudInit.d tool provides management to virtual machines deployed and allows compensation of stressed workloads based on policies and sensor information. Nimbus also provides tools to handle capacity allocation and capacity overflow. For example, the attribution of variable lease limits to different users - as a means of scheduling - is standard within Nimbus. In addition, the idea of allowing EC2 or another cloud the ability to pick up excess demand is heavily researched with Nimbus [28]. - Fault tolerance: Nimbus presents fault tolerance only at storage level, through the integration of Nimbus Storage Service with Globus GridFTP [10]. GridFTP - an extension of the standard File Transfer Protocol (FTP) for use with Grid computing - provides a fault tolerant implementation of FTP, to handle network unavailability and server problems. Moreover, transfers can be automatically restarted if a problem occurs [31]. - **Availability**: On the platform point of view, the EPU provides high accessible services to the user. On the infrastructure point of view, Nimbus provides high-available services through the hosted service Phantom. The Nimbus Phantom leverages on-demand resources provided by infrastructure clouds and allows users to scale VMs that are running on the many clouds of FutureSystem as well as Amazon EC2. The Phantom can be extended through decision engines, components that determine the behavior of the service. Phantom is freely available on the FutureSystem infrastructure and is provided as a highly available service itself. - **Security**: Nimbus provide GSI authentication and authorization - through PKI credentials, grid proxies, VOMS, Shibboleth (via GridShib) and custom PDPs. It also guarantees secure access to VMs via EC2 key generation. In addition, Nimbus allows images and image data validation. - **Compatibility**: Nimbus can be integrated with various cloud services and multi-platform mainly through web services. Nimbus Infrastructure is EC2/S3-compatible, with SOAP and Query front-ends. It is possible to upload VM images to Cumulus with the Python library Boto, or with s3cmd. It is also possible to use EC2 spot instances. 7. **Cloud Solution Comparisons.** This section provides a comparison between the analyzed cloud solutions, aiming at three different levels: (i) general comparison aimed at providing high level analysis in terms of model, policy and architecture, (ii) functional comparison, whose goal is to compare supported functionalities, and (iii) property comparison, which considers cloud properties implemented in these platforms. 7.1. **General Comparison.** The general comparison is provided in Table 7.1, considering general aspects: licensing, commercial model, cloud model compatibility, easiness of installation, architecture and adopters. Table 7.1 <table> <thead> <tr> <th>Property</th> <th>OpenStack</th> <th>CloudStack</th> <th>OpenNebula</th> <th>Eucalyptus</th> <th>Nimbus</th> </tr> </thead> <tbody> <tr> <td>Open Source License</td> <td>Apache 2.0</td> <td>Apache 2.0</td> <td>Apache 2.0</td> <td>Linux Open-Source</td> <td>Apache 2.0</td> </tr> <tr> <td>Commercial model</td> <td>Free</td> <td>Free</td> <td>Free</td> <td>Free, GPLv3 (only), with proprietary relicensing</td> <td>Free</td> </tr> <tr> <td>Compatibility with</td> <td>Private, public and hybrid clouds</td> <td>Private, public and hybrid clouds</td> <td>Private, public and hybrid clouds</td> <td>Private and hybrid clouds</td> <td>Private, public and hybrid clouds</td> </tr> <tr> <td>Installation Effort</td> <td>Difficult (many choices, not enough automation)</td> <td>Medium (Few parts to install)</td> <td>Easy (process based package installers)</td> <td>Difficult (different configuration possibilities)</td> <td>Easy (no root account required)</td> </tr> <tr> <td>Architecture</td> <td>Fragmented into many pieces</td> <td>Monolithic controller</td> <td>Modular (third-party component)</td> <td>Five part controller and AWS</td> <td>Lightweight components (IaaS service and VMM node)</td> </tr> <tr> <td>Large organizations adopters</td> <td>Yahoo, IBM, VMWare, Rackspace, Redhat, Intel, HP, etc.</td> <td>Nokia, Orange, Apple, Citrix, Huawei, TomTom, Tata, etc.</td> <td>CERN, Cloud-Weavers, IBM, Hexafrid</td> <td>UEC, NASA, Sony, HP, Cloudera, Puma, USDA, FDA</td> <td>Brookhaven National Labs, Cumulus project</td> </tr> </tbody> </table> As it can be seen, the five frameworks are generally equal with respect to commercial model, licensing policy and cloud models. Each of them has been adopted by large organizations. Nevertheless, a big difference is spotted from the architecture viewpoint. While OpenStack is fragmented into modules, CloudStack has a monolithic central controller, OpenNebula has three main components, Eucalyptus has five parts controllers with AWS, and Nimbus have lightweight based components. This difference is explained by the open philosophy of OpenStack and OpenNebula which tries to avoid technology lock-ins and provides high degree of flexibility, extension and availability. Nimbus is also relatively easy to install and deploy comparing to others solutions. The decentralized design and different configuration possibilities of Eucalyptus make it difficult to configure and install. Like Eucalyptus, OpenStack are also characterized by increasing complexity of installation and configuration. 7.2. Functional Comparison. The functional comparison looks at the offered functionalities or technical aspects of the five presented solutions, as described in Table 7.2. Most popular hypervisors such as: Xen and KVM are supported by all the platforms, but for example VMware is not available on Nimbus. We mention here that OpenStack and CloudStack have the largest number of supported hypervisors, even though there are ways to interface with non-supported ones. Administration feature is the interface available to interact with these platforms. All solutions present Web interfaces (Web UI) and command line interfaces (CLI). Also user management is provided in all this five platforms. <table> <thead> <tr> <th>Functionality</th> <th>OpenStack</th> <th>CloudStack</th> <th>Eucalyptus</th> <th>OpenNebula</th> <th>Nimbus</th> </tr> </thead> <tbody> <tr> <td>Supported hypervisors</td> <td>Xen, KVM, HyperV, VMWare, LXC, vSphere</td> <td>Xen, KVM, HyperV, VMWare, LXC, vSphere</td> <td>Xen, KVM, VMware</td> <td>Xen, KVM, VMware, vCenter</td> <td>Xen, KVM</td> </tr> <tr> <td>Administration</td> <td>Web UI, CLI</td> <td>Web UI, CLI</td> <td>Web UI, CLI</td> <td>Web UI, CLI</td> <td>Web UI, CLI</td> </tr> <tr> <td>User management</td> <td>yes</td> <td>yes</td> <td>yes</td> <td>yes</td> <td>yes</td> </tr> </tbody> </table> Other important functional aspect of open source cloud solutions is the activeness of its community. A solution that is always seeing new releases is constantly evolving. An active community, with well documented wiki, good bug reporting and fixing system and active users support are fundamental features for the success of an open source solution. At this topic OpenStack remains the largest and most active open source cloud computing project [21]. Nevertheless, CloudStack and Eucalyptus are growing and have an important participation in the market, while OpenNebula and Nimbus are less active. In this point, OpenStack has a bigger and more active community, followed by CloudStack, Eucalyptus, OpenNebula and finally Nimbus. The number of releases of a platform also indicates the constant evolution of a tool. OpenStack has a strict policy of regular updates, with two big releases per year and some minor releases in each version. For Eucalyptus the last major release is Version 4.1.1 (release date: 11-05-2015) and the one before was Version 4.0.2 (release date: 20-10-2014). On CloudStack the last major release was 4.5.1 (release date 03/06/2015). For OpenNebula the last major release is old, the 4.4 Beta (release date: 07-11-2013), but 13 minor releases were announced since that time, the last one is 4.12.1 (release date: 08-04-2015). The Nimbus last major release was 2.10.1 (release date: 27/02/2013) and a minor update on cloud client (release date: 2/10/2013). From this we can conclude that OpenStack, Eucalyptus and CloudStack are the most active and evolving technologies. OpenNebula also evolves, but in a slower pace, meanwhile Nimbus gives signs of possible discontinuity. Regarding benchmark tests, as far as we know, there is no study that have made performance tests to compare this five platforms, but there are several papers comparing two or three of them. In [39] the authors performed the performance evaluation of CloudStack and OpenStack using a mutual hypervisor and under a set of defined criteria. This study showed the effect of varying resources performances (processor and RAM, hard disk size) on deployment and deletion time. The results showed that performance of OpenStack supersedes that of CloudStack. The authors in [40] compared performances of VMs for CloudStack and Eucalyptus in terms of CPU utilization, memory bandwidth, disk I/O access speed, and network performance using different benchmarks. Mainly the results shown that CloudStack performed better than Eucalyptus in most of tests. Other benchmarks could be found in [41] where the authors evaluated performances of Nimbus, OpenNebula and OpenStack, for High Performance Computing according to HPC Challenge (HPCC) benchmark suite. The results showed that OpenStack had the best performance for HPC. ### 7.3. Properties Comparison Properties comparison gives deeper insights into the five platforms, considering some important properties that an IaaS has to provide. The comparison is given in Table 7.3. <table> <thead> <tr> <th>Property</th> <th>OpenStack</th> <th>CloudStack</th> <th>Nimbus</th> <th>Eucalyptus</th> <th>OpenNebula</th> </tr> </thead> <tbody> <tr> <td>Live migration</td> <td>Yes</td> <td>Yes</td> <td>No</td> <td>No</td> <td>Yes</td> </tr> <tr> <td>Load balancing</td> <td>Yes</td> <td>Yes</td> <td>Yes</td> <td>Yes</td> <td>Yes</td> </tr> <tr> <td>Fault tolerance</td> <td>VM scheduling, replication</td> <td>VM scheduling, replication</td> <td>Through Globus GridFTP</td> <td>Through AWS Elastic Load Balancing</td> <td>VM scheduling, replication</td> </tr> <tr> <td>High availability</td> <td>Yes</td> <td>Yes</td> <td>Yes</td> <td>Yes</td> <td>Yes</td> </tr> <tr> <td>Security</td> <td>VPNs, firewall, user authentication, others</td> <td>VPNs, firewall, user management, others</td> <td>user authentication</td> <td>group and users policies</td> <td>user authentication</td> </tr> <tr> <td>Compatibility</td> <td>Amazon EC2, Amazon S3</td> <td>Amazon EC2, Amazon S3</td> <td>Amazon EC2, Amazon S3, WSRF</td> <td>Amazon EC2, Amazon S3</td> <td>All Amazon Interfaces</td> </tr> </tbody> </table> **Live Migration** may be approached in two ways: shared storage based live migration, and block live migration. OpenNebula and OpenStack offer both possibilities. CloudStack also offers both possibilities, but the conditions change according with the user hypervisor. Eucalyptus and Nimbus offers no integrated live migration system. This way, if the live migration is sensitive to the application, OpenNebula and OpenStack are more adequate solutions. **Load balancing** can be considered on the VM level or on the host level. Load balancing at host level is implemented in OpenStack through live migration, which is the same in CloudStack; Nimbus does the back-filling of partially used physical nodes, allowing also preemptable virtual machines. All the solutions approach VM level load balancing through the establishment of a plug-in architecture. OpenNebula can be coupled with NGINX, Eucalyptus with the ELB of AWS and Nimbus with Nagios plugins. Similarly OpenStack and Cloudstack present flexible plug-in architecture on network component. In resume, at host level, live migration is used to provide load balancing. At VM level, the cloud solutions trust on plugins to provide load balancing. Also, the automatic leasing of resources seems to be a tendency. For example, allowing EC2 or another cloud the ability to pick up excess demand is heavily researched with Nimbus [28]. **Fault tolerance** mechanisms exists on VM or on storage/database levels. At VM level, fault tolerance is approached under the policies to schedule VM placement or services replication. OpenNebula comes with a match making scheduler - that implements the Rank Scheduling Policy - and the quote management system, that ensure that any user gets a adequate quantity of resources. OpenStack has in-built scheduling algorithms (group scheduling and rescheduling) and newer ones can be implemented by the user. Nimbus has no already implemented fault tolerance system, but it can provide through Globus GridFTP. At storage or database level, fault tolerance is achieved by using replication and synchronization to ensure that a failure occurred at one device will not break the whole system. Eucalyptus has no in-built mechanism for fault tolerance, but can provide it at storage level, through the AWS Elastic Load Balancing. **High availability** is approached in all platforms by means of using redundant service instances and load balancing to distribute workloads among those instances. In the case of the replication of service instances, some synchronization technique has to be considered. Security is provided on different levels by each cloud solution. Centralized in-built user authentication is provided on Nimbus, OpenStack and OpenNebula. The establishment of security policies for users, groups and accounts is possible on CloudStack, Eucalyptus and OpenNebula. On OpenStack is also possible to extend the security of the cloud through the addition of plugins. Compatibility refers to the capability of the cloud solution to integrate with other tools and cloud solution. In this topic, the Amazon Web Services are a common place on the solutions, thanks to its dominance on commercial public clouds. All open source analyzed solutions, in different levels, present some integration with AWS services, being Amazon EC2 and S3 the most popular. 7.4. Resume. In general lines, Eucalyptus offers a flexible solution for users that want privacy in specific modules while keep managing their clouds with AWS. OpenNebula is for someone interested in the internal technical details of the cloud, but also seems to be a good solution for someone that wants to build up a cloud quickly using just a few machines. OpenStack and CloudStack have the largest developing community, but have opposite approaches, since OpenStack has as modularized architecture, while CloudStack has a monolithic centralized one. Nimbus is easy to deploy and is suitable for inexperienced users willing to have a first contact with cloud platforms or to scientific investigations, although the lack of recent releases and an active community. 8. Conclusions. We have presented the up-to-date architecture of five prominent open source cloud platforms, looking into details of the provided functionalities and their properties. The analyzed platforms are under continuous development. Therefore their documentation and technical reviews are often updated and have to be regularly checked. We argue that there is no best solution to any general case, but there are tools more adapted to specific audiences. The comparison was carried out from the user perspective, considering the properties that a user needs to know when choosing a IaaS cloud solution. Acknowledgment. Work funded by the European Commission under the Erasmus Mundus Green IT project (Green IT for the benefit of civil society, 3772227-1-2012-ES-ERA MUNDUS-EM21, Grant Agreement n 2012-2625/001-001-EMA2). And CAPES, Coordenação de Aperfeiçoamento de Pessoal de Nível Superior - Brasil. REFERENCES Edited by: Dana Petcu Received: May 14, 2015 Accepted: Jun 24, 2015
{"Source-Url": "https://iris.polito.it/retrieve/handle/11583/2654067/128932/1089-952-1-PB.pdf", "len_cl100k_base": 15779, "olmocr-version": "0.1.49", "pdf-total-pages": 19, "total-fallback-pages": 0, "total-input-tokens": 52127, "total-output-tokens": 18495, "length": "2e13", "weborganizer": {"__label__adult": 0.0003120899200439453, "__label__art_design": 0.0010900497436523438, "__label__crime_law": 0.0004072189331054687, "__label__education_jobs": 0.00286865234375, "__label__entertainment": 0.00020420551300048828, "__label__fashion_beauty": 0.0002015829086303711, "__label__finance_business": 0.00315093994140625, "__label__food_dining": 0.00031495094299316406, "__label__games": 0.0007796287536621094, "__label__hardware": 0.00232696533203125, "__label__health": 0.0004725456237792969, "__label__history": 0.0006046295166015625, "__label__home_hobbies": 0.000213623046875, "__label__industrial": 0.0008473396301269531, "__label__literature": 0.00032401084899902344, "__label__politics": 0.0004243850708007813, "__label__religion": 0.0004551410675048828, "__label__science_tech": 0.299560546875, "__label__social_life": 0.0001817941665649414, "__label__software": 0.1287841796875, "__label__software_dev": 0.55517578125, "__label__sports_fitness": 0.0002048015594482422, "__label__transportation": 0.0005726814270019531, "__label__travel": 0.0003046989440917969}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 82163, 0.02582]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 82163, 0.26528]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 82163, 0.89494]], "google_gemma-3-12b-it_contains_pii": [[0, 642, false], [642, 4924, null], [4924, 9162, null], [9162, 13925, null], [13925, 18539, null], [18539, 23455, null], [23455, 28136, null], [28136, 32673, null], [32673, 37523, null], [37523, 42101, null], [42101, 46743, null], [46743, 51589, null], [51589, 56294, null], [56294, 61063, null], [61063, 64641, null], [64641, 69523, null], [69523, 73495, null], [73495, 78208, null], [78208, 82163, null]], "google_gemma-3-12b-it_is_public_document": [[0, 642, true], [642, 4924, null], [4924, 9162, null], [9162, 13925, null], [13925, 18539, null], [18539, 23455, null], [23455, 28136, null], [28136, 32673, null], [32673, 37523, null], [37523, 42101, null], [42101, 46743, null], [46743, 51589, null], [51589, 56294, null], [56294, 61063, null], [61063, 64641, null], [64641, 69523, null], [69523, 73495, null], [73495, 78208, null], [78208, 82163, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 82163, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 82163, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 82163, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 82163, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 82163, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 82163, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 82163, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 82163, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 82163, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 82163, null]], "pdf_page_numbers": [[0, 642, 1], [642, 4924, 2], [4924, 9162, 3], [9162, 13925, 4], [13925, 18539, 5], [18539, 23455, 6], [23455, 28136, 7], [28136, 32673, 8], [32673, 37523, 9], [37523, 42101, 10], [42101, 46743, 11], [46743, 51589, 12], [51589, 56294, 13], [56294, 61063, 14], [61063, 64641, 15], [64641, 69523, 16], [69523, 73495, 17], [73495, 78208, 18], [78208, 82163, 19]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 82163, 0.11481]]}
olmocr_science_pdfs
2024-11-27
2024-11-27
03223aea75852135e650becfbbae2bcb66bc883b
[REMOVED]
{"len_cl100k_base": 11306, "olmocr-version": "0.1.53", "pdf-total-pages": 12, "total-fallback-pages": 0, "total-input-tokens": 39325, "total-output-tokens": 14452, "length": "2e13", "weborganizer": {"__label__adult": 0.0003268718719482422, "__label__art_design": 0.00029397010803222656, "__label__crime_law": 0.0002689361572265625, "__label__education_jobs": 0.0007748603820800781, "__label__entertainment": 4.208087921142578e-05, "__label__fashion_beauty": 0.00013124942779541016, "__label__finance_business": 0.00011390447616577148, "__label__food_dining": 0.0002343654632568359, "__label__games": 0.0003998279571533203, "__label__hardware": 0.0004448890686035156, "__label__health": 0.0002925395965576172, "__label__history": 0.0001678466796875, "__label__home_hobbies": 6.681680679321289e-05, "__label__industrial": 0.0001964569091796875, "__label__literature": 0.0002162456512451172, "__label__politics": 0.00017762184143066406, "__label__religion": 0.00034165382385253906, "__label__science_tech": 0.003261566162109375, "__label__social_life": 8.350610733032227e-05, "__label__software": 0.0043182373046875, "__label__software_dev": 0.9873046875, "__label__sports_fitness": 0.0002288818359375, "__label__transportation": 0.00028824806213378906, "__label__travel": 0.0001596212387084961}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 64819, 0.02967]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 64819, 0.6221]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 64819, 0.89068]], "google_gemma-3-12b-it_contains_pii": [[0, 5667, false], [5667, 10943, null], [10943, 16576, null], [16576, 22235, null], [22235, 26213, null], [26213, 28150, null], [28150, 34428, null], [34428, 41038, null], [41038, 47010, null], [47010, 53598, null], [53598, 60833, null], [60833, 64819, null]], "google_gemma-3-12b-it_is_public_document": [[0, 5667, true], [5667, 10943, null], [10943, 16576, null], [16576, 22235, null], [22235, 26213, null], [26213, 28150, null], [28150, 34428, null], [34428, 41038, null], [41038, 47010, null], [47010, 53598, null], [53598, 60833, null], [60833, 64819, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 64819, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 64819, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 64819, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 64819, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 64819, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 64819, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 64819, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 64819, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 64819, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 64819, null]], "pdf_page_numbers": [[0, 5667, 1], [5667, 10943, 2], [10943, 16576, 3], [16576, 22235, 4], [22235, 26213, 5], [26213, 28150, 6], [28150, 34428, 7], [34428, 41038, 8], [41038, 47010, 9], [47010, 53598, 10], [53598, 60833, 11], [60833, 64819, 12]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 64819, 0.11364]]}
olmocr_science_pdfs
2024-12-10
2024-12-10
490a98b8ceb47c06dff7e4bb267c288f97650a5f
More Data Locality for Static Control Programs on NUMA Architectures Adilla Susungi, Albert Cohen, Claude Tadonki To cite this version: Adilla Susungi, Albert Cohen, Claude Tadonki. More Data Locality for Static Control Programs on NUMA Architectures. IMPACT 2017 - 7th International Workshop on Polyhedral Compilation Techniques IMPACT 2017, Jan 2017, Stockholm, Sweden. pp.11. hal-01529354 HAL Id: hal-01529354 https://hal-mines-paristech.archives-ouvertes.fr/hal-01529354 Submitted on 30 May 2017 HAL is a multi-disciplinary open access archive for the deposit and dissemination of scientific research documents, whether they are published or not. The documents may come from teaching and research institutions in France or abroad, or from public or private research centers. L’archive ouverte pluridisciplinaire HAL, est destinée au dépôt et à la diffusion de documents scientifiques de niveau recherche, publiés ou non, émanant des établissements d’enseignement et de recherche français ou étrangers, des laboratoires publics ou privés. More Data Locality for Static Control Programs on NUMA Architectures Adilla Susungi MINES ParisTech, PSL Research University Albert Cohen INRIA and DI, Ecole Normale Supérieure Claude Tadonki MINES ParisTech, PSL Research University ABSTRACT The polyhedral model is powerful for analyzing and transforming static control programs, hence its intensive use for the optimization of data locality and automatic parallelization. Affine transformations excel at modeling control flow, to promote data reuse and to expose parallelism. The approach has also successfully been applied to the optimization of memory accesses (array expansion and contraction), although the available tools in the area are not as mature. Yet data locality also depends on other parameters such as data layout and data placement relatively to the memory hierarchy; these include spatial locality in cache lines and scalability on NUMA systems. This paper presents IVIE, a parallel intermediate language which complements affine transformations implemented in state-of-the-art polyhedral compilers and supports spatial and NUMA-aware data locality optimizations. We validate the design of the intermediate language on representative benchmarks. Keywords data locality, parallel intermediate language, NUMA systems, data layout 1. INTRODUCTION Writing a program with good data locality involves multiple expertises, from the application domain to the computer architecture. It is also an intrinsically non-portable approach. This task must therefore be left to automatic tools capable of finding the appropriate code transformations. Loop transformations (e.g., tiling, fusion or interchange), layout transformations and data placement are examples of techniques involved in temporal and spatial locality optimization. The powerful abstraction provided by the polyhedral model has led to its intensive use for analyzing and performing many of these transformations, targeting regions of the control flow that fit the model constraints (SCoPs). Today, polyhedral tools are capable of producing highly optimized parallel code for multicore CPUs [19], distributed systems [18], GPUs [39] or FPGAs [36]. Unfortunately, data layout transformations are not always taken into account as a first-class citizen in the design and implementation of such tools. Furthermore, an important category of multicore CPUs has been overlooked by most polyhedral compilation studies: Non-Uniform Memory Access (NUMA) systems. These large scale systems organize the physically shared memory across several nodes connected through cache-coherent high-performance links. With such a design, threads either access the memory resources located on the same node as the core executing the thread—the local node—or on a different node—a remote node. Consequently, uncontrolled data placement may yield traffic contention when all threads are accessing the same memory bank. Moreover, accessing data on remote nodes may increase memory latency. NUMA systems were initially introduced as a cure to the scalability issues of symmetric multiprocessors with Uniform Memory Access (UMA), yet ironically, NUMA-unaware programs running on NUMA platforms tend to not benefit from the additional computational power and memory bandwidth offered by the multiple nodes of the system. NUMA-awareness is commonly introduced at run time using tools such as numactl [7], but introducing NUMA-awareness to the application or better, to the compiled code automatically, provides much greater performance portability and transparency for the user. The purpose of this paper is twofold: • highlighting the benefits of integrating NUMA-awareness and layout transformations, more specifically transpositions, in polyhedral compilation; • providing a concrete means for implementing these features in a polyhedral tool. As a proof of concept, Pluto [19] is our demonstration framework but our work is applicable to other tools. It is probably best to consider integrating these features as an ad-hoc implementation in the considered polyhedral tool. Nevertheless, we choose to add such features by the means of a parallel intermediate language which design is currently in progress. This allows us to anticipate future extensions beyond static control region, as our aim for such an intermediate language is its integration in a general purpose compiler. To model different loop- and data-centric optimizations, we implement our intermediate language as a meta-language. Meta-programming facilitates the development of prototypes to study the impact of data placement and layout transformations on a given program. In turn, this study allows to deduce a general algorithm that can be implemented towards complete automation from a high-level programming language such as OpenMP or C. Our contributions are as follows: - We present Ivie, a parallel intermediate language (IL) focusing on the abstraction of array layout and mapping and on the ordering of the operations applied to these arrays. The IL decouples the expression of data transposition, implicit transposition through access functions, and placement on NUMA nodes. - We provide a prototype compilation flow where Pluto is interfaced with a downstream automatic transformation step based on the IL. - We present experiments on several, automatically parallelized PolyBench programs [8]. We study the effect of controlling the data placement on NUMA nodes and of different ways to implement array transpositions (explicitly or implicitly), considering both naively parallelized and tiled versions generated by Pluto. This paper is structured as follows. The Ivie parallel intermediate language is presented in Section 2, the compilation flow for Pluto in Section 3 and experimental results in Section 4. Finally, in Sections 5, 6 and 7, we respectively discuss future work, related work and conclude. 2. **IVIE, AN ARRAY-CENTRIC PARALLEL INTERMEDIATE LANGUAGE** We introduce the Ivie parallel intermediate language (IL), where arrays are considered as first-class data structures with decoupled data layout and NUMA allocation policy control. We choose a decoupled approach for manipulating arrays: the layout, NUMA mapping, and subscript expressions can be modified independently from one another. The language is also designed to ease the composition of array optimizations. Dedicated language constructs are provided for manipulating data layouts and memory allocation policies. And rather than explicit array subscripts, the language provides more abstracted iterators and additional constructs to manipulate iteration spaces—effectively making loop bounds implicit. Figure 1 describes the syntax of the language. We will informally define each construct through small examples. Let us first present the abstraction of access functions, then introduce the memory model and layout for the different types of arrays, and finally the NUMA mapping of these. ### 2.1 Access Function Abstraction A nested loop is abstracted as follows: ```plaintext with i as piter: with j as siter: A[i][j] = k1(A[i][j], u1[i], v1[j], u2[i], v2[j]) ``` First, we need to distinguish iterators for parallel loops from those for sequential loops. Hence, the `with` construct is used to declare an iterator and the `as piter` and `as siter` constructs are respectively used to qualify the declared iterator as used in a parallel and a sequential loop. Secondly, statements are abstracted as functions performing element-wise operations. That is, it takes as arguments and returns array elements only. The order in which arguments are listed corresponds to their order of appearance in the source program. Inductive definitions are made explicit by listing the target array element as the first one in the list. Arrays have a dimension and a layout, set at declaration time. The layout of multi-dimensional may be transposed, i.e., the storage ordering of its elements in memory may follow a permutation of its dimensions. 2.2 **Memory Model and Types of Arrays** Arrays may follow a virtual and a physical memory abstraction. The virtual memory abstraction is a single memory block whereas the physical memory abstraction may take the form of a collection of memory blocks distributed over different NUMA nodes. Virtual arrays are abstract views of physical arrays, derived from the latter through a specific declaration construct. Physical arrays match the row-major layout of C arrays. Arrays of the source code processed by Pluto are mapped to physical arrays when generating the intermediate language from the Pluto output. Virtual arrays insert a layer of abstraction before physical indexing. For example, they may reorder the dimensions of the attached physical array so that indexes in the virtual array may implicitly translated into transposed index of the underlying physical array. The Pluto output is analyzed to detect all occurrences of transposed data accesses, and virtual arrays abstracting the associated dimension reorderings are declared accordingly. For instance, a column-major traversal of the form `A[j][i]` will lead, in Ivie, to the declaration of a virtual array `A_v` associated with the physical array `A`, such that the subscript expression `A_v[i][j]` will implicitly refer to `A[j][i]`. This form of array layout virtualization, and the distributed and replicated patterns over NUMA node, are both inspired from the alignment constructs in High Performance Fortran [2]. 2.3 **Basic Physical Array Declaration** There are two basic constructs for declaring a physical array: - `array(N_d, dtype, [size_1, ..., size_N_d])`, where `N_d` is the number of dimensions, `dtype` is the data type and `size_k` is the size of dimension `k`; - `replicate(name)`, where `name` is that of the array that must replicated. The array declared using this construct inherits the number of dimensions, the data type, the dimensions sizes and the data layout of the original array. ```plaintext # Default declaration mode A1 = array(2, double, [N,N]) # Declaration via replication of existing array A2 = replicate(A1) ``` When converting from Pluto generated code, we only use the `array()` declaration. The `replicate()` construct is used for meta-programming. 2.4 **Data Layout Management** The only layout transformation currently supported is the transposition. Transpositions can be performed using explicitly transposed copies or loop permutations. Loop permutations can be manually handled through interchangeing `with` constructs. In addition, we need other constructs to combine them with the manipulation of access functions and perform explicitly transposed copies. To control which dimensions are the subject of a permutation, array dimensions are ranked in a numerical order with respect to their depth; an N-dimensional array has its dimensions ranked from 1 to N from the outermost to the innermost dimension. Based on this principle, there are two types of transposition constructs for each type of array: - **transpose(name, rank1, rank2)** for transposing a physical or virtual array into a physical array. This also serves as a physical array declaration; - **vtranspose(name, rank1, rank2)** for transposing a physical or virtual array into a virtual array. In both cases, name is the name of the array to be transposed, and rank1 and rank2 are ranks denoting the dimensions to be permuted. Here is an example of the transposition of a 2-dimensional array A into a physical array B: ``` # Transposition stored in a physical array B = transpose(A, 1, 2) ``` We specify ranks 1 and 2 to indicate the corresponding dimensions to be permuted. The order of specification for rank1 and rank2 is interchangeable, meaning that transpose(name, rank1, rank2) is interpreted exactly the same way as transpose(name, rank2, rank1). This was a trivial example. Now, let us assume that array A is a 4-dimensional array for which we want to permute ranks 1 with 3 and 2 with 4. The principle remains the same but requires successive calls to transpose() as in the following sample: ``` # Permuting several dimensions of the same array A2 = transpose(A, 1, 3) B = transpose(A2, 2, 4) ``` Note that if we specify B = transpose(A, 2, 4) instead of B = transpose(A2, 2, 4), the resulting array corresponds to array A with only ranks 1 and 3 permuted. Therefore, when permuting several dimensions of the same array, we need to make sure that at each step, the array of origin stores the latest accumulation of permutations. As memory management is made explicit, it is forbidden to encode such accumulation of permutations as B = transpose(transpose, 2, 4), 1, 3). These principles also apply to vtranspose(). While their syntactic use is similar, using either transpose() or vtranspose() have different impact on the generated code. Using transpose() generates an explicitly transposed copy into a new array and its corresponding function accesses are modified accordingly. Generated code for accumulated permutations is to be optimized and the loops performing the copies should be properly scheduled. On the other hand, as vtranspose() creates a virtual array that will not appear in the generated code, using it allows us to abstract and modify the access function of an array. ### 2.5 Data Placement for NUMA We currently handle two types of placement policies: interleaved allocation and allocation on a specific node. Data placement can only be applied to physical arrays as they are stored in the NUMA memory model. At this stage of the language design, these directly correspond to their respective Linux NUMA API functions [6] (numa_alloc_interleaved() and numa_alloc_onnode()). #### 2.5.1 Interleaving Interleaved allocation of an array consists in mapping memory blocks of size \( N_b \) across a set of NUMA nodes in a round-robin fashion. The numa_alloc_interleaved() function performs this on all nodes available using page sizes only (4096 bytes). In addition, we would like to support any size multiple of a page size as we consider implementing an extended version of numa_alloc_interleaved(). Therefore, considering that the minimum block granularity required is 4096 bytes, we introduce: - **map_interleaved(granul)**, where granul > 0, so that \( N_b = 4096 \times \text{granul} \). The following code sample is an example: ``` # Distribution of each page A.map_interleaved(1) # Distribution by pairs of 2 pages B.map_interleaved(2) ``` #### 2.5.2 Allocation on Specific Node Allocating a physical array on a specific node is done using the construct: ``` 1Data mapping in the memory necessarily involves page sizes; even when wanting to map a single element (e.g., 8 bytes), the entire page size containing the element will be mapped. Hence, we can only handle multiple of page sizes. 2.5.3 Data Replication on Several Nodes Data replication on several nodes requires (i) using `replicate()` and `onnode()`, (ii) introducing as `cpiter`, a new category of iterators and (iii) virtual arrays declared using a special construct: ``` select([cond, name], ..., [condN, nameN]) ``` where `[cond, name]` is a pair associating a condition `cond` to an array `name`. The number of arguments is equal to the number of NUMA nodes considered. Conditions are specified with respect to the NUMA system’s topology and additional thread scheduling. Supposing that we need to replicate array `A` on 2 NUMA nodes, Listing 1 provides a full example of how to do so. Listing 2 is an example of generated code. This example shows the complementary usage of virtual arrays besides abstracting function accesses. As one purpose of replicating the same array on several node is to avoid threads performing remote accesses, in a parallel loop, we need to modify the control flow so that each thread accesses the closest copy provided that thread migration is disabled. Using `select()` allows us to concisely abstract such modification. In the condition, `{it}` denotes an iterator that is the same across all conditions of the same `select()`. It may also denote the retrieval of a thread ID using an API function. In order to identify to which iterator `{it}` actually corresponds in the loop of interest, as `cpiter` is used. Nevertheless, we look forward to provide a more robust abstraction than `{it}` to be able to handle a wider range of applications. Several virtual arrays declared using `select()` within the same statement must either have the same set of conditions, or a least a subset of the greatest set of conditions that exists. Remarks. In theory, any `piter` can be transformed into a `cpiter`, meaning that any parallel dimension in the same nested loop is eligible for such an iterator characterization. Furthermore, due to the composability of array declarations, an array associated to a condition can also be a virtual array declared using `select()`. In practice, these would definitely require optimizations but in the case of SCOPs, this is unlikely to occur. Therefore, we omit the extended syntax that allows us to match a `cpiter` to virtual array and we assume only one `cpiter` per loop. Preventing threads from performing remote accesses can be done in different ways. We currently limit ourselves to the method shown in Listing 2, despite not being the most optimal. Other more efficient methods are considered as future work. 2.6 Implementation and Code Generation IVIE IL perfectly fits into the syntax of Python. Thus, it is implemented similarly to a domain-specific language embedded into Python for quick usage as a meta-programming language. Even though our implementation is close to deep embedding, as an intermediate language, we have a slightly different approach. We reuse the existing expression tree, that is, the C abstract syntax tree (AST) already provided after parsing the source code using pycparser [9]. More precisely, we parse the IVIE program to generate its corresponding Python AST using RedBaron [11], a parser and full syntax tree (FST) generator for Python programs. This allows us to perform automatic IL transformations in the near future. When the IVIE program is transformed and ready for code generation, its FST is analyzed for extracting any information concerning arrays. Then, the C AST is modified with respect to the extracted information. Finally, we generate the resulting OpenMP C code. Remark. As stated in Section 2.1, the order of appearance of arguments corresponds to the order in which array elements appear when traversing the C AST. In an inductive definition, the target array is positioned as the first argument. Consequently, modifying an argument in IVIE code results into the modification of the array element whose position matches in the C AST. RedBaron’s functionalities ease our decoupling principle. Indeed, we do not need to explicitly traverse the Python AST to extract information; we can directly find different categories of nodes using pattern matching. Thus, when wanting to extract any information on array allocation, we just need to find the list of nodes containing the string "map_". We then identify to which array name the allocation policy is associated and we store it in the data structure corresponding to the concerned array. 3. A MODIFIED PLUTO TOOL FLOW Our IL can be integrated into the flow of Pluto to enable NUMA-awareness and additional layout transformations. We simply need to generate an IVIE program from a Pluto-generated code, exporting the relevant semantical properties (starting with parallelism) from bands of per- mutable dimensions exposed by the Pluto algorithm. To simplify this process, we delimit array declarations and SCoPs using pragmas. The tool flow is as follows (Pluto default steps in italic): 1. Extract polyhedral representation using Clan. 2. Perform optimizations and parallelization. 3. Generate C code using CLooG. 4. Apply GCC preprocessing on the CLooG-generated code to replace each #define by their actual statements. 5. Generate the IVIE program: A. collect array declarations; B. parse the preprocessed code; and for each dimension in each band, i. if the dimension is marked parallel, characterize the IVIE iterator as \texttt{piter}, ii. if not, characterize it as \texttt{siter}; C. print output IVIE file. 6. [Currently handled by hand] Meta-program the desired IVIE code transformation. 7. Parse the IVIE program and generate its Python AST using RedBaron. 8. Parse the OpenMP C program and generate its C AST using pycparser. 9. From the Python AST, collect all information concerning arrays and store them in data structures, creating sets of physical arrays and virtual arrays. 7. Proceed with C AST modification, using the Pluto-generated code and the transformed IVIE meta-program. 8. Generate code from modified C AST. We currently express IVIE code transformations through manual (IVIE) meta-programming. This should be automated when the appropriate heuristics will be stabilized. The present study can be seen as an important step towards the design and implementation of such automated optimizations. 4. EXPERIMENTAL RESULTS The purpose of this section is to present the effects of additional NUMA allocation and transposition in different application scenarios. There is a clear separation between the optimizations handled by Pluto and those handled by IVIE IL. Pluto is in charge of all control flow optimizations and parallelism extraction, whereas our post-pass implements data placement on NUMA systems as well as the actual transpositions. Pluto outputs may be complex; hence we handle affordable cases. The automated search for optimal solutions involving, for instance, the time spent in any additional data copying, or coupling NUMA decisions which additional run-time specifications such as thread binding, is part of future work. We present case studies of several PolyBench [8] programs: Gemver, Gesummv, Gemm and Covariance. The minimal set of Pluto options are tiling for L1 cache, parallelism and vectorization. All programs are compiled with gcc -03 -march-native which enables vectorization by default. We execute them on a 2 sockets NUMA system with 36 Intel Xeon cores E5-2697 v4 (Broadwell) at 2.30 GHz distributed across 4 nodes (9 cores per node, L1 cache; 32K). NUMA optimizations involve interleaved allocation and data replications. We use simple guidelines to decide which policy to choose: - An array is replicated on all nodes if each thread performs read-only accesses on the entire array. As replicating written arrays would require additional heuristics to ensure data coherence, we do not yet handle such cases. - The remainder may be interleaved on all nodes, especially multi-dimensional arrays, to reduce traffic contention. Following this rule, Gemver appears to be the only program in which we apply additional data replications. Transpositions are performed at initialization time using indexes permutation only. Although our framework supports transpositions at well-defined points in the control flow, no such additional data copying was attempted in the current set of experiments. Some examples of meta-programs are provided in Appendix. Gemver. We compare different Pluto-generated versions of Gemver: - The default output of Pluto; - The addition of NUMA placement only, using replication and interleaved allocation; - The addition of transpositions only; - The addition of combined NUMA placement and transposition. Moreover, we consider two Pluto outputs as our baselines: the first is generated using the no fuse heuristic and the second, the smart fuse heuristic. We do not consider the max fuse option as it is not suitable for Gemver. Figure 2 shows the speedup of each program with respect to the default Pluto output considered. The smart fuse version scales better than the no fuse version. Indeed, the fusion of the two first loops favours cache reuse. However, compared with a naive parallel version of Gemver, the two Pluto outputs fare no better, meaning that optimizing temporal locality only is not sufficient. As 10 cores is the threshold from which NUMA effects appear, we can also see in Figure 2 that they poorly scale with 16 and 36 cores. According to the aforementioned guidelines, we applied the exact same NUMA placement in both outputs. While this solution improves both, no fuse provides the best performance with 36 cores. When using interleaved allocation for an array, the different threads accessing it must perform row-major accesses to preserve node locality as much as possible. This is the case with no fuse. With smart fuse, the first loop is permuted in order to perform the fusion legally. Despite enhancing cache reuse, as column-major accesses are still performed, some node locality is lost. Thread binding using \texttt{OMP_PROC_BIND} seem not to significantly improve performance. It may even lower the speedup. We noticed that when performing the same experiments with NUMA placement based on replications only, the positive effects of thread binding were much more noticeable despite less absolute speedup. Interleaved allocation therefore seem to inhibit the effects of thread binding as it may reduce node locality per threads; in this case, thread migration may operate as a counterbalance. On the other hand, layout transformations are better suited to smart fuse as data reuse is much more enhanced. Furthermore, this allows threads to perform row-major accesses with respect to interleaved mapping. Yet such a systematic transformation does not align well with the schedule of the no fuse version, hence the degraded performance. Therefore, at this level of optimizations, the best version of Gemver appears to involve smart fuse, NUMA placement and transposition. Additional data replications using memcpy add 0.3 ms to all execution instances of versions with NUMA placement. They therefore have a negligible impact on the performance observed. Figure 2: Speedups for different versions of Gemver. Execution instances with thread binding marked with [b]. Gesummv. Gesummv with no fuse and max fuse are our Pluto baselines. Results are depicted in Figure 3. Similarly to the case of Gemver, optimized temporal locality alone does not provide better performance than the naive parallel version for Pluto-generated codes. These also scale poorly without NUMA-aware placement. We applied interleaved allocation, which brings a 3× speedup on 16 cores and 4× speedup on all 36 cores. As we observed that thread binding may not match with interleaved allocations, we consider exploring the effects of changing the granularity of interleaving for further improvements. Covariance. In this case, Pluto delivers much better performance than the naive parallel version. We compare versions with NUMA placement only (interleaved data allocation), transposition as shown in Figure 4, and both together. Figure 5 shows that the main improvement on the naive parallel version results from the transposition. However, applying the same transposition to the Pluto output considerably hurt the program’s performance, similarly to what we observe for Gemver with no fuse. NUMA allocations have little positive impact on the naive version and none on the Pluto output, given that temporal locality already optimizes cache usage. 2 No fuse and smart fuse heuristics result into the same generated code. Figure 3: Speedups for different versions of Gesummv Figure 4: Covariance with transposition of array data Figure 5: Speedups for different versions of Covariance Gemm. As shown in Figure 6, all versions scale very well, but additional locality optimization and vectorization in Pluto-based outputs considerably improve performance. We measure the execution time of multiple untiled parallel versions including two methods for eliminating column-major accesses. The first version eliminates such accesses through data transposition, and the second version is obtained through loop interchange (ijk). Loop interchange is also the transformation that Pluto performs, in addition to tiling. On this machine, loop interchange seems more appropriate than data transposition on the naive parallel version. We reproduced these experiments on two other machines: a 4 core Intel Core i7-4910MQ CPU (Haswell) at 2.90GHz and a 16 core Intel Xeon CPU E5-2660 (Sandy Bridge) at 2.20GHz. While we observed the same tendency on the Haswell with or without the -O3 option, we noticed the opposite on the Sandybridge when disabling this option. This is probably due to the lower AVX computation throughput compared to memory bandwidth: the program (with these optimizations) is definitely compute-bound on Sandybridge and NUMA optimizations have little impact. These results show that, on one hand, bandwidth-bound programs that cannot be improved using Pluto’s default heuristics (Gemver and Gesummv) do benefit from heuristics on NUMA placement and transpositions. On the other hand, programs already benefiting a lot from Pluto’s heuristics do not require additional NUMA placement as most data accesses hit the cache. Moreover, in some cases and depending on the machine, it seems wiser to rely on loop scheduling transformations rather than data layout transformations. These case studies show the advantages of complementing polyhedral tools with placement heuristics on NUMA nodes and transposition. NUMA placement tend to improve a program’s scalability, especially from the threshold from which the NUMA effect appears. On the other hand, transposition helps improving the absolute speed-up. Combining both is an interesting alternative provided that further optimizations are performed. Indeed, control flow modifications introduced to incorporate more optimizations opened the door for additional loop optimizations that we were not yet able to implement. Introducing IVIE IL in Pluto allows widening the range of options for optimizing SCoPs, especially on NUMA systems. Through static analyses, optimization decisions could be automatically provided. For NUMA optimizations, this could reduce the need to handle all heuristics at execution time. 5. FUTURE WORK Our first experiments call for deeper investigation of the interplay of data layout and schedule transformations, and for the design and implementation of the associated heuristics. Control flow optimizations. For the moment, all control flow optimizations are left to Pluto. For greater impact, we need to integrate complementary control flow optimizations on the IL itself. This has several advantages: - Performing layout transformations may open the door for further loop transformation such as fusion. On the other hand, data replications as currently performed definitely require some form of hoisting. More generally, the methods for handling replicated data may generate as many loops as there are replicated arrays and assign each loop to a thread group. Being able to manipulate the control flow will allow us to generate more efficient programs. - Concerning replications again, the method involving complementary hoisting may only be implemented in a polyhedral framework if the condition is affine. Yet replication conditions may depend on a built-in function (e.g., to retrieve the thread id, using a parallel programming API). Such transformations are out of the model’s scope, and are typically not supported by compilers either. Thanks to the semantics of our IL, we will be able to handle such optimizations. More expressiveness for loop iterators. At this stage of design, we distinguish iterators that are used in a parallel or a sequential loop. Such distinction is based on explicit parallelism exposed in the source code (with pragmas for instance). However, when dealing with Pluto’s own internal tree representation(s), some dimensions may be parallel yet not exploited as a parallel loop, and some bands of dimensions may carry permutability properties. We need to carry these properties along the IL, to preserve the capability to implement loop permutations or any other loop transformations. Implementation. For more complex code transformations, a deeper embedding into Python may be considered, instead of directly patching the existing AST. Indeed, modifications such as generating multiple loops, each one assigned to a thread group, may motivate the reconstruction of a complete tree. Maintenance and greater flexibility of the design are other motivations for such a refactoring. Optimizations. Another aspect that must be taken into account is the time spent in data copying when replicating over several nodes. This depends on the machine and on the way arrays are allocated. The same applies to explicit transposition. We need to make sure that this does not overshadow the program’s performance, and a model must be developed to better assess the profitability of replication and transposition. Polyhedral analyses may be leveraged to do so. Provided a known number of threads and a static thread scheduling, we can determine the set of elements accessed per thread, using the size of their loop chunk. Then, we can choose which NUMA policy can be applied, for instance, according to the guidelines listed at the beginning of Section 4. If interleaved allocation is chosen, such information can also help determining the interleaving granularity. As for transpositions, we can determine different possible schedules for explicit transpositions and their possible transformation into implicit ones. Finally, using iterative compilation and auto-tuning, we may determine the appropriate choices for a given architecture. 6. RELATED WORK Data placement using parallel languages. Optimizations for NUMA systems is a broad research topic. We therefore limit ourselves to closely related work in programming language design and implementation. One motivation for handling NUMA placement in an intermediate language is the lack of such support in existing parallel programming languages. HPF, X10 or Chapel provide constructs for data distribution across processes. Chapel also includes preliminary support for NUMA in its locale models; OpenMP only provides the OMP_PROC_BIND environment variable to disable thread migration; both mechanisms take action at execution time only. One exception is GNU UPC [1], a toolset providing a compilation and NUMA-aware execution environment for programs written in UPC. Very few languages allow data distribution on NUMA nodes. This task is generally performed with third party tools such as libnuma [6] or hwloc [6]. Some attempts to fill this gap have been proposed for OpenMP [17, 25, 33] and Intel TBB [32]. Yet none of these have been integrated into the official language specifications. Languages and efficient code generation. IVIE is not to be considered, strictly speaking, as a new programming language. Nevertheless, being implemented as meta-language to model optimizations, it presents some similarity with several other languages summarized in Table 1. Most of the presented languages target GPUs, except Halide [38] and PolyMage [34] but these do not provide explicit constructs for NUMA placement. Vobla [15] and Loo.py [30] appear to be the only languages that provide explicit constructs for performing layout transformations. However Loo.py provides additional layout transformation such as padding. IVIE is the only language that is used post-polyhedral techniques; besides the non polyhedral Halide, PolyMage and Xfor are fully polyhedral-based and Loo.py has access to polyhedral optimization by means of the islpy library. As for Vobla and Pencil, the latter implements domain-specific transformations and compiles to the latter, Pencil serving as an intermediate language for Vobla to generate high performance GPU code using PPCG [39]. Other non polyhedral-related solutions have been proposed to take into account data layout transformations, such as Raja [10] and Kokkos [5]. These tools target both CPUs and GPUs, and the ability to apply specific layouts to both architectures is crucial. Furthermore, Kokkos proposes an interface with hwloc, mostly for retrieving information on the topology and performing thread binding. The approach of combining the polyhedral representation with another intermediate representation has also been applied in the CHILL compiler targeting both GPUS and multicore. Indeed, Zhang et al. [41] compose AST transformations to polyhedral transformation for optimizations such as loop unrolling or partial sum for higher-order stencils. Parallel optimizations in the polyhedral model. Being able to handle parallel programs within the polyhedral model has been the subject of several investigations. Basically, three main approaches have been used. The first approach is to use the model as is; Basupalli et al [14] consider the parallel construct omp for as a program transformation that assigns new time-stamps to instances of the program and Darte et al. [23] propose a method for liveliness analysis where conflicting variables are computed based on the notion of partial order and the happens-before relationship that can be computed with the ISCC calculator. The second approach is characterizing an analyzable subset for a specific parallel language; indeed, Yuki et al [40], Pellegrini et al. [35] and Cohen et al [22] respectively defined polyhedral subsets of X10, MPI and OpenStream [37]. The last approach is extending the model, which has been proposed by Chatarasi et al [20]. Parallel intermediate languages. Despite being coupled with the polyhedral model in this paper, we are not working towards a polyhedral-specific intermediate language. We rather aim at general-purpose compilation of parallel languages, following the steps of INSPIRE [26] or SPIRE- d [28]. INSPIRE is the intermediate representation of the Insieemer compiler [4] and SPIRE is a methodology for introducing the semantics of parallel programs in existing intermediate representations; proofs of concepts for these have been demonstrated for compilers such as PIPS [27] or LLVM [29]. Such intermediate representations abstract the semantics of parallel programs, i.e. parallel constructs, barriers or communications, but none of them handle data placement or layout transformation. Memory optimizations. As for optimizations targeting memory, tools such as Bee+Cl0k [12] or SMO [16] tackle the reduction of memory footprint through intra- or even inter-array memory reuse. Clauss and Meister [21] also perform layout transformation to enhance spatial locality but our work is much more similar to that of Lu et al. [31]; it focuses on layout transformations for locality on NUCA (Non-Uniform Cache Access) multiprocessors. In this work, the polyhedral model is first used to analyze indexes and array reference functions, then layout optimizations are applied. 7. CONCLUSION We highlighted the benefit of introducing NUMA-awareness and additional layout transformations to a state-of-the-art polyhedral flow. In particular, we demonstrated the feasibility of a static placement heuristic matching the NUMA topology. We illustrated these results on a modified version of the automatic parallelizer and locality optimizer Pluto, integrating it with IVIE, a specifically-designed parallel intermediate language to model such layout and mapping transformations. In IVIE, arrays are first-class data structures on which operations such as data placement or transposition can be performed. Future work involves being able to integrate more closely with control flow optimizations, adding expressiveness for further abstracting a diverse range of loop iterators, and a designing a more robust implementation of the code generator supporting complex compositions of optimizations. 8. REFERENCES Table 1: Current position of Ivie towards several languages. (N/A: not applicable) <table> <thead> <tr> <th>Target</th> <th>Constructs for layout management</th> <th>Constructs for NUMA placement</th> <th>Position towards polyhedral techniques</th> </tr> </thead> <tbody> <tr> <td>Halide [38]</td> <td>CPU / GPU</td> <td>No</td> <td>No</td> </tr> <tr> <td>PolyMage [34]</td> <td>CPU / GPU</td> <td>No</td> <td>Yes</td> </tr> <tr> <td>Xfor [24]</td> <td>CPU / GPU</td> <td>No</td> <td>No</td> </tr> <tr> <td>Vobla [15]</td> <td>GPU</td> <td>Yes</td> <td>N/A</td> </tr> <tr> <td>PENCIL [13]</td> <td>GPU</td> <td>No</td> <td>N/A</td> </tr> <tr> <td>Loo.py [30]</td> <td>GPU</td> <td>Yes</td> <td>N/A</td> </tr> </tbody> </table> [29] D. Khaldi, P. Jouvelot, F. Irigoin, C. Ancourt, and ### APPENDIX #### A. GEMVER SMART/NO FUSE WITH NUMA PLACEMENT AND TRANSPosition The following is Gemver smart fuse with NUMA placement and transposition meta-programmed in Ivy. ```python # Default declarations A = array(2, DATA_TYPE, [n, n]) u1 = array(1, DATA_TYPE, [n]) A_v = vtranspose(A, 1, 2) A_v[i][j] = init() # Meta-programmed declarations A_v = vtranspose(A, 1, 2) A_map_interleaved(1) u1_map_interleaved(1) u2_map_interleaved(1) u1_1 = array(1, DATA_TYPE, [n]) u1_2 = array(1, DATA_TYPE, [n]), v1_3 = array(1, DATA_TYPE, [n]) v2_2 = array(1, DATA_TYPE, [n]) v2_1 = array(1, DATA_TYPE, [n]) v2 = array(1, DATA_TYPE, [n]) z = array(1, DATA_TYPE, [n]) x = array(1, DATA_TYPE, [n]) y = array(1, DATA_TYPE, [n]) w = array(1, DATA_TYPE, [n]) # (it) denotes here the retrieval of thread IDs with i as siter: u1 = array(1, DATA_TYPE, [n]) u2 = array(1, DATA_TYPE, [n]) u3 = array(1, DATA_TYPE, [n]) u = array(1, DATA_TYPE, [n]) w = array(1, DATA_TYPE, [n]) x = array(1, DATA_TYPE, [n]) y = array(1, DATA_TYPE, [n]) z = array(1, DATA_TYPE, [n]) with j as siter: A_v[i][j] = init() ``` Gemver has no fuse with NUMA placement and transposition is almost the same code. The following code shows the differences. ```c # Tile dimension with t2 for t5 # Tile dimension with t3 for t4 with t2 as piter: with t3 as siter: with t4 as siter: with t5 as siter: A[t4][t5] = f3(A[t4][t5], u1_s[t4], v1[t5], u2_s[t4], v2[t5]) x[t5] = f3(x[t5], A[t4][t5], y[t4]) with t2 as piter: with t3 as siter: x[t3] = f5(x[t3], z[t3]) with t2 as piter: with t3 as siter: with t4 as siter: with t5 as siter: w[t4] = f9(w[t4], A[t4][t5], x[t5]) with t1 as piter: with t4 as siter: y[t4] = f1() with t3 as siter: with t4 as siter: with t6 as siter: y[t4] = f4(B[t4][t6], x[t6], y[t4]) with t4 as siter: with t6 as siter: tmp[t4] = f5() with t3 as siter: with t4 as siter: with t6 as siter: tmp[t4] = f8(A[t4][t6], x[t6], tmp[t4]) with t4 as siter: with t6 as siter: y[t4] = f9(tmp[t4], y[t4]) ``` The *max fuse* version has the same NUMA mapping but fuses all loops as follows: ```c with t1 as piter: with t4 as siter: y[t4] = f1() with t3 as siter: with t4 as siter: with t6 as siter: y[t4] = f4(B[t4][t6], x[t6], y[t4]) with t4 as siter: with t6 as siter: tmp[t4] = f5() with t3 as siter: with t4 as siter: with t6 as siter: tmp[t4] = f8(A[t4][t6], x[t6], tmp[t4]) with t4 as siter: with t6 as siter: y[t4] = f9(tmp[t4], y[t4]) ``` C. PLUTO-GENERATED GEMM WITH TRANSPOSITION The following is the *no fuse* version. ```c # Default declarations A = array(2, DATA_TYPE, [ni, nk]) B = array(2, DATA_TYPE, [nk, nj]) C = array(2, DATA_TYPE, [ni, nj]) # Meta-programmed declaration B_v = vtranspose(B, 1, 2) # Initializations with i as siter: with j as siter: B_v[i][j] = init() with t2 as piter: with t3 as siter: with t4 as siter: with t5 as siter: C[t4][t5] = f3() with t2 as piter: with t3 as siter: with t4 as siter: with t5 as siter: tmp[t5] = f9(C[t5][t6], A[t5][t7], B[t6][t7]) ``` B. GESUMMV MAX/NO FUSE WITH NUMA PLACEMENT The following is the *no fuse* version. ```c # Default declarations A = array(2, DATA_TYPE, [n, n]) B = array(2, DATA_TYPE, [n, n]) tmp = array(1, DATA_TYPE, [n]) x = array(1, DATA_TYPE, [n]) y = array(1, DATA_TYPE, [n]) # Meta-programmed mapping A.map_interleaved(1) B.map_interleaved(1) with t2 as piter: with t3 as siter: with t4 as siter: with t5 as siter: x[t5] = f7(x[t5], A[t4][t5], y[t4]) with t2 as piter: with t3 as siter: x[t3] = f5(x[t3], z[t3]) with t2 as piter: with t3 as siter: with t4 as siter: with t5 as siter: w[t4] = f9(w[t4], A[t4][t5], x[t5]) with t1 as piter: with t4 as siter: y[t4] = f1() with t3 as siter: with t4 as siter: with t6 as siter: y[t4] = f4(B[t4][t6], x[t6], y[t4]) with t4 as siter: with t6 as siter: tmp[t4] = f5() with t3 as siter: with t4 as siter: with t6 as siter: tmp[t4] = f8(A[t4][t6], x[t6], tmp[t4]) with t4 as siter: with t6 as siter: y[t4] = f9(tmp[t4], y[t4]) ```
{"Source-Url": "https://hal-mines-paristech.archives-ouvertes.fr/hal-01529354/file/A-649.pdf", "len_cl100k_base": 10275, "olmocr-version": "0.1.50", "pdf-total-pages": 12, "total-fallback-pages": 0, "total-input-tokens": 40423, "total-output-tokens": 13560, "length": "2e13", "weborganizer": {"__label__adult": 0.00047969818115234375, "__label__art_design": 0.0005178451538085938, "__label__crime_law": 0.0004241466522216797, "__label__education_jobs": 0.0005803108215332031, "__label__entertainment": 0.00011032819747924803, "__label__fashion_beauty": 0.0002224445343017578, "__label__finance_business": 0.0002987384796142578, "__label__food_dining": 0.0004651546478271485, "__label__games": 0.0008673667907714844, "__label__hardware": 0.00267791748046875, "__label__health": 0.0007395744323730469, "__label__history": 0.0004761219024658203, "__label__home_hobbies": 0.0001544952392578125, "__label__industrial": 0.0010128021240234375, "__label__literature": 0.00026798248291015625, "__label__politics": 0.0004608631134033203, "__label__religion": 0.0008921623229980469, "__label__science_tech": 0.1256103515625, "__label__social_life": 9.91225242614746e-05, "__label__software": 0.007183074951171875, "__label__software_dev": 0.85498046875, "__label__sports_fitness": 0.00046896934509277344, "__label__transportation": 0.0009565353393554688, "__label__travel": 0.00031876564025878906}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 54177, 0.0364]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 54177, 0.41414]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 54177, 0.87184]], "google_gemma-3-12b-it_contains_pii": [[0, 1046, false], [1046, 5721, null], [5721, 11589, null], [11589, 15888, null], [15888, 20641, null], [20641, 26684, null], [26684, 29001, null], [29001, 34211, null], [34211, 41025, null], [41025, 46928, null], [46928, 51032, null], [51032, 54177, null]], "google_gemma-3-12b-it_is_public_document": [[0, 1046, true], [1046, 5721, null], [5721, 11589, null], [11589, 15888, null], [15888, 20641, null], [20641, 26684, null], [26684, 29001, null], [29001, 34211, null], [34211, 41025, null], [41025, 46928, null], [46928, 51032, null], [51032, 54177, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 54177, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 54177, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 54177, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 54177, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 54177, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 54177, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 54177, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 54177, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 54177, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 54177, null]], "pdf_page_numbers": [[0, 1046, 1], [1046, 5721, 2], [5721, 11589, 3], [11589, 15888, 4], [15888, 20641, 5], [20641, 26684, 6], [26684, 29001, 7], [29001, 34211, 8], [34211, 41025, 9], [41025, 46928, 10], [46928, 51032, 11], [51032, 54177, 12]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 54177, 0.02025]]}
olmocr_science_pdfs
2024-11-27
2024-11-27
6c56aedeb1d9581264ab2711c8ec58d8cd0e11c8
Helping Analysts Trace Requirements: An Objective Look Jane Huffman Hayes, Alex Dekhtyar, Senthil Karthikeyan Sundaram, Sarah Howard Computer Science Department University of Kentucky hayes@cs.uky.edu, dekhtyar@cs.uky.edu, skart2@uky.edu, sehowa2@uky.edu Abstract This paper addresses the issues related to improving the overall quality of the requirements tracing process for Independent Verification and Validation analysts. The contribution of the paper is three-fold: we define requirements for a tracing tool based on analyst responsibilities in the tracing process; we introduce several new measures for validating that the requirements have been satisfied; and we present a prototype tool that we built, RETRO (REquirements TRacing On-target), to address these requirements. We also present the results of a study used to assess RETRO’s support of requirements and requirement elements that can be measured objectively. Research 1. Introduction The fundamental purpose of Verification and Validation (V&V) and Independent Verification and Validation (IV&V) is to ensure that the right processes have been used to build the right system. To that end, we must verify that the approved processes and artifacts are guiding development during each lifecycle phase as well as validate that all requirements have been implemented at the end of the lifecycle. A requirements traceability matrix (RTM) is a prerequisite for both of these. Though Computer-Aided Software Engineering tools such as DOORS [23], RDD-100 [12], and Rational RequisitePro [20] can assist, we have found that often developers do not build the RTM to the proper level of detail or at all. V&V and IV&V analysts are faced with the time consuming, mind numbing, person-power intensive, error prone task of “after the fact” requirements tracing to build and maintain the RTM. Examples of V&V/IV&V activities that can’t be undertaken without an RTM include, but are not limited to: verification that a design satisfies the requirements; verification that code satisfies a design; validation that requirements have been implemented and satisfied; criticality analysis; risk assessment; change impact analysis; system level test coverage analysis; regression test selection. V&V/IV&V can be viewed as the backbone of safety-critical, mission-critical, and Critical-Catastrophic High Risk (CCHR) systems. Similarly, the RTM can be viewed as the backbone of V&V/IV&V. Requirements tracing consists of document parsing, candidate link generation, candidate link evaluation, and traceability analysis. As an example, consider requirements in a high level document such as a System Specification being traced to elements in a lower level document such as a Software Requirement Specification. Generally, after the documents have been parsed and requirements have been extracted from the two document levels, an analyst will manually read each high level requirement and low-level element and assign keywords to each. A keyword-matching algorithm is then applied to build lists of low-level elements that may potentially satisfy a given high-level requirement. These are called candidate links. There are two commonly accepted metrics in evaluating candidate links: the percentage of actual matches that are found (recall) and the percentage of correct matches as a ratio to the total number of candidate links returned (precision). In the process called candidate link evaluation, the analyst reviews the candidate links and determines which are actual, or true links, and which are not links (false-positives, bad links). To achieve this, the analyst typically examines visually the text of the requirements, determines the meanings of the requirements, compares the meanings and makes the decision based on whether (s)he believes that the meanings are sufficiently close. This determination is based on human judgment and bears all the advantages and disadvantages that are associated with that. After tracing is complete, the analyst generates reports of the high level requirements that do not have children and the low level elements that do not have parents (traceability analysis). Current approaches to after-the-fact tracing have numerous shortcomings: they require the user to perform interactive searches for potential linking requirements or design elements, they require the user to assign keywords to all the elements in both document levels prior to tracing, they return many potential or candidate links that are not correct, they fail to return correct links, and they do not provide support for easily retracing new versions of documents. To ensure requirement completion and to facilitate change impact assessment, a method for easy “after-the-fact” requirements tracing is needed. Previously, we focused solely on the problem of generating candidate links, discussed in [11]. Specifically, we showed that information retrieval (IR) methods were effective and efficient when used to generate candidate link lists. Our focus has now broadened to the overall requirements tracing process. The penultimate goal of this NASA-funded research is to develop an efficient, effective tracing tool that makes the best use of the analyst’s time and expertise (the ultimate goal being the actual improvement in requirements tracing analysis). To that end, this paper provides three contributions: (i) we investigate the analyst responsibilities in performing tracing; (ii) we derive unique high-level analyst-oriented tool requirements from these; and, (iii) we present a prototype tool, RETRO (REquirements TRacing On-target), and evaluate it with respect to the requirements. The paper is organized as follows. Section 2 presents the requirements for an effective requirements tracing tool. Section 3 discusses our tool and how it satisfies the requirements of Section 2. Section 4 discusses the results obtained from evaluation. Related work in requirements tracing is presented in Section 5. Finally, Section 6 presents conclusions and areas for future work. 2. Requirements for an effective requirements tracing tool To set the stage for our work, we must first understand the responsibilities of an analyst who has been tasked to perform a requirements trace. The analyst is required to: (a) identify each requirement; (b) assign a unique identifier to each requirement; (c) for each requirement to be traced (say for example from a high level document to a low level document), locate all children requirements present in the lower level document; (d) for each low level requirement, locate a parent requirement in the high level document; (e) examine each high level traced requirement and determine if it has been completely satisfied by the low level requirements that were selected as links; (f) prepare a report that presents the traceability matrix (low level requirements traced to high level requirements); and (g) prepare a summary report that expresses the level of traceability of the document pair (that is, what percentage of the high level requirements were completely satisfied, what percentage of low level documents had no parents, etc.). Let us next examine how automation may facilitate these responsibilities. A tool could easily assist the analyst in the identification and subsequent extraction and “tagging” of requirements [(a), (b)]. Similarly, generation of requirements traceability matrix reports and traceability summary reports lends itself well to automation [(f), (g)]. In fact, a number of proprietary tools, such as SuperTracePlus (STP) [10,16], and commercial tools already address these items. The remaining items are of greater interest and importance to researchers and practitioners. Items (c)–(e) conceivably require the analyst to examine every low level requirement for each high level requirement. Even in a small document pair that consists of 20 high level requirements and 20 low level requirements, an analyst might have to examine 400 candidate links. If we build a tool to automate items (c) - (e), the analyst will still have certain critical responsibilities. These include evaluating candidate links; making decisions on whether or not candidate links should be accepted or rejected; making decisions on whether or not to look for additional candidate links; making decisions on whether or not a requirement has been satisfied completely by its links; and deciding if the tracing process is complete. It is clear that a human analyst must have the final say in all decisions. The key to successful automation lies not in removing the human decision-maker from the loop, but rather, in introducing an automated agent that takes care of the mundane, time-consuming parts of the process and allows the analyst to concentrate on the parts that really require human decision-making. What can be automated, as shown in [11], is the generation of candidate links to address items (c) and (d). With this in mind, we move to the identification of the desirable attributes of an effective tracing tool. Most research in the area of requirements tracing has focused on models of requirements tracing [19] or has looked at recall and precision to assess the accuracy of the applied linking algorithms [3, 14]. To our knowledge, there has not been work published that details the requirements for an effective requirements tracing tool. In addition to specifying such requirements, we provide a validation mechanism for each requirement, and then in Sections 3 and 4 demonstrate that our tracing tool satisfies the requirements we have addressed to date. Note that we have chosen to define the requirements in an informal, textual narrative format. We do not claim that these requirements possess the quality attributes that should be present in formal software requirements. Rather, we offer them as a starting point for discussion with other researchers. First, we define a requirements tracing tool as a special-purpose software that takes as input two or more documents in the project document hierarchy (without loss of generality we assume that individual requirements in these documents have been successfully defined and are easily extractable) and outputs a traceability matrix, that is a mapping between the requirements of the input documents. In the rest of the paper, we concentrate on the process of forward tracing for a pair of documents --- most other requirements tracing tasks can be reduced to this problem. From the perspective of a development manager or a safety manager (in the case of a safety-critical system), the most important attribute that a requirements tracing tool can possess is that its final results are believable and can be trusted. Similarly, the analysts who use the tool should have confidence in the candidate link lists provided by the software (addressing items (c) and (d)). Lack of this quality in a tool might result in an analyst wasting time by searching for additional candidate links. We refer to this attribute as “believability,” and it constitutes the first requirement. **Requirement 1:** **Specification:** “Believability” - The requirements tracing tool shall generate candidate links and shall solicit analyst feedback and shall re-generate candidate links based on the feedback such that the final trace shall very accurately reflect the theoretical “true trace.” Believability is constituted of three sub-requirements or sub-elements: accuracy, scalability, and utility discussed below. **Accuracy:** The extent to which a requirements tracing tool returns all correct links and the extent to which the tool does not return incorrect links. **Scalability:** The extent to which the requirements tracing tool is able to achieve accuracy for “small” tracesets as well as “large” tracesets. In this context, we define a “small” traceset to constitute 3000 combinatorial links or less. For example, a traceset consisting of 20 high level requirements and 50 low level requirements would have $20 \times 50 = 1000$ combinatorial links. Any traceset with more than 3000 combinatorial links is considered large. **Utility:** The extent to which an analyst believes the tool has helped to achieve good trace results. If the analyst has (justified) confidence in the accuracy and scalability of the tool, the tool possesses utility for the analyst. In addition to analyst belief about accuracy and scalability, other items can impact utility. This is a very subjective item, and we are still in the process of elucidating its sub-elements. Thus far we have defined Operability and Process Enforcement. Operability is the capability of the software product to enable the user to operate and control it [4]. Process Enforcement refers to the tool implementing tracing in such a way that the analyst is guided through the process. **Validation mechanism:** The standard measures of accuracy are recall and precision. Accuracy can be measured objectively, but only when we have the theoretical “true trace” (i.e., the actual traceability matrix) available. Even when we do not have such an “answer set” *a priori*, we can build an RTM using the tool, capturing the candidate links returned at each stage. Then, we can compare the candidate links supplied by the tool at each stage to the final RTM (treating it as the answer set). Precision and recall quantify accuracy in two different, complimentary, even orthogonal, ways. In an ideal setting, a list of candidate links is *accurate* when it contains all the high—low level requirements pairs that trace to each other and does not contain any extra pairs. *Recall* measures the degree to which the first condition is met, while *precision* looks at the second. We note a certain asymmetry between the two measures. A candidate link list with high recall and low precision means that the analyst has to weed out the many false-positive links from it before the requirements tracing task is complete. On the other hand, if the same list has high precision and low recall, the analyst would have to examine a lot of potential links *outside* the list. In this respect, high-recall, low-precision lists of links appear to be preferable to high-precision, low recall links. That is because humans seem to be better at determining whether a specific pair of links from the list is a match than at discovering new pairs of links in the document from scratch. For scalability, we must examine the tool’s results for both small and large trace sets to determine that the accuracy has not been significantly degraded. Validation of utility requires subjective measures and hence a separate experimental design. In addition, we must first establish accuracy and scalability before progressing to a subjective study, thus ensuring that the tool performs in such a way that there is a basis for analyst confidence. This study is left for future research. **Discussion:** Believability is a high level, overarching requirement. Utility is important because in any tracing exercises other than controlled experiments, the theoretical “true trace” will not be known. Therefore, an analyst has to decide whether candidate links are correct or not and/or whether to search for additional candidate links. The analyst must feel confident that good results have been achieved by using the tool. Scalability is not addressed in this paper, as we do not currently have large trace sets with a “true trace” (See Section 6). Accuracy is evaluated, though. Recall is more important in tracing than precision because we do not want analysts to have to search for additional candidate links. We also want precision to be as high as possible. But note that precision values can be a bit misleading. For example, 50% precision means the existence of one false positive for each true link, which would be relatively easy for the analyst to deal with. Improvement beyond 50% does not provide as much benefit to the analyst as for example improving from 10% to 33% (which corresponds to improving from one true Requirement 1: Specification: “Endurability:” The requirements tracing tool shall generate candidate links and shall solicit analyst feedback and shall re-generate candidate links based on the feedback such that the process of requirements tracing is not arduous. Validation mechanism: Part of Endurability can be measured objectively by examining the time it takes to complete a tracing project using the tool. However, Endurability also refers to subjective satisfaction of the analyst with the tool and requires subjective measures and a separate experimental design. This study is left for future research. Discussion: In general, requirements tracing is a very time consuming, arduous process, even when using a tool. We strive to decrease the tedium of the tracing experience for the analyst (addressing items (c) - (e)). This is a subjective item, tying in with usability. A separate study is planned to assess analyst attitude toward our tracing tool. 3. Effective requirements tracing with RETRO 3.1 Why use Information Retrieval? The problem of requirements tracing boils down to determining, for each pair of requirements from high- and low-level requirements documents, whether they are “similar.” Stated as such, requirements tracing bears a striking similarity to the standard problem of Information Retrieval (IR): given a document collection and a query, determine which documents from the collection are relevant to the query. In the tracing scenario, high-level requirements play the role of queries, while the “document collection” is made up of low-level requirements (these roles are switched if back-tracing is desired). The key to understanding whether IR methods can aid requirements tracing lies in examining the concept of requirement “similarity.” This concept is used by the analysts to determine the trace. We must see if requirements similarity can be modeled, or at least approximated, by the document relevance notions on which different IR algorithms rely. The major difference in the similarity concepts used by analysts and the measures used in IR algorithms is that human analysts are not limited in their decisions by purely arithmetical considerations. A human analyst can use any tool available in her arsenal to determine the trace, and that may include “hunches,” jumping to conclusions, and/or ignoring assignments prescribed by any specific methodology. Such diversity of sources for human decision-making can be both a blessing and a bane link out of 10 to one true link out of three candidates). Thus, drastic improvements in precision occur only at low percentages. The true measure of the effectiveness of a tracing tool lies in its ability to help an analyst find the correct links, as easily as possible. In earlier studies [11], we found that an analyst using the STP requirements tracing tool actually ended up with a worse final answer than the tool had originally proposed. If the analyst throws away good links, recall will decrease. If the analyst keeps bad links, precision will decrease. It is important that the tool prompts/assists the analyst to make the right choices (addressing items (c) and (d)). To that end, we have requirement 2, “discernability.” Requirement 2: Specification: “Discernability” The requirements tracing tool shall generate candidate links and display their similarity measures in such a way to make it easy for the analyst to discern true links (from the theoretical “true trace”) from false links (candidate links that are not really links). Validation mechanism: There are four aspects to this requirement. In general, we want to ensure that the software communicates information (such as requirement text), process flow (such as what to do next), and results in a manner that facilitates the tracing process. We refer to this as communicability. In addition, we want to ensure that, as the stages of tracing proceed, good links (true links) rise to the top of the candidate link list and that bad links (false links) fall to the bottom. And we want to ensure that the similarity measures given for candidate links reflect the “cut off” line between true and false links. To that end, we define objective measures for all the items above except communicability. “Good links rising” and “bad links sinking” are measured using DiffAR and Lag, while the existence of a cutoff is studied using different filtering techniques on the candidate link lists. These measures are formally defined in Section 4. Discussion: This requirement must be satisfied to support the satisfaction of Requirement 1. As has been suggested above, requirements tracing is an iterative process. An analyst will examine a subset of the candidate links and then determine if the links are good or not. This information, even for a small number of candidate links, is very valuable and should be fed back into the algorithms to support the generation of more accurate candidate links. If the tool does not provide the candidate links in a manner that facilitates discernment, the analyst will get frustrated with the tool and will not be able to efficiently complete the task. That leads us to our final requirement, “endurability.” Requirement 3: to the requirements tracing process. On one hand, it may lead to discovery of hard-to-find matches between the requirements. On the other hand, human analysts do make errors in their work. These errors may be explicit, the analyst discards correct links and keeps incorrect ones, and implicit, the analyst does not notice some of the true links between the documents. Similarity (relevance) measures computed by IR algorithms are not prone to errors in judgment. But they may fail to yield connections that humans might notice despite differences in text. Even taking this observation into account, there is still enough evidence to suggest that IR methods are applicable. Indeed, the actual procedures employed by an IR algorithm in RETRO and by the analyst, working, for example with the STP tool [10,16] are very similar. In both cases, the lists of requirements from both document levels are scanned and for each requirement a representation based on its text is chosen. After that, in both instances, matching is done automatically, and the analyst then inspects the candidate links. 3.2 RETRO In contrast with such comprehensive requirements management tools as STP [10, 16], RETRO (REquirements TRacing On-target) is a special-purpose tool, designed exclusively for requirements tracing. It can be used as a standalone tool to discover traceability matrices. It can also be used in conjunction with other project management software: the requirements tracing information is exported in a simple, easy-to-parse XML form. The overall look of RETRO GUI (Win32 port) is shown in Figure 1. ![Figure 1. A screenshot of RETRO.](image) At the heart of RETRO lies the IR toolbox (C++): a collection of implementations of IR methods, adapted for the purposes of the requirements tracing task. Methods from this toolbox are accessed from the GUI block (Java) to parse and analyze the incoming requirements documents and construct relevance judgments. The Filtering/Analysis component (C++) of RETRO takes in the list of candidate links constructed by any of the toolbox methods and prepares a list to be shown to the analyst. This preparation may involve the application of some cleaning, filtering and other techniques. The GUI of RETRO guides the entire requirements tracing process, from setting up a specific project, to going through the candidate link lists. At the top of the screen, the analyst sees the list of high level requirements (left) and the list of current candidate links for it, with relevance judgments (right). In the middle part of the interface, the text of the current pair of requirements is displayed. At the bottom, there are controls allowing the analyst to make a decision on whether the candidate link under consideration is, indeed, a true link. This information is accumulated and, upon analyst request, is fed into the feedback processing module (C++). The module takes the results of analyst decisions and updates the discovery process consistent with the changes. If needed, the IR method is re-run and the requirements tracing process proceeds into the next iteration. 3.3 Information Retrieval methods in RETRO The IR toolbox of RETRO implements a variety of methods for determining requirement similarity. For this study we have used two IR algorithms implemented previously [11]: tf-idf vector retrieval and vector retrieval with a simple thesaurus. To process feedback we have used the Standard Rochio [9] method for the vector model. The methods used are briefly described below. 3.3.1 Tf-Idf model. Standard vector model (also known as tf-idf model) for information retrieval is defined as follows. Let \( V = \{k_1, ..., k_N\} \) be the vocabulary of a given document collection. Then, a vector model of a document \( d \) is a vector \((w_1, ..., w_N)\) of keywords weights, where \( w_i \) is computed as \( w_i = tf_i(d) \cdot idf_i \). Here \( tf_i(d) \) is the so-called term frequency: the frequency of keyword \( k_i \) in the document \( d \), and \( idf_i \), called inverse document frequency is computed as \( idf_i = \log_2 \left( \frac{n}{df_i} \right) \), where \( n \) is the number of documents in the document collection and \( df_i \) is the number of documents in which keyword \( k_i \) occurs. Given a document vector \( d=(w_1, ..., w_N) \) and a similarly computed query vector \( q=(q_1, ..., q_N) \) the similarity between \( d \) and \( q \) is defined as the cosine of the angle between the vectors: 3.3.2 Tf-Idf + Simple Thesaurus. The second method used in [11] extends tf-idf model with a simple thesaurus of terms and key phrases. A simple thesaurus $T$ is a set of triples $<t_i, t'_i, \alpha_i>$, where $t_i$ and $t'_i$ are matching thesaurus terms and $\alpha_i$ is the similarity coefficient between them. Thesaurus terms can be either single keywords or key phrases – sequences of two or more keywords. The vector model is augmented to account for thesaurus matches as follows. First, all thesaurus terms that are not keywords (i.e., thesaurus terms that consist of more than one keyword) are added as separate keywords to the document collection vocabulary. Given a thesaurus $T = \{<\text{w}_1, \text{w}_2, \alpha_1>, \ldots, <\text{w}_N, \text{w}_N, \alpha_N>\}$ and document/query vectors $d=(\text{w}_1, \ldots, \text{w}_N)$, $q=(q_1, \ldots, q_N)$, the similarity between $d$ and $q$ is computed as: $$\text{sim}(d, q) = \cos(d, q) = \frac{\sum_{i=1}^{N} w_i \cdot q_i}{\sqrt{\sum_{i=1}^{N} w_i^2 \cdot \sum_{i=1}^{N} q_i^2}}.$$ 3.4 Incorporating relevance feedback Relevance feedback is a technique to utilize user input to improve the performance of the retrieval algorithms. Relevance feedback techniques for tf-idf methods adjust the keyword weights of query vectors according to the relevant and irrelevant documents found for them, as supplied by the user. More formally, let $q$ be a query vector, and $D_q$ be a list of document vectors returned by some IR method given $q$. Further, assume that $D$ has two subsets: $D_r$ of size $R$ of documents relevant to $q$ and $D_{ir}$ of size $S$ of irrelevant documents that have been provided by the user. Note that $D_r$ and $D_{ir}$ are disjoint, but do not necessarily cover the entire set $D_q$. We use Standard Rochio [9] feedback processing method: $$q_{\text{new}} = \alpha q + \left( \beta \frac{1}{r} \sum_{d_j \in D_r} d_j \right) + \left( \gamma \frac{1}{s} \sum_{d_k \in D_{ir}} d_k \right),$$ Intuitively, query $q$ is adjusted by adding to its vector a vector consisting of the document vectors identified as relevant, and subtracting from it the sum of all document vectors identified as false positives. The first adjustment is designed to potentially increase recall. The second adjustment can potentially increase precision. The constants $\alpha$, $\beta$, $\gamma$ in the formulas above can be adjusted in order to emphasize positive or negative feedback as well as the importance of the original query vector (in our tests all three values were set to 1). Once the query vectors have been recomputed, the selected IR algorithm is re-run with the modified query vectors. This cycle can be repeated until the user is satisfied with the results. 4. Evaluation 4.1 Study design The purpose of our current study is to see whether RETRO satisfies the requirements specified in Section 2. We notice that all three major requirements have two components: objective, that can be measured by running tests on the tool, and subjective, examining user interaction with it. This study validates parts of the requirements that can be measured objectively. A study of the use of the tool by analysts for the purpose of determining its usability is planned next. In particular, in this study, we concentrate on determining the accuracy and discernability of the results of the analysis. To assess the accuracy and discernability of requirements tracing with RETRO, we performed tests on tf-idf and thesaurus approaches, as described in Section 3.3. We used a modified dataset from [11] based on open source NASA Moderate Resolution Imaging Spectroradiometer (MODIS) documents [13,15]. The dataset contains 19 high level and 49 low-level requirements. The trace for the dataset was manually verified. The “theoretical true trace” built for this dataset consisted of 42 correct links. In the test, we have assumed that during the feedback process, analysts provide correct information to the tool. That is, both true links and false positives, when discovered are marked as such. At the beginning of each test, the traceset was loaded into RETRO and a particular IR method (tf-idf, or thesaurus) was selected. For each method, four different feedback strategies or behaviors, called **Top 1**, **Top 2**, **Top 3** and **Top 4** were tested. The **Top i** behavior meant that at each iteration, we simulated correct analyst feedback for the top $i$ unmarked candidate links from the list for each high-level requirement. For example, for each high level requirement, **Top 1** behavior examined the top candidate link suggested by the IR procedure that had not yet been marked as true. If the link was found in the verified trace, it was marked as true, otherwise – as false. After repeating the **Top i** relevance feedback procedure for each high level requirement, the answers were submitted to the feedback processing module. At this point, the Standard Rochio procedure was used to update query (high-level requirement) keyword weights, and to submit the new queries to the IR method. The process continued for a maximum of eight iterations or until the results had converged. To check the accuracy of the results, we measured precision and recall of the candidate link lists produced at each iteration of the process. To check discernability, we devised and computed a number of measures that allow us better insight into the evolution of the candidate link lists provided by RETRO from iteration to iteration. As stated in Section 2, we want to ensure that (a) true links rise to the top of the lists, (b) false positives sink to the bottom of the lists, and that (c) a reasonable cut-off is possible that separates the majority of the true links from the majority of the false positives. The metrics measuring the degrees to which (a) and (b) were satisfied are: \( ART \): Average relevance of a true link in the list; \( ARF \): Average relevance of a false positive in the list; \( DiffAR = ART – ARF \): the difference between average relevances of true links and false positives; and \( Lag \): average number of false positives with higher relevance coefficient than a true link. To measure the ability to establish a cut-off, we have examined a number of filtering techniques. A filtering technique is a simple decision procedure that examines each candidate link produced by the IR method and decides whether to show it to the analyst. In our study, in addition to the test run involving no filtering, we used the following three filtering techniques: **Above 0.1**: throw out a candidate link if its relevance is below 0.1. **Within 0.5**: For each high-level requirement, compare the relevance of each candidate link with the relevance of the top candidate link. The candidate link is retained iff its relevance is within 0.5 of the relevance of the top link. **Top 42**: For each high-level requirement \( i \), retain the top \( ki \) candidate links, where \( ki \) is the number of true links for \( i \). The filtered answer set contained 42 (or fewer) candidate links distributed exactly as in the answer set. ### 4.2 Results We address accuracy followed by discernability. As discussed above, recall and precision will be used to assess accuracy. The precision and recall results obtained in our tests are summarized in Table 1. The first column indicates the iteration, with iteration 0 being the iteration before the feedback. In each cell, precision is indicated first followed by recall. For example, iteration 7, Top 3, for Thesaurus method had precision of 24.6% and recall of 80.9%. The maximal precision and recall achieved in each experiment are highlighted and the maximal values for each retrieval method are also underlined. The results are also visualized in Figure 2, which contains the precision/recall trajectories for all experiments, grouped by the IR method used (top: tf-idf, bottom: simple thesaurus). The importance of the results ties back to the requirement of believability in Section 2. The candidate link lists generated using the thesaurus method are decent, but are greatly improved with analyst feedback. Also, improvements in recall are seen in early iterations (as early as iteration 3) and with the analyst only providing feedback on the Top 2 links. We feel that these accuracy results should also contribute to utility and endurance. Note that our shortcoming in recall is accounted for by a few requirements for which the IR methods did not return any true candidate links at iteration 0. This meant that feedback methods could not improve as they could not acquire positive feedback information. Precision does not appear to improve as much. It doubles over six or seven iterations, but on iterations 1 and 2 it decreases before starting to increase again with iteration 3. However, precision was improved without much impact to recall by using filtering. Table 2 summarizes the results of applying different filters to the candidate link lists. For each filter and for each test run, the best precision/recall pair was always achieved on the last iteration of the experiment – a contrast with the results without filtering. For each filter, the table also contains the differences in percentages for recall and precision between the list with no filtering and the list obtained by applying the filter. As evidenced in the table, the improvement in precision is significant for most filter-ex IR algorithm—behavior combinations. An important observation is that removal of a candidate link from the list by a filtering technique at some iteration does not preclude this link from appearing again in a subsequent iteration. What this means is that if we filtered out some good links originally, they may reappear later with higher similarity measures. Filtering also ties to discernability. Recall that we use filtering to determine if there is eventual separation between good and bad links in the candidate link list, or the cutoff sub-element of discernability. Our results show that for above 0.1 in Top 42 filters such separation is eventually achieved for most of the behaviors, as precision increases drastically while the decrease in recall is not large. For example, using thesaurus retrieval for Top 3 behavior and above 0.1 filtering, precision is almost 40% with recall of 80%. The other sub-elements of discernability examine whether good links rise to the top of the list and bad links sink to the bottom. Recall that we use \( DiffAR \) and \( Lag \) to assess these. Figure 3 shows the changes in the \( DiffAR \) metric: the difference in average relevances between the true links (\( ART \)) and false positives (\( ARF \)) as the iterations... Table 1. Results of experiments: Precision and recall. <table> <thead> <tr> <th></th> <th>Top 1</th> <th>Top 2</th> </tr> </thead> <tbody> <tr> <td></td> <td>TF-IDF</td> <td>Thesaurus</td> </tr> <tr> <td>0</td> <td>11.3%, 57.1%</td> <td>12.2%, 64.2%</td> </tr> <tr> <td>1</td> <td>8.4%, 59.5%</td> <td>9.4%, 69%</td> </tr> <tr> <td>2</td> <td>7.7%, 59.5%</td> <td>8.3%, 64.2%</td> </tr> <tr> <td>3</td> <td>9.2%, 66.6%</td> <td>8.6%, 61.9%</td> </tr> <tr> <td>4</td> <td>9.9%, 71.4%</td> <td>10.6%, 71.4%</td> </tr> <tr> <td>5</td> <td>12.5%, 76.1%</td> <td>12.5%, 78.5%</td> </tr> <tr> <td>6</td> <td>15.3%, 76.1%</td> <td>14.8%, 76.1%</td> </tr> <tr> <td>7</td> <td>16%, 71.4%</td> <td>23.3%, 69%</td> </tr> <tr> <td>8</td> <td>17.3%, 73.8%</td> <td>25.6%, 69%</td> </tr> </tbody> </table> <table> <thead> <tr> <th></th> <th>Top 3</th> <th>Top 4</th> </tr> </thead> <tbody> <tr> <td></td> <td>TF-IDF</td> <td>Thesaurus</td> </tr> <tr> <td>0</td> <td>11.3%, 57.1%</td> <td>12.2%, 64.2%</td> </tr> <tr> <td>1</td> <td>7.3%, 61.9%</td> <td>7.8%, 66.6%</td> </tr> <tr> <td>2</td> <td>11.6%, 73.8%</td> <td>10.6%, 83.3%</td> </tr> <tr> <td>3</td> <td>14.6%, 73.8%</td> <td>13.6%, 80.9%</td> </tr> <tr> <td>4</td> <td>18.6%, 76.2%</td> <td>17.4%, 83.3%</td> </tr> <tr> <td>5</td> <td>17.1%, 71.4%</td> <td>18.1%, 83.3%</td> </tr> <tr> <td>6</td> <td>20.9%, 73.8%</td> <td>20.2%, 80.9%</td> </tr> <tr> <td>7</td> <td>21.4%, 69%</td> <td>24.6%, 80.9%</td> </tr> <tr> <td>8</td> <td>22.7%, 66.6%</td> <td></td> </tr> </tbody> </table> progress. Intuitively, the larger the difference, the more likely it is that most of the true links will be at the top of the candidate link lists for high-level requirements. Note from the figure that the difference between ART and ARF is around 0.2 at iteration 0 for both tf-idf and simple thesaurus retrieval algorithms. At subsequent iterations for both retrieval algorithms and all behaviors, DiffAR grows significantly, ranging from 0.489 to 0.758 at the last iterations. While DiffAR measures the quantitative separation between true links and false positives, Lag is a measure of qualitative separation. Lag is defined for each true link in the list as the number of false positives for its high-level requirement that have a higher relevance (i.e., the number of false positives that are higher up in the list). The Lag of a list of candidate links is the average Lag of its true links. Note that when Lag=0, total separation of links has been achieved: all true links appear higher up in the lists of candidate links than all false positives. Figures 4 and 5 show the progress of the Lag measure for tf-idf and thesaurus retrieval tests respectively. It can be observed that in all experiments Lag behaved in a similar manner. For both tf-idf and thesaurus retrieval, Lag starts at just above 6. During the first 1-2 iterations, Lag grows, and for some experiments can go as high as 10. But at subsequent iterations, Lag drops significantly, and in all but one experiment, finishes under 3. 4.3 Discussion of results Table 3 summarizes the contributions of the paper. It is evident that RETRO supports the objective sub-elements of discernibility. The measures ART, ARF, and DiffAR indicate that using the relevance feedback option of RETRO provides the analyst with similarity measures that clearly discern between good links and bad links. In addition, the Lag measure shows that by the later iterations, there are very few bad links at the top of the candidate link lists. A special comment needs to be made concerning the precision values obtained during the experiment. As shown in Tables 2 and 3, precision in our experiments hovered between 20 and 25% without filters and went up to 30—40% without significant loss in recall when filtering was used. To put these numbers into perspective, we note, that when precision is 20% (assuming perfect recall), for each correct link in the list of candidate links, there are four false positives, i.e., in our case, the number of false positives in the list would be 42*4 = 168 and the total size of the candidate link list is 42*5 = 210. This is about 22% of the total number of potential links (19*49 = 931). Consider, for example the Top 3 run using Above 0.1 filter (see Table 3). Here, recall of 80.9% means that 34 out of 42 links from the theoretical true trace have been identified correctly. Precision of 39.5% means that the total number of the candidate links in the list was 86, i.e., about 9% of the total number (931) of potential links. We also note that when comparing precision numbers, their ratio is more important than their absolute difference. It is much better to be able to raise precision from 10% to 20% (from 420 to 210 candidate links with perfect recall) than from 70% to 80% (from 60 to 52 candidate links with perfect recall), as the decrease in the size of the candidate link lists is proportional to the ratio, not the absolute different. Because of these considerations, precision levels obtained during the experiment are quite acceptable in practice. The results of this study combined with the results of an earlier study [11] indicate that RETRO is a step forward with respect to other existing tools in terms of the accuracy sub-element of believability. In this study, RETRO with relevance feedback and thesaurus and filtering achieved recall of 80.9% and precision of almost 40%. In a comparable but different study (different part of the MODIS dataset), STP achieved overall recall and precision of 63.4% and 38.8% and RETRO, without feedback or filtering, achieved overall recall and precision of 85.4% and 40.7% on the same dataset [11]. The current study clearly points to avenues for improvement. For example, modifying our methods to ensure that we always return at least one true link per requirement at iteration 0 will greatly enhance our recall in the process of feedback. We also noted that the poor results on just a few requirements greatly influenced the precision measures. By studying these “problem” requirements, we hope to gain insight that will allow us to improve the methods of RETRO. 5. Related work In the context of our work, there are two areas of interest: requirements tracing and IR as it has been applied to the problem of requirements analysis. Each will be addressed below. Extensive work in the area of requirements tracing has been performed by numerous researchers, including but not limited to: Pierce [17], Hayes et al [10], Mundie and Hallsworth [16], Abrahams and Barkley [1], Ramesh [18,19], and Watkins and Neal [25] Casotto [7], Tsumaki and Morisawa [24], Savvidis [21], Bohner [5], Anezin and Brouse [2,6], and Cleland-Huang [8]. A survey of work in the field of requirements tracing can be found in [11]. In addition, Spanoudakis [22] proposes a rule-based method for generation of traceability relations. His approach automatically detects traceability relations between artifacts and object models using heuristic traceability rules [22]. Recently, a number of researchers investigated the use of IR methods for requirements analysis. Antoniol, Canfora, De Lucia and Merlo [3] considered two IR methods, probabilistic IR and vector retrieval (tf-idf) in studying the traceability of requirements to code for two datasets. Following them, Marcus and Maletic [14] applied latent semantic indexing (LSI) technique to the same problem. While those papers studied requirements-to-code traceability, in [11] we have addressed the problem of tracing requirements between different documents in the project document hierarchy. Figure 5. Lag for thesaurus retrieval tests. 6. Conclusions and future work RETRO was designed for the specific purpose of supporting the IV&V analyst in performing requirements tracing. The analyst’s responsibilities for finding and evaluating candidate links have been facilitated by RETRO. In addition, the objective sub-elements of the requirements of believability and discernability have been evaluated. RETRO supports accuracy and the three sub-elements of discernability of ensuring that good links rise to the top of candidate link lists, that bad links sink, and that a cutoff between good and bad links is apparent. Also, Science Applications International Corporation (SAIC), the developer of STP, is in the process of integrating the backend of RETRO (IR toolkit and feedback processing module) with the front end of STP. This is further evidence of RETRO’s ability to support IV&V analysts. Future work can be separated into two directions: improvement of the underlying technologies (IR methods, etc.); and study of the analyst’s interaction with RETRO (subjective sub-elements of the requirements). Technical enhancements include use of IR methods better suited for work with small datasets, implementation of additional feedback processing methods, implementation of more intricate techniques for filtering and analysis of candidate link lists, and using IR techniques to predict the coverage or satisfaction of traced requirements by their matches. A study to determine scalability of RETRO will be undertaken. Finally, we will conduct a study of the work of analysts with RETRO. This will be a subjective study to assess the utility sub-element of believability, the communicability sub-element of discernibility, and endurability. This study will also yield suggestions for the improvement of the RETRO GUI. 7. Acknowledgments Our work is funded by NASA under grant NAG5-11732. Our thanks to Ken McGill, Tim Menzies, Stephanie Ferguson, Pete Cerna, Mike Norris, Bill Gerstenmaier, Bill Panter, the International Space Station project, Mike Chapman and the Metrics Data Program, and the MODIS project for maintaining their website that provides such useful data. We thank Hua Shao and James Osborne for assistance with the tf-idf algorithm. We thank Ines Chemmannoor, Ganapathy Chidambaram, Ramkumar Singh S, and Rijo Jose Thozhal for their assistance. 8. References [13] Level 1A (L1A) and Geolocation Processing Software Requirements Specification, SDST-059A, GSFC SBRS, September 11, 1997.
{"Source-Url": "https://digitalcommons.calpoly.edu/cgi/viewcontent.cgi?referer=&httpsredir=1&article=1137&context=csse_fac", "len_cl100k_base": 10169, "olmocr-version": "0.1.53", "pdf-total-pages": 11, "total-fallback-pages": 0, "total-input-tokens": 40730, "total-output-tokens": 12179, "length": "2e13", "weborganizer": {"__label__adult": 0.000263214111328125, "__label__art_design": 0.0004072189331054687, "__label__crime_law": 0.00031256675720214844, "__label__education_jobs": 0.0023059844970703125, "__label__entertainment": 7.18235969543457e-05, "__label__fashion_beauty": 0.0001531839370727539, "__label__finance_business": 0.0004870891571044922, "__label__food_dining": 0.00023758411407470703, "__label__games": 0.0006060600280761719, "__label__hardware": 0.0006017684936523438, "__label__health": 0.0003192424774169922, "__label__history": 0.0002474784851074219, "__label__home_hobbies": 9.137392044067384e-05, "__label__industrial": 0.0002906322479248047, "__label__literature": 0.00031280517578125, "__label__politics": 0.00018227100372314453, "__label__religion": 0.00030493736267089844, "__label__science_tech": 0.029541015625, "__label__social_life": 0.00010949373245239258, "__label__software": 0.018096923828125, "__label__software_dev": 0.9443359375, "__label__sports_fitness": 0.00019860267639160156, "__label__transportation": 0.0003209114074707031, "__label__travel": 0.00016939640045166016}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 50226, 0.06366]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 50226, 0.28295]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 50226, 0.91747]], "google_gemma-3-12b-it_contains_pii": [[0, 4769, false], [4769, 10387, null], [10387, 16023, null], [16023, 21233, null], [21233, 25708, null], [25708, 30771, null], [30771, 36426, null], [36426, 39761, null], [39761, 42506, null], [42506, 45139, null], [45139, 50226, null]], "google_gemma-3-12b-it_is_public_document": [[0, 4769, true], [4769, 10387, null], [10387, 16023, null], [16023, 21233, null], [21233, 25708, null], [25708, 30771, null], [30771, 36426, null], [36426, 39761, null], [39761, 42506, null], [42506, 45139, null], [45139, 50226, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 50226, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 50226, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 50226, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 50226, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 50226, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 50226, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 50226, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 50226, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 50226, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 50226, null]], "pdf_page_numbers": [[0, 4769, 1], [4769, 10387, 2], [10387, 16023, 3], [16023, 21233, 4], [21233, 25708, 5], [25708, 30771, 6], [30771, 36426, 7], [36426, 39761, 8], [39761, 42506, 9], [42506, 45139, 10], [45139, 50226, 11]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 50226, 0.14545]]}
olmocr_science_pdfs
2024-12-11
2024-12-11
8df4cf77480d0f8e38ab00e3e66e2dca7587bec3
LeanReasoner: Boosting Complex Logical Reasoning with Lean Dongwei Jiang♡ Marcio Fonseca♢ Shay B. Cohen♢ ♡ Johns Hopkins University ♢ University of Edinburgh djiang21@jhu.edu m.fonseca@ed.ac.uk scohen@inf.ed.ac.uk Abstract Large language models (LLMs) often struggle with complex logical reasoning due to logical inconsistencies and the inherent difficulty of such reasoning. We use Lean, a theorem proving framework, to address these challenges. By formalizing logical reasoning problems into theorems within Lean, we can solve them by proving or disproving the corresponding theorems. This method reduces the risk of logical inconsistencies with the help of Lean’s symbolic solver. It also enhances our ability to treat complex reasoning tasks by using Lean’s extensive library of theorem proofs. Our method achieves state-of-the-art performance on the FOLIO dataset and achieves performance near this level on ProofWriter. Notably, these results were accomplished by fine-tuning on fewer than 100 in-domain samples for each dataset.1 1 Introduction Logical reasoning, a bedrock of intelligence and a core capability of humans, has been a challenging issue for machine learning systems for a long time. LLMs, despite their impressive abilities to understand and generate natural language, often fall short when dealing with complex logical reasoning tasks. They frequently suffer from logical inconsistencies, where the model hallucinates and makes statements not grounded in premises, leading to spurious results (Saparov and He, 2023; Dasgupta et al., 2022). Recent advances in AI have adopted a structured approach to tackle these reasoning problems by splitting them into symbolic formalization and problem-solving (He-Yueya et al., 2023; Pan et al., 2023; Ye et al., 2023). Specifically, the formalization step is often handled by a large language model, while problem-solving is handled by an off-the-shelf symbolic solver. In this approach, symbolic solvers essentially act as a rigorous check-point, ensuring that the model outputs align with logical rules, thereby mitigating the issue of logic inconsistency. In these approaches, solvers may range from being completely deterministic, like SymPy (He-Yueya et al., 2023), or relying on a combination of heuristics and basic machine learning techniques, as is the case with Pyke (Pan et al., 2023) and Z3 (Ye et al., 2023; de Moura and Bjørner, 2008). While this approach successfully addresses hallucinations, it still struggles with more complex problems. As a powerful theorem prover and a versatile programming language, Lean (de Moura et al., 2015) presents a compelling solution to connect symbolic solvers with linguistic resources. Much like symbolic solvers, Lean has a strict checking system that ensures each reasoning step is certified. What distinguishes it, however, is its additional functionality as a programming language developed specifically for theorem proving. Every day, a substantial amount of code is written in Lean, capturing reasoning “nuggets” with step-by-step rationals that are useful for training LLMs. A few recent studies have already tapped into Lean for mathematical theorem-proving tasks (Polu et al., 2023; Han et al., 2022a; Lample et al., 2022), showing its potential in tackling difficult reasoning challenges. In this paper, we propose LeanReasoner, a Lean-based framework to tackle logical reasoning problems. We use LLMs to formalize natural language context into Lean and fine-tune a custom model on these problems using a modest amount of data annotated ourselves. As we use LLMs to dynamically generate solutions within the Lean environment, our approach stands in stark contrast to the static, pre-defined solution-finding methods of LogicLM (Pan et al., 2023), which only rely on traditional techniques like forward and backward chaining, and SATLM (Ye et al., 2023), which operates within the Z3 environment using a suite of prede- 1Our code and data is available at https://github.com/Some-random/theorem-proving-reasoning. terminated algorithms and heuristics. The adaptive nature of LLMs as a solution-finding tool allows our system to evolve continuously, harnessing a vast array of reasoning data and information. Our contributions in this paper are three-fold. • To our knowledge, this is the first attempt to use Lean, traditionally associated with mathematical theorem proving, for natural language logical reasoning. This effort highlights a possible intersection between mathematical theorem proving and logical reasoning. • Our research revealed that incorporating pre-training data from mathematical theorem proofs enhances the development of a more effective solver for logical reasoning compared to previous techniques. Additionally, this approach enabled us to achieve SOTA results on FOLIO. • We make available the training data accumulated in this research, comprising 100 Leanformalized logic reasoning problems from ProofWriter, along with 27 analogous formalizations from FOLIO. The corresponding proofs in Lean are also included. 2 Problem Definition and Notation The task we aim to solve is logical reasoning, taking the form of multi-choice questions given a natural language context. The answer to the question can be logically deduced based on the context. The framework we use for solving the problem is Lean.² Lean is an open-source theorem-proving programming language with vibrant community support. Its current base includes over 100,000 theorems and 1,000,000 lines of code.³ We use Lean as a generic theorem prover, outside of mathematics. The task and our solution to it, consist of the following components: • **Context**, which is composed of natural language utterances, composing a set of rules and facts. For example: *Hudson is a cat, all cats are animals, and cats often meow.* • **Question**, which denotes the posed question. For example, *Does Hudson often meow?* • **Options** is a set of available answers (discrete categories) from which an answer can be chosen. For example, *True, False or Unknown.* • **Formalized context** refers to the representation of context in Lean. For example, the formalized context for our example would be: *axiom A1 is_cat Hudson, axiom A2 ∀x, is_cat x → is_animal x and axiom A3 ∀x, is_cat x → often_meow x.* • **Formalized question**: Given that Lean operates as a theorem prover, questions are transformed into dual theorems: one asserting the positive stance and the other negating it. For the given example, the formalized questions would be: *Theorem hudson_often_meows: often_meow Hudson and Theorem not_hudson_often_meows: ¬ often_meow Hudson.* • **Goal**: In the context of proving theorems with Lean, a ”goal” is a logical statement that needs to be proven true, given a set of axioms and rules. When we set out to answer a question using the Lean prover, this question becomes our root goal. At that point, we can apply various instructions in Lean to simplify or break down this primary goal and generate intermediate goals. For instance, using our earlier examples, if the root goal is proving *Theorem hudson_often_meows: often_meow Hudson*, an intermediate goal might be proving that *Hudson is a cat*. We aim to resolve each intermediate goal using our provided context, gradually working our way towards proving the root goal. Once all intermediate goals are resolved, we have effectively proven our root goal, and the proof search concludes successfully. • **Tactics** are the instructions in the Lean theorem proving language that are used to manipulate goals to obtain a proof for a given goal. For example, *apply A3 Hudson* is a tactic that uses modus ponens on the **Goal** *often_meow Hudson* and transforms it to a new **Goal** *is_cat Hudson*. A diagram of these components and the relations between them is depicted in Figure 1. This procedure is framed within the language of the Lean theorem prover as a goal-satisfying process. 3 LeanReasoner Our framework, LeanReasoner, is composed of four main components: a **formalizer**, a **tactic generator**, a **proof search** mechanism, and a **result interpreter**. The formalizer converts the context and question to formalized context and formalized question. The tactic generator then generates tactics based on premises extracted from the formalized context. The proof search mechanism oversees tactic execution and goal expansion. The result interpreter analyses the output of the proof search and identifies the correct answer in the options. In this section, we detail each of those components. ### 3.1 Formalizer As formalizers, we used OpenAI models text-davinci-003 (GPT-3) and GPT-4 (OpenAI, 2023). For text-davinci-003, we followed the same prompting approach as Logic-LM (Pan et al., 2023) to separate task specifications and problems, thereby enabling the model to continue with the task of formalization through next-token-prediction. For GPT-4, we used similar prompts but included the task specification in the system prompt. There is no automatic way to assert all the entities, relationships, and constraints of the context have been captured by the formalized result. However, the syntax of the formalized result can be checked by Lean. Because correct syntax is a prerequisite for downstream theorem proving, if an error is encountered during compilation, we provide the error message generated by Lean along with the faulty formalization and ask the formalizer to regenerate the result. We further manually inspect the formalizer in §5. We note that we take a strict approach, and if the formalizer fails more than once, then the problem is counted as not being correctly solved. ### 3.2 Tactic Generator The model we used for tactic generation is ReProver (Yang et al., 2023). This model contains two parts: a retriever that employs retrieval mechanisms to explicitly select premises when provided with the current goal, and a generator that generates tactics using the goal and the retrieved premises. The division of the problem-solving task into premise selection and tactic generation simplifies the process and facilitates easier troubleshooting. It isolates the source of potential issues, be it in the premise selection or the tactic generation, thus reducing the complexity of the problem. Also, this division of responsibilities eases the burden on the tactic generator. Choosing the right premise with numerous distractions is challenging, especially in logical reasoning problems when several options might seem promising for the current step but will not ultimately lead to the desired goal. The premise retrieval component of our process draws from the Dense Passage Retriever (DPR) (Karpukhin et al., 2020). Provided with a goal $g$ as the query and a set of candidate premises $P$, it generates a ranked list of $m$ premises from $P$. In DPR, both $g$ and $P$ are treated as raw texts that are embedded in a vector space. We then retrieve the top $m$ premises that maximize the cosine similarity between the goal and the premise. For tactic generation, we use a standard sequence-to-sequence model. The goal and the premises are concatenated together as a string to generate new tactics. As a baseline, we also prompt GPT-4 to generate proofs. For cases when the chosen theorem to prove aligns with the answer (say the chosen theorem is the positive stance of the question and the answer is $Y\hat{E}S$), we present GPT-4 with the correct proof as part of the prompt. Conversely, if the answer does not align with the chosen theorem or the answer is $N\hat{O}$ $G\hat{a}l$ $o$s. UNKNOW, the formalized theorem is unprovable. In those cases, we still encourage the model to engage in step-by-step reasoning, even though it will eventually hit a roadblock. An example of the prompt to GPT-4 can be found in Appendix A.1. 3.3 Proof Search The proof search module controls the overall search process that selects tactics and maintains states during proof construction. Essentially, the goal of the search method is to build a proof tree that incrementally evolves the goal through tactic invocations. This approach was first introduced in GPT-F (Polu and Sutskever, 2020). LeanDoJo (Yang et al., 2023), a recently released framework that enables interaction with Lean programmatically, subsequently provided an implementation of this method, which we use for our study. As a reference, the middle part of Figure 1 provides a practical illustration of this process. Starting from the root goal, for each given proof goal, we explore 64 possible tactics. All goals are maintained in a priority queue and expanded based on cumulative log probabilities of the goal. The cumulative log probability is defined as the summation of the log probabilities of the tactics that brought us to the goal from the root. This implies that we tend to expand those goals where our generative model has the highest global confidence. To enhance search efficiency and circumvent potential loops, we have incorporated a mechanism that stops the expansion of a node $N$ if we have already explored another node $M$ with a state sequence that prefixes $N$. Essentially, if the current goal being explored contains all the elements of a previously explored goal, then it shouldn’t be further expanded. This is based on the observation that if we have already assessed the potential paths and outcomes for a specific goal, then exploring a more generalized version of the same goal is redundant. Such a mechanism avoids unnecessary repetitions, which streamlines the search process and improves the overall efficiency. Moreover, we define a valid proof as one that is devoid of “cheating” tactics (such as sorry) that tell Lean to assume that the current goal is completed, even though it has not been proven. This means that every path containing “cheating” tactics is disregarded. Errors in the search process typically manifest in two ways: a timeout or an exhaustion of nodes to search. We have allocated a three-minute window for each search, which is usually sufficient. We provided more analysis of the errors made by tactic generator in the experiment section. 3.4 Result Interpreter If the correct answer is Unknown, we only regard the result as correct if neither True nor False can be proven. All datasets investigated in this study only contain questions with only one correct answer. Consequently, if the proof system verifies more than one option, the response is immediately marked as incorrect. 4 Experimental Setup We now describe our experimental setup: the datasets we used for evaluation and model training and the details of model training. 4.1 Evaluation Data In our evaluation, we use two common logical reasoning datasets as testbeds: **ProofWriter:** This deductive logical reasoning dataset presents problems in an intuitive language form. We incorporated the Open-World Assumption (OWA) subset as per (Pan et al., 2023), where each instance is characterized by a (problem, goal) pairing. The label for each pair contains True, False, or UNKNOW. It encompasses five segments based on the required reasoning depth. Our focus is the depth-5 subset, which is the most challenging one. To get a fair comparison against LogicLM, we used the same 600 sample tests, ensuring an even label distribution. **FOLIO:** Unlike ProofWriter, FOLIO is constructed using first-order logic. This increases the complexity of the proving part. The dataset also presents problems in a more natural wording, with relationships that are considerably more complex. Such a combination of advanced logic and rich linguistic structure makes the formalization task in FOLIO substantially tougher than in ProofWriter. For our analysis, we turned to the entire FOLIO test set, encompassing 204 examples. 4.2 Training Data for Domain Adaptation Regarding the data for model training, we collected 100 theorem proofs for ProofWriter and 27 theorem proofs for FOLIO, where each problem’s proof was either manually annotated or collected from successful proofs generated by GPT-4. The data collection took about eight days. During data annotation, we adopted two divergent approaches for constructing proofs. One approach emulated a straightforward strategy, encompassing a detailed procedure with all of the intermediate steps and lemmas, similar to how we humans might derive proof when given theorem-proving tasks. Conversely, the second approach resembles the proof formats found in mathlib. We generate more succinct proofs of the same problem by reducing the number of intermediate lemmas and combining multiple tactics into a single compound tactic. The objective of having two annotations for the same problem was to examine the influence of annotation style on downstream logical reasoning. In the following experiments, we use Intuitive to refer to the first annotation style and Concise to denote the second annotation style. An illustrative example is available in Appendix C. It is important to mention that despite the limited data collected, the reasoning patterns for logical reasoning likely mirror those found in mathematical reasoning, which were potentially learned during pretraining. The main purpose of this data collection is domain adaptation to transfer from math to natural language logical reasoning. 4.3 Model Training We used the same model structure for pretraining as in the ReProver paper, namely, Google’s Byte-T5 (Xue et al., 2022). We also experimented with the pretrained ReProver from LeanDoJo (Yang et al., 2023), which was pretrained on mathlib. The fine-tuning of our collected data took about six hours on one A100 40G. The hyperparameters are the same as in the original LeanDoJo paper. 5 Results We present our experimental results, including an examination of prompting-based baseline, experimental results for LeanReasoner, and a comparison between our work and other baselines. 5.1 Prompting-Based Baselines Since there is no automated method to verify the accuracy of formalization, we conducted manual examinations of the formalized results to determine whether errors occur during formalization or proof generation stages. In this examination, only formalizations that correctly capture every fact, axiom, and rule are counted as accurate. We manually examined 100 questions from ProofWriter’s validation set and 40 questions from FOLIO’s training set. The findings have been summarized in Table 1. Comparison of formalization accuracy. The formalization accuracy of ProofWriter is much higher than FOLIO. This can be attributed to its simpler language structure. In the case of FOLIO, although using LLM for formalization helped in filtering out unnecessary details from the natural language context, there still exists some common error patterns. We have illustrated typical GPT-4 error patterns in Appendix B using a composite sample derived from various error instances. Interestingly, Lean’s formalization accuracy is on par with both Prolog and FOL in Logic-LM. This consistency underscores Lean’s versatility, allowing it to uniformly represent different problem types within a single framework. Adding textual comments increases formalization accuracy. We observed improved results when formalized code was paired with descriptive textual comments (example in Appendix A.1) sourced from the context. This approach further splits the formalization task into two subtasks: 1) linking textual context with formalized code and 2) generating formalized code based on the prior textual context. These textual cues acted as a bridge between raw text and formalized code, enhancing the performance of formalization. GPT-3’s performance on formalization is worse than GPT-4. The distinction in performance between GPT-3 and GPT-4 is evident. While the formalization for simpler problems is the same, GPT-3 struggles with intricate logic and complex problems. As such, we opted not to use GPT-3 in further tests. Additionally, we experimented with the CodeLLAMA (Baptiste Rozière and et.al, 2023) model family for similar tasks, but found that their accuracy in formalization was significantly lower than that of GPT-3, achieving less than 30% on ProofWriter. The proof accuracy of prompting-based baseline is very low. The proof accuracy section of the table is determined by whether the generated proof can be validated successfully in Lean. If the formalization of the question as a theorem is correct and the proof can be validated without any error or warning, then we can treat the proof as valid. However, the accuracy of rendered proofs is very low. The issue could stem from assigning too many tasks to the large language model, making it challenging to address both within a single prompt. Despite our efforts to separate formalization and proof, the results were still disappointing, which highlights GPT-3 and GPT-4’s struggle with generating correct Lean proof. Interestingly, the proof accuracy of Logic-LM wasn’t as high as we expected. Upon replicating their code, we found their chosen solver Pyke to be suboptimal, struggling to identify an answer when multiple search paths are available and some could result in loops. The answer accuracy of prompting-based baseline is surprisingly high. Despite the low accuracy in most of GPT-4’s proofs, it achieved high accuracy for final choices on ProofWriter (as shown in column Answer). We believe this may be due to GPT-4’s training exposure to the dataset, potentially leading to a degree of memorization. ### 5.2 LeanReasoner In this section, we focus on training our own models to do tactic generation using our annotated training data. To isolate the impact of erroneous formalization, we only used the accurate formalizations from the previous subsection for testing. This gave us 99 test examples for ProofWriter and 28 for FOLIO. All findings are detailed in Table 2. **Fine-tuning on annotated data increases premise selection accuracy.** We first compare the results on premise selection using the metrics recall@1 and recall@4. The recall@k metric is defined as follows: $$\text{recall@k} = \frac{|\text{GT}_\text{Prem} \cap \text{Pred}_\text{Prem}[0:k]|}{|\text{GT}_\text{Prem}|},$$ where GT_Prem means ground truth premises and Pred_Prem means top predicted premises. The suboptimal results of LeanReasoner pretrained solely with math data may be attributed to the domain mismatch between mathematical theorem proving and logical reasoning. The model frequently makes mistakes by attempting to use other, unrelated tactics that are useful in mathematical theorem proving (like `ring`, `linarith`) but not applicable in logical reasoning. Furthermore, the accuracy for FOLIO was noticeably poorer than that of ProofWriter. This disparity is likely due to FOLIO’s intricate logic and its need for a broader array of first-order logic tactics such as `cases`, `have`, and `contradiction`. In contrast, ProofWriter primarily employs tactics like `apply`, `exact`, and `split`. **Pretraining on theorem proving data increases overall accuracy.** Regarding the overall proof results, LeanReasoner pretrained on math theorem proving data consistently outperformed other approaches for both ProofWriter and FOLIO datasets. This success indicates that our model effectively uses the logical “nuggets” found in mathematical theorem proofs. While the premise selector benefits from distinct cues and a limited range of choices, the realm of tactic generation is much broader. This vastness of options renders the ReProver baseline’s proof accuracy nearly negligible. But other than that, there is a strong correlation between premise selection accuracy and overall proof accuracy. While the benefits of a pretrained LeanReasoner may not be as noticeable for simpler datasets like ProofWriter, its value becomes evident for more complex datasets, such as FOLIO. **Concise annotation gives better result on premise selection.** Fine-tuning with different an- notations has a slight effect on premise selection and tactic generation in this small test set. When fine-tuned with Concise annotations, LeanReasoner would also try to generate concise proofs, which usually use compound tactics that offer more information for premise selection. However, the final proof accuracy has not changed on this small test set. Figure 2 displays an example of proofs for the same question, produced by the three primary methods we compared. In the absence of pretraining, the model struggles to identify an appropriate approach for solving the problem. It merely attempts to apply the next applicable theorem, lacking a clear objective. While Intuitive data offers numerous lemmas that assist in the thought process during proof-writing, these excessive lemmas do not aid LLMs in generating tactics effectively. 5.3 Other Baselines Having demonstrated that pretraining on theorem-proving data yields superior performance, we proceed to benchmark our results against established baselines for both ProofWriter and FOLIO. The evaluation uses the same set of 600 problems from LogicLM and the entire FOLIO test set. Our approach yields near-perfect accuracy on ProofWriter with significantly less data. As illustrated in Table 3, our approach yields near-perfect accuracy on the ProofWriter dataset. While other methods except Logic-LM and GPT-4 CoT use the entire training set of ProofWriter, our approach relies on just 100 examples, underscoring the efficiency of our method. Fine-tuning on Concise annotation does not bring any advantage to the final performance on this dataset. <table> <thead> <tr> <th>Method</th> <th>Pretrained on Math Data</th> <th>Fine-tuned on our Annotation</th> <th>ProofWriter</th> <th>FOLIO</th> </tr> </thead> <tbody> <tr> <td></td> <td></td> <td></td> <td>Premise Selection</td> <td>Proof Accuracy</td> </tr> <tr> <td>GPT-4</td> <td>N/A</td> <td>N/A</td> <td>N/A</td> <td>15%</td> </tr> <tr> <td>LeanReasoner</td> <td>Yes</td> <td>No</td> <td>56.2%</td> <td>100%</td> </tr> <tr> <td>LeanReasoner</td> <td>No</td> <td>Intuitive</td> <td>62.5%</td> <td>100%</td> </tr> <tr> <td>LeanReasoner</td> <td>Yes</td> <td>Intuitive</td> <td>75%</td> <td>100%</td> </tr> <tr> <td>LeanReasoner</td> <td>Yes</td> <td>Concise</td> <td>75%</td> <td>100%</td> </tr> </tbody> </table> Table 2: Comparative Analysis of Recall@k in premise selection and overall proof accuracy for 99 ProofWriter test samples and 28 FOLIO test samples. Note the proof accuracy here is different from Table 1 because it is directly linked to the final accuracy. The effects of pretraining and fine-tuning on LeanReasoner are evaluated using theorem-proving data and both Intuitive and Concise annotation sets, respectively. Premise Selection accuracy was not calculated for the GPT-4 baseline due to the complexities in prompting GPT-4 with Lean goals. <table> <thead> <tr> <th>Method</th> <th>Acc</th> </tr> </thead> <tbody> <tr> <td>Full training set method</td> <td></td> </tr> <tr> <td>Abs Biases (Gontier et al., 2022)</td> <td>80.6%</td> </tr> <tr> <td>MetaInduce (Yang et al., 2022)</td> <td>98.6%</td> </tr> <tr> <td>RECKONING (Chen et al., 2023b)</td> <td>99.8%</td> </tr> <tr> <td>Zero-shot method</td> <td></td> </tr> <tr> <td>GPT-4 CoT (Pan et al., 2023)</td> <td>68.1%</td> </tr> <tr> <td>Logic-LM (Pan et al., 2023)</td> <td>79.3%</td> </tr> <tr> <td>Our method (finetuned on 100 samples)</td> <td></td> </tr> <tr> <td>LeanReasoner without Pretraining</td> <td>95.8%</td> </tr> <tr> <td>LeanReasoner fine-tuned on Intuitive</td> <td>98.3%</td> </tr> <tr> <td>LeanReasoner fine-tuned on Concise</td> <td>98.3%</td> </tr> </tbody> </table> Table 3: The fine-tuned LeanReasoner has been pretrained on mathlib. Full training set method means the model has been trained on the full training set of ProofWriter. Fine-tuning on Concise achieves near-perfect accuracy with significantly less data. <table> <thead> <tr> <th>Method</th> <th>Acc</th> </tr> </thead> <tbody> <tr> <td>Full training set method</td> <td></td> </tr> <tr> <td>Roberta (Han et al., 2022b)</td> <td>62.1%</td> </tr> <tr> <td>FOLNet (Chen, 2023)</td> <td>70.6%</td> </tr> <tr> <td>Zero-shot method</td> <td></td> </tr> <tr> <td>GPT-4 CoT (Pan et al., 2023)</td> <td>70.6%</td> </tr> <tr> <td>Logic-LM (Pan et al., 2023)</td> <td>74.5%</td> </tr> <tr> <td>Lean Z3 (SATLM)</td> <td>77.5%</td> </tr> <tr> <td>Our method (finetuned on 27 samples)</td> <td></td> </tr> <tr> <td>LeanReasoner without Pretraining</td> <td>66.2%</td> </tr> <tr> <td>LeanReasoner fine-tuned on Intuitive</td> <td>78.4%</td> </tr> <tr> <td>LeanReasoner fine-tuned on Concise</td> <td>82.6%</td> </tr> </tbody> </table> Table 4: Result from “Lean Z3” is derived from lean-smt applied to formalized Lean Code. The fine-tuned LeanReasoner has been pretrained on mathlib. Full training set method means the model has been trained on the full training set of ProofWriter. Our approach achieves state-of-the-arts performance on FOLIO. Our approach achieves state-of-the-arts performance on FOLIO. Table 4 presents our performance on FOLIO. For a fair comparison with SATLM that uses the Z3 solver, we used the lean-smt tool\(^5\) on our formalized Lean code. This tool produces outcomes in the form of “sat/unsat”. In Z3, “sat” stands for “satisfiable.” When Z3 returns “sat” as the result, it means that there exists a set of variable values that makes the theorem true. On the other hand, “unsat” stands for “unsatisfiable”. When Z3 returns “unsat”, it means that the formula is inherently contradictory and cannot be satisfied under any circumstance. We interpret these results similarly to “found a proof/didn’t find a proof” using our result interpreter. Due to the extensive length of proofs for FOLIO problems, we observed that when LeanReasoner is fine-tuned on the Intuitive dataset, it often allocates an excessive amount of time for exploration and occasionally enters loops. In contrast, generating shorter proofs tends to ease the discovery of the proof. While the tactics generated when fine-tuned on the Concise dataset are more challenging to produce, the bottleneck for LeanReasoner on FOLIO resides in the search process. Challenges in Benchmarking. It is important to acknowledge that there can be scenarios where errors in problem formalization or proof generation may occur, yet the final answer is still deemed correct. A case in point is when the answer to a problem is Unknown, and errors arise in these stages. In such instances, the model would struggle to prove either the positive or negative theorem. However, with our result interpreter, these instances would still be classified as correct despite the underlying issues in problem handling. 6 Related Work Combining LLM with symbolic solver. Several past studies (Chen, 2023; Creswell and Shanahan, 2022; Chen et al., 2023b) used symbolic solvers to augment neural networks with logical reasoning. Many of these approaches have limitations, like the necessity for custom or specialized module designs that lack broad applicability. Recent work (Pan et al., 2023; Ye et al., 2023; Poesia et al., 2023; Olausson et al., 2023) presents a more general framework that combines contemporary LLMs with symbolic logic, bypassing the need to train or craft intricate modules tailored for specific problems. While our research aligns with these, we do not exclusively rely on off-the-shelf solvers. Boosting the reasoning skill of LLM by training on reasoning data. A common way to boost the reasoning skills of LLMs is by training them on data that requires some form of reasoning. As noted by Lewkowycz et al. (2022), LLMs trained with science and math data do better on tasks that require reasoning, especially when using CoT. --- \(^5\)https://github.com/ufmg-smite/lean-smt prompting. Other results by Fu and Khot (2022) and Fu et al. (2023) suggest that powerful LLMs obtain advanced reasoning capabilities from being trained on code. This work is an extension of this idea to theorem proving. 7 Conclusion We introduced LeanReasoner, a framework based on Lean that augments the logical reasoning abilities of LLMs. We follow an extensive examination of errors from the formalization and proof generation stages that are present in our framework. We also examine the performance enhancements from pretraining on theorem-proving data and annotation styles (concise v.s. intuitive). We offered a comprehensive comparison with other techniques that highlight the strengths of our model. Our results underscore the potential of integrating theorem-proving frameworks with LLMs in advancing logical reasoning. Limitations Despite our promising results, our method encounters limitations when dealing with problems that involve commonsense and factual reasoning. In these cases, it is challenging to retrieve all the necessary information and accurately represent it in Lean. Consider MMLU (Hendrycks et al., 2020) and SummEdits (Laban et al., 2023): MMLU requires the model to possess extensive world knowledge, while SummEdits involves determining consistency in summaries of different edits. In both instances, the ability to represent the complexity and nuance of real-world knowledge in Lean is severely limited. Further complications arise when dealing with math word problems (Cobbe et al., 2021) and similar tasks (Hendrycks et al., 2021), where the goal is to derive a numeric solution rather than a proof. The theorem-proving approach, while effective for certifying the validity of logical reasoning, does not directly yield a numerical answer. Lastly, our method grapples with problems found in more complicated reasoning datasets like TheoremQA (Chen et al., 2023a). These problems require an advanced understanding of complex concepts and the ability to formalize these concepts into Lean. Our current framework struggles with this level of complexity, underscoring the need for more sophisticated formalization techniques and a deeper integration between language understanding and theorem proving. Even in the context of symbolic problems, there are challenges. For instance, consider the LogicalDeduction task from the BigBench dataset (Srivastava et al., 2022). Although this problem appears straightforward, employing Lean to solve it is neither the most practical nor the most efficient approach. Lean, as a theorem prover, is excellent in abstract reasoning and proof construction, but when faced with tasks involving constraints and variable possibilities, it falls short. To solve the problems in LogicDeduction, using Lean would require us to formalize the concepts of ordering and relative positioning. Even after doing so, generating proof would necessitate significant labor and wouldn’t necessarily yield a readily interpretable answer. In contrast, a Constraint Satisfaction Problem (CSP) solver can effectively manage constraints and generate potential solutions efficiently. Ethical Considerations Incorporating Lean’s theorem-proving capabilities into LLMs offers a layer of mathematical rigor that improves the reliability of conclusions derived. However, LLMs are known to be susceptible to data biases, which may manifest in critical applications. This issue can inadvertently lead to skewed logic or unintended bias in sensitive domains such as medical diagnoses or legal interpretations. While our method’s foundation in Lean’s theorem proving data acts as a rigorous check, complete reliance on it is not foolproof. A proactive approach in reviewing both training data and model outcomes is essential to uphold unbiased reasoning. Acknowledgements We thank the reviewers and members of the Cohort for the valuable feedback and comments on the paper. We appreciate the provision of computing resources through the Baskerville cluster at the University of Birmingham. References Wenhui Chen, Ming Yin, Max Ku, Pan Lu, Yixin Wan, Xueguang Ma, Jianyu Xu, Xinyi Wang, and Tony Xia. 2023a. Theoremqa: A theorem-driven question answering dataset. Hao Fu, Yao; Peng and Tushar Khot. 2022. How does gpt obtain its ability? tracing emergent abilities of language models to their sources. Yao Fu’s Notion. Jesse Michael Han, Jason Rute, Yuhuai Wu, Edward W. Ayers, and Stanislas Polu. 2022a. Proof artifact co-training for theorem proving with language models. In ICLR. OpenAI. 2023. GPT-4 technical report. CoRR. Liangming Pan, Alon Albalak, Xinyi Wang, and et.al. 2023. Logic-lm: Empowering large language models with symbolic solvers for faithful logical reasoning. A Prompts for Formalization A.1 Prompts for ProofWriter In subsection 5.1, we discussed various formalization approaches. In this section, we present the results using the GPT-4 Base Comments method on ProofWriter when the answer is False. As evident from the last line, the predicted outcome from GPT-4 can be derived easily. System Message: You are a logician with a background in mathematics that translates natural language reasoning text to Lean code so that these natural language reasoning problems can be solved. During the translation, please pay close attention to the predicates and entities. There is an additional requirement: I also want you to try to prove the theorem you translated to Lean. If you can prove the theorem, give me True at the end of the answer. If you can prove the negation of the theorem, write False at the end of the answer. If you can neither prove the original theorem nor the negation of the theorem, please give me Unknown at the end of the answer. Input: Textual context: The cat is blue. The cat is nice. The cat likes the cow. The cat needs the cow. The cat needs the rabbit. The cow does not need the rabbit. The cow needs the tiger. The rabbit is round. The tiger is nice. The tiger does not like the cow. If someone likes the cat and they chase the cat then they are blue. If someone likes the cow and they are red then the cow is round. If someone needs the tiger and they need the cat then they do not chase the cow. If someone needs the cat and the cat is blue then the cat is red. If someone is round then they need the cat. If someone likes the cat and the cat needs the rabbit then the cat chases the tiger. If the rabbit needs the tiger then the rabbit is not round. Question: Based on the above information, is the following statement true, false, or unknown? The cow chases the cow. A.2 Prompts Used for FOLIO For FOLIO, the prompts differ slightly from those used for ProofWriter. Since FOLIO's textual context remains consistent across multiple questions, we concatenate questions sharing the same context and prompt the large language model in a single instance. An illustrative example is provided below. --- The negation of the theorem can be proven in Lean. So --- The answer is False The theorem cannot be proven in Lean. So let's try to prove the negation of the theorem instead. The answer is True Output: -- Introducing basic types for entities in our universe. constant Turkey : Type constant Tom : Turkey constant Joey : Turkey -- Defining properties for the turkeys in our universe. constant is_eastern_turkey : Turkey → Prop constant is_osceola_turkey : Turkey → Prop constant is_merriams_turkey : Turkey → Prop constant is_rio_grande_turkey : Turkey → Prop constant is_goulds_turkey : Turkey → Prop constant is_ocellated_turkey : Turkey → Prop -- Context from the information constant is_ocellated_wild_turkey : Turkey constant is_rio_grande_wild_turkey : Turkey constant is_merriams_wild_turkey : Turkey constant is_goulds_wild_turkey : Turkey constant is_osceola_wild_turkey : Turkey constant is_eastern_wild_turkey : Turkey constant is_wild_turkey : Turkey -- Formalizing the Questions axiom turkey_type_exclusivity : ∀ (t : Turkey), bites t ∨ stings t axiom A6 : bites Bob axiom A7 : ∀ (t : Turkey), eastern_bite_causes_death t 13 begin -- Let's try the negative case. theorem not_tom_is_ocellated_wild_turkey : ¬ is_ocellated_wild_turkey Tom := begin exact A2, end -- The answer is Unknown -- Question 2 begin end -- Let's try the negative case. theorem not_tom_is_eastern_wild_turkey : ¬ is_eastern_wild_turkey Tom := begin exact A1, end -- The answer is False -- Question 3 begin end -- Let's try the negative case. theorem not_joey_is_wild_turkey : ¬ is_wild_turkey Joey := begin sorry, -- Placeholder for proof end -- The answer is Unknown end begin theorem tom_is_eastern_wild_turkey : begin end -- Let's first prove the positive case. -- Tom is an Eastern wild turkey. -- Question 2 begin end -- The answer is Unknown begin end -- Let's first prove the positive case. -- Tom is a wild turkey. begin end -- Context from the information -- Tom is not an Eastern wild turkey. axiom A1 : ¬ is_eastern_wild_turkey Tom -- Tom is not an Osceola wild turkey. axiom A2 : ¬ is_osceola_wild_turkey Tom -- Tom is also not a Gould's wild turkey. axiom A3 : ¬ is_goulds_wild_turkey Tom -- Tom is also not a Merriam's wild turkey. axiom A4 : ¬ is_merriams_wild_turkey Tom -- Tom is not a Rio Grande wild turkey. axiom A5 : ¬ is_rio_grande_wild_turkey Tom -- There are six types of wild turkeys: Eastern wild turkey, Osceola wild turkey, 'Goulds wild turkey, 'Merriam's wild turkey, Rio Grande wild turkey, and Ocellated wild turkey. axiom type_exclusivity : ∀ (t : Turkey), is_wild_turkey t → is_eastern_wild_turkey t ∨ is_osceola_wild_turkey t ∨ is_goulds_wild_turkey t ∨ is_merriams_wild_turkey t ∨ is_rio_grande_wild_turkey t ∨ is_ocellated_wild_turkey t -- Formalizing the Questions -- Question 1 begin end -- Tom is an Ocellated wild turkey. theorem tom_is_ocellated_wild_turkey : begin end -- Let's try the negative case. theorem not_tom_is_eastern_wild_turkey : begin end -- The answer is Unknown begin end -- Question 2 begin end -- Tom is a wild turkey. Bob is an Eastern turkey. begin end -- The answer is False begin end -- Question 3: If Bob bites you, you will die. Theorem 3: If Bob bites you, you will die. B Example Errors During Formalization This is an artificial example highlighting typical errors encountered in the formalization stage. Input: There are three types of wild turkeys: Eastern turkey, Osceola turkey, Gould's turkey. Tom is neither an Eastern turkey nor an Osceola turkey. Tom is a wild turkey. Bob is a Eastern turkey. Bob weights 86 pounds and Tom weights 73 pounds. Turkeys either bites or stings. Bob bites. Eastern turkey’s bite would cause death. Question 1: Tom is a Gould’s turkey. Question 2: Bob is heavier than Tom. Question 3: If Bob bites you, you will die. Output: constant Turkey : Type constant Eastern Osceola Goulds : Turkey → Prop constant weight_86 weight_73 : Turkey → Prop constant bites stings : Turkey → Prop constant eastern_bite_causes_death : Turkey → Prop constant Tom : Turkey axiom A1 : ¬ Eastern Tom ∧ ¬ Osceola Tom axiom A2 : Eastern Bob axiom A3 : weight_86 Bob axiom A4 : weight_73 Tom axiom A5 : ∀ (t : Turkey), bites t ∨ stings t axiom A6 : bites Bob axiom A7 : ∀ (t : Turkey), eastern_bite_causes_death t There are a few errors in the above code, including: - There is a missing axiom that corresponds to “There are three types of wild turkeys”: Goulds Tom ∨ Eastern Tom ∨ Osceola Tom - The formalization of numbers is incorrect, it should be: \[ \text{constant weight : Turkey} \to \mathbb{N} \] \[ \text{axiom A3 : weight Bob = 86} \] \[ \text{axiom A4 : weight Tom = 73} \] - The formalization of logic is incorrect, it should be: \[ \neg \text{bite\_causes\_death}\ t \land \neg \text{bite\_causes\_itching}\ t \lor \neg \neg \text{bite\_causes\_death}\ t \] - There is an incorrect division of concepts that would make the proving impossible, the correct version should be: \[ \forall (t : \text{Turkey}), \text{Eastern}\ t \land \text{bite\_causes\_death}\ t \] C Example Proof Annotation with Different Annotation Styles Here we’re showing two example proofs created on the same problem with ‘Intuitive’ annotation style and ‘Concise’ annotation style. Input: "Textual Context": All eels are fish. No fish are plants. A thing is either a plant or animal. Nothing that breathes is paper. All animals breathe. If a sea eel is either an eel or a plant, then a sea eel is an eel or an animal. "Question": Based on the above information, is the following statement true, false, or uncertain? Sea eel is a paper. Formalized Context: \[ \begin{align*} \text{constant Thing : Type} \\ \text{constant is\_eel : Thing} \to \text{Prop} \\ \text{constant is\_fish : Thing} \to \text{Prop} \\ \text{constant is\_plant : Thing} \to \text{Prop} \\ \text{constant is\_animal : Thing} \to \text{Prop} \\ \text{constant breathes : Thing} \to \text{Prop} \\ \text{constant sea\_eel : Thing} \\ \end{align*} \] \[ \text{-- All eels are fish.} \] \[ \text{axiom A1 : \forall (t : \text{Thing}), is\_eel}\ t \to \text{is\_fish}\ t \] \[ \text{-- No fish are plants.} \] \[ \text{axiom A2 : \forall (t : \text{Thing}), is\_fish}\ t \to \neg \text{is\_plant}\ t \] \[ \text{-- A thing is either a plant or animal.} \] \[ \text{axiom A3 : \forall (t : \text{Thing}), is\_plant}\ t \lor \text{is\_animal}\ t \] \[ \text{-- Nothing that breathes is paper.} \] \[ \text{axiom A4 : \forall (t : \text{Thing}), breathes}\ t \to \neg \text{is\_paper}\ t \] \[ \text{-- All animals breathe.} \] Intuitive Proof: \[ \text{theorem not\_sea\_eel\_is\_paper : \neg \text{is\_paper}\ \text{sea\_eel}} := \begin{align*} \text{cases A3 sea\_eel,} \\ \text{cases A6 (or.inr h),} \\ \text{have h1 : \neg \text{is\_fish}\ \text{sea\_eel},} \\ \text{intro h,} \\ \text{have temp := A2 sea\_eel h,} \\ \text{contradiction,} \\ \text{have h2 : \neg \text{is\_eel}\ \text{sea\_eel},} \\ \text{intro h,} \\ \text{have temp := A1 sea\_eel h,} \\ \text{contradiction,} \\ \text{have h3 : \neg \text{is\_eel}\ \text{sea\_eel} \lor \text{is\_plant}\ \text{sea\_eel},} \\ \text{right,} \\ \text{assumption,} \\ \text{have h4 : \neg \text{is\_eel}\ \text{sea\_eel} \lor \text{is\_animal}\ \text{sea\_eel} := A6 h_3,} \\ \text{cases h4,} \\ \text{have h5 : breathes\ \text{sea\_eel} := A5 sea\_eel h_4,} \\ \text{have h6 : \neg \text{is\_paper}\ \text{sea\_eel} := A4 sea\_eel h_5,} \\ \text{contradiction,} \\ \text{have h1 : breathes\ \text{sea\_eel} := A5 sea\_eel h,} \\ \text{have h2 : \neg \text{is\_paper}\ \text{sea\_eel} := A4 sea\_eel h_1,} \\ \text{contradiction,} \\ \end{align*} \] Concise Proof: \[ \text{theorem not\_sea\_eel\_is\_paper : \neg \text{is\_paper}\ \text{sea\_eel}} := \begin{align*} \text{begin} \\ \text{cases A3 sea\_eel,} \\ \text{cases A6 (or.inr h),} \\ \text{have h1 := A2 sea\_eel (A1 sea\_eel h_1),} \\ \text{contradiction,} \\ \text{have h4 := A4 sea\_eel (A5 sea\_eel h_1),} \\ \text{exact A4 sea\_eel (A5 sea\_eel h_1),} \\ \end{align*} \]
{"Source-Url": "https://aclanthology.org/2024.naacl-long.416.pdf", "len_cl100k_base": 11200, "olmocr-version": "0.1.53", "pdf-total-pages": 14, "total-fallback-pages": 0, "total-input-tokens": 48072, "total-output-tokens": 13241, "length": "2e13", "weborganizer": {"__label__adult": 0.0004470348358154297, "__label__art_design": 0.0008516311645507812, "__label__crime_law": 0.000667572021484375, "__label__education_jobs": 0.004756927490234375, "__label__entertainment": 0.0002677440643310547, "__label__fashion_beauty": 0.00030875205993652344, "__label__finance_business": 0.000591278076171875, "__label__food_dining": 0.0006766319274902344, "__label__games": 0.0016841888427734375, "__label__hardware": 0.0008788108825683594, "__label__health": 0.000751495361328125, "__label__history": 0.0004420280456542969, "__label__home_hobbies": 0.0002105236053466797, "__label__industrial": 0.0007920265197753906, "__label__literature": 0.0011320114135742188, "__label__politics": 0.00045418739318847656, "__label__religion": 0.0006918907165527344, "__label__science_tech": 0.220703125, "__label__social_life": 0.00026702880859375, "__label__software": 0.0185394287109375, "__label__software_dev": 0.74365234375, "__label__sports_fitness": 0.00041604042053222656, "__label__transportation": 0.0006427764892578125, "__label__travel": 0.0002225637435913086}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 50625, 0.02279]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 50625, 0.40276]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 50625, 0.87774]], "google_gemma-3-12b-it_contains_pii": [[0, 4045, false], [4045, 8241, null], [8241, 11614, null], [11614, 16136, null], [16136, 20568, null], [20568, 24000, null], [24000, 28891, null], [28891, 31712, null], [31712, 35747, null], [35747, 40413, null], [40413, 42256, null], [42256, 42785, null], [42785, 46870, null], [46870, 50625, null]], "google_gemma-3-12b-it_is_public_document": [[0, 4045, true], [4045, 8241, null], [8241, 11614, null], [11614, 16136, null], [16136, 20568, null], [20568, 24000, null], [24000, 28891, null], [28891, 31712, null], [31712, 35747, null], [35747, 40413, null], [40413, 42256, null], [42256, 42785, null], [42785, 46870, null], [46870, 50625, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 50625, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 50625, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 50625, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 50625, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 50625, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 50625, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 50625, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 50625, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 50625, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 50625, null]], "pdf_page_numbers": [[0, 4045, 1], [4045, 8241, 2], [8241, 11614, 3], [11614, 16136, 4], [16136, 20568, 5], [20568, 24000, 6], [24000, 28891, 7], [28891, 31712, 8], [31712, 35747, 9], [35747, 40413, 10], [40413, 42256, 11], [42256, 42785, 12], [42785, 46870, 13], [46870, 50625, 14]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 50625, 0.085]]}
olmocr_science_pdfs
2024-12-09
2024-12-09
69849db4d3f674459259c92225a10c4d26f5f52b
Evaluating Value-Graph Translation Validation for LLVM The Harvard community has made this article openly available. Please share how this access benefits you. Your story matters Citation Citable link http://nrs.harvard.edu/urn-3:HUL.InstRepos:4762396 Terms of Use This article was downloaded from Harvard University’s DASH repository, and is made available under the terms and conditions applicable to Other Posted Material, as set forth at http://nrs.harvard.edu/urn-3:HUL.InstRepos:dash.current.terms-of-use#LAA Evaluating Value-Graph Translation Validation for LLVM Jean-Baptiste Tristan Paul Govereau Greg Morrisett Harvard University {tristan,govereau,greg}@seas.harvard.edu Abstract Translation validators are static analyzers that attempt to verify that program transformations preserve semantics. Normalizing translation validators do so by trying to match the value-graphs of an original function and its transformed counterpart. In this paper, we present the design of such a validator for LLVM’s intra-procedural optimizations, a design that does not require any instrumentation of the optimizer, nor any rewriting of the source code to compile, and needs to run only once to validate a pipeline of optimizations. We present the results of our preliminary experiments on a set of benchmarks that include GCC, a perl interpreter, SQLite3, and other C programs. Categories and Subject Descriptors F.3.2 [Logics and Meanings of Programs]: Semantics of Programming Languages - Algebraic approaches to semantics; F.3.1 [Logics and Meanings of Programs]: Specifying and Verifying and Reasoning about Programs - Mechanical Verification; F.3.3 [Logics and Meanings of Programs]: Studies of Program Constructs - Program and recursion schemes General Terms Algorithms, languages, reliability, theory, verification Keywords Translation validation, symbolic evaluation, LLVM, optimization 1. Introduction Translation validation is a static analysis that, given two programs, tries to verify that they have the same semantics [13]. It can be used to ensure that program transformations do not introduce semantic discrepancies, or to improve testing and debugging. Previous experiments have successfully applied a range of translation validation techniques to a variety of real-world compilers. Necula [11] experimented on GCC 2.7; Zuck et al. [4] experimented on the Tru64 compiler; Rival [14] experimented on unoptimized GCC 3.0; and Kanade et al. [8] experimented on GCC 4. Given all these results, can we effectively validate a production optimizer? For a production optimizer, we chose LLVM. To be effective, we believe our validator must satisfy the following criteria. First, we do not want to instrument the optimizer. LLVM has a large collection of program transformations that are updated and improved at a frantic pace. To be effective, we want to treat the optimizer as a “black box”. Second, we do not want to modify the source code of the input programs. This means that we handle the output of the optimizer when run on the input C programs “as is.” Third, we want to run only one pass of validation for the whole optimization pipeline. This is important for efficiency, and also because the boundaries between different optimizations are not always firm. Finally, it is crucial that the validator can scale to large functions. The experiments of Kanade et al. are the most impressive of all, with an exceptionally low rate of false alarms (note the validator requires heavy instrumentation of the compiler). However the authors admit that their approach does not scale beyond a few hundred instructions. In our experiments, we routinely have to deal with functions having several thousand instructions. The most important issue is the instrumentation. To our knowledge, two previous works have proposed solutions that do not require instrumentation of the optimizer. Necula evaluated the effectiveness of a translation validator for GCC 2.7 with common-subexpression elimination, register allocation, scheduling, and loop inversion. The validator is simulation-based: it verifies that a simulation-relation holds between the two programs. Since the compiler is not instrumented, this simulation relation is inferred by collecting constraints. The experimental validation shows that this approach scales, as the validator handles the compilation of programs such as GCC or Linux. However, adding other optimizations such as loop-unswitch or loop-deletion is likely to break the collection of constraints. On the other hand, Tate et al. [16] recently proposed a system for translation validation. They compute a value-graph for an input function and its optimized counterpart. They then augment the terms of the graphs by adding equivalent terms through a process known as equality saturation, resulting in a data structure similar to the E-graphs of congruence closure. If, after saturation, the two graphs are the same, they can safely conclude that the two programs they represent are equivalent. However, equality saturation was originally designed for other purposes, namely the search for better optimizations. For translation validation, it is unnecessary to saturate the value-graph, and generally more efficient and scalable to simply normalize the graph by picking an orientation to the equations that agrees with what a typical compiler will do (e.g. 1 + 1 is replaced by 2). Their preliminary experimental evaluation for the Soot optimizer on the JVM shows that the approach is effective and can lead to an acceptable rate of false alarms. However, it is unclear how well this approach would work for the more challenging optimizations available in LLVM, such as global-value-numbering with alias analysis or sparse-conditional constant propagation. We believe that a normalizing value-graph translation validator would have both the simplicity of the saturation validator proposed by Tate et al., and the scalability of Necula’s constraint-based approach. In this paper we set out to evaluate how well such a design works. We therefore present the design and implementation of such a validator along with experimental results for a number of benchmarks including SQLite [2] and programs drawn from... spec marks [5], including GCC and a perl interpreter. The optimizations we consider include global-value numbering with alias analysis, sparse-conditional constant propagation, aggressive dead-code elimination, loop invariant code motion, loop unswitching, loop deletion, instruction combining, and dead-store elimination. We have also experimented, on a smaller suite of hand-written programs and optimizations, that our tool could handle without further modification various flavors of scheduling (list, trace, etc.) and loop fusion and fission. While Tate et al. tried a saturation approach on JVM code and found the approach to be effective, we consider here a normalization approach in the context of C code. C code is challenging to validate because of the lack of strong typing and the relatively low-level nature of the code when compared to the JVM. However, our results show that a normalizing value-graph translation validator can effectively validate the most challenging intra-procedural optimizations of the LLVM compiler. Another significant contribution of our work is that we provide a detailed analysis of the effectiveness of the validator with respect to the different optimizations. Finally, we discuss a number of more complicated approaches that we tried but ultimately found less successful than our relatively simple architecture. The remainder of the paper is organized as follows. Section 2 presents the design of our tool. Section 3 details the construction of the value-graph using examples. Section 4 reviews the normalization rules that we use and addresses their effectiveness through examples. Section 5 presents the results of our experiments. We discuss related work in Section 6 and conclude in Section 7. 2. Normalizing translation validation Our validation tool is called LLVM-MD. At a high-level, LLVM-MD is an optimizer: it takes as input an LLVM assembly file and outputs an LLVM assembly file. The difference between our tool and the usual LLVM optimizer is that our tool certifies that the semantics of the program is preserved. LLVM-MD has two components, the usual off-the-shelf LLVM optimizer, and a translation validator. The validator takes two inputs: the assembly code of a function before and after it has been transformed by the optimizer. The validator outputs a boolean: true if it can prove the assembly codes have the same semantics, and false otherwise. Assuming the correctness of our validator, a semantics-preserving LLVM optimizer can be constructed as follows (opt is the command-line LLVM optimizer, validate is our translation validator): ```c function llvm-md(var input) { output = opt -options input for each function f in input { extract f from input as fi and output as fo if (!validate fi fo) { replace fo by fi in output } } return output } ``` For now, our validator works on each function independently, hence the limitation to intra-procedural optimizations. We believe that standard techniques can be used to validate programs in the presence of function inlining, but have not yet implemented these. Rather, we concentrate on the workhorse intra-procedural optimizations of LLVM. At a high level, our tool works as follows. First, it “compiles” each of the two functions into a value-graph that represents the data dependencies of the functions. Such a value-graph can be thought of as a dataflow program, or as a generalization of the result of symbolic evaluation. Then, each graph is normalized by rewriting using rules that mirror the rewritings that may be applied by the off-the-shelf optimizer. For instance, it will rewrite the 3-node sub-graph representing the expression 2 + 3 into a single node representing the value 5, as this corresponds to constant folding. Finally, we compare the resulting value-graphs. If they are syntactically equivalent, the validator returns true. To make comparison efficient, the value-graphs are hash-consed (from now on, we will say “reduced”). In addition, we construct a single graph for both functions to allow sharing between the two (conceptually distinct) graphs. Therefore, in the best case—when semantics has been preserved—the comparison of the two functions has complexity O(1). The best-case complexity is important because we expect most optimizations to be semantics-preserving. The LLVM-MD validation process is depicted in figure 1. First, each function is converted into Monadic Gated SSA form [6, 10, 18]. The goal of this representation is to make the assembly instructions referentially transparent: all of the information required to compute the value of an instruction is contained within the instruction. More importantly, referential transparency allows us to substitute sub-graphs with equivalent sub-graphs without worrying about computational effects. Computing Monadic Gated SSA form is done in two steps: 1. Make side-effects explicit in the syntax by interpreting assembly instructions as monadic commands. For example, a load instruction will have a extra parameter representing the memory state. 2. Compute Gated SSA form, which extends $\phi$-nodes with conditions, insert $\mu$-nodes at loop headers, and $\eta$-nodes at loop exits[18]. Once we have the Monadic Gated SSA form, we compute a shared value-graph by replacing each variable with its definition, being careful to maximize sharing within the graph. Finally, we apply normalization rules and maximize sharing until the value of the two functions merge into a single node, or we cannot perform any more normalization. It is important to note that the precision of the semantics-preservation property depends on the precision of the monadic form. If the monadic representation does not model arithmetic overflow or exceptions, then a successful validation does not guarantee anything about those effects. At present, we model memory state, including the local stack frame and the heap. We do not model runtime errors or non-termination, although our approach can be extended to include them. Hence, a successful run of our validator implies that if the input function terminates and does not produce a runtime error, then the output function has the same semantics. Our tool does not yet offer formal guarantees for non-terminating or semantically undefined programs. 3. Validation by Example 3.1 Basic Blocks We begin by explaining how the validation process works for basic blocks. Considering basic blocks is interesting because it allows us to focus on the monadic representation and the construction of the value-graph, leaving for later the tricky problem of placing gates in $\phi$- and $\eta$-nodes. Our validator uses LLVM assembly language as input. LLVM is a portable SSA-form assembly language with an infinite number of registers. Because we start with SSA-form, producing the value-graph consists of replacing variables by their definitions while maximizing sharing among graph nodes. For example, consider the following basic block, B1: \[ \begin{align*} B1: & \quad x_1 = 3 + 3 \\ & \quad x_2 = a \ast x_1 \\ & \quad x_3 = x_2 + x_2 \end{align*} \] and its optimized counterpart, B2: \[ \begin{align*} B2: & \quad y_1 = a \ast 6 \\ & \quad y_2 = y_1 << 1 \end{align*} \] Replacing variables \(x_1, x_2, a\) and \(y_1\) by their definitions, we obtain the value-graph presented below. The dashed arrows are not part of the graph, they are only meant to point out which parts of the graph correspond to which program variables. Note that both blocks have been represented within one value graph, and the node for the variable \(a\) has been shared. Suppose that we want to show that the variables \(x_3\) and \(y_2\) will hold the same value. Once we have the shared value graph in hand, we simply need to check if \(x_3\) and \(y_2\) are represented by subgraphs rooted at the same graph node. In the value graph above, \(x_3\) and \(y_2\) are not represented by the same subgraph, so we cannot conclude they are equivalent. However, we can now apply normalization rules to the graph. First, we can apply a constant folding rule to reduce the subgraph \(3 + 3\) to a single node \(6\). The resulting graph is shown below (we have maximized sharing in the graph). We have managed to make the value graph smaller, but we still cannot conclude that the two variables are equivalent. So, we continue to normalize the graph. A second rewrite rule allows us to replace \(x + x\) with \(x \ll 1\) for any \(x\). In our setting, this rule is only appropriate if the optimizer would prefer the shift instruction to addition (which LLVM does). After replacing addition with left shift, and maximizing sharing, \(x_3\) and \(y_2\) point to the same node and we can conclude that the two blocks are equivalent. **Side Effects.** The translation we have described up to this point would not be correct in the presence of side effects. Consider the following basic block. \[ \begin{align*} p_1 & = \text{alloc} 1 \\ p_2 & = \text{alloc} 1 \\ \text{store} & \quad x,p_1 \\ \text{store} & \quad y,p_2 \\ z & = \text{load} p_1 \end{align*} \] If we naively apply our translation, then the graph corresponding to \(z\) would be: \(z \mapsto \text{load} (\text{alloc} 1)\), which does not capture the complete computation for register \(z\). In order to make sure that we do not lose track of side effects, we use abstract state variables to capture the dependencies between instructions. A simple translation gives the following sequence of instructions for this block: \[ \begin{align*} p_1,m_1 & = \text{alloc} 1,m_0 \\ p_2,m_2 & = \text{alloc} 1,m_1 \\ m_3 & = \text{store} (x,p_1,m_2) \\ m_4 & = \text{store} (y,p_2,m_3) \\ z,m_5 & = \text{load} (p_1,m_4) \end{align*} \] Here, the current memory state is represented by the \(m\) registers. Each instruction requires and produces a memory register in addition to its usual parameters. This extra register enforces a dependency between, for instance, the \text{load} instruction and the preceding \text{store} instructions. This translation is the same as we would get if we interpreted the assembly instructions as a sequence of monadic commands in a simple state monad\[10\]. Using these “monadic” instructions, we can apply our transformation and produce a value graph that captures all of the relevant information for each register. The rewriting rules in our system are able to take into account aliasing information to relax the strict ordering of instructions imposed by the monadic transformation. In our setting (LLVM), we know that pointers returned by \text{alloc} never alias with each other. Using this information, we are able to replace \( m_4 \) with \( m_3 \) in the load instruction for \( x \). Then, because we have a load from a memory consisting of a store to the same pointer, we can simplify the load to \( x \). Using the state variables, we can validate that a function not only computes the same value as another function, but also affects the heap in the same way. The same technique can be applied to different kinds of side effects, such as arithmetic overflow, division by zero, and non-termination. Thus far we have only modeled memory side-effects in our implementation. Hence, we only prove semantics preservation for terminating programs that do not raise runtime errors. However, our structure allows us to easily extend our implementation to a more accurate model, though doing so may make it harder to validate optimizations. ### 3.2 Extended Basic Blocks These ideas can be generalized to extended basic blocks as long as \( \phi \)-nodes are referentially transparent. We ensure this through the use of gated \( \phi \)-nodes. Consider the following program, which uses a normal \( \phi \)-node as you would find in an SSA-form assembly program. \[ \begin{align*} \text{entry} & : \ c = a < b \\ \text{true} & : \ x_1 = x_0 + x_0 \quad (\text{True branch}) \\ \text{false} & : \ x_2 = x_0 \ast x_0 \quad (\text{False branch}) \\ \text{join} & : \ x_3 = \phi(x_1, x_2) \quad (\text{Join point}) \end{align*} \] Rewriting these instructions as is would not be correct. For instance, replacing the condition \( a < b \) by \( a \geq b \) would result in the same value-graph, and we could not distinguish these two different programs. However, if the \( \phi \)-node is extended to include the conditions for taking each branch, then we can distinguish the two programs. In our example, the last instruction would become \( x_3 = \phi(b, x_1, x_2) \), which means \( x_3 \) is \( x_1 \) if \( b \) is \( \text{true} \), and \( x_2 \) otherwise. In order to handle real C programs, the actual syntax of \( \phi \)-nodes has to be a bit more complex. In general, a \( \phi \)-node is composed of a set of possible branches, one for each control-flow edge that enters the \( \phi \)-node. Each branch has a set of conditions, all of which must be true for the branch to be taken.\(^1\) \[ \phi = \left\{ \begin{array}{c} \phi_{c_1} : c_{1n} \rightarrow v_1 \\ \; \vdots \; \phi_{c_k} : c_{kn} \rightarrow v_k \end{array} \right\} \] Given this more general syntax, the notation \( \phi(c, x, y) \) is simply shorthand for \( \phi(c \rightarrow x, c \rightarrow y) \). Gated \( \phi \)-nodes come along with a set of normalization rules that we present in the next section. When generating gated \( \phi \)-nodes, it is important that the conditions for each branch are mutually exclusive with the other branches. This way, we are free to apply normalization rules to \( \phi \)-nodes (such as reordering conditions and branches) without worrying about changing the semantics. It is also worth noting that if the values coming from various paths are equivalent, then they will be shared in the value graph. This makes it possible to validate optimizations based on global-value numbering that is aware of equivalences between definitions from distinct paths. ### 3.3 Loops In order to generalize our technique to loops, we must come up with a way to place gates within looping control flow (including breaks, continues, and returns) from within a loop. Also, we need a way to represent values constructed within loops in a referentially transparent way. Happily, Gated SSA form is ideally suited to our purpose. Gated SSA uses two constructs to represent loops in a referentially transparent fashion. The first, \( \mu \), is used to define variables that are modified within a loop. Each \( \mu \) is placed at a loop header and holds the initial value of the variable on entry to the loop and a value for successive iterations. The \( \mu \)-node is equivalent to a nongated \( \phi \)-node from classical SSA. The second, \( \eta \), is used to refer to loop-defined variables from outside their defining loops. The \( \eta \)-node carries the variable being referred to along with the condition required to reach the \( \eta \) from the variable definition. Figure 2a shows a simple while loop in SSA form. The Gated SSA form of the same loop is shown in figure 2b. The \( \phi \)-nodes in the loop header have been replaced with \( \mu \)-nodes, and the access to the \( x_p \) register from outside to loop is transformed into an \( \eta \)-node that carries the condition required to exit the loop and arrive at this definition. With Gated SSA form, recursively defined variables must contain a \( \mu \)-node. The recursion can be thought of as a cycle in the value graph, and all cycles are dominated by a \( \mu \)-node. The value graph corresponding to our previous example is presented in figure 2c. Intuitively, the cycle in the value-graph can be thought of as generating a stream of values. The \( \mu \)-nodes start by selecting the initial value from the arm marked with an “\( i \)”. Successive values are generated from the cyclic graph structure attached to the other arm. This \( \mu \)-node “produces” the values \( c, c + 1, c + 2, \ldots \). The \( \eta \) receives a stream of values and a stream of conditions. When the stream of conditions goes from \( \text{true} \) to \( \text{false} \), the \( \eta \) selects the corresponding value in the value stream. Generally, we can think of \( \mu \) and \( \eta \) behaving according to the following formulas: \[ \begin{align*} \mu(a, n) & = a : \mu(n[a/x], n) \\ \eta(0: b, x : \tau) & = \eta(b, \tau) \\ \eta(1: \tau, x : \tau) & = x \end{align*} \] Of course, for our purposes, we do not need to evaluate these formulas, we simply need an adequate, symbolic representation for the registers \( x, x_p \), and \( b_p \). A more formal semantics should probably borrow ideas from dataflow programming languages such as those studied by Tate et al.[16]. ### 4. Normalization Once a graph is constructed for two functions, if the functions’ values are not already equivalent, we begin to normalize the graph. We normalize value graphs using a set of rewrite rules. We apply the rules to each graph node individually. When no more rules can be applied, we maximize sharing within the graph and then reapply our rules. When no more sharing or rules can be applied, the process terminates. Our rewrite rules come in two basic types: general simplification rules and optimization-specific rules. The general simplification rules reduce the number of graph nodes by removing unnecessary structure. We say general because these rules only depend on the graph representation, replacing graph structures with smaller, simpler graph structures. The optimization-specific rules rewrite graphs in a way that mirrors the effects of specific optimizations. \(^1\) \( \phi \)-nodes with several branches and many conditions are very common in C programs. For example, an if-statement with a condition that uses short-cut boolean operators, can produce complex \( \phi \)-nodes. These rules do not always make the graph smaller or simpler, and one often needs to have specific optimizations in mind when adding them to the system. **General Simplification Rules.** The notation $a \downarrow b$ means that we match graphs with structure $a$ and replace them with $b$. The first four general rules simplify boolean expressions: 1. $a = a \downarrow \text{true}$ 2. $a \neq a \downarrow \text{false}$ 3. $a = \text{true} \downarrow a$ 4. $a \neq \text{false} \downarrow a$ These last two rules only apply if the comparison is performed at the boolean type. In fact, all LLVM operations, and hence our graph nodes, are typed. The types of operators are important and uninteresting: we do not discuss types in this paper. There are two general rules for removing unnecessary $\phi$-nodes. 1. $\phi \{ \ldots, \text{true}_i \rightarrow t, \ldots \} \downarrow t$ 2. $\phi \{ \text{false}_i \rightarrow t \} \downarrow t$ The first rule replaces a $\phi$-node with one of its branches if all of its conditions are satisfied for that branch. We write $\text{false}_i$ for a set of terms indexed by $i$. In the first rule, we have a set of true values. Note that the conditions for each branch are mutually exclusive with the other branches, so only one branch can have conditions which are all true. The second rule removes the $\phi$-node if all of the branches contain the same value. A special case of this rule is a $\phi$-node with only one branch indicating that there is only one possible path to the $\phi$-node, as happens with branch elimination. The $\phi$ rules are required to validate sparse conditional constant propagation (SCCP) and global value numbering (GVN). The following example can be optimized by both: ```plaintext if (c) {a = 1; b = 1; d = a;} else {a = 2; b = 2; d = 1;} if (a == b) {x = d;} else {x = 0;} return x; ``` Applying global-value numbering followed by sparse conditional constant propagation transforms this program to return 1. Indeed, in each of the branches of the first if-statement, $a$ is equal to $b$. Since $a == b$ is always true, the condition of the second if-statement is constant, and sparse conditional constant propagation can propagate the left definition of $x$. The above program and return 1 have the same normalized value graph, computed as follows: $$x \mapsto \phi(c, 1, 2) = \phi(c, 1, 2), \phi(c, 1, 1).0$$ $$\downarrow \phi(\text{true}, \phi(c, 1, 1), 0) \quad \text{by (1)}$$ $$\downarrow \phi(c, 1, 1) \quad \text{by (5)}$$ $$\downarrow 1 \quad \text{by (6)}$$ There are also general rules for simplifying $\eta$- and $\mu$-nodes. The first rule allows us to remove loops that never execute. $$\eta(\text{false}, \mu(x, y)) \downarrow x \quad \text{(7)}$$ This rule rewrites to the initial value of the $\mu$-node before the loop is entered, namely $x$. This rule is needed to validate loop-deletion, a form of dead code elimination. In addition, there are two rules for loop invariants. The first says that if we have a constant $\mu$-node, then the corresponding $\eta$-node can be removed: $$\eta(c, \mu(x, x)) \downarrow x \quad \text{(8)}$$ $$\eta(c, y \mapsto \mu(x, y)) \downarrow x \quad \text{(9)}$$ In rule (8), the $\mu$-node has an initial value of $x$, which must be defined outside of the loop, and therefore cannot vary within the loop. Since, $x$ does not vary within the loop the $\mu$-node does not vary, and the loop structure can be removed. Rule (9), expresses the same condition, but the second term in the $\mu$-node is again the same $\mu$-node (we use the notation $y \mapsto \mu(x, y)$ to represent this self-reference). These rules are necessary to validate loop invariant code motion. As an example, consider the following program: ```plaintext x = a + 3; c = 3; for (i = 0; i < n; i++) {x = a + c;} return x; ``` In this program, variable $x$ is defined within a loop, but it is invariant. Moreover, variable $c$ is a constant. Applying global constant propagation, followed by loop-invariant code motion and loop deletion transforms the program to return $(a + 3)$. The value graph for $x$ is computed as follows: $$i_n \mapsto \mu(0, i_n + 1)$$ $$x \mapsto \eta(i_n < n, \mu(a + 3, a + 3))$$ $$\downarrow a + c \quad \text{(by 8)}$$ Note that the global copy propagation is taken care of “automatically” by our representation, and we can apply our rule (8) immediately. The other nodes of the graph $(i_n)$ are eliminated since they are no longer needed. Optimization-specific Rules. In addition to the general rules, we also have a number of rewrite rules that are derived from the semantics of LLVM. For example, we have a family of laws for simplifying constant expressions, such as: \[ \begin{align*} \text{add } 3 & \downarrow 5 \\ \text{mul } 3 & \downarrow 6 \\ \text{sub } 3 & \downarrow 1 \end{align*} \] Currently we have rules for simplifying constant expressions over integers, but not floating point or vector types. There are also rules for rewriting instructions such as: \[ \begin{align*} \text{add } a & \downarrow \text{shl } a 1 \\ \text{mul } a & \downarrow \text{shl } a 2 \end{align*} \] These last two rules are included in our validator because we know the LLVM's optimizer prefers the shift left instruction. While preferring shift left may be obvious, there are some less obvious rules such as: \[ \begin{align*} \text{add } x (\neg k) & \downarrow \text{sub } x k \\ \text{gt } 10 & \downarrow \text{lt } a 10 \\ \text{lt } a b & \downarrow \text{le } a (\text{sub } b 1) \end{align*} \] While these transformations may not be optimizations, we believe LLVM makes them to give the instructions a more regular structure. Finally, we also have rules that make use of aliasing information to simplify memory accesses. For example, we have the following two rules for simplifying loads from memory: \[ \begin{align*} \text{load}(p, \text{store}(x, q, m)) & \downarrow \text{load}(p, m) \quad (10) \\ \text{load}(p, \text{store}(x, p, m)) & \downarrow x \quad (11) \end{align*} \] when \(p\) and \(q\) do not alias. Our validator can use the result of a may alias analysis. For now, we only use simple non-aliasing rules: two pointers that originate from two distinct stack allocations may not alias; two pointers forged using \text{getelementptr} with different parameters may not alias, etc. 4.1 Efficiency At this point is natural to wonder why we did not simply define a normal form for expressions and rewrite our graphs to this normal form. This is a good option, and we have experimented with this strategy using external SMT provers to find equivalences between expressions. However, one of our goals is to build a practical tool which optimizes the best case performance of the validator (we expect most optimizations to be correct). Using our strategy of performing rewrites motivated by the optimizer, we are often able to validate functions with tens of thousands of instructions (resulting in value graphs with hundreds of thousands of nodes) with only a few dozen rewritings. That is, we strive to make the amount of work done by the validator proportional to the number of transformations performed by the optimizer. To this end, the rewrite rules derived from LLVM semantics are designed to mirror the kinds of rewritings that are done by the LLVM optimization pipeline. In practice, it is much more efficient to transform the value graphs in the same way the optimizer transforms the assembly code: if we know that LLVM will prefer \text{ashl } a 1 to \(a + a\), then we will rewrite \(a + a\) but not the other way around. As another, more extreme, example, consider the following C code, and two possible optimizations: SCCP and GVN. \[ \begin{align*} a &= x < y; \\ b &= x < y; \\ \text{if } (a) \{ \\ \text{if } (a == b) \{ c = 1; \} \text{ else } \{ c = 2; \} \end{align*} \] If the optimization pipeline is setup to apply SCCP first, then \(a\) may be replaced by \text{true}. In this case, GVN can not recognize that \(a\) and \(b\) are equal, and the inner condition will not be simplified. However, if GVN is applied first, then the inner condition can be simplified, and SCCP will propagate the value of \(c\), leading to the program that simply returns 1. The problem of how to order optimizations is well-known, and an optimization pipeline may be reordered to achieve better results. If the optimization pipeline is configured to use GVN before SCCP, then, for efficiency, our simplification should be setup to simplify at join points before we substitute the value of \(a\). 4.2 Extended Example We now present an example where all these laws interplay to produce the normalized value-graph. Consider the C code below: ```c int f(int n, int m) { int * t = NULL; int * t1 = alloca(sizeof(int)); int * t2 = alloca(sizeof(int)); int x, y, z = 0; *t1 = 1; *t2 = m; t = t1; for (int i = 0; i < n; ++i) { if (i % 3) { x = 1; z = x << y; y = x; } else { x = 2; y = 2; } if (x == y) t = t1; else t = t2; } *t = 42; return *t2 + *t2; } ``` First, note that this function returns \(m + m\). Indeed, \(x\) is always equal to \(y\) after the execution of the first conditional statement in Figure 3: A shared value-graph the for loop. Therefore, the second conditional statement always executes the left branch and assigns \( t_1 \) to \( t \). This is actually a loop invariant, and, since \( t_1 \) is assigned to \( t \) before the loop, \( t_1 \) is always equal to \( t \). \( t_1 \) and \( t_2 \) are pointers to two distinct regions of memory and cannot alias. Writing through \( t_1 \) does not affect what is pointed to by \( t_2 \), namely \( m \). The function therefore returns \( m + m \). Since the loop terminates, an optimizer may replace the body of this function with \( m \ll 1 \), using a blend of global-value numbering with alias analysis, sparse-conditional constant propagation and loop deletion. Our value-graph construction and normalization produces the value-graph corresponding to \( m \ll 1 \) for this example. The initial value-graph is presented in figure 3. Some details of the graph have been elided for clarity. We represent \texttt{load}, \texttt{store}, and \texttt{alloca} nodes with 1d, \texttt{st}, and a1 respectively. To make the graph easier to read, we also used dashed lines for edges that go to pointer values. Below is a potential normalization scenario. - The arguments of the \( == \) node are shared; it is rewritten to true. - The gate of the \( \phi \) node is true; its predecessor, \( \mu \), is modified to point to the target of the true branch of the \( \phi \) node rather than to \( \phi \) itself. - The arguments of this \( \mu \) node are shared; its predecessor, \( \eta \), is modified to point to the target of \( \mu \) instead of \( \mu \) itself. - The condition of the \( \eta \) node is terminating, and its value is true; its predecessor, \( \pi \) or \( t \), is modified to point to the target of \( \eta \) instead of \( \eta \) itself. - It is now obvious that the load and its following store use distinct memory regions; the load can “jump over the store.” - The load and its new store use the same memory region; the load is therefore replaced by the stored value, \( m \). - The arguments of the \( + \) node are shared; The \( + \) node is rewritten into a left shift. 5. Experimental evaluation In our experimental evaluation, we aim to answer three different questions. 1. How effective is the tool for a decent pipeline of optimization? 2. How effective is the tool optimization-by-optimization? 3. What is the effect of normalization? Our measure of effectiveness is simple: the fewer false alarms our tool produces, the more optimized the code will be. Put another way, assuming the optimizer is always correct, what is the cost of validation? In our experiments, we consider any alarm to be a false alarm. 5.1 The big picture We have tested our prototype validator on the pure C programs of the SPECCPU 2006[5] benchmark (The xalancbmk benchmark is missing because the LLVM bitcode linker fails on this large program). In addition, we also tested our validator on the SQLite embedded database[2]. Each program was first compiled with clang version 2.8[1], and then processed with the mem2reg pass of the LLVM compiler to place \( \phi \)-nodes. These assembly files make up the unoptimized inputs to our validation tool. Each unoptimized input was optimized with LLVM, and the result compared to the unoptimized input by our validation tool. Test suite information. Table 1 lists the benchmark programs with the size of the LLVM-assembly code file, number of lines of assembly, and the number of functions in the program. Our research prototype does not analyze functions with irreducible control flow graphs. This restriction comes from the front-end’s computation of Gated SSA form. It is well known how to compute Gated SSA form for any control-flow graph[18]. However, we have not extended our front-end to handle irreducible control flow graphs. We do not believe the few irreducible functions in our benchmarks will pose any new problems, since neither the Gated SSA nor our graph representation would need to be modified. Pipeline information. For our experiment, we used a pipeline consisting of: - ADCE (advanced dead code elimination), followed by - GVN (global value numbering), - SCCP (sparse-condition constant propagation), - LICM (loop invariant code motion), - LD (loop deletion), - LU (loop unswitching), - DSE (dead store elimination). The optimizations chosen are meant to cover, as much as possible, the intra-procedural optimizations available in LLVM. We do not include constant propagation and constant folding because both of these are subsumed by sparse-conditional constant propagation (SCCP). Similarly, dead-code and dead-instruction elimination are subsumed by aggressive dead-code elimination (ADCE). We did not include reassociate and instcombine because we haven’t addressed those yet. One reason these haven’t been our priority is that they are conceptually simple to validate but require many rules. For each benchmark, we ran all of the optimizations, and then attempted to validate the final result. Since we used the SQLite benchmark to engineer our rules, it is not surprising that, overall, that benchmark is very close to 90%. The rules chosen by studying SQLite are also very effective across the other benchmarks. We do not do quite as well for the perlbench and gcc benchmarks. Currently, our tool uses the basic rewrite rules we have described here. Also we do not handle global constants or floating point expressions. Pipeline Results. Overall, with the small number of rules we have described in this paper, we can validate 80% of the per-function optimizations. The results per-benchmark are shown in figure 4. For our measurements, we counted the number of functions for which we could validate all of the optimizations performed on the function: even though we may validate many optimizations, if even one optimization fails to validate we count the entire function as failed. We found that this conservative approach, while rejecting more optimizations, leads to a simpler design for our validated optimizer which rejects or accepts whole functions at a time. The validation time for GCC is 19m19s, perl 2m56s, and SQLite 55s. 5.2 Testing Individual Optimizations The charts in Figure 5 summarize the results of validating functions for different, single optimizations. The height of each bar indicates the total number of functions transformed for a given benchmark and optimization. The bar is split showing the number of validated (below) and unvalidated (above) functions. The total number of functions is lower in these charts because we do not count functions that are not transformed by the optimization. It is clear from the charts that GVN with alias analysis is the most challenging optimization for our tool. It is also the most important as it performs many more transformations than the other optimizations. In the next section we will study the effectiveness of rewrite rules on our system. 5.3 Rewrite Rules Figure 6 shows the effect of different rewrite rules for the GVN optimization with our benchmarks. The total height of each bar shows the percentage of functions we validated for each benchmark after the GVN optimization. The bars are divided to show how the results improve as we add rewrite rules to the system. We start with no rewrite rules, then we add rules and measure the improvement. The bars correspond to adding rules as follows: 1. no rules 2. \( \phi \) simplification 3. constant folding 4. load/store simplification 5. \( \eta \) simplification 6. commuting rules We have already described the first five rules. The last set of rules tries to rearrange the graph nodes to enable the former rules. For example, we have a rule that tries to “push down” \( \eta \)-nodes to get them close to the matching \( \mu \)-nodes. We can see from this chart that different benchmarks are affected differently by the different rules. For example, SQLite is not improved by adding rules for constant folding or \( \phi \) simplification. However, load/store simplification has an effect. This is probably because SQLite has been carefully tuned by hand and does not have many opportunities for constant folding or branch elimination. The llvm benchmark, on the other hand, benefits quite a lot from \( \phi \) simplification. From the data we have, it seems that our technique is able to successfully validate approximately 50% of GVN optimizations with no rewrite rules at all. This makes intuitive sense because our symbolic evaluation hides many of the syntactic details of the programs, and the transformations performed by many optimizations are, in the end, minor syntactic changes. By adding rewrite rules we can dramatically improve our results. Up to this point, we have avoided adding “special purpose” rules. For instance, we could improve our results by adding rules that allow us to reason about specific C library functions. For example, the rule: \[ x = \text{atoi}(p); \quad y = \text{atoi}(q); \] \[ \Rightarrow \quad y = \text{atoi}(p); \] can be added because \( \text{atoi} \) does not modify memory. Another example is: \[ \begin{align*} \text{memset}(p, x, l_1); & \quad \Rightarrow \quad y = x \\ \text{load}(\text{getelem.ptr}(p, t_2)) & \quad \Rightarrow \quad y = x \end{align*} \] which enables more aggressive constant propagation. Both of these rules seem to be used by the LLVM optimizer, but we have not added them to our validator at this time. However, adding these sorts of rules is fairly easy, and in a realistic setting many such rules would likely be desired. Figure 7 shows similar results for loop-invariant code motion (LICM). The baseline LICM, with no rewrite rules, is approximately 75-80%. If we add in all of our rewrite rules, we only improve very slightly. In theory, we should be able to completely validate LICM with no rules. However, again, LLVM uses specific knowledge of certain C library functions. For example, in the following loop: \[ \text{for } (\text{int } i = 0; i < \text{strlen}(p); i++) f(p[i]); \] the call to strlen is known (by LLVM) to be constant. Therefore, LLVM will lift the call to strlen out of the loop: \[ \text{int tmp = strlen}(p); \] \[ \text{for } (\text{int } i = 0; i < \text{tmp}; i++) f(p[i]); \] Our tool does not have any rules for specific functions, and therefore we do not validate this transformation. The reason why we sometimes get a small improvement in LICM is because very occasionally a rewriting like the one above corresponds to one of our general rules. Finally, figure 8 shows the effect of rewrite rules on sparse-conditional constant propagation. For this optimization, we used four configurations: 1. no rules However, once we moved away from the structured-code restriction, code, and the (binary) \( \phi \)-nodes. In an earlier version of this work we focused on structured essentially all of the technical difficulties lie in the complex \( \phi \)-nodes. In order to achieve good results, it is important to find equivalent cycles in the graphs and merge them. Again, matching complex \( \phi \)-nodes seems to be the difficult part. To match cycles, we find pairs of \( \mu \)-nodes in the graph, and trace along their paths in parallel trying to build up a unifying substitution for the graph nodes involved. For \( \phi \)-nodes we sort the branches and conditions and perform a syntactic equality check. This technique is very simple, and we encountered more problems. First, although the algorithms are known, computing the gates for arbitrary control flow is a fairly involved task. Also, since the gates are dependent on the paths in the CFG, and general C code does not have a simple structured control flow, optimizations will often change the gating conditions even if the control flow is not changed. Another important aspect of the implementation is the technique for maximizing sharing within the graph. The rewrite rules do a good job of exposing equivalent leaf nodes in the graphs. However, in order to achieve good results, it is important to find equivalent cycles in the graphs and merge them. Again, matching complex \( \phi \)-nodes seems to be the difficult part. To match cycles, we find pairs of \( \mu \)-nodes in the graph, and trace along their paths in parallel trying to build up a unifying substitution for the graph nodes involved. For \( \phi \)-nodes we sort the branches and conditions and perform a syntactic equality check. This technique is very simple, and 2. constant folding 3. \( \phi \) simplification 4. all rules As expected, with no rules the results are very poor. However, if we add rules for constant folding, we see an immediate improvement, as expected. If we also add rules for reducing \( \phi \)-nodes, bzip2 immediately goes to 100\%, even though these rules have no effect on SQLite. However, additional rules do improve SQLite, but not the other benchmarks. 5.4 Discussion While implementing our prototype, we were surprised to find that essentially all of the technical difficulties lie in the complex \( \phi \)-nodes. In an earlier version of this work we focused on structured code, and the (binary) \( \phi \)-nodes did not present any real difficulties. However, once we moved away from the structured-code restriction efficient because it only needs to query and update a small portion of the graph. We also experimented with a Hopcroft partitioning algorithm [7]. Rather than a simple syntactic matching, our partitioning algorithm uses a prolog-style backtracking unification algorithm to find congruences between nodes. Surprisingly, the partitioning algorithm with backtracking does not perform better than the simple unification algorithm. Both algorithms give us roughly the same percentage of validation. Our implementation uses the simple algorithm by default, and when this fails it falls back to the slower, partitioning algorithm. Interestingly, this strategy performs slightly better than either technique alone, but not significantly better. Matching expressions with complex nodes seems well within the reach of any SMT prover. Our preliminary experiments with Z3 suggest that it can easily handle the sort of equivalences we need to show. However, this seems like a very heavy-weight tool. One question in our minds is whether or not there is an effective technique somewhere in the middle: more sophisticated than syntactic matching, but short of a full SMT prover. 6. Related work How do those results compare with the work of Necula and Tate et al.? The validator of Necula validates part of GCC 2.7 and the experiments show the results of compiling, and validating, GCC 2.91. It is important to note that the experiments were run on a Pentium Pro machine running at 400 MHz. Four optimizations were considered. Common-subexpression elimination, with a rate of false alarms of roughly 5% and roughly 7 minutes running time. Loop unrolling with a rate of false alarms of 6.3% and roughly 17 minutes running time. Register allocation with a rate of false alarms of 0.1% and around 10 minutes running time. Finally, instruction scheduling with a rate of false alarms of 0.01% and around 9 minutes running time. Unfortunately, the only optimization that we can compare to is CSE as we do not handle loop unrolling, and register allocation is part of the LLVM backend. In theory, we could handle scheduling (with as good results) but LLVM does not have this optimization. For CSE, our results are not as good as Necula’s. However, we are dealing with a more complex optimization: global value numbering with partial redundancy elimination and alias information, libc knowledge, and some constant folding. The running times are also similar, but on different hardware. It is therefore unclear whether our validator does better or worse. The validator of Tate et al. validates the Soot research compiler which compiles Java code to the JVM. On SpecJVM they report an impressive rate of alarms of only 2%. However, the version of the Soot optimizer they validate uses more basic optimizations than LLVM, and does not include, for instance, GVN. Given that our results are mostly directed by GVN with alias analysis, it makes comparisons difficult. Moreover, they do not explain whether the number they report takes into account all the functions or only the ones that were actually optimized. The validator of Kanade et al., even though heavily instrumented, is also interesting. They validate GCC 4.1.0 and report no false alarms for CSE, LICM, and copy propagation. To our knowledge, this experiment has the best results. However, it is unclear whether their approach can scale. The authors say that their approach is limited to functions with several hundred RTL instructions and a few hundred transformations. As explained in the introduction, functions with more than a thousand instructions are common in our setting. There is a wide array of choices for value-graph representations of programs. Weise et al. [19] have a nice summary of the various value-graphs. Ours is close to the representation that results from the hash-consed symbolic analysis of a gated SSA graph [6, 18]. 7. Conclusion In conclusion, we believe that normalizing value-graph translation validation of industrial-strength compilers without instrumentation is feasible. The design relies on well established algorithms and is simple enough to implement. We have been able, in roughly 3 man-months, to build a tool that can validate the optimizations of a decent LLVM pipeline on challenging benchmarks, with a reasonable rate of false alarms. Better yet, we know that many of the false alarms that we witness now require the addition of normalization rules but no significant changes in the design. For instance, insider knowledge of libc functions, floating-points constant folding and folding of global variables are sources of false alarms that can be dealt with by adding normalization rules. There is also room for improvement of the runtime performance of the tool. There are still a few difficult challenges ahead of us, the most important of which is inter-procedural optimizations. With LLVM, even -O1 makes use of such optimizations and, even though it is clear that simulation-based translation validation can handle inter-procedural optimizations [12], we do not yet know how to precisely generalize normalizing translation. We remark that, in the case of safety-critical code that respects standard code practices [3], as can be produced by tools like Simulink [15], the absence of recursive functions allows us to inline every function (which is reasonable with hash-consing). Preliminary experiments indicate that we are able to validate very effectively inter-procedural optimizations in such a restricted case. Advanced loop transformations are also important, and we believe that this problem may not be as hard as it may seem at first. Previous work [9, 17] has shown that it can be surprisingly easy to validate advanced loop optimizations such as software pipelining with modulo variable expansion if we reason at the value-graph level. Acknowledgments We would like to thank Vikram Adve for his early interest and enthusiasm, and Sorin Lerner for discussing this project and exchanging ideas. References
{"Source-Url": "https://dash.harvard.edu/bitstream/handle/1/4762396/pldi84-tristan.pdf", "len_cl100k_base": 12039, "olmocr-version": "0.1.53", "pdf-total-pages": 12, "total-fallback-pages": 0, "total-input-tokens": 44283, "total-output-tokens": 13964, "length": "2e13", "weborganizer": {"__label__adult": 0.0003619194030761719, "__label__art_design": 0.00026535987854003906, "__label__crime_law": 0.0003132820129394531, "__label__education_jobs": 0.0004069805145263672, "__label__entertainment": 5.614757537841797e-05, "__label__fashion_beauty": 0.0001518726348876953, "__label__finance_business": 0.00020182132720947263, "__label__food_dining": 0.0003616809844970703, "__label__games": 0.0005645751953125, "__label__hardware": 0.0011453628540039062, "__label__health": 0.0005092620849609375, "__label__history": 0.00021469593048095703, "__label__home_hobbies": 8.493661880493164e-05, "__label__industrial": 0.00041413307189941406, "__label__literature": 0.0002313852310180664, "__label__politics": 0.0002701282501220703, "__label__religion": 0.000507354736328125, "__label__science_tech": 0.0194091796875, "__label__social_life": 6.961822509765625e-05, "__label__software": 0.0042724609375, "__label__software_dev": 0.96875, "__label__sports_fitness": 0.00035119056701660156, "__label__transportation": 0.0006227493286132812, "__label__travel": 0.0002161264419555664}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 55882, 0.02224]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 55882, 0.45838]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 55882, 0.90136]], "google_gemma-3-12b-it_contains_pii": [[0, 778, false], [778, 6503, null], [6503, 13505, null], [13505, 17148, null], [17148, 24335, null], [24335, 28828, null], [28828, 33659, null], [33659, 39621, null], [39621, 44348, null], [44348, 46929, null], [46929, 54315, null], [54315, 55882, null]], "google_gemma-3-12b-it_is_public_document": [[0, 778, true], [778, 6503, null], [6503, 13505, null], [13505, 17148, null], [17148, 24335, null], [24335, 28828, null], [28828, 33659, null], [33659, 39621, null], [39621, 44348, null], [44348, 46929, null], [46929, 54315, null], [54315, 55882, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 55882, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 55882, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 55882, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 55882, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 55882, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 55882, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 55882, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 55882, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 55882, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 55882, null]], "pdf_page_numbers": [[0, 778, 1], [778, 6503, 2], [6503, 13505, 3], [13505, 17148, 4], [17148, 24335, 5], [24335, 28828, 6], [28828, 33659, 7], [33659, 39621, 8], [39621, 44348, 9], [44348, 46929, 10], [46929, 54315, 11], [54315, 55882, 12]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 55882, 0.0]]}
olmocr_science_pdfs
2024-12-11
2024-12-11
4a5838a6cb2edbc1862a627eabbff69181abfc39
IBM InfoSphere Streams for Scalable, Real-Time, Intelligent Transportation Services Alain Biem, Eric Bouillet, Hanhua Feng, Anand Ranganathan, Anton Riabov, Olivier Verscheure IBM TJ Watson Research Center, Hawthorne, NY 10532 {biem, ericbou, hanhfeng, arangana, riabov,ov1}@us.ibm.com Haris Koutsopoulos, Carlos Moran KTH Royal Institute of Technology, Stockholm {hnk, carlos}@infra.kth.se ABSTRACT With the widespread adoption of location tracking technologies like GPS, the domain of intelligent transportation services has seen growing interest in the last few years. Services in this domain make use of real-time location-based data from a variety of sources, combine this data with static location-based data such as maps and points of interest databases, and provide useful information to end-users. Some of the major challenges in this domain include i) scalability, in terms of processing large volumes of real-time and static data; ii) extensibility, in terms of being able to add new kinds of analyses on the data rapidly, and iii) user interaction, in terms of being able to support different kinds of one-time and continuous queries from the end-user. In this paper, we demonstrate the use of IBM InfoSphere Streams, a scalable stream processing platform, for tackling these challenges. We describe a prototype system that generates dynamic, multi-faceted views of transportation information for the city of Stockholm, using real vehicle GPS and road network data. The system also continuously derives current traffic statistics, and provides useful value-added information such as shortest-time routes from real-time observed and inferred traffic conditions. Our performance experiments illustrate the scalability of the system. For instance, our system can process over 120000 incoming GPS points per second, combine it with a map containing over 600,000 links, continuously generate different kinds of traffic statistics and answer user queries. Categories and Subject Descriptors H.3 [Information Storage and Retrieval]: Systems and Software; J.0 [Computer Applications]: General General Terms Performance, Design Keywords Stream Processing, Transportation, Geostreaming 1. INTRODUCTION The rapid growth of demand for transportation and high levels of car dependency caused by urban sprawl have caused great stresses to the transportation infrastructure in many areas. This has resulted in severe traffic congestion, and associated productivity loss, environmental degradation, and consumption of scarce resources. In urban areas, adding capacity through construction of new facilities is a very difficult endeavor due to lack of space and prohibitive costs. Intelligence Transportation Systems (ITS) is an umbrella term encompassing sensor, communications and computing technologies to manage existing infrastructure and transportation systems more efficiently, and hence contribute to the reduction of congestion. An important development within ITS is the emergence and installation of different kinds of sensor technologies for collecting data on the state of the transport system [1]. An important example is the use of GPS for traffic data collection. GPS data and other opportunistic sensors (e.g. smart phones) have great potential to provide the large amounts of data that is needed to support real time management of traffic systems. Intelligent Transportation Systems can make use of these data sources and data from other related sources (e.g. weather, video cameras, etc) to enable real time traffic monitoring and management with a broader scope and sustainability than usually achieved. There are, however, major challenges in building systems that are flexible and powerful enough to handle diverse demands from a large user base. The first challenge is one of scalability. As various kinds of sensor technologies become available and adopted, the data they produce must be fused and analyzed in real-time. The rate of processing such data in cities can easily exceed hundreds of thousands of points per second. In addition, the GPS data must be integrated in large maps (road networks) that can potentially contain hundreds of thousands of nodes and links. A second challenge is the development of the computing infrastructure required to support the needed functionality of ITS, especially given the large volumes and variety of data available and the diverse set of parties involved (such as government agencies, commercial enterprises and end-user commuters). Studies have shown that developing and in- integrating the various components of an ITS infrastructure constitute a significant portion of the capital cost and complexity of such systems [14]. These systems access different types of data sources, that produce different kinds of content with different levels of quality. They may use different kinds of software components to process the data. Also, the systems developed by the different parties are not necessarily developed for interoperability. These factors add to the complexity of the system. Furthermore, there are diverse needs of the traffic data, coming from different kinds of end-users. These end-users include commuters, highway patrols, public service vehicles like fire-engines and ambulances, departments of transportation, urban planners, commercial vehicle operators, etc. These users not only pose large numbers of simultaneous analysis requests, but also require analyses of significantly different natures. For example, dynamic traffic management as performed by the department of transportation requires real time processing of detailed traffic data across the urban area. However, the analysis performed by urban planners requires high level aggregation of the data and the updating of historical databases. This further increases the complexity of the system. In this paper, we demonstrate the use of IBM InfoSphere Streams 1, a scalable stream processing platform, for tackling these challenges. Stream processing applications in InfoSphere Streams take the form of graphs of modular, reusable software components (called operators) interconnected by data streams. Each operator takes data of certain content and format and perform various analysis. These applications can be deployed on a distributed runtime infrastructure to allow scalability via pipelining and parallelization. InfoSphere Streams provides various services to manage the infrastructure and the applications deployed on it so as to support high-throughput, low-latency stream processing. One of the key features of InfoSphere Streams is it’s component-based programming model. This allows composing and reconfiguring individual components to create different applications that answer different kinds of queries or perform different kinds of analysis. In addition, it enables the creation and deployment of new applications without disrupting existing ones. This facilitates the growth and incorporation of new technologies. Furthermore, InfoSphere Streams allows the new applications to reuse intermediate derived streams produced by existing applications in order to minimize duplicate or redundant processing of data. These different features help in tackling the challenges of dealing with diverse data sources and diverse end-user needs. We describe a case study demonstrating the use of InfoSphere Streams for Intelligent Transportation Systems. This case study consists of a set of stream processing applications that process real-time GPS data, generate different kinds of real-time traffic statistics, and perform customized analyses in response to user queries. Examples of customized analyses include continuously updated speed and traffic flow measurements for all the different streets in a city, traffic volume measurements by region, estimates of travel times between different points of the city, stochastic shortest-path routes based on current traffic conditions and real time prediction of travel times and traffic conditions (prediction horizons may vary from few minutes to an hour, depending on the application and the conditions), etc. Our performance experiments illustrate the scalability of the system. For instance, our system can process over 120000 incoming GPS points per second, combine it with a map containing over 600,000 links, continuously generate different kinds of traffic statistics and answer user queries. This system runs on a cluster of four x86 blade servers. In the rest of the paper, we describe the InfoSphere Streams platform and our case study in the Intelligent Transportation Systems space. Section 2 introduces InfoSphere Streams and its features. Section 3 describes the ITS case study and Section 4 goes into details of one of the critical components in our system; viz. the stream visualization framework. Section 5 provides some performance numbers for our system. We then describe related work in Section 7 and finally conclude. 2. INFOSPHERE STREAMS InfoSphere Streams [7] (or Streams) is a new IBM product that supports high performance stream processing. It has been used in a variety of sense-and-respond application domains, from environmental monitoring to algorithmic trading. It offers both language and runtime support for improving the performance of sense-and-respond applications in processing data from high rate streams. InfoSphere Streams (or just Streams) supports structured as well as unstructured data stream processing and can be scaled to a large number of compute nodes. The runtime can execute a large number of long-running jobs (queries) that take the form of data-flow graphs. A data-flow graph consists of a set of operators connected by streams, where each stream carries a series of Stream Data Objects (SDOs). Each operator implements data stream analytics and resides in execution containers called Processing Elements (PEs), which are distributed over the compute nodes. The compute nodes are organized as a shared-nothing cluster of workstations or as a large supercomputer (e.g., Blue Gene). The operators communicate with each other via their input and output ports, connected by streams. The operator ports as well as streams connecting them are typed. SPADE [5] (Stream Processing Application Declarative Engine) is the declarative stream processing engine of Streams. It is also the name of the declarative language used to program SPADE applications. SPADE provides a rapid application development (RAD) front-end for Streams. Concretely, SPADE offers: 1. An intermediate language for flexible composition of parallel and distributed data flow graphs. This language sits in-between higher level programming tools and languages such as the Streams IDE or Stream SQL and the lower level Streams programming APIs. 2. A toolkit of type-generic built-in stream processing operators. SPADE supports all basic stream-relational operators with rich windowing semantics. 3. The ability to extend the set of built-in operators with user-defined ones, programmable in either C++ or Java. 4. A broad range of stream adapters. These adapters are used to ingest data from outside sources and publish data to outside destinations, such as network sockets, In the stream-relational toolkit are: user defined operators. The operators currently supported refer to these operators as built-in operators (as opposed to boundaries, among other functionalities. We commonly re- workload partitioning capabilities and generation of window required by streaming applications. Additional convenience of operators. These operators can be used to implement any 2.1 Language Support via different kinds of scheduling decisions. Spade supports a modular, component-based programming model, which allows reuse, extensibility and rapid prototyping. Apart from the built-in operators and stream adapters that it provides, it also allows developers to create new operators in either C++ or Java. It also allows developing applications that offer high-availability through replicated processing and operator checkpointing. InfoSphere Streams includes a scheduler component that decides how best to partition a data-flow graph across a distributed set of physical nodes [15]. The scheduler uses the the computational profiles of the operators, the loads on the nodes and the priority of the application in making its scheduling decisions. 2.1 Language Support via different kinds of operators Spade was conceived around the idea of providing toolkits of operators. These operators can be used to implement any relational query as well as windowing extensions commonly required by streaming applications. Additional convenience stream manipulation operators are also included, providing workload partitioning capabilities and generation of window boundaries, among other functionalities. We commonly refer to these operators as built-in operators (as opposed to user defined operators). The operators currently supported in the stream-relational toolkit are: 1. **Source** A Source operator is used for creating a stream of data flowing from an external source. This operator is capable of performing parsing and tuple creation as well as interacting with external devices. 2. **Sink:** A Sink operator is used for converting a stream into a flow of tuples that can be used by components that are not part of System S. Its main task consists of converting tuples into objects accessible externally through the file system or network. 3. **Functo**r: A Functo operator is used for performing tuple-level manipulations such as filtering, projection, mapping, attribute creation and transformation. In these manipulations, the Functo operator can access tuples that have appeared earlier in the input stream. 4. **Aggregate:** An Aggregate operator is used for grouping and summarization of incoming tuples. This operator supports a large number of grouping mechanism and summarization functions. 5. **Join:** A Join operation is used for correlating two streams. System S can be paired up in several ways and the join predicate, i.e., the expression determining when tuples from the two streams are joined, can be arbitrarily complex. 6. **Sort:** A Sort operator is used for imposing an order on incoming tuples in a stream. The ordering algorithm can be tweaked in several ways. 7. **Bari**er: A Barrier operator is used as a synchronization point. It consumes tuples from multiple streams, outputting a tuple only when a tuple from each of the input streams has arrived. 8. **Punctor:** A Puncto operator is used for performing tuple-level manipulations, with the exception of filtering. Unlike a Functo, a Puncto can insert punctuations into the output stream based on a user supplied punctuation condition. 9. **Split:** A Split operator is used for splitting a stream into multiple output streams, based on a split condition that is used to determine which of the output streams a tuple is to be forwarded to. 10. **Delay:** A Delay operator is used for delaying a stream based on a specified amount of delay, allowing time-shifting of streams. In addition to the existing relational algebra toolkit, the language was designed to support extensions. Currently there are three ways of extending the language: 1. The developer can create User-Defined Operators (UDOPs), which are operators that can be used to wrap legacy libraries and provide customized processing. UDOPs are specialized for application-specific stream schemas. 2. The developer can create User Builtin Operators (UBOPs), which are fully templatized operators. UBOPs’ names and associated syntax are recognized by the Spade language parser. The templatization makes these operators usable in a type- and stream schema- generic fashion, similarly to regular built-in operators. The UBOP support is the fundamental aspect that allows the language to provide support for the creation of toolkits geared towards other application domains like, for example, signal processing, scientific computing, and stream data mining. 3. The developer also can create user-defined functions that can be used in expressions within operators anywhere in the program. For example, the functions can be used in the filtering predicates of a Functo, or they may be used for parsing or formatting in Source and Sink operators, etc. 2.2 Compiler and Runtime Support Given an application specification in SPADE’s intermediate language, the SPADE compiler generates optimized code that will run on InfoSphere Streams. SPADE’s effective code generation and optimization framework enables it to fully exploit the performance and scalability of InfoSphere Streams. The reliance on code generation provides the means for the creation of highly optimized platform- and application-specific code. In contrast to traditional database query compilers, the SPADE compiler outputs code that is tailored to the application at hand as well as system-specific aspects such as: the underlying network topology, the distributed processing topology for the application (i.e., where each piece will run), and the computational environment. In most cases, applications created with SPADE are long-running queries. Hence the long running times amortize the build costs. Nevertheless, the SPADE compiler has numerous features to support incremental builds, reducing the build costs as well. 3. THE INTELLIGENT TRANSPORTATION SYSTEMS PILOT In the last few years, there has been an explosion in the number and variety of data sources that are available for monitoring the transportation system. These include GPS devices on different kinds of vehicles, GPS-enabled cell-phones, video-cameras monitoring roads, loop-detectors, toll booths, congestion pricing portals, etc. As a result, transport agencies and organizations have moved from a state of no data, to a state of data overload, and are ill prepared to deal with the challenges of the new environment and take full advantage of the opportunities. The goal of the Intelligent Transportation Systems Pilot was to show city transport agencies the possibilities of processing the large amounts of streaming data in real time. In this pilot, we focused on the city of Stockholm. We obtained historical vehicle GPS data from Trafik Stockholm, as well as information on the road network. We identified a set of useful, real-time services for both individual drivers and for the transport agency, and developed stream processing applications on InfoSphere Streams to support these services. These services included monitoring the current traffic conditions in different parts of the city (on a link or over a region), comparing these conditions with historical statistics, estimating travel times between different points in the city, and computing stochastic shortest paths between different points in the city. For demonstration purposes, we replayed and processed the historical data. In the future, though, we will be able to directly access the real-time feeds from the data sources. 3.1 Input Data We obtained historical GPS data traces from Trafik Stockholm [13] for the year of 2008. This data included traces from about 1500 taxis and 400 trucks that plied the streets of Stockholm. In total, there was about 170 million GPS probe points for the whole year. Each taxi produces a GPS probe reading once every 60 seconds that includes taxi identification and location information. Also, for privacy reasons, taxis produce the readings only when they are not carrying any passengers. Trucks use more recent and more accurate GPS devices, that produce readings once every 30 seconds and include identification location, speed and heading information. The peak data rate for the whole city was over 1000 GPS readings per minute. In our pilot, though, we often replayed the data at several times the actual rate, just to demonstrate the scalability of the system. Another information we obtained was information about the city road network. The road network contained about 628,095 directed links spread over a 80km x 80km area around Stockholm. Each link represented a uni-directional road segment, hence two-ways roads are represented with two parallel links in opposite directions. 3.2 Overall Application Description Having large numbers of vehicles sending real-time GPS data for the city allows us to create a picture of the traffic condition in time and space [9]. We now describe the stream processing applications that allow us to come up with the traffic information, as well as provide various value-added services on top of the basic information. The application processes the data in three distinct phases. The first phase consists of real-time processing of the data. This includes obtaining, cleaning, de-noising, and matching the GPS data to the underlying road network or specified regions. In the second phase, the data is aggregated to produce traffic statistics per link and per time interval. The traffic statistics are in the form of medians and quartiles of vehicle speeds and vehicle counts on the link or region for the time interval. In the final phase, we make use of the statistics to compute different kinds of derived information such as the estimated travel times and shortest paths between different parts of the city. The final outputs can be sent to the user on different kinds of visualization platforms such as Google Earth, or may be stored in a database for additional offline analysis. A high level flow graph of the application is depicted in Figure 1. ![Figure 1: Application Flowgraph](image) 3.3 Real-time GPS data processing The GPS data is first received by the source operator and converted to tuples with time stamps, GPS device identification, latitude, longitude, heading (i.e. direction), and instantaneous speed attributes. The heading and speed at- tributes are null when not available. Following the source, we have a preprocessing operator that extracts the time of day and day of week, in tandem with an operator that filters entries whose time stamps, latitudes or longitudes are out of range. For the GPS data to be useful for measuring traffic conditions on roads, it must be matched with the underlying road network. An important issue with GPS data is its accuracy. There are two kinds of errors that we encounter with GPS data: measurement error caused by the limited GPS accuracy, and the sampling error caused by the sampling rate. The measurement error of GPS devices is typically in the order of a few meters. While this may seem small, this causes a problem when the GPS reading is located close to different links, such as at an intersection. The sampling error causes uncertainty in the vehicle’s movement. To illustrate the impact of the sampling rate on the imprecision of the interpolated trajectory data, consider sampling the position of a vehicle every 30 seconds, which is the typical sampling rate for the trucks in our data. At a speed of 100km/h, the traveled distance between position samples is over 833 meters. Since we do not know the positions in-between two consecutive position samples, the best we can do is to limit the possibilities of where the moving vehicle could have traveled. In order to correct the effect of both kinds of errors the application processes the GPS data in two steps, called geo-matching and geo-tracking. Geo-matching (also called Map-matching) consists of finding a set of links that are within a distance $d$ meters from the GPS probe. The parameter $d$ denotes the maximum expected measurement error, and is set to $d = 10$ meters. For the case where the GPS heading is available, the search is further restricted to links that are within 45 degrees of the heading. The algorithm uses the Harversine formula [12] to calculate geodetic distances in the WGS84 coordinate systems. Our implementation of this formula is accurate to within one meter, but is also computationally intensive and calculating the distance to all the links in order to determine the nearest one is not a tractable solution. Instead the algorithm employs a divide and conquer approach, illustrated in Figure 2, in which it divides the map into a grid of equal areas, and focuses its search to the nearest links within the area that contains the GPS coordinates. Included in the search are links that are up to a distance $d$ from the area’s perimeter to account for eventual errors in the GPS measurements. The grid is sized to cap the number of links per area, and the list of links contained in each area can be computed offline. As a result it takes a constant time complexity for the method to find the nearest links to a given location, independently of the size of the road network. For our particular purpose, a single geo-matching operator is sufficient to handle the Stockholm road network size. But if needed, the algorithm can easily be distributed into a hierarchy of operators, whereby the upstream operator distributes the GPS data by means of the grid-based method into downstream operators, each of which applies the geo-matching algorithm on a sub-region of the road-network. Since the operators can be deployed on separate machines, such decomposition makes it possible to handle arbitrarily large road networks, and take advantage of parallel processing to handle higher data rates. In other work [4], we describe how we can scale the geo-matching operation, so as to be able to match GPS data arriving at a rate of 1 million points per second onto a map with 1 billion links. After matching each GPS reading to the map, the next operation consists of estimating the trajectory of each vehicle, and removing the bad readings. This is achieved by means of a geo-tracking operator that looks for a sequence of GPS probes and compares all possible path combinations connecting the matching links. Our current implementation considers the last two GPS probe readings and finds the possible paths connecting them. In order to minimize sampling errors, the operator only considers probes that are less than 75 seconds apart, which corresponds to the maximum average sampling interval of the GPS devices plus a 25% margin to account for possible fluctuations in the transmission latency. Given the paths, the operator derives the average speed from the path lengths and time stamp information, and selects the path that results in the most realistic speed. The operation is illustrated in Figure 3. The SPADE code snippet below shows the implementation of this operation. It uses a User-Defined Built-in Operator (or UBOP) called GpsTrack, which takes as input a stream of map-matched GPS points, and generates the heading, estspeed and other attributes. The UBOP is parameterized by the maxinterval, the map information, etc. There is also a node annotation, which instructs the SPADE compiler to place the operator in the first node in a defined pool of nodes. ``` stream geoTrackStream(schemaFor(geoRichStream), avgheading : Long, estspeed : Float, confidence : Float) := GpsTrack(geoRichStream)[ maxinterval : 75; map : "/data/stockholm.lnk" ]{} -> node(mainpool,1) ``` Another use of the GPS data is to match it to regions instead of links. Such information can be used, for instance, to count the number of vehicles in a parking area or other enclosures that cannot be represented with line segments. The method is reminiscent of the geo-matching algorithm, with the exception that matching is done by detecting if a groups by estimated speed of the vehicle. The Aggregate operator each GPS point mapped to a link, and the instantaneous is a the schema as shown, containing 8 fields. The input stream dex in the previous tuple is greater than 0). The current sTimeIndex aggregation operator. The window slides whenever the period of time and reorders them within that time window is accessed in increasing order. This requirement is satisfied approach requires that the time-stamp attribute of the tuples interval since midnight. In order to work properly, this ap- link tumbling windows which are shifted (i.e., tumbled) each in InfoSphere Streams using built-in Aggregators with per- ing the time frame). This operation is easily implemented the number of vehicles (each vehicle being counted once dur- Figure 3: Illustration of the geo tracking process. The same vehicle appears at different points in time joined by the estimated trajectory. point is inside a polygon delineating the region instead of computing distances to the links. 3.4 Traffic Statistics Generation Once the GPS data is matched with a road network link, we want to use this information to generate statistics such as average vehicle speeds and unique vehicle counts per link at various times of the day. For this purpose, the application uses an Aggregator operator to slice the data every five minutes. In this time frame, this operator computes, for every link, the average estimated speeds of vehicles and also, the number of vehicles (each vehicle being counted once during the time frame). This operation is easily implemented in InfoSphere Streams using built-in Aggregators with per-link tumbling windows which are shifted (i.e., tumbled) each time the time stamp attribute enters a new five minute interval since midnight. In order to work properly, this approach requires that the time-stamp attribute of the tuples is accessed in increasing order. This requirement is satisfied with a Sort operator, which holds onto the tuples for a brief period of time and reorders them within that time window before sending them to the aggregator. The code snippet below shows an implementation of the aggregation operator. The window slides whenever the absTimeIndex field is incremented (i.e., when the difference of the current absTimeIndex value compared with the value in the previous tuple is greater than 0). The absTimeIndex is incremented by 1 every 5 minutes. The output of the operator is a stream called roadAttributeStream with the schema as shown, containing 8 fields. The input stream is a sortedGeoTrackStream that contains the mapping of each GPS point mapped to a link, and the instantaneous estimated speed of the vehicle. The Aggregate operator groups by timeIndex and shapeid (which is the link id). For each unique pair of timeIndex and shapeid, it generates the avgSpeed, minSpeed and maxSpeed over a 5 minute period. Finally, there is a partition annotation, which tells the SPADE compiler to fuse this operator with any other operator that has the same annotation value. ``` stream roadAttributeStream( timestamp : Long, shapeid : Long, timeIndex : Long, weekday : Integer, monthId : Integer, avgSpeed : Float, minSpeed : Float, maxSpeed : Float, ) := Aggregate(sortedGeoTrackStream <attrib(absTimeIndex, 01), perGroup>) [ timeIndex . shapeid ] { timestamp := Any(timestamp), shapeid := Any(shapeid), timeIndex := Any(timeIndex), weekday := Any(weekday), monthId := Any(monthId), avgSpeed := Avg(estSpeed), minSpeed := Min(estSpeed), maxSpeed := Max(estSpeed), estRoute := Any(estroute) } -> partition["GpsAggregation"] ``` The speed and the vehicle count estimates are then fed to another type of operator, called Inter-Quartiles Range or IQR operator. The role of this operator is to gather primary first-order statistics of the speeds and vehicle counts. Every five minutes during a day for every link, the IQR operator computes the speed and vehicle count summaries (smallest non-outlier, lower, median, upper quartiles and largest non-outlier) from historical observations collected over a several months period. Due to obvious differences in the traffic patterns between working days and non-working days we keep separate set of statistics for week days and week-ends. This is easily implemented in InfoSphere Streams with the help of a generic Split operator, which directs the data flow to one of several IQR operators depending on an expression of the day of week tuple attribute. If desired, this expression can be improved to include holidays or other scheduled events that are known to impact the traffic conditions. The IQR operator, in combination with the output of the per-link and time interval aggregation, allows us to generate views for each link in which we can compare the current road conditions on the link with statistical measurements collected over longer time period on the same link. This allows us to detect, for instance, whether the road conditions are normal for that time of the day or not. An example of such a view is illustrated in Figure 4. 3.5 Additional User-Specific Computations - Travel Times and Shortest Paths The traffic statistics generated are used to compute different kinds of derived information such as the estimated travel times and traffic-dependent shortest paths between different parts of the city. These computations are performed continuously for each individual end-user query that contains information on the source and destination points. In the next section, we describe how the queries are actually obtained from the end-user and used to direct these computations. In order to compute the travel times and the shortest paths, we first compute the stochastic travel times for each link. This involves computing a time-varying probability distribution of the time taken to traverse each link. This distribution information for each link can then be used to compute the distribution information for a whole path using a convolution operation. The stochastic travel times for each link are also used to calculate the shortest path (in terms of travel time) between any two points. This calculation uses the Dijkstra algorithm. Since the shortest path calculation is computationally expensive, we split the computation across different operators that can be placed on different hosts. SPADE offers declarative ways of doing the splitting that makes it easy for developers to parallelize various kinds of computations. For example, the code snippet below shows the use of for loops to first split the stream of shortest path requests by destID and then calculate shortest paths using sp_num different operators: ```java # Shortest path operators. Each operator gets a # part of gpsSPQueryStream for_begin @part 1 to sp_num stream shortestPathStream_P@part (gpsId : Long, fromArc : Long, toArc : Long, path : LongList, starttime : Long, endtime : Long, traveltime : Long ) := ShortestPath(gpsSPQueryStream_P@part; roadUpdateStream)[]{} for_end # Split for_begin @part 1 to sp_num stream gpsSPQueryStream_P@part (schemaFor(gpsJoinStream)) := Split(gpsSPQueryStream) [hashCode(mod(destId,sp_num1) )]{} for_end ``` 4. END-USER INTERACTIONS WITH STREAM PROCESSING APPLICATIONS End-users can interact with the ITS application in different ways. They can visualize traffic statistics for the whole city of Stockholm on Google Earth. They can also submit specific queries, such as to view the average speed on different links, the estimated travel time between two different points, and the shortest path between two different points that takes into account the current traffic conditions. In this pilot, we support a web-based visualization and interaction mechanism. For this, we make use of the web browser integrated within Google Earth. The overall interaction framework includes a Visualization Server, which is a standalone web-server using the Java Servlet framework, running outside of InfoSphere Streams. In addition to the HTTP port, this Visualization Server listens to a data port for incoming connections from various stream processing application. The Visualization Server maintains a buffer for each user-requested output of the application, e.g. the traffic statistics for a single link. Each buffer stores a time-series of some kind (e.g. average vehicle speeds on a link). Each buffer is also associated with a query ID. So, a browser can query the time series from any buffer, and it is possible to share the same server to show subsequences of one or more streams in one or more browsers. The visualization component comprises several types of visualizers, which can show data in different ways. All these visualizers are AJAX-based, using XMLHttpRequest to periodically get data from the same data servlet, which responds with the data from one of the buffers. Users have to specify the data identifier in URLs to select the buffer they want to see. In order to save bandwidth, we use CSV-formatted text for these XMLHttpRequest connections. On the browser side, this format can be handled by a very short piece of Javascript code. The CSV format consumes much less bandwidth than other formats such as JSON or XML. In visualizer URLs, users can specify the window size, the columns they want to see (so that other columns can be removed by the server to save bandwidth), and refresh rate of data (i.e., the frequency of XMLHttpRequest), among others. Almost all configurable parameters can be specified in a URL, as long as there are no security issues, and most of them have default values; the requirements for server-side customization are then minimized. Queries from the end-users are handled via a servlet in the visualization component that allows web clients to send a tuple to interact with InfoSphere Streams. The tuple is sent to a remote TCP or UDP port that the stream processing application listens to. This allows us to establish a feedback control mechanism that allows the web-client to specify the desired output to the application. This mechanism is illustrated in Figure 5 and works as follows: the client queries a time series from the visualization server. In the query the client describes the desired output in a form that the data streams processing application understands. This can be the unique numerical identifier of given road network link. The client also specifies the identifier of a circular buffer in which the results will be stored in the visualization server. This URL is decoded and both identifiers are included in a tuple that is sent to the data streams processing application. The application uses the description of the output to control the flow of data and ensure that at the sink operator connecting to the visualization component, only the output matching this description is sent. As shown in Figure 5, this can be done with the help of a Join operator that selects only tuples that match the output description (e.g., matching link identifiers). If historical data is required, such as time series since the start of the current day, the window Join operator can be used instead. The Join operator inserts the specified buffer identifier in the tuple, so that the visualization components stores the time series in the appropriate buffer, from where the client can later retrieve it. Figure 5: Architecture of visualization component. This query servlet can be either used through AJAX or with a page, or frame, or iframe URL. For the latter case, the query servlet automatically redirect the returned page to a visualization URL. After the results from InfoSphere Streams arrive, they are sent to the browser in the same page or frame for visualization. 5. PERFORMANCE EVALUATION For the performance measurements we deployed the ITS application on a cluster of 64bit Intel Xeon® quad-core machines running at 3Ghz with 16G bytes of memory each. The tested application consists of a total of 46 operators, 10 of which are UBOPs (user-defined built-in) operator, and others are built-in operators. Figure 6 shows a screenshot of the deployed application. In the figure, boxes represent operators, interconnections represent data streams, and the resulting topology represents the entire application flowgraph. It also shows how the operators are fused together to form a PE (Processing Element), represented as large dark background rectangles that contain one or more individual operators. Figure 7 shows how those PEs are distributed across various hosts (nodes). In this example, the distribution is based on instructions in the SPADE program assigning different operators to various nodes, but it can also be done automatically by the InfoSphere Streams scheduler. Finally, Figure 8 shows the performance of the ITS application with changing hardware infrastructure. The metric is the throughput, measured as the number of tuples per second processed by the source operators as we increase the total number of hosts used for the entire application. Here each tuple corresponds to one GPS point. As we increase the number of hosts, the InfoSphere Streams runtime can distribute the different operators across different hosts. For example, Figure 7 shows how the runtime distributes the operators in the ITS application on 4 different hosts. Figure 8 shows that the throughput scales well as we increase the number of nodes. The data-pipelining and parallelization features of InfoSphere Streams play a key role in achieving this scaling property. In this particular instantiation of the application, we used up to 4 different source operators to read the GPS data from files in parallel. When run on one single node, the system performance is the worst as all the software components share that single resource, even though that single resources is made of various cores. Increasing the number of nodes addresses the bottleneck due to resource limitation. Hence, we see a steady increase in performance as the number of nodes increases. The throughput achieved by our application is more than enough for our current needs. We are also confident that the throughput can be increased even more with additional tuning of the application, including tuning the placement of the different operators on the available nodes, tuning the structure of the application to take further advantage of the parallelism offered by the system, and tuning the operators themselves. Note that InfoSphere Streams can support a distributed cluster containing over a hundred nodes, which offers plenty of scope for improving the performance of the application. In other work [4], we describe a different example where we used up to 10 nodes to map-match GPS data and in that application, we were able to achieve a throughput of 1 million GPS points per second, mapped onto a road network containing 1 billion links. Figure 7: Application flow graph showing PE within hosts. Figure 8: Performance of the ITS Application with increasing number of nodes. The y-axis shows the throughput and the x-axis shows the total number of nodes used for the entire application. Average throughput (# GPS Points processed per second) 6. EXPERIENCES We have already seen how we can scale the ITS application using various InfoSphere Streams features, such as distributing the computation over different nodes and fusing operators into PEs to reduce communication cost. In this section, we describe some of our experiences in using the SPADE language and compiler in developing the application. We describe how various features of SPADE and InfoSphere Streams facilitate the development of stream processing applications. As an example, our team, consisting of 5 developers, was able to develop the ITS application within a month. These features are particularly important when we develop large ITS applications that tap onto diverse sources of data and meet diverse user needs. 6.1 Component-based model InfoSphere Streams allows applications to be developed as a graph of reusable components (or operators). This makes it easy to develop new applications by reusing existing components. It also encourages developers to develop their component in as general a manner as possible. InfoSphere Streams supports “User-defined Built-in Operators” (or UBOPs), which are operators that can operate on input data of different formats and be used in different contexts and implemented in either C++ or Java. In our prototype, for example, we were able to build a number of reusable map-matching operators that used different algorithms. We were easily able to plug these operators into the overall ITS application. More generally, we have a toolkit of various geo-spatial operators like map-matching, vehicle tracking, road traffic statistics generation, shortest-path route generation, stochastic travel time computation, etc. that we have been able to reuse in different applications. 6.2 Modular application development InfoSphere Streams supports two different models of stream interconnections between operators. The application data flow-graph in Spade can specify the interconnections explicitly, or it can use a publish-subscribe mechanism supported by Streams for the interconnections to be established. This publish-subscribe mechanism can be based on either names of streams or based on the properties of the streams. In addition, InfoSphere Streams allows separate applications to communicate with one another via streams. In this mechanism, one application can export streams, and another application can then import these streams, either explicitly by name, or implicitly by specifying properties of the desired input streams. These features of Streams are extremely useful in decomposing potentially large and complex applications into a number of smaller pieces that can communicate with one another. For example, we actually organized the ITS application as a set of multiple independent applications. One application does the basic GPS data processing, there are then one or more statistics computing applica- tions that take the processed GPS data streams as input. There are also many user-specific applications that take the streams of statistics as input and perform different computations, such as calculating the shortest route and travel time. These different applications can be composed together dynamically using exported and imported streams. The component-based model and modular application development features of InfoSphere Streams allows a large group of developers to collaborate in developing the applications. Once the types of the input/output streams of components and the imported and exported streams of applications are agreed upon, the developers can program independently and later integrate fairly easily. Also, stream processing by its very nature, limits interactions between components to the streams interconnecting them. This means that there is no need to maintain any global state, which often complicates software integration in many other kinds of systems. One outcome of these two features is that SPADE allows having developers of two different roles work together: operator developers and application developers. The operator developers write operators to perform a specific task in C++ or Java, and typically supply samples and test-cases showing how their operators can be invoked. The application developers compose these developers' operators along with SPADE built-in operators to come up with an application that meets some end-user's need. 6.3 Declarative Application Configuration The SPADE language includes constructs to specify how the application is to be deployed on the runtime. 1. SPADE allows specifying the degree of parallelization of an operation. This is achieved by a SPADE pre-processor which allows specifying for-loops in the SPADE program. The pre-processor unrolls the for-loop and allows creating an expanded SPADE graph that then gets compiled. Also, SPADE allows grouping streams into "bundles" so that they can all be referred as a single entity. This is useful, e.g., in specifying all the inputs to a barrier operator as a single bundle. 2. SPADE allows specifying operator fusion constraints. For example, it allows specifying that a certain set of operators must be fused into the same partition, or must be located in different partitions. Note that this is optional; the SPADE compiler can automatically compute the best operator fusion sets by using profiles of each operator's computational characteristics. 3. SPADE allows specifying the assignment of operators to physical nodes. Again this is optional; InfoSphere Streams includes a scheduler component that can make such placement decisions based on the load on each physical node. Thus, we can easily change the application deployment configuration by simply changing a few lines of the SPADE program, and then recompiling and redeploying it. This facilitates rapid prototyping, which is immensely useful in fine-tuning the application to meet various performance objectives. This proved particularly useful when we tuned our map-matching, source and aggregation components to improve their performance. 6.4 Rich set of built-in operators SPADE supports a very rich set of built-in operators, including different kinds of filters, joins, aggregations, etc. It also comes with a number of built-in operators for accessing external sources and sending data to external sinks. It also supports different ways of creating and updating windows that can be used in some of the built-in operators. The different variations include tumbling and sliding windows, count-based and time-based windows, windows based on differences in attribute values, punctuation based (where punctuations can be inserted by preceding operators), etc. In fact, most of the operators we use in the ITS application were built-in operators, which significantly saved development time. 7. RELATED WORK There has been plenty of work in the areas of acquiring GPS and other traffic data, mapping it to road-networks, using the data for traffic prediction, and determining shortest paths. Most works however tackle these problems independently, while we have developed an end-to-end application that takes raw GPS data to provide useful real-time services to end-users. Also, many of these works focus more on accuracy rather than throughput. For example, most publications in map matching focus on the accuracy of map-matching, rather than the on improving the throughput of map-matching as the size of the underlying map increases and as the rate of incoming GPS data increases. A number of approaches have been proposed in the area of matching GPS positions of a moving vehicle to a map. Brakatsoulas et al [2] proposed incremental and global algorithms that consider the trajectory of the moving vehicle and try to minimize the Frechet distance between the trajectory and the sequence of mapped links. Greenfeld [6] introduced a map-matching strategy based on distance and orientation that does not assert any further knowledge about the movement besides the position samples. Civilis et al. [3] in their work in location-based services introduce a map-matching algorithm that is based on edge distance and direction similar to [6]. Yin and Wolfson [16] propose an algorithm based on a weighted graph representation of the road network in which the weights of each edge represent the distance of the edge to the trajectory. Marchal et al [11] describe an approach that maintains a set of candidate paths as GPS data are fed in and to update, constantly, their matching scores. Lou et al [10] propose a global map-matching algorithm called ST-Matching for GPS trajectories with low sampling rate. Our approach is most similar to the incremental algorithm proposed by Brakatsoulas, where we use shortest-path trajectories between successive GPS points to estimate the path taken by the vehicle. Various approaches have also been proposed for calculating travel times and shortest paths. Our key contribution in this paper is not in the individual algorithms (like map matching or shortest paths), but in demonstrating how these different algorithms can be deployed on a distributed stream processing infrastructure for purposes of scalability. A number of map-matching and route planning systems have been deployed in the real world (for example, the systems behind services like Google Maps and Google Earth, various navigation guidance systems, etc.). However, we have not been able to get a hold of the descriptions of these systems. 8. CONCLUSION In this paper, we described the use of IBM InfoSphere Streams, a component-based distributed stream processing platform, for tackling the challenges of scalability, extensibility and user interaction in the domain of Intelligent Transportation Services. We described a prototype system that generates dynamic, multi-faceted views of transportation information for the city of Stockholm, using real vehicle GPS and road-network data. We also described some of our experiences in using InfoSphere Streams for this application. 9. ACKNOWLEDGMENTS We would like to thank IngaMaj Eriksson from the Swedish Road Administration and Tomas Julner from Trafik Stockholm for their support, feedback, and provision of the data for this study and Erling Weibust of IBM for facilitating the IBM/KTH collaboration. 10. REFERENCES
{"Source-Url": "http://imobilitylab.se/Publications_files/Biem%20et%20al.%20-%202010%20-%20IBM%20InfoSphere%20Streams%20for%20Scalable,%20Real-Time,%20Intelligent%20Transportation%20Services.pdf", "len_cl100k_base": 10148, "olmocr-version": "0.1.53", "pdf-total-pages": 11, "total-fallback-pages": 0, "total-input-tokens": 35229, "total-output-tokens": 11580, "length": "2e13", "weborganizer": {"__label__adult": 0.0021343231201171875, "__label__art_design": 0.000964641571044922, "__label__crime_law": 0.0015058517456054688, "__label__education_jobs": 0.0014438629150390625, "__label__entertainment": 0.0004506111145019531, "__label__fashion_beauty": 0.0006113052368164062, "__label__finance_business": 0.0007495880126953125, "__label__food_dining": 0.0013570785522460938, "__label__games": 0.004497528076171875, "__label__hardware": 0.01016998291015625, "__label__health": 0.0013294219970703125, "__label__history": 0.00212860107421875, "__label__home_hobbies": 0.00028324127197265625, "__label__industrial": 0.0031375885009765625, "__label__literature": 0.0009832382202148438, "__label__politics": 0.0014600753784179688, "__label__religion": 0.0017852783203125, "__label__science_tech": 0.16650390625, "__label__social_life": 0.0003402233123779297, "__label__software": 0.04010009765625, "__label__software_dev": 0.5439453125, "__label__sports_fitness": 0.0017709732055664062, "__label__transportation": 0.2105712890625, "__label__travel": 0.0018186569213867188}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 55444, 0.01431]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 55444, 0.66805]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 55444, 0.914]], "google_gemma-3-12b-it_contains_pii": [[0, 4550, false], [4550, 11202, null], [11202, 16322, null], [16322, 21832, null], [21832, 27479, null], [27479, 33195, null], [33195, 38240, null], [38240, 42711, null], [42711, 45603, null], [45603, 52143, null], [52143, 55444, null]], "google_gemma-3-12b-it_is_public_document": [[0, 4550, true], [4550, 11202, null], [11202, 16322, null], [16322, 21832, null], [21832, 27479, null], [27479, 33195, null], [33195, 38240, null], [38240, 42711, null], [42711, 45603, null], [45603, 52143, null], [52143, 55444, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 55444, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 55444, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 55444, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 55444, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 55444, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 55444, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 55444, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 55444, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 55444, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 55444, null]], "pdf_page_numbers": [[0, 4550, 1], [4550, 11202, 2], [11202, 16322, 3], [16322, 21832, 4], [21832, 27479, 5], [27479, 33195, 6], [33195, 38240, 7], [38240, 42711, 8], [42711, 45603, 9], [45603, 52143, 10], [52143, 55444, 11]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 55444, 0.0]]}
olmocr_science_pdfs
2024-12-07
2024-12-07
ea48a30c8af9853da925b4395fa4fc94e803146b
[REMOVED]
{"len_cl100k_base": 9330, "olmocr-version": "0.1.50", "pdf-total-pages": 15, "total-fallback-pages": 0, "total-input-tokens": 44897, "total-output-tokens": 11395, "length": "2e13", "weborganizer": {"__label__adult": 0.0003097057342529297, "__label__art_design": 0.000522613525390625, "__label__crime_law": 0.00034117698669433594, "__label__education_jobs": 0.0020465850830078125, "__label__entertainment": 0.00012695789337158203, "__label__fashion_beauty": 0.0001920461654663086, "__label__finance_business": 0.0005517005920410156, "__label__food_dining": 0.0003383159637451172, "__label__games": 0.0005846023559570312, "__label__hardware": 0.0019369125366210935, "__label__health": 0.0008120536804199219, "__label__history": 0.000438690185546875, "__label__home_hobbies": 0.00012254714965820312, "__label__industrial": 0.0005512237548828125, "__label__literature": 0.0004041194915771485, "__label__politics": 0.0003330707550048828, "__label__religion": 0.0004901885986328125, "__label__science_tech": 0.25634765625, "__label__social_life": 0.00011038780212402344, "__label__software": 0.0276031494140625, "__label__software_dev": 0.705078125, "__label__sports_fitness": 0.0002130270004272461, "__label__transportation": 0.0005707740783691406, "__label__travel": 0.0002543926239013672}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 46630, 0.03529]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 46630, 0.43152]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 46630, 0.91118]], "google_gemma-3-12b-it_contains_pii": [[0, 2687, false], [2687, 7201, null], [7201, 11743, null], [11743, 16357, null], [16357, 19290, null], [19290, 22621, null], [22621, 25838, null], [25838, 29760, null], [29760, 32491, null], [32491, 32568, null], [32568, 36767, null], [36767, 36844, null], [36844, 39648, null], [39648, 43428, null], [43428, 46630, null]], "google_gemma-3-12b-it_is_public_document": [[0, 2687, true], [2687, 7201, null], [7201, 11743, null], [11743, 16357, null], [16357, 19290, null], [19290, 22621, null], [22621, 25838, null], [25838, 29760, null], [29760, 32491, null], [32491, 32568, null], [32568, 36767, null], [36767, 36844, null], [36844, 39648, null], [39648, 43428, null], [43428, 46630, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 46630, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 46630, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 46630, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 46630, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 46630, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 46630, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 46630, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 46630, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 46630, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 46630, null]], "pdf_page_numbers": [[0, 2687, 1], [2687, 7201, 2], [7201, 11743, 3], [11743, 16357, 4], [16357, 19290, 5], [19290, 22621, 6], [22621, 25838, 7], [25838, 29760, 8], [29760, 32491, 9], [32491, 32568, 10], [32568, 36767, 11], [36767, 36844, 12], [36844, 39648, 13], [39648, 43428, 14], [43428, 46630, 15]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 46630, 0.04762]]}
olmocr_science_pdfs
2024-12-02
2024-12-02
20bcd3a35a1d54f9376ed1c6458bcda8f2a318e6
Augmenting Static Source Views in IDEs with Dynamic Metrics David Röthlisberger¹, Marcel Härry¹, Alex Villazón², Danilo Ansaloni², Walter Binder², Oscar Nierstrasz¹, Philippe Moret² ¹Software Composition Group, University of Bern, Switzerland ²University of Lugano, Switzerland Abstract Mainstream IDEs such as Eclipse support developers in managing software projects mainly by offering static views of the source code. Such a static perspective neglects any information about runtime behavior. However, object-oriented programs heavily rely on polymorphism and late-binding, which makes them difficult to understand just based on their static structure. Developers thus resort to debuggers or profilers to study the system’s dynamics. However, the information provided by these tools is volatile and hence cannot be exploited to ease the navigation of the source space. In this paper we present an approach to augment the static source perspective with dynamic metrics such as precise runtime type information, or memory and object allocation statistics. Dynamic metrics can leverage the understanding for the behavior and structure of a system. We rely on dynamic data gathering based on aspects to analyze running Java systems. By solving concrete use cases we illustrate how dynamic metrics directly available in the IDE are useful. We also comprehensively report on the efficiency of our approach to gather dynamic metrics. 1. Introduction Maintaining object-oriented systems is complicated by the fact that conceptually related code is often scattered over a large source space. The use of inheritance, interface types and polymorphism leads to hard to understand source code, as it is unclear which concrete methods are invoked at runtime at a polymorphic call site even in statically-typed languages. As IDEs typically focus on browsing static source code, they provide little help to reveal the execution paths a system actually takes at runtime. However, being able to, for instance, reconstruct the execution flow of a system while working in the IDE, can lead to a better understanding and a more focused navigation of the source space. In this paper we claim that developers can more efficiently maintain object-oriented code in the IDE if the static views of the IDE are augmented with dynamic information. The importance of execution path information becomes clear when inspecting Java applications employing abstract classes or interfaces. Source code of such applications usually refers to these abstract types, while at runtime concrete types are used. However, locating the concrete class whose methods are executed at runtime when the source code just refers to interface types, can be extremely cumbersome with static navigation, since there may be a large number of concrete implementations of a declared type. Similarly, when examining source code that invokes a particular method, a large list of candidate method implementations may be generated. Static analysis alone will not tell you how frequently, if at all, each of these candidates is actually invoked. However, such information is crucial to assess the performance impact of particular code statements. Developers usually resort to debuggers to determine the execution flow of an application. However, information extracted in a debugging session is volatile, that is, it disappears at the end of the session. Furthermore such information is bound to specific executions, so it cannot be used in general to tell which runtime types occur how often at a specific place in source code. To analyze and improve the performance of a system, developers typically use profilers, which suffer from the same drawbacks as debuggers: neither tool feeds aggregated information back to the IDE, thus developers use them only occasionally instead of benefiting from runtime information directly in the static IDE views. This paper presents an approach to dynamically analyze systems, and to augment the static perspectives of IDEs with various dynamic metrics. To prototype this approach we implemented Senseo, an Eclipse plugin that enables developers to dynamically analyze Java applications. Senseo enriches the source views of Eclipse with several dynamic metrics such as information about which concrete methods a particular method invokes how often at runtime, which methods invoke this particular method, or how many objects or how much memory is allocated in particular methods. These dynamic metrics are aggregated over several runs of the subject system; the developer decides which runs to take into account. The paper contributes the following: (i) a technique to efficiently analyze systems dynamically, (ii) useful dynamic metrics for software maintenance, (iii) means to integrate these metrics in IDEs, and (iv) an evaluation of the efficiency and usefulness of the entire approach. The paper is structured as follows: In Section 2 we present several concrete use cases highlighting the need for dynamic metrics available directly in the IDE. Section 3 illustrates our approach to integrate dynamic metrics in IDEs; we introduce Senseo, our prototype to augment Eclipse with dynamic metrics. In this section we also validate the practical usefulness by solving the use cases from Section 2 with Senseo. Section 4 explains our approach to gather dynamic metrics from running applications and validates this approach with efficiency benchmarks. Section 5 presents related work in the context of gathering dynamic data and its visualization. Finally, Section 6 concludes the paper. 2. Use Cases Senseo aims primarily at supporting two typical use cases that arise when maintaining object-oriented software systems. In the first use case developers attempt to gain an understanding of the execution paths and runtime types of an object-oriented system employing complex hierarchies including abstract classes and interfaces. In the second use case, developers must improve the overall speed of the system due to critical performance issues. We summarize the difficulties arising in each use case when the developer is limited to using the plain static views of a typical IDE. Understanding abstract class and interface hierarchies. As a case study we take the Eclipse JDT\(^1\), a set of plug-ins implementing the Eclipse Java IDE. JDT encompasses interfaces and classes modeling Java source code artifacts such as classes, methods, fields, or local variables. Figure 1 shows an extract of the JDT interfaces and classes representing static artifacts of a class. Clients of this representation usually refer to interface types such as IJavaElement or IJavaProject, as the following code snippet found in JavadocHover illustrates: \[ \begin{align*} \text{IJavaElement} \ element & = \ elements[0]; \\ \text{if} \ (\text{element}.\text{getElementType}() == \\ \text{IJavaElement}.\text{FIELD}) \{ \\ \text{IJavaProject} \ javaProject = \ element.\text{getJavaProject}(); \\ \} \text{ else if} \ (\text{element}.\text{getElementType}() == \\ \text{IJavaElement}.\text{LOCAL_VARIABLE}) \{ \\ \text{IJavaProject} \ javaProject = \ element.\text{getParent}().\text{getJavaProject}(); \\ \} \end{align*} \] There is a problem in this code: For some elements the resulting \text{javaProject} is wrong or undefined. The developer has the impression that the if conditions are not comprehensive or not correct at all. Another possibility is that the method \text{getJavaProject} is wrongly implemented for some element types. Thus the developer has several questions about this code: 1. Which \text{getJavaProject} methods are invoked? 2. Which types are stored in variable \text{element}; are all relevant cases covered with if statements? To answer these questions purely based on static information, we can use the references and declarations search tool of Eclipse. For the first question, we search for all declarations of method \text{getJavaProject}. However, the JDT declares more than 20 methods with this name, most of which are not related to the representation of source code elements. We have to skim through this list to find out which declarations are defined in subtypes of IJavaElement. After having found those declarations, we still cannot be sure which are actually invoked in this code. To address the second question, we first search for all classes implementing IJavaElement in the list of references to this interface. This yields a list with more than 2000 elements; all are false positives as IJavaElement is not supposed to be implemented by clients. We thus search for all sub-interfaces of IJavaElement to see whether those have implementing classes. After locating two direct sub-interfaces (IReference and ILocalVariable), each of which has more than 1000 references in JDT, we give up searching for references to indirect sub-interfaces such as IField or IType. It is not possible to statically find all concrete implementing classes of IJavaElement, in particular not those actually used in this code. Thus we resort to use the debugger. We find out that \text{element} is of type SourceField in one scenario. However, we know that debuggers focus on specific runs, thus we still cannot know all the different types \text{element} has in this code. To reveal all types of \text{element} and all \text{getJavaProject} methods invoked by this polymorphic message send, we would have to debug many more scenarios, which is very time-consuming as this code is executed many times for each system run. For all these reasons, it is much more convenient for a developer if the IDE itself could collect and show runtime information aggregated over several runs together with the static structure, that is, augmenting Eclipse’s source code viewer to show precisely which methods are invoked at runtime and how often, optionally even displaying runtime types for receiver, arguments, and return values. Assessing runtime complexity. Running this code shows that accessing the Java-project for some types of source elements is remarkably slow. Developers addressing the efficiency problem need to know for which types the implementation of \text{getJavaProject} is slow and why, that \(^1\)http://www.eclipse.org/jdt is, for instance, whether the inefficient implementations create many objects or repeatedly execute code. We tackle these questions by profiling this code example. The profiler indeed gives us answers about the code’s execution performance, but similarly to debuggers, profilers also focus on specific runs of a system and hence only show the efficiency of `getJavaProject` for the particular types used in a specific run. In the profiled run, all executed `getJavaProject` methods are reasonably efficient. However, it turns out that for very specific runs not reproducible while profiling, very slow implementations of `getJavaProject` are executed. The runtime performance of this method obviously depends heavily on the receiver of the message send. Thus, we need to have information about runtime complexity aggregated over multiple runs to pinpoint specific method executions being slow. We claim that it is best to have such aggregated information in the IDE, at a fine-grained method level to illustrate complexity, for instance, based on receivers of a message send, but also at a more coarse-grained level, for instance, entire packages or classes, to allow candidate locations in source code for performance issues to be quickly identified at a glance. The IDE itself should give general evidence about possible performance bottlenecks. 3. Integrating Dynamic Metrics in IDEs In this section we present an approach to augment IDEs with dynamic metrics, towards the goal of supporting the understanding of runtime behavior of applications. We prototyped this approach in Senseo, a plugin for the Eclipse Java IDE integrating dynamic metrics in familiar Eclipse tools such as package explorer, source editor, or ruler columns (the vertical bars next to the editor view). We first present the basic architecture of Senseo and second discuss dynamic metrics that can leverage runtime understanding directly in the IDE. Third, we illustrate several practical integrations and visualizations of these dynamic metrics brought to Eclipse by Senseo. Eventually, we solve the use cases of Section 2 to validate how useful our approach is. 3.1. Architecture Senseo uses MAJOR, an aspect weaving tool enabling comprehensive aspect weaving into every class loaded in a Java VM, including the standard Java class library, vendor specific classes, and dynamically generated classes. MAJOR is based on the standard AspectJ [9] compiler and weaver and uses advanced bytecode instrumentation techniques to ensure portability [3]. MAJOR provides aspects to gather runtime information of the application under instrumentation. The collected data is used to build calling context profiles containing different dynamic metrics such as number of created objects. The application to be analyzed is executed in a separate application VM where MAJOR weaves the data gathering aspect into every loaded class, while the Eclipse IDE runs in a standard VM to avoid perturbations. While the subject system is still running, we periodically transfer the gathered dynamic data from the application VM to Eclipse using a socket. We do not have to halt the application to obtain its dynamic data. Senseo receives the transferred data, processes it and stores the aggregated information in its own storage system which is optimized for fast access from the IDE. Figure 2 gives an overview of the setup of our approach. To analyze the application dynamically within the IDE, developers have to execute it with Senseo. Before starting the application, developers can define which dynamic met- metrics should be gathered at runtime. By default, all packages and classes of the application are dynamically analyzed. However, developers can restrict the analysis to specific classes or even methods to reduce the analysis overhead if only specific areas need to be observed. As soon as Eclipse receives the raw dynamic data over the socket from MAJOR, Senseo aggregates the received data (for instance, counting how often a method was invoked) and then directly displays the dynamic information. Section 3.2 proposes useful dynamic metrics to gather and Section 3.3 illustrates means to integrate these metrics in Eclipse. Usually Senseo aggregates dynamic data over all application runs executed with it, but developers can empty the storage and start afresh. 3.2. Dynamic Metrics To support the use cases of Section 2, we integrate the following dynamic metrics into the IDE. Message sending. In object-oriented programs, understanding how objects send messages to each other at runtime is crucial. We therefore extract the following information about message sends: Invoked Methods. Often invoked methods are not implemented in the statically defined type (i.e., class), but in its super- or subtypes, when inheritance, respectively dynamic binding, are used. Having information in the IDE about the methods invoked is intended to help developers better understand collaborations between objects and ease navigation of the runtime execution flow. Optionally, developers can ask to gather more information about message sends when starting the application with Senseo. Such additional information includes: • Receiver types. Often sub-types of the type implementing the method receive the message send at runtime. Knowing receiver types and their frequency thus further increases program understanding. • Argument types. Information about actual argument types and their frequency increases the understanding for a method, i.e., how it is used at runtime. • Return types. As return values pass results from one method to another, knowing their types and their frequency helps developers to better understand communication between different methods, for instance, whether a null return value is to be expected. Number of invocations. This dynamic metric helps the developer quickly identify hot spots in code, that is, very frequently invoked methods or classes containing such methods. Furthermore, methods never invoked at runtime become visible, which is useful when removing dead code or extending the test coverage of the application’s test suite. Related to this metric is the number of invocations of other methods triggered from a particular method. Number of created objects. By reading static source code, a developer usually cannot tell how many objects are created at runtime in a class, in a method or in a line of source code. It is unclear whether a source artifact creates one or one thousand objects — or none at all. This dynamic metric, however, is useful to assess the costs imposed by the execution of a source artifact, to locate inefficient code, or to discover potential problems, for instance inefficient algorithms creating enormous numbers of objects. Allocated memory. Different objects vary in memory size. Having many but very tiny objects might not be an issue, whereas creating a few but very huge objects could be a sign of an efficiency problem. Hence, we also provide a dynamic metric recording memory usage of various source artifacts such as classes or methods. This metric can be combined with the number of created objects metric to reveal which types of objects consume most memory and thus are candidates for optimization. 3.3. Enhancements to the IDE All these dynamic metrics are seamlessly integrated with the static perspective provided by the Eclipse IDE. This ensures that the dynamic metrics augment the static view of a system. In the following we describe how the available dynamic metrics augment the IDE. Source code enhancements. As a technique to complement source code without impeding its readability we opted to use hovers, small windows that pop up when the mouse hovers over a source element (a method name, a variable, etc.). Hovers are interactive, which means the developer can for instance open the class of a receiver type by clicking on it. We now describe the integration of dynamic metrics with Senseo: Method header. The hover that appears on mouse over the method name in a method header shows (i) all senders invoking that particular method, (ii) all callees, that is, all methods invoked by this method, and optionally (iii) all argument and return value types. For each piece of information we also show how often a particular invocation occurred. For instance for a sender, we display the qualified name of the method containing the send (that is, the calling method) and the number of invocations from this sender. Optionally, we also display the type of object to which the message triggering the invocation of the current method was sent, if this is a sub-type of the class implementing the current method. For a callee we provide similar information: The class implementing the invoked method, the name of the message, and how often a particular method was invoked. Additionally, we can show concrete receiver types of the message send, if they are not the same as the class implementing the called method. Figure 3 shows a concrete method name hover for method `readFileEntriesWithException`. In a method header, we can optionally show information about argument and return types, if developers have chosen to gather such data. Hovers presenting this information appear when the mouse is over the declared arguments of a method or the defined return type. These hovers also include numbers about how often specific argument and return value types occurred at runtime. **Method body.** We also augment source elements in the method body with hovers. For each message send defined in the method, we provide the dynamic callee information similarly as for the method name, namely concretely invoked methods, optionally along with argument or return types that occurred in this method for that particular message send at runtime, as shown in Figure 4. Of course all these types listed are always accompanied with the number of occurrences and the relative frequency of the specific types at runtime. **Ruler columns.** There are two kind of rulers next to the source editor: (i) the standard ruler on the left showing local information and (ii) the overview ruler on the right giving an overview over the entire file opened in the editor. In the traditional Eclipse IDE these rulers denote annotations for errors or warnings in the source file. Ruler (i) only shows the annotations for the currently visible part of the file, while the overview ruler (ii) displays all available annotations for the entire file. Clicking on such an annotation in (ii) brings the developer to the annotated line in the source file, for instance to a line containing an error. We extended these two rulers to also display dynamic metrics. For every executed method in a Java source file the overview ruler presents, for instance, how often it has been executed in average per system run using three different icons colored in a hot/cold scheme: blue means only a few, yellow several, and red many invocations [19]. Clicking on such an annotation icon causes a jump to the declaration of the method in the file. The ruler on the left side provides more detailed information: It shows on a scale from 1 to 6 the frequency of invocation of a particular method compared to all other invoked methods, see Figure 5. A completely filled bar for a method denotes methods that have been invoked the most in this application. The dynamic metrics in these two rulers allow developers to quickly identify hot spots in their code, that is, methods being invoked frequently. The applied heat metaphor allows different methods to be compared in terms of number of invocations. To associate the continuous distribution of metric values to a discrete scale with for instance three representations (e.g., red, yellow, and blue), we use the k-means clustering algorithm [12]. To see fine-grained values for the dynamic metrics, the annotations in the two columns are also enriched with hovers. Developers hovering over a heat bar in the left column or over the annotation icon in the right bar get a hover displaying precise metric values, for instance exact total numbers of invocations or even number of invocations from specific methods or receiver types. Furthermore, developers can choose between different dynamic metrics to be visualized in the rulers. Besides number of invocations of methods, we also provide metrics such as the number of objects a method creates, the number of bytecodes it executes, and the amount of memory it allocates, either on average or in total over all executions. Such metrics allow developers to quickly assess the runtime complexity of specific methods and thus to locate candidate methods for optimization. Changing the dynamic metrics to be displayed is done in the Eclipse preferences; the chosen metric is immediately displayed in the rulers. **Package Explorer.** The package explorer is the primary tool in Eclipse to locate packages and classes of an application. Senseo augments the package explorer with dynamic information to guide the developer at a high level to the source artifacts of interest, for instance to classes creating many objects. For that purpose, we annotate packages and classes in the explorer tree with icons denoting the degree with which they contribute to the selected dynamic metric such as amount of allocated memory. A class for instance aggregates the metric value of all its methods, a package the value of all its classes. Similar to the overview ruler the metric values are mapped to three different package explorer icons: blue, yellow, and red, representing a heat coloring scheme [19]. ### 3.4. Evaluation In Section 2 we raised two questions about a typical code example from the Eclipse JDT. We show that with Senseo developers can answer such questions directly in the source perspective of Eclipse. First, to determine the `getJavaProject` methods invoked in the given code example, developers hold the mouse over the call site written in source code to get a hover mentioning all distinct methods that have been invoked at runtime at this call site, along with the number of invocations. This hover saves us from browsing the statically generated list of more than 20 declarations of this method by showing us precisely the actually invoked methods. Second, to find out which types of objects have been stored in `element`, we can look at the method call to `getElementType`, whose statically defined receiver is the variable `element`. The hover can also show the runtime receiver types of a message send, which are all types stored in `element` in this case. It turns out that the types of `element` are `SourceField`, `LocalVariable`, but also `SourceMethod`, thus the `if` statements in this code have to be extended to also cover `SourceMethod` elements. We were unable to statically elicit this information. To assess the efficiency of the various invoked `getJavaProject` methods, we navigate to the declaration of each such method. The dynamic metrics in the ruler columns reveal how complex an invocation of this method is, that is for instance how many objects an invocation creates in average, even depending on the receiver type. Thanks to these metrics we find out that if the receiver of `getJavaProject` is of type `LocalVariable`, the code searches iteratively in the chain of parents of this local variable for a defined Java-project. We can optimize this by searching directly in the enclosing type of the local variable. ### 4. Dynamic Metrics Collection In this section we first explain our approach to dynamic metrics collection and afterwards investigate its overhead. #### 4.1. Aspect-based Calling Context Tree Construction Senseo requires support for flexibly aggregating dynamic metrics in various ways. For instance, runtime type information is needed separately for each pair of caller and callee methods, while memory allocation metrics need to be aggregated for the whole execution of a method (including the execution of its direct and indirect callees). In order to support different ways of aggregating metrics, we resort to a generic datastructure that is able to hold different metrics for each executed calling context. The Calling Context Tree (CCT) [1] perfectly fits this requirement. Figure 6 illustrates a code snippet together with the corresponding CCT (showing only method invocation counts as metric). Each CCT node stores dynamic metrics and refers to an identifier of the target method for which the metrics have been collected. It also has links to the parent and child nodes for navigation in the CCT. Our CCT representation is designed for extensibility so that additional metrics can be easily integrated. CCT construction and collection of dynamic metrics can be implemented either with a modified Java Virtual Machine (JVM), or through a profiling agent implemented in native code using the standard JVM Tool Interface (JVMTI), or with the aid of program transformation respectively bytecode instrumentation techniques. For portability and compatibility reasons, we chose the latter approach. However, instead of using a low-level bytecode engineering library for implementing the instrumentation, we rely on high-level aspect-oriented programming (AOP) [10] techniques in order to specify CCT construction and metrics collection as an aspect. This approach not only results in a compact implementation, but it ensures ease of maintenance and extension. Our implementation leverages MAJOR [21, 22], an aspect weaver based on AspectJ [9] offering two distinguishing features. First, MAJOR allows for complete method coverage. That is, all methods executing in the JVM (after it has completed bootstrapping) can be woven, including methods in the standard Java class library. Consequently, the CCT generated with an aspect that is woven by MAJOR faithfully represents the complete program execution. Method invocations through reflection and callbacks from native code into bytecode are correctly handled. Second, MAJOR provides efficient access to complete calling context information through customizable, thread-local shadow stacks. Using the new pseudo-variables $thisStack$ and $thisSP$, the aspect gets access to the array holding the current thread’s shadow stack, respectively to the array index (shadow stack pointer) corresponding to the currently executing method. Figure 7 illustrates three advices\(^2\) of our aspect for CCT construction and dynamic metrics collection. In the CCTAspect, each thread generates a separate, thread-local CCT. The shadow stack is an array of CCTNode instances, representing nodes in the thread-local CCT. A special root node is stored at position zero. Periodically, after a configurable number of profiled method calls, each thread integrates its thread-local CCT into a shared CCT in a synchronized manner. This approach reduces contention on the shared CCT, yielding significant overhead reduction in comparison with an alternative solution where all threads directly update a shared CCT upon each method invocation. Because of space limitations, the details of periodic CCT integration are not shown in Figure 7. The first advice in Figure 7 intercepts method entries and pushes the CCTNode representing the invoked method onto the shadow stack. To this end, it gets the caller’s CCTNode instance from the shadow stack \(^2\text{Aspects specify pointcuts to intercept certain points in the execution of programs (so-called join points), such as method calls, fields access, etc. Before, after, or around the intercepted join points specified advices are executed. Advices are methods that have access to some contextual information of the join points.}\) ### Code Sample ```java void f() { for(int i=1; i<=10; ++i) { h(); g(i); } } void g(int i) { for(int j=1; j<=i; ++j) { h(); } } void h() { return; } ``` ### Figure 6. Sample code and its corresponding CCT ![Call graph](image) ### Figure 7. Simplified excerpt of the CCTAspect (i.e., at position $sp-1$) and invokes the `profileCall` method, which takes as argument an identifier of the callee method. We use static join points, accessed through AspectJ’s `thisJoinPointStaticPart` pseudo-variable, to uniquely identify method entries; they provide information about the method signature, modifiers, etc. The `profileCall` method returns the callee’s CCTNode instance and increments its invocation counter; if the same callee has not been invoked in the same calling context before, a new CCTNode instance is created as child of the caller’s node. The second advice in Figure 7 deals with normal method completion, popping the method’s entry from the shadow stack. For simplicity, here we do not show cleanup of the shadow stack in the case of abnormal method completion throwing an exception [22]. The third advice in Figure 7 intercepts object instantiations to keep track of the number of created objects and of allocated memory for each calling context. The method `storeObjAlloc(Object)` uses the object size estimation functionality provided by the `java.lang.instrumentation` API (which is exposed to the aspect) to update the memory allocation statistics in the corresponding `CCTNode` instance. In addition to the number of method invocations and to the object allocation metrics, the CCTAspect collects the runtime types of receiver, arguments, and result. For receiver and arguments, this functionality is implemented in method `storeRcvArgRuntimeTypes` used upon method entry. It takes a dynamic join point instance, which is accessed through AspectJ’s thisJoinPoint pseudo-variable in the advice. The dynamic join point instance provides references to the receiver and to the method arguments. Upon method completion, the storeRetRuntimeType method stores the runtime type of the result. The result object is passed as context information (returning(Object o)) to the advice. During the execution, the aspect also takes care of periodically sending the collected metrics to the Senseo plugin in the IDE. Upon metrics transmission, thread-local CCTs of terminated threads are first integrated into the shared CCT. Afterwards, the shared CCT is traversed to aggregate the metrics as required by Senseo. Finally, the aggregated metrics are sent to the plugin through a socket. Metrics aggregation and serialization may proceed in parallel with the program threads, since they operate on thread-local CCTs most of the time. 4.2. Performance We evaluate our approach in two different settings. We use MAJOR\(^2\) version 0.5 with AspectJ\(^4\) version 1.6.2 and the SunJDK 1.6.0_13 Hotspot Server Virtual Machine. In the first setting, we assess the overhead caused by the collection of dynamic metrics using the standard DaCapo benchmark suite\(^5\); we also explore the different sources of overhead and their contributions to the overall overhead. We focus only on the performance of MAJOR and exclude the overhead of communication with the Senseo plugin. MAJOR is configured to ensure complete method coverage, profiling also execution within the Java class library. In the first setting, our measurement environment is a 16-core machine running RedHat Enterprise Linux 5.2 (Intel Xeon, 2.4GHz, 16GB RAM). We chose a high-end machine in order to speed up the benchmarking process, and each measurement represents the median of the overhead factor of 15 runs within the same JVM process. In the second setting, we measure end-to-end performance of our system (i.e., including MAJOR and Senseo), as experienced by the user. In this setting, we use a typical developer machine (Intel Core 2 Duo, 2.16GHz, 2GB RAM). **Setting 1.** Figure 8 illustrates the overhead due to the CCTAspect. We explore and segregate the overhead contributions of shadow stack maintenance, of CCT construction, and of collecting memory allocation metrics. The geometric mean of the overhead for all the benchmarks is factor 3.98, while the maximum overhead is factor 8.75 for “xalan”. The biggest part of this overhead stems from CCT creation, which is particularly expensive in the presence of recursions. The collection of memory allocation metrics causes relatively little overhead, because object allocation is far less frequent than method invocation and the corresponding advice can directly access the CCTNode that has to be updated on the top of the shadow stack. **Setting 2.** In order to assess end-to-end performance of our system, we measure the overhead of running an application with Senseo. As a case study, we ran Eclipse itself as target application and analyzed the usage of the JDT core. Without Senseo, starting and terminating Eclipse takes 53 seconds; executing the same scenario with Senseo takes 188 seconds, i.e., the overhead is 255%. This overhead includes the collection of all dynamic metrics discussed in this paper within all JDT core classes, metrics aggregation, data transmission through a socket, and visualization of the data in the developer’s Eclipse environment. Eclipse is conveniently usable while being analyzed. Considering that the JDT is a large application consisting of more than 1000 classes and approximately 16000 methods, our measurements confirm that our approach is practical also for large workloads. 5. Related Work 5.1. Metrics Collection JFluid exploits dynamic bytecode instrumentation and code hotswapping to collect dynamic metrics \([4]\). JFluid uses a hard-coded, low-level instrumentation to collect gross time for a single code region and to build a Calling Context Tree (CCT) augmented with accumulated execution time for individual methods. In contrast, we use a flexible, high-level, aspect-based approach to specify CCT construction, and aggregation and serialization may proceed in parallel with the program threads, since they operate on thread-local CCTs most of the time. \(^2\)http://www.inf.unisi.ch/projects/ferrari \(^4\)http://www.eclipse.org/aspectj \(^5\)http://dacapobench.org/ construction and dynamic metrics collection, which eases customization and extension. In addition, JFluid relies on a customized JVM, whereas our tools are fully portable and compatible with standard JVMs. Similar to Senseo, JFluid runs the application under instrumentation in a separate JVM, which communicates with the visualization part through a socket and also through shared memory. JFluid is a pure profiling tool, whereas Senseo was designed to support program understanding and maintenance. The JFluid technology is integrated into the NetBeans Profiler [14]. Dufour et al. [5] present a variety of dynamic metrics for Java programs. They introduce a tool called *J [6] for metrics measurement. In contrast to our fully portable approach, *J relies on the Java Virtual Machine Profiler Interface (JVMPI), which is known to cause high performance overhead and requires profiler agents to be written in native code. PROSE [16] provides aspect support within the JVM, which may ease the collection of certain dynamic metrics with aspects, thanks to the direct access to JVM internals. PROSE combines bytecode instrumentation and aspect support at the just-in-time compiler level. It does not support aspect weaving in the standard Java class library, a distinguishing feature of MAJOR. Sampling-based profiling techniques, which are often used for feedback-directed optimizations in dynamic compilers [2], help significantly reduce the overhead of metrics collection. However, sampling produces incomplete and possibly inaccurate information, whereas Senseo requires complete and exact metrics for all executed methods. Hence, we rely on MAJOR to comprehensively weave our aspect into all methods in the system. Dynamic analyses based on tracing mechanisms traditionally focus on capturing a call tree of message sends, but existing approaches do not bridge the gap between dynamic behavior and the static structure of a program [7, 23]. Our work aims at incorporating the information obtained through dynamic analyses into the IDE and thus connecting the static structure with the dynamic behavior of the system. Dynamic analyses only focus on capturing a call tree of message sends, but existing approaches do not bridge the gap between dynamic behavior and the static structure of a program [7, 23]. Our work aims at incorporating the information obtained through dynamic analyses into the IDE and thus connecting the static structure with the dynamic behavior of the system. With static analysis, especially with static type inference [15], it is possible to gain insights into the types that variables assume at runtime. However, static type inference is a computationally expensive task and cannot always provide precise results in the context of object-oriented languages [17]. Furthermore, static analysis does not cover dynamically generated code, although dynamic bytecode generation is a common technique, for instance used in the “jython” benchmark of the DaCapo suite. 5.2. Augmenting IDEs Reiss [18] visualizes the dynamics of Java programs in real time, e.g., the number of message sends received by a class. Löwe et al. [13] follows a similar approach by merging information from static analysis with information from dynamic analysis to generate visualizations. The visualizations of these two approaches are not tightly integrated in an IDE though, but are provided by a separated tool. Thus, it is not directly possible to use these analyses while working with source code. We consider it as crucial to incorporate knowledge about the dynamics of programs into the IDE to ease navigating within the source space. Other approaches ease and support the navigation of large software systems by different means than program analysis. For instance, NavTracks [20] keeps track of the navigation history of software developers. Using this history, NavTracks forms associations between related source files (e.g., class files) and can hence present a recommendation list of entities related to the current selected source file, that is, source files developers browsed in the past along with the currently selected file. Mylar [8] computes a degree-of-interest value for each source artifact based on historical navigation. The relative degree-of-interest of artifacts is highlighted using colors — interesting entities are assigned a “hot” color. We also use heat colors to denote the degree of dynamic metrics such as number of invocations, but base our model on dynamic data. 6. Conclusions In this paper we motivated the integration of dynamic information into IDEs such as Eclipse to ease maintaining object-oriented applications written in languages such as Java. We presented Senseo, an Eclipse plugin enabling developers to dynamically analyze their applications from within Eclipse. Senseo uses aspect-oriented programming techniques to gather runtime data from the system. Senseo presents gathered dynamic metrics such as execution flow information, runtime type information, numbers of method invocations, or amount of memory executed by augmenting the familiar static source views (package explorer, source editor, etc.). For instance, Senseo integrates dynamic metrics in hovers, in the ruler columns of the editor, or by annotating icons in the package explorer. We evaluated our work by solving concrete, practical use cases with Senseo and by thoroughly conducting performance benchmarks, as efficiency is most critical when it comes to dynamic analysis. Senseo as a tool is described in more detail in a separate tool demonstration paper. We plan to exploit the dynamic data gathered with Senseo by other means than augmenting the source perspective, for instance by visualizing the data in software maps [11]. Other future works include studying how to employ Senseo in a team environment, for instance by making accessible data of different runs to all team members working on the same project. Moreover, Senseo should automatically choose the most useful dynamic metric for... the task-at-hand, for instance dependent on the particular performance bottleneck to be fixed. References
{"Source-Url": "https://www.inf.usi.ch/faculty/binder/documents/icsm09.pdf", "len_cl100k_base": 8244, "olmocr-version": "0.1.53", "pdf-total-pages": 10, "total-fallback-pages": 0, "total-input-tokens": 33140, "total-output-tokens": 10556, "length": "2e13", "weborganizer": {"__label__adult": 0.0003006458282470703, "__label__art_design": 0.00019431114196777344, "__label__crime_law": 0.0002213716506958008, "__label__education_jobs": 0.00038743019104003906, "__label__entertainment": 3.62396240234375e-05, "__label__fashion_beauty": 0.00011098384857177734, "__label__finance_business": 0.00012189149856567384, "__label__food_dining": 0.000209808349609375, "__label__games": 0.0003376007080078125, "__label__hardware": 0.0004420280456542969, "__label__health": 0.0002310276031494141, "__label__history": 0.00013303756713867188, "__label__home_hobbies": 4.941225051879883e-05, "__label__industrial": 0.0001933574676513672, "__label__literature": 0.0001424551010131836, "__label__politics": 0.00017690658569335938, "__label__religion": 0.00030875205993652344, "__label__science_tech": 0.001880645751953125, "__label__social_life": 5.9664249420166016e-05, "__label__software": 0.004085540771484375, "__label__software_dev": 0.98974609375, "__label__sports_fitness": 0.00021791458129882812, "__label__transportation": 0.0003082752227783203, "__label__travel": 0.00016391277313232422}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 47714, 0.02259]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 47714, 0.41098]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 47714, 0.88645]], "google_gemma-3-12b-it_contains_pii": [[0, 4576, false], [4576, 10232, null], [10232, 13806, null], [13806, 18651, null], [18651, 22428, null], [22428, 27836, null], [27836, 31750, null], [31750, 36232, null], [36232, 42258, null], [42258, 47714, null]], "google_gemma-3-12b-it_is_public_document": [[0, 4576, true], [4576, 10232, null], [10232, 13806, null], [13806, 18651, null], [18651, 22428, null], [22428, 27836, null], [27836, 31750, null], [31750, 36232, null], [36232, 42258, null], [42258, 47714, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 47714, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 47714, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 47714, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 47714, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 47714, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 47714, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 47714, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 47714, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 47714, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 47714, null]], "pdf_page_numbers": [[0, 4576, 1], [4576, 10232, 2], [10232, 13806, 3], [13806, 18651, 4], [18651, 22428, 5], [22428, 27836, 6], [27836, 31750, 7], [31750, 36232, 8], [36232, 42258, 9], [42258, 47714, 10]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 47714, 0.0]]}
olmocr_science_pdfs
2024-12-07
2024-12-07
cfc8c2cb5a7b779a7a4777c8773fab4ef1632d3b
Lawrence Berkeley National Laboratory Recent Work Title Currency-Based Updates to Distributed Materialized Views Permalink https://escholarship.org/uc/item/5zz8n5r3 Authors Segev, A. Fang, W. Publication Date 1989-06-01 Currency-Based Updates to Distributed Materialized Views A. Segev and W. Fang June 1989 CURRENCY-BASED UPDATES TO DISTRIBUTED MATERIALIZED VIEWS Arie Segev† and Weiping Fang‡ † School of Business Administration University of California at Berkeley and Computer Science Research Department Lawrence Berkeley Laboratory 1 Cyclotron Road Berkeley, California, 94720 ‡ Department of Industrial Engineering and Operations Research University of California at Berkeley and Computer Science Research Department Lawrence Berkeley Laboratory 1 Cyclotron Road Berkeley, California, 94720 Abstract In currency-based updates, processing a query to a materialized view has to satisfy a currency constraint which specifies the maximum time lag of the view data with respect to a transaction database. Currency-based update policies are more general than periodical, deferred, and immediate updates; they provide additional opportunities for optimization and allow updating a materialized view from other materialized views. In this paper, we present algorithms to determine the source and timing of view updates and validate the resulting cost savings through simulation results. This work was supported by the Applied Mathematical Sciences Research Program of the Office of Energy Research, U.S. Department of Energy under Contract DE-AC03-76SF00098. 1. Introduction In a distributed environment, materialized views are a compromise between fully synchronized replicated data and single copies of data. Unlike synchronized replicated data, update transactions to the base data do not update the materialized data. After a base data transaction is committed, update transaction(s) to the materialized view(s) may be generated. The decoupling of base data transactions from updating materialized views raises three questions: when to update a materialized view? where to update it from? and how to perform the update? In updating a materialized view, an obvious solution is to rematerialize it from the base data on which it is defined, but normally a differential update procedure (e.g., [LIND86]) is superior. Since it is possible that modified base data is irrelevant to the view, screen test procedures to determine its relevance have been devised [BUNE79, BLAK86]. Three general approaches to the timing of materialized view updates have been considered in previous research. The first approach is to update the view immediately after each update to the base tables [SHMU84, BLAK86], the second one defers the updates until issuing a query to the view [ROUS86, HANS87], and the third is to refresh the view periodically [ADIB80, LIND86, SEGE89a]. The tradeoff involved in choosing an approach is the currency of the materialized view vs. the cost of updating it. Most of the studies of view management have been done for the case of a centralized DBMS. The subject of distributed materialized views has been addressed recently by [LIND86, KAHL87, SEGE89a]. These studies are concerned with "how" rather than "when" to update a materialized view. A recent work by [SRIV88] has modeled the "when" problem analytically for a single centralized view. The problem of quasi-copies which are similar to distributed materialized views is addressed in [ALON88]. In all the above works, the base data was assumed to be the source of updates to the materialized views. In [SEGE89b], currency-based updates policies are introduced and optimal update times are derived. The notion of currency (which measures the time lag of the view data relative to the base data) allows more flexibility in cost optimization including the possibility of updating a materialized view from another materialized view. In this paper, we extend the results of [SEGE89b] to determine the optimal update sources and timing for a set of distributed materialized views defined on the same base data. The paper is organized as follows. In Section 2, we introduce the problem definition, notation and assumptions. An optimization model and algorithms are presented in Section 3. Section 4 gives a detailed example of how to derive the input data used by the algorithms as well as how to apply them. Section 5 presents the results of simulation experiments that were done using DeNet [LIVN88]; the results demonstrate the cost savings that can be realized from our approach and algorithms. The paper is concluded in Section 6. 2. Problem Definition and Assumptions Let $R$ be a base relation and assume that $n$ materialized† views $MV = \{V_i\}, i = 1, \ldots, n$, are defined over $R$. View $V_i$ is stored at view site $i$, and without loss of generality, we assume that all site numbers are distinct. Occasionally, we will use $v$ to mean $V_1$; it will be clear from the context. We are interested in finding an optimal view update policy for each $V_i \in MV$. The optimal policy is defined to be the one that minimizes the view update cost subject to a currency constraint. Currency constraints are defined as follows. View Currency Let $\{\text{State}_B(t_i)\}$ be a description of the base table states at time points $t_i$. We assume that $t_i$ are expressed as integers and represent the lowest time granularity of interest. Similarly, let $\{\text{State}_v(t_i)\}$ be the state description of view $v$. We require that $\text{State}_v(t_i) \in \{\text{State}_B(t_j) \mid t_j \leq t_i\}$, that is, the view state at time $t_i$ was a state of the base table at some time $t_j \leq t_i$. The view currency at time $t_i$ is defined as $$T_v^{(t_i)} = t_i - \max_{t \in S_i} \{t \mid \text{State}_v(t_i) = \text{State}_B(t)\}.$$ In practice one does not know that $\text{State}_v(t_i) = \text{State}_B(t)$ except for states that were reflected at view † Unless stated otherwise, we will use the term ‘view’ to mean ‘materialized view’ in the remainder of this paper. update times. Consequently, if the last update of the view was at time \( t_u \leq t_i \) and that update reflected the base table state at time \( t_j \leq t_u \), then the working definition of view currency is \( T_v(t_i) = t_i - t_j \). Informally, this definition means that the view data is at most \( t_i - t_j \) time units 'old'. A currency constraint may be associated with a view and/or a query. Associating the constraint with the view implies that the view data has to satisfy it at all times. Associating the constraint with a query implies that data retrieved by the query has to satisfy it. In this work, we assume that the currency constraint is associated with queries (we denote it by \( T_Q \)). Query Processing and View Update Constraints When a query is to be processed at time \( t_i \), \( T_Q \) is satisfied by the view data if \( T_v(t_i) \leq T_Q \). We also assume that a query is answered from the view only, that is, if \( T_Q \) is satisfied, the query is processed against the current state of the view; otherwise, the view is updated such that the new currency\(^\dagger\), \( T_v(t_i) \), is less than or equal to \( T_Q \), and the query is processed against the new state. Since the view data is not synchronized with the base relation at the transaction level, \( T_Q = 0 \) or \( T_v = 0 \) should be interpreted as \( 0^+ \), that is, the state of the view changes according to an immediate update policy (e.g. [SHMU84, BLAK86]). Consider a view \( \mathcal{V} \). Let \( SV \subseteq MV \) be such that for each \( v \in SV \), View_Predicate(\( \mathcal{V} \)) = View_Predicate(\( v \)) or View_Predicate(\( \mathcal{V} \)) \Rightarrow View_Predicate(\( v \)), and \( T_v \leq T_Q \). The set \( SV \) represents a set of views that can be used to update \( \mathcal{V} \) such that the new currency of \( \mathcal{V} \) will satisfy \( T_Q \). See [FINK82] for the subject of identifying relationships between predicates. There are two advantages to having the option of updating a view from other views. First, it may be cheaper than using a base relation, and second, it frees the base relation processor (if the views are stored at other sites) from a portion of the view maintenance activity. \[^\dagger\] In practice the various events, and the update process in particular, are not instantaneous. We assume that the new view currency is effective as of the beginning of the update process. **View Update Policies** The foregoing discussion implies the following constraint on a view update policy: prior to processing a query $Q$, the currency of the view has to satisfy $T_Q$. Subject to this constraint there are several possible policies of timing the view update. These policies can be classified as follows: - **P1**: Periodical updates - view updates are done on a pre-determined cyclical basis. - **P2**: On-Demand - view updates are done only at query processing time. - **P3**: Random Updates - view updates are done at random times. - **P4**: Hybrids - view updates are done according to combinations of the first three policies. In [SEGE89b] we have derived optimal analytical results for hybrid policies of which P1 and P2 are special cases. The results of that paper are applicable to the case where the set $SV$ is given. However, a membership in $SV$ (relative to view $\mathcal{V}$) is qualified on both currencies and predicates, and therefore can not be determined a priori if the view update sources are not known. In this paper we are interested in determining optimal update policies for all the views in $MV$ given that a Periodical Or Demand (POD) policy is followed. Figure 1 illustrates the POD policy for updating $\mathcal{V}$ from $\mathcal{V}$ where $T_\mathcal{V}$ is constant (the results are applicable to random $T_\mathcal{V}$ as well). In this policy, an update to $\mathcal{V}$ is triggered by either of the following two events: (1) A query arrives and the currency of $\mathcal{V}$ is unsatisfactory; (2) The time from the last update is $s$. This policy provides a mechanism to balance the system’s objective with the user’s objective. In this policy, there are two types of updates; the first update type is triggered by a query, while the second type is clock-triggered when a cycle time elapsed. The cycle time is restarted after each update (either a query-triggered or a clock-triggered), and by changing $s$, one can control the cost of query-triggered updates. Note that the view currency is measured in time units relative to the states of the base table; Therefore, a higher currency value means that the view data is older. In the figure, we assumed that initially $\mathcal{V}$ is generated from the base table, and subsequently, is updated from $\mathcal{V}$. The figure shows three updates; the first two updates are triggered by queries 3 and 5, and the third update is clock-triggered because $s$ time units elapsed from the second update. Queries that find the currency value below $T_Q$ do not The goal of the analytical analysis is to derive the following results. (1) Choose a $v \in SV \cup \{R\}$, and $s$ such that $\lim_{t \to \# \text{ of query arrivals in } [0, t]}$ updating cost in $[0, t]$ is minimized. The above expression represents the average view update cost per query, and its minimization is a system's objective. (2) We would like to minimize the expression in (1) subject to a user's response time constraint. The constraint is given as follows. let $UT_Q^{i,t}$ be the view update time for a query-triggered update (it is a function of $v$ and $s$). We require that $Pr\{UT_Q^{i,t} > H_1\} \leq H_2$, where $H_1$ and $H_2$ are user-provided threshold values. The results (which are used in this paper) are summarized in Appendix 1. The underlying cost function is discussed next. Cost Functions The cost of updating a view is dependent on the particular algorithm, size of the data files, processing cost, communication costs, and the currency constraints. View update algorithms that were proposed in previous studies can be classified into two general categories: rematerializations and differential updates. An algorithm in the first category regenerates the view from the base table. In differential updates, only changes to the base table(s) since the last view update are processed against the view. There are two approaches to differential updates, one is to use a differential file (e.g. [SEGE89a]) and the other is to use the base table (e.g. [LIND86]). Under the assumption that the size of relations and materialized views are stable over a relatively long period of time, we use an update cost function of the form $ax + b$. For rematerialization-type updates $a = 0$. For differential-type updates we assume that the cost is linear with respect to time $x$ (the precise definition of $x$ is given below). We feel that this function is an appropriate representation for a differential-file algorithm. For example, in [SEGE89a] the major cost components are a sequential backwards scan of the differential file, transmission of the differential tuples that pass a screening test, and updating the remote view. If the average selectivities and activity patterns are constant over a period of time, then in that period, the first two cost components are linear with respect to the time between view updates. The behavior of the third component is dependent on how the remote view update is done; it is possible that (even if the update volume is linear with time) a cost linear with time is an over-estimate because of Yao-function [YAO77] behavior of view update cost. In the remainder of the paper we will assume a differential-file-based view update algorithm. If we use $V_i$ to update $V = V_j$, the update cost is $a_{ij}x + b_{ij}$, and the cost coefficients represent processing and communication costs; $x$ is the difference between the currencies of $V$ after and before the † The Yao-function is not related to the time between updates, but to the size of the view and number of records to be updated at any time. If the number of records to be updated is either very large or very small, a linear cost function is appropriate. Also, a very good piecewise-linear approximation of the Yao-function is given in [BERN81]. update. We also assume that the optimization procedure is static with respect to a given period of time, that is, during that period only one relation (or view) \( v \in SV \cup \{ R \} \) is used to update \( \mathcal{V} \), and the average post-update currency of \( \mathcal{V} \) is the same after each update from \( v \). In this case, we use the time between updates as the value of \( x \) in the cost formula. Note that previous studies are a special case, where the view currency after each update is a constant and equal to 0. In section 4, we show how to derive the coefficients \( a_{ij} \) and \( b_{ij} \). 3. A Model and Algorithms for Multiple View Updates In this section, we formalize the optimization problem of determining optimal POD update poli- cies for a collection of views. In order to simplify the subscripting we refer to the base relation as \( V_0 \). A collection of views \( V_i, i = 1, \ldots, n \), are defined over \( V_0 \). Each \( V_i \) is *derivable* from \( V_i \) if the selection predicate of \( V_i \), and all attributes of \( V_j \) appear in \( V_i \). View \( V_j \) can be updated from \( V_i \) if it is derivable from it; the update is *satisfactory* if the currency requirements of queries to \( V_j \) are satisfied by the updated data; in that case we denote \( V_i \) and \( V_j \) as the source and target of the update respectively. For a particular target a source is satisfactory if the resulting update is satisfactory. The following input data is used by the algorithms described below. The update cost coefficients \( a_{ij} \) and \( b_{ij} \) are used to calculate \( c_{ij}(x) = a_{ij}x + b_{ij} \) which is the cost of updating \( V_j \) from \( V_i \), where \( x \) is the time from the last update of \( V_j \); if \( V_j \) is not derivable from \( V_i \), then \( a_{ij} \) and \( b_{ij} \) are \( \infty \). A coefficient \( d_i \) describes the cost rate of creating a differential file at view site \( i \); this file is required if \( V_i \) is used to differentially update at least one \( V_k, k \neq i \); if \( x \) is the time between two consecutive updates of \( V_i \), then \( d_i x \) is the differential file writing cost associated with an update of \( V_i \). A directed weighted graph is given as \( G = (V, A, C, D) \) where \( V = \{ i \mid i = 0, \ldots, n \} \), \( A = \{ (i, j) \mid i, j \in V \& V_j \text{ is derivable from } V_i \} \), \( C = \{ (a_{ij}, b_{ij}) \mid (i, j) \in A \} \), and \( D = \{ d_i \mid i \in V \} \). The node numbers in \( G \) correspond to view numbers. Each element in \( C \) is associated with the corresponding arc, and each element of \( D \) is the weight of the corresponding node. Queries to \( V_i \) arrive according to a Poisson process with a rate \( \lambda_i \), and have a currency requirement \( T^i_Q \). In the algorithmic analysis, we distinguish between two cases -- acyclic $G$ and cyclic $G$. An acyclic graph represents the case where no two views are identical. This case results in the simpler algorithm (Algorithm 1 in Section 3.1). Section 3.2 extends Algorithm 1 to handle the case of identical views. 3.1. The Case of an Acyclic Graph Algorithm 1 is of a greedy type. At each iteration an update source and timing is determined for the next view (the one for which the incremental cost is minimized); once this is done, the average currency of that view is calculated. Consequently, at each iteration there are two sets of views; the first set contains the views for which an update source and optimal update times have been determined, and the second set contains the rest ("unfixed") of the views. Note that given a set of fixed views the calculation for each of the unfixed views (based on the formulae in Appendix 1) is optimal, the overall procedure, though, is heuristic. The previous steps assume that the differential files at view sites are free; the final step of the algorithm evaluates this additional cost for each view that is used as an update source, and if this cost is greater than the savings realized by the target views (compared to being updated from the base table), the base table is fixed as the update source for those target views. If the differential file cost incurred by other applications at the view site, this final step should be omitted. The outcome from the above steps is dependent on the order in which the views are examined. A topological order [KNUT73] is used by the algorithm. The reason for a topological order is that all views from which view $V_j$ is derivable, are by definition, topologically before $V_j$ in the graph $G$. Therefore, when $V_j$ is being evaluated to determine its source of update, all views that can be used to update it have already been evaluated (including their average currencies $T_i$'s). A formal statement of the algorithm follows. Algorithm 1 Step 1. Initialization: Relabels $V_j$'s in topological order, i.e., if $(i, j) \in A$, then $i < j$ in $V$. For each $j \in V$, find the set of immediate predecessors of $V_j$, $I_j = \{ i \mid (i, j) \in A \}$. Set $T_0 = 0.$ Step 2. For $j \in V - \{0\}$ in topological order, do the following: 2.1 Find $i^*$ such that $$\frac{a_{i^* j}}{\lambda_j} + \frac{b_{i^* j}}{\lambda_j (T^j - T_{i^*}) + 1 - e^{-\lambda_j (s_j - (T^j - T_{i^*}))}}$$ $$= \min_{i^* \in \mathcal{I}_j, \mathcal{T}_i < T^j} \left\{ \frac{a_{ij}}{\lambda_j} + \frac{b_{ij}}{\lambda_j (T^j - T_i) + 1 - e^{-\lambda_j (s_j - (T^j - T_i))}} \right\}$$ 2.2 $\text{SOURCE}(j) = i^*$. 2.3 $T_j = \frac{E(X_j(s_j))}{2} = \frac{1}{2} \left\{ T^j - T_{i^*} + \frac{1 - e^{-\lambda_j (s_j - (T^j - T_{i^*}))}}{\lambda_j} \right\}.$ Step 3. For $i \in V - \{0\}$ in topological order, do the following: 3.1 Find $J = \{ j \mid \text{SOURCE}(j) = i \}$. 3.2 If $J \neq \emptyset$, find $J' \subset J$ such that for $j \in J'$ $$\frac{a_{ij} + d_i}{|J|} + \frac{b_{ij}}{\lambda_j (T^j - T_i) + 1 - e^{-\lambda_j (s_j - (T^j - T_i))}}$$ $$> \frac{a_{0j}}{\lambda_j} + \frac{b_{0j}}{\lambda_j (T^0 - T_0) + 1 - e^{-\lambda_j (s_j - (T^0 - T_0))}}.$$ 3.3 If $J' \neq \emptyset$, for $j \in J'$ set $\text{SOURCE}(j) = 0$ and $$T_j = \frac{1}{2} \left\{ T^j - T_0 + \frac{1 - e^{-\lambda_j (s_j - (T^j - T_0))}}{\lambda_j} \right\}, J \leftarrow J - J',$$ and go to 3.2. In the above algorithm, Step 1 topologically sorts the vertex set $V$ and for each vertex (view) $j$ in $V$ finds the set of its immediate predecessors, which, in other words, can be used to update $V_j$ in terms of their view expressions. Step 2 finds an update source that minimizes based on Appendix 1 the average update cost per query for the target view, and calculates its mean currency to be used in case this view is used as an update source. Step 3 considers the cost of creating a differential file at each update source and may change the update source of views to the base table. The cost of the differential files is considered after the update sources are fixed in Step 2, in order to account for cost sharing by multiple target views. When the algorithm terminates the update source of each $V_j$ is given by $V_{\text{SOURCE}_j}$. As a final note, the algorithm assumes linear update cost functions. However, if the cost functions are piecewise linear as in the example in Section 4, the cost coefficients are different in different intervals. We then, for each possible update source (in $I_j$), calculate the mean update cycle length ($E(X_j(s_j))$) and use it to determine those cost coefficients ($a$'s and $b$'s) before the minimization in step 2. 3.2. The Case of a Cyclic Graph The presence of identical views at different sites introduces cycles into the graph $G$. Each group of identical views leads to a maximal complete subgraph of $G$. Algorithm 2 is an augmentation of Algorithm 1 to handle this case. It first (Step 1) transform $G$ into $G'$ by shrinking every maximal complete subgraph of $G$ into a single node of $G'$ to make it acyclic. Then (Step 2) the nodes of $G'$ are evaluated in a topological order. If a node corresponds to a single node of $G$, Algorithm 2 does exactly the same as algorithm 1; Otherwise, it acts like a greedy algorithm for a minimum spanning tree, and repeatedly removes a node from the corresponding complete subgraph to the set of predecessors (see Step 2.3 below). The following is a formal statement of the algorithm. Algorithm 2 Step 1. Initialization: 1. By shrinking every cycle into a single node, transform $G$ into $G'(V', A')$, where $V'$ is actually a partition of $V$; i.e., each element in $V'$ is a subset of $V$, and these subsets covering $V$ are disjoint. Since $A$ is transitive, every element in $V'$ constitutes a maximal (not maximum) complete subgraph of $G$. $A' = \{(u', v') | u', v' \in V' \& (u, v) \in A \text{ for } u \in u', v \in v'\}.$ 1.2 Sort $V'$ topologically according to $A'$. Let $V' = \{V'_1, \ldots, V'_m\}$. Step 2. For $l = 1, \ldots, m$, do the following: 2.1 Set $J \leftarrow V'_1$. $J$ is the set of views for which their source views are to be chosen from $I$. 2.2 Find $I = \{i \mid i \in V_k' \& (V_k', V_i') \in A'\}$. $I$ is the set of views that can be used to update views in $J$. 2.3 While $J \neq \emptyset$, repeat the following: 2.3.1 Find $i^* \in I$, $j^* \in J$, and $T_{i^*} < T_{j^*}$ such that the following expression is minimized $$\frac{a_{i^*j^*}}{\lambda_{j^*}} + \frac{b_{i^*j^*}}{\lambda_{j^*}(T_{j^*} - T_{i^*}) + 1 - e^{-\lambda_{j^*}(s_{i^*} - (T_{j^*} - T_{i^*}))}}.$$ 2.3.2 $J \leftarrow J - \{j^*\}$, $I \leftarrow I \cup \{j^*\}$. 2.3.3 $\text{SOURCE}[j^*] = i^*$. 2.3.4 $T_{j^*} = \frac{1}{2} \left[ T_{j^*} + 1 - e^{-\lambda_{j^*}(s_{i^*} - (T_{j^*} - T_{i^*}))} \right]$. Step 3. Same as Algorithm 1. 4. An Example In this section, we illustrate the algorithm for the acyclic case using a simple example given below. The syntax of the view definition follows INGRES/SQL [RTI86]. /* $V_0$: employee base relation containing 100,000 92-byte tuples stored at site 0. */ create table V0 ( EMP# integer, NAME char(20), ADDRESS char(40), SALARY money, JOB_CODE char(4), DEPT char(12), PROJ# integer ); /*============================================================================*/ /* V1: set of employees whose salary is greater than $50000. */ /* We assume 10,000 qualifying tuples stored at site 1; tuple width = 52 */ create view V1 as select EMP#, NAME, SALARY, JOB_CODE, DEPT, PROJ# from EMPLOYEE where SALARY > 50000; /*============================================================================*/ /* V2: set of employees whose salary is greater than $40000. */ /* We assume 20,000 qualifying tuples stored at site 2; tuple width = 52 */ create view V2 as select EMP#, NAME, SALARY, JOB_CODE, DEPT, PROJ# from EMPLOYEE where SALARY > 40000; /*============================================================================*/ /* V3: set of employees in Engineering Department with salary greater than $50000. */ /* We assume 1,000 qualifying tuples stored at site 3; tuple width = 52 */ create view V3 as select EMP#, NAME, SALARY, JOB_CODE, DEPT, PROJ# from EMPLOYEE where SALARY > 50000 and DEPT = 'ENGINEERING'; 4.1. Deriving the Update Cost Coefficients It is clear in the example that $V_0 \supseteq V_2 \supseteq V_1 \supseteq V_3$; therefore, $V = \{0, 1, 2, 3\}$ and $A = \{(0, 1), (0, 2), (0, 3), (2, 1), (1, 3), (2, 3)\}$. To find out view updating costs ($C$ in our algorithm), we use the formulae of [SEGE89a] which are given in Appendix 2. The appendix also contains the linearization of the nonlinear expressions. The following parameter values are common to all updates: - $C_{\text{i/o}} = 0.025 \text{ sec}$ - $B = 1024 \text{ bytes}$ - $W_B = 8 \text{ bytes}$ - $W_v = 52 \text{ bytes}$ - $W_i = 56 \text{ bytes}$ - $W_d = 4 \text{ bytes}$ - $C_{\text{comm}} = 100000 \text{ bps}$ Costs for updating $V_1$ from $V_0$ Further assumptions specific to this case: - $U = 20t/60 = t/3$; ($t$: time in seconds) - $W_R = 92$ - $N_R = 100,000$ - $\alpha_s = 0.1$ Based on those assumptions, we then have - $DIO 1 = 0.025 \times \frac{t}{3} \times \frac{92}{1024} = 0.7487 \times 10^{-3} t$ - $DIO 2 = 0.025 \times 2 \times \frac{t}{3} \times \frac{10000}{100000} \times \frac{92}{1024} = 0.1497 \times 10^{-3} t$ - $DIO 3 = 0.025 + 0.025 \times \begin{cases} t/30 & \text{if } t/30 \leq 39.06 \\ (t/30 + 78.125)/3 & 39.06 < t/30 \leq 156.25 \\ 78.125 & 156.25 < t/30 \end{cases}$ - $DIO 4 = 0.05 \times \begin{cases} t/30 & \text{if } t/30 \leq 253.91 \\ (t/30 + 507.81)/3 & 253.91 < t/30 \leq 1015.625 \\ 507.81 & 1015.625 < t/30 \end{cases}$ - $DCOM = 8(\frac{t}{60} \times 56 + \frac{t}{60} \times 4)/100,000 = 0.08 \times 10^{-3} t$ Adding the above cost components we get $$DIO 1 + DIO 2 + DIO 3 + DIO 4 + DCOM$$ \[ 3.478 \times 10^{-3}t + 0.025 \quad t \leq 1171.875 \\ 2.923 \times 10^{-3}t + 0.676 \quad 1171.875 < t \leq 4687.5 \\ 2.645 \times 10^{-3}t + 1.978 \quad 4687.5 < t \leq 7617.19 \\ 1.534 \times 10^{-3}t + 10.44 \quad 7617.19 < t \leq 30468.75 \\ 0.978 \times 10^{-3}t + 27.37 \quad 30468.75 < t \] \[DIO 5 = 0.7487 \times 10^{-3}t\] Therefore, \[(a_{0,1}, b_{0,1}) = \begin{cases} (3.478 \times 10^{-3}, 0.025) & t \leq 1171.875 \\ (2.923 \times 10^{-3}, 0.676) & 1171.875 < t \leq 4687.5 \\ (2.645 \times 10^{-3}, 1.978) & 4687.5 < t \leq 7617.19 \\ (1.534 \times 10^{-3}, 10.44) & 7617.19 < t \leq 30468.75 \\ (0.978 \times 10^{-3}, 27.37) & 30468.75 < t \end{cases}\] and \[d_0 = 0.7487 \times 10^{-3}.\] Similarly, we get the following cost coefficients: Updating \(V_2\) from \(V_0\) under assumptions \(U = t/3\), \(W_R = 92\), \(N_R = 100,000\), \(\alpha_s = 0.2\): \[(a_{0,2}, b_{0,2}) = \begin{cases} (6.208 \times 10^{-3}, 0.05) & t \leq 1171.875 \\ (5.097 \times 10^{-3}, 1.352) & 1171.875 < t \leq 4687.5 \\ (4.542 \times 10^{-3}, 3.956) & 4687.5 < t \leq 7617.19 \\ (2.319 \times 10^{-3}, 20.883) & 7617.19 < t \leq 30468.75 \\ (1.208 \times 10^{-3}, 54.737) & 30468.75 < t \end{cases}\] Updating \(V_1\) from \(V_2\) under assumptions \(U = t/15\), \(W_R = 52\), \(N_R = 20,000\), \(\alpha_s = 0.5\): \[(a_{2,1}, b_{2,1}) = \begin{cases} (2.749 \times 10^{-3}, 0.025) & t \leq 1171.875 \\ (2.194 \times 10^{-3}, 0.676) & 1171.875 < t \leq 4687.5 \\ (1.916 \times 10^{-3}, 1.978) & 4687.5 < t \leq 7617.19 \\ (0.805 \times 10^{-3}, 10.44) & 7617.19 < t \leq 30468.75 \\ (0.249 \times 10^{-3}, 27.37) & 30468.75 < t \end{cases}\] Updating $V_3$ from $V_0$ given that $U = t/3$, $W_R = 92$, $N_R = 100,000$, $\alpha_z = 0.01$: $$(a_{0,3}, b_{0,3}) = \begin{cases} (1.022 \times 10^{-3}, 0.025) & t \leq 1171.875 \\ (0.966 \times 10^{-3}, 0.09) & 1171.875 < t \leq 4687.5 \\ (0.938 \times 10^{-3}, 0.22) & 4687.5 < t \leq 7617.19 \\ (0.827 \times 10^{-3}, 1.067) & 7617.19 < t \leq 30468.75 \\ (0.772 \times 10^{-3}, 2.759) & 30468.75 < t \end{cases}$$ Updating $V_3$ from $V_1$ given that $U = t/30$, $W_R = 52$, $N_R = 10,000$, $\alpha_z = 0.1$: $$(a_{1,3}, b_{1,3}) = \begin{cases} (0.309 \times 10^{-3}, 0.025) & t \leq 1171.875 \\ (0.254 \times 10^{-3}, 0.09) & 1171.875 < t \leq 4687.5 \\ (0.225 \times 10^{-3}, 0.22) & 4687.5 < t \leq 7617.19 \\ (0.114 \times 10^{-3}, 1.067) & 7617.19 < t \leq 30468.75 \\ (0.059 \times 10^{-3}, 2.759) & 30468.75 < t \end{cases}$$ Updating $V_3$ from $V_2$ given that $U = t/15$, $W_R = 52$, $N_R = 20,000$, $\alpha_z = 0.05$: $$(a_{2,3}, b_{2,3}) = \begin{cases} (0.351 \times 10^{-3}, 0.025) & t \leq 1171.875 \\ (0.296 \times 10^{-3}, 0.09) & 1171.875 < t \leq 4687.5 \\ (0.267 \times 10^{-3}, 0.22) & 4687.5 < t \leq 7617.19 \\ (0.156 \times 10^{-3}, 1.067) & 7617.19 < t \leq 30468.75 \\ (0.101 \times 10^{-3}, 2.759) & 30468.75 < t \end{cases}$$ Cost of differential files: $$d_1 = 0.0423 \times 10^{-3}$$ $$d_2 = 0.0846 \times 10^{-3}$$ 4.2. Applying Algorithm 1 We now illustrate how to use Algorithm 1 with the cost coefficients derived in Section 4.1. Asssume that the query arrival rates are $\lambda_1 = 1/20$, $\lambda_2 = 1/10$, $\lambda_3 = 1/200$; also let $T_Q^1 = T_Q^2 = T_Q^3 = T_Q = 60$, and $s_1 = s_2 = s_3 = \infty$. Since $E(X_j(s_j))$ are less then 1171.875 for all $j$. 15 and thus fall into the first interval \([0, 1171.876]\), we take \(a\)'s and \(b\)'s for that interval and omit the calculations of \(E(X_j(s_j))\); otherwise we would pick \(a\)'s and \(b\)'s for the time interval containing \(E(X_j(s_j))\). After the initialization in Step 1 we get \(V = \{0, 2, 1, 3\}\); and \(I_2 = \{0\}, I_1 = \{0, 2\}, I_3 = \{0, 1, 2\}\). In Step 2, for \(j = 2\), the only possible source is \(V_0\), and therefore \(\text{SOURCE}[2] = 0\) and \(T_2 = 35\). For \(j = 1\), \(\frac{a_{2,1}}{\lambda_1} + \frac{b_{2,1}}{\lambda_1(T_Q^1 - T_2) + 1} = 0.066\) is less than \(\frac{a_{0,1}}{\lambda_1} + \frac{b_{0,1}}{\lambda_1(T_Q^1 - T_0) + 1} = 0.076\), and therefore \(\text{SOURCE}[1] = 2\) and \(T_1 = 22.5\). Similarly, for \(j = 3\), we get \(\text{SOURCE}[3] = 1\) and \(T_3 = 118.75\). In Step 3, for \(i = 2, J = \{1\}\), and \(J' = \emptyset\) because \(\frac{a_{2,1} + d_2}{\lambda_1} + \frac{b_{2,1}}{\lambda_1(T_Q^1 - T_2) + 1} = 0.068\) is still less than 0.076. Thus the update source of \(V_1\) remains unchanged. Similarly the source of \(V_3\) also remains unchanged. 5. Simulation Experiments The purpose of the simulation experiments reported in this section was two-fold. First, the view update decisions generated by the algorithms presented in this paper are based on a linear approximation of the cost function and an assumption that each view is updated from a single source. The latter assumption may significantly affect the error of the estimated cost because, in an actual system, it is possible that a view designated as an update source will not have a satisfactory currency at all update points (even though its average currency is satisfactory). In that case, either the source view is updated to a satisfactory currency (this may have to be done recursively for more than one view) or an alternative source is used (by the definition of currency the base table is always an acceptable source). In the simulation experiments, if an update source is a view, its currency is checked and if not satisfactory the update is done from the base table instead. We are interested in finding the ratio of the estimated update cost and the simulated update cost. The second (and the more important) objective of the simulations was to evaluate the benefit of using views as update sources. The best measure of the benefit is derived from the simulation experiments; we ran simulations for cases where view update are done only with the base table as a source (the update times are determined based on the POD policy), and for cases (with the same parameter values) where the view update sources are determined by Algorithm 1. The ratio of the resulting costs indicates the benefit of updates from views. Next, we describe the specific details of the simulation experiments and their results. The simulation model was built using DeNet [LIVN88] for a 4-node network representing the example of Section 4. The parameter values that were changed from one run to another were the Poisson arrival rates of queries and the currency requirements. All other parameters were fixed at the values given in Section 4. Each run lasted 100,000 seconds of simulation time. For each set of parameter values, Algorithm 1 generates the primary update sources for the case where views can be used as an update source (we refer to this case as "view-to-view updates"). The case of using only the base table for updates (referred to as "base-to-view updates") was handled according to Appendix 1. We report here the main results of the simulations. Figure 2 shows the ratio of the simulated total update cost to the estimated total update cost as a function of the query currency (the same query currency requirement was associated with all views). The inter-arrival times of queries were drawn from an Exponential distribution with a mean \((1/\lambda)\) of 20, 10, and 200 seconds for views 1, 2, and 3 respectively. The graph of Figure 2 shows that the degree of underestimation is decreasing with the required currency. Figure 3 demonstrates the more important result that it pays to allow view-to-view updates (even if the cost estimates used to determine the sources are not accurate). For all the simulations represented in Figure 3, the source for updating view 2 was the base table (this is the only choice because of the view predicates and the reason why its cost ratio is 1). View 2 was chosen as the update source for View 1 which in turn was chosen as the update source for View 3. The query arrival rates were the same as for Figure 2. The figure illustrates that substantial cost savings can be realized from using views as update sources (in this particular example up to 60% for View 3). general the cost savings increase with the query currency; this can be explained by the fact that the higher the value of $T_Q$, the higher the probability that a non-base table update source will have a satisfactory currency, and thus, the savings opportunity is realized by the target more frequently. 6. Summary and Future Research Distributed materialized views can be a cost effective alternative to synchronized replicated data in many environments. In order for a DBMS to support materialized views, three problems have to be solved; the first is "when to update the view," the second is "where to update it from," and the third is "how to update the view." In this paper we have been primarily concerned with the first two problems, and introduced the concept of view currency. By allowing queries on a materialized view to specify a currency requirement, a more powerful and flexible update policy results. If the currency does not imply immediate updates, it may be possible to update one materialized view from another rather than from a base table. This can reduce the Fig. 3: A Comparison of View-to-View and Base-to-View Update Costs. cost of maintaining distributed materialized views significantly, as well as lead to a further reduction in the interference with base table transactions. We have introduced an optimization model and algorithms to determine the optimal update sources and timing for a collection of views defined on common base data. A detailed example has been presented showing how to get the cost coefficients needed at the abstraction level of the algorithms; the example also demonstrated how the algorithms are applied. A DeNet simulation model was constructed in order to capture the cost of the algorithm's decision in more detail. In particular, the algorithm's cost estimation is based on a fixed update cost; however, in an actual system, if a currency is not satisfied for a particular update, then the source has to be changed to the case table; this 're-routing' is captured in the simulation experiments. The results of these experiments have demonstrated the potential cost savings from our approach and algorithms; in current work are extending the simulations to cover additional cases. Finally, it should be noted that at the algorithm level the base data can be a set of relations, and the views can be general. However, the details of deriving the linear cost coefficients (and their quality) will be different for general Select-Project-Join views. ACKNOWLEDGEMENT We would like to thank Miron Livny for providing us with the discrete event network simulation language DeNet. APPENDIX 1 The following results were derived in [SEGE89b], for the POD policy. Summary of the Basic Model A base relation: \( R \). View to be updated: \( \bar{V} \). Views implied by or identical to \( \bar{V} \): \( SV, \bar{V} \in SV \). Cost of updating \( \bar{V} \) from \( v \in SV \cup \{ R \} \): \( c_v(x) = a_v x + b_v \), where \( x \) is the time between view updates. \( (a_v \text{ and } b_v \text{ are an abbreviated notation for } a_{v\bar{V}} \text{ and } b_{v\bar{V}} \text{ respectively.}) \) Currency of \( v \in SV \): Uniformly distributed over the interval \([0, t_v]\). Query (to \( \bar{V} \)) arrival: Poisson process with arrival rate of \( \lambda \). \[ \Rightarrow \text{inter-arrival time: Exponential with mean } \frac{1}{\lambda}. \] Required currency for query \( Q \): \( T_Q \). Objective: find a \( v \in SV \cup \{ R \} \) to be used in updating \( \bar{V} \) with minimum cost subject to currency, policy, and response time constraints. Note that the currency of the base table is 0. Theorem 1: The values of \( s \) and \( v \) that minimize the average cost per query are given by \( s^* = \infty \), and \( v^* \) is such that \[ \frac{a_v^* \lambda}{\lambda} + \frac{b_v^*}{\lambda \left[ T_Q - \frac{t_v^* \lambda}{2} \right] + 1} = \min_{v \in SV \cup \{ R \}} \frac{a_v}{\lambda} + \frac{b_v}{\lambda \left[ T_Q - \frac{t_v \lambda}{2} \right] + 1}. \] **Theorem 2:** For any view $v$, the optimal $s$ value subject to update time constraints $H_1$ and $H_2$ is given by $$s^* = \frac{1}{\lambda} \ln \frac{1 - e^{-\lambda u}}{\lambda H_1 - H_2 \sum_0^H e^{-\lambda s} - \lambda H_2 e^{-\lambda T_0}}.$$ **APPENDIX 2** To calculate the cost of updating materialized views we use the following notation and cost expressions from [SEGE89a]: - **DIO1**: cost of reading tuples from the differential file - **DIO2**: cost of sorting the tuples after the screen test - **DIO3**: cost of accessing the $B^+$ tree - **DIO4**: cost of updating the data in the view table - **DCOM**: cost of transmitting over the network - **DIO5**: cost of creating a differential file at the update source Let: - $B$: block size (bytes) - $C_{I/O}$: I/O cost (second/block) - $U$: number of tuples in the differential file - $W_R$: width (bytes) of each tuple for the base table - $U_s$: number of tuples that pass the screen test - $N_v$: number of tuples in the view table - $H_B$: height of a $B^+$ tree record at the view site ($\lceil \log_B W_B N_v \rceil$) The expected number of blocks fetched when accessing $K$ out of $N$ tuples in $P$ blocks is: $$f(N, P, K) = [YAO77]$$ $W_B$: width of a $B^+$ tree record at the view site $U_i$: number of tuples to be transmitted to the view site $W_v$: width of a view tuple $W_i$: width of an insertion tuple $W_d$: width of a deletion tuple $C_{comm}$: transmission rate (bps) The resulting cost expressions are: \[ DIO 1 = C_{1/0} UWR/B \] \[ DIO 2 = C_{1/0} 2U^tWR/B \] \[ DIO 3 = C_{1/0} (H_B - 1 + f (N_v, N_vWR/B, U^t)) \] \[ DIO 4 = C_{1/0} 2f (N_v, N_vWR/B, U^t) \] \[ DCOM = 8(U^tIW_i + U^tIW_d)/C_{comm} \] \[ DIO 5 = DIO 1 \] Using the linearization of the Yao function from [BERN81], \[ f (N, P, K) =\begin{cases} K, & K \leq \frac{1}{2} P \\ (K + P)/3, & \frac{1}{2} P < K \leq 2P \\ P, & 2P < K \end{cases} \] we get \[ DIO 3 = C_{1/0} (H_B - 1) + C_{1/0} \begin{cases} U^t, & U^t \leq \frac{1}{2} N_vWR/B \\ (U^t + N_vWR/B)/3, & \frac{1}{2} N_vWR/B < U^t \leq 2N_vWR/B \\ N_vWR/B, & 2N_vWR/B < U^t \end{cases} \] \[ DIO 4 = C_{1/0} \times 2 \begin{cases} U^t, & U^t \leq \frac{1}{2} N_vWR/v \\ (U^t + N_vWR/v)/3, & \frac{1}{2} N_vWR/v < U^t \leq 2N_vWR/v \\ N_vWR/v, & 2N_vWR/v < U^t \end{cases} \] REFERENCES
{"Source-Url": "https://cloudfront.escholarship.org/dist/prd/content/qt5zz8n5r3/qt5zz8n5r3.pdf?t=p0gia1", "len_cl100k_base": 12350, "olmocr-version": "0.1.53", "pdf-total-pages": 30, "total-fallback-pages": 0, "total-input-tokens": 71664, "total-output-tokens": 15714, "length": "2e13", "weborganizer": {"__label__adult": 0.0004320144653320313, "__label__art_design": 0.000518798828125, "__label__crime_law": 0.0005183219909667969, "__label__education_jobs": 0.0032024383544921875, "__label__entertainment": 0.0001474618911743164, "__label__fashion_beauty": 0.0002586841583251953, "__label__finance_business": 0.002178192138671875, "__label__food_dining": 0.0004525184631347656, "__label__games": 0.0008144378662109375, "__label__hardware": 0.0014495849609375, "__label__health": 0.0013113021850585938, "__label__history": 0.0006275177001953125, "__label__home_hobbies": 0.0001829862594604492, "__label__industrial": 0.0008559226989746094, "__label__literature": 0.0005640983581542969, "__label__politics": 0.00034117698669433594, "__label__religion": 0.0005254745483398438, "__label__science_tech": 0.356689453125, "__label__social_life": 0.0001398324966430664, "__label__software": 0.02996826171875, "__label__software_dev": 0.59716796875, "__label__sports_fitness": 0.00035762786865234375, "__label__transportation": 0.000888824462890625, "__label__travel": 0.0003204345703125}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 45235, 0.07482]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 45235, 0.37679]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 45235, 0.84256]], "google_gemma-3-12b-it_contains_pii": [[0, 224, false], [224, 314, null], [314, 314, null], [314, 1570, null], [1570, 4052, null], [4052, 6070, null], [6070, 8515, null], [8515, 11079, null], [11079, 11769, null], [11769, 14354, null], [14354, 17206, null], [17206, 19465, null], [19465, 21091, null], [21091, 23222, null], [23222, 24434, null], [24434, 25605, null], [25605, 27228, null], [27228, 28886, null], [28886, 30608, null], [30608, 32825, null], [32825, 35349, null], [35349, 36433, null], [36433, 37829, null], [37829, 37985, null], [37985, 39401, null], [39401, 40617, null], [40617, 41715, null], [41715, 43494, null], [43494, 45235, null], [45235, 45235, null]], "google_gemma-3-12b-it_is_public_document": [[0, 224, true], [224, 314, null], [314, 314, null], [314, 1570, null], [1570, 4052, null], [4052, 6070, null], [6070, 8515, null], [8515, 11079, null], [11079, 11769, null], [11769, 14354, null], [14354, 17206, null], [17206, 19465, null], [19465, 21091, null], [21091, 23222, null], [23222, 24434, null], [24434, 25605, null], [25605, 27228, null], [27228, 28886, null], [28886, 30608, null], [30608, 32825, null], [32825, 35349, null], [35349, 36433, null], [36433, 37829, null], [37829, 37985, null], [37985, 39401, null], [39401, 40617, null], [40617, 41715, null], [41715, 43494, null], [43494, 45235, null], [45235, 45235, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 45235, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 45235, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 45235, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 45235, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 45235, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 45235, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 45235, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 45235, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 45235, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 45235, null]], "pdf_page_numbers": [[0, 224, 1], [224, 314, 2], [314, 314, 3], [314, 1570, 4], [1570, 4052, 5], [4052, 6070, 6], [6070, 8515, 7], [8515, 11079, 8], [11079, 11769, 9], [11769, 14354, 10], [14354, 17206, 11], [17206, 19465, 12], [19465, 21091, 13], [21091, 23222, 14], [23222, 24434, 15], [24434, 25605, 16], [25605, 27228, 17], [27228, 28886, 18], [28886, 30608, 19], [30608, 32825, 20], [32825, 35349, 21], [35349, 36433, 22], [36433, 37829, 23], [37829, 37985, 24], [37985, 39401, 25], [39401, 40617, 26], [40617, 41715, 27], [41715, 43494, 28], [43494, 45235, 29], [45235, 45235, 30]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 45235, 0.0]]}
olmocr_science_pdfs
2024-12-07
2024-12-07
a73467323195a4ea179ba15d99166fe73ce3567f
Software Engineers’ Response to Public Crisis: Lessons Learnt from Spontaneously Building an Informative COVID-19 Dashboard Han Wang han.wang@monash.edu Faculty of Information Technology, Monash University Australia Chao Wu benyunlongwu@gmail.com Faculty of Information Technology, Monash University Australia Chunyang Chen∗ chunyang.chen@monash.edu Faculty of Information Technology, Monash University Australia Burak Turhan burak.turhan@oulu.fi Faculty of Info. Tech. and Electrical Eng., University of Oulu Finland Shiping Chen shiping.chen@data61.csiro.au Data61 CSIRO Australia Jon Whittle jon.whittle@data61.csiro.au Data61 CSIRO Australia ABSTRACT The Coronavirus disease 2019 (COVID-19) outbreak quickly spread around the world, resulting in over 240 million infections and 4 million deaths by Oct 2021. While the virus is spreading from person to person silently, fear has also been spreading around the globe. The COVID-19 information from the Australian Government is convincing but not timely or detailed, and there is much information on social networks with both facts and rumors. As software engineers, we have spontaneously and rapidly constructed a COVID-19 information dashboard aggregating reliable information semi-automatically checked from different sources for providing one-stop information sharing site about the latest status in Australia. Inspired by the John Hopkins University COVID-19 Map, our dashboard contains the case statistics, case distribution, government policy, latest news, with interactive visualization. In this paper, we present a participant’s in-person observations in which the authors acted as founders of https://covid-19-au.com/ serving more than 830K users with 14M page views since March 2020. According to our first-hand experience, we summarize 9 lessons for developers, researchers and instructors. These lessons may inspire the development, research and teaching in software engineer aspects for coping with similar public crises in the future. KEYWORDS COVID-19, information dashboard, design lessons, education Permission to make digital or hard copies of all or part of this work for personal or classroom use is granted without fee provided that copies are not made or distributed for profit or commercial advantage and that copies bear this notice and the full citation on the first page. Copyrights for components of this work owned by others than the author(s) must be honored. Abstracting with credit is permitted. To copy otherwise, or republish, to post on servers or to redistribute to lists, requires prior specific permission and/or a fee. Request permissions from permissions@acm.org. ACM Reference Format: LAY ABSTRACT The 2019 Coronavirus Disease (COVID-19) outbreak has spread rapidly around the world. By October 2021, it has caused more than 240 million infections and 4 million deaths. Although the world is acting against the virus, some information on the Internet has not been updated in time, and there are also many rumors on social media. Therefore, software engineers have developed COVID-19 information dashboards such as the Johns Hopkins University COVID-19 Map and the World Health Organization COVID-19 website to provide the public with one-stop reliable COVID-19 related information. The author has also developed a COVID-19 dashboard https://covid-19-au.com/ that provides case statistics, case distribution, government policies, latest news, and interactive visualization during the pandemic in Australia. It has been popular since March 2020 and has provided 14 million page views to more than 830,000 users. In this paper, the authors discussed how they built the COVID-19 dashboard website and how they managed a team of volunteers to help and maintain the project. More importantly, the authors summarized 9 lessons for developers, researchers and instructors based on experience. These courses may inspire them in development, research and teaching to deal with similar public crises in the future, and ultimately bring accurate information to public users more effectively. 1 INTRODUCTION Coronavirus disease 2019 (COVID-19) [85] is an infectious disease caused by severe acute respiratory syndrome coronavirus 2 (SARS-CoV-2). Since its first identification in December 2019, COVID-19 has spread globally, resulting in an ongoing pandemic. By the time we write this paper, there have been over 240 million confirmed cases and caused over 4 million lives lost in more than 192 countries and territories by Oct 2021. To avoid the transmission of the virus, over 90 governments have taken actions such as lockdowns, border closures, working from home arrangements, enforcing social distancing, which influenced over half of the world’s population [66]. The pandemic has a severe influence on society, which has also caused global economic disruptions, education interruptions, and discrimination. Under this unprecedented situation, it is usual for people to feel the urge to constantly check for the latest updates and information via government websites, news outlets, and social media. Considering that COVID-19 transmission, it is important to inform people frequently and accurately with the latest status of COVID-19, particularly in their locality. Furthermore, the information can help the public take proper actions, and also guide governments’ policy making for maintaining the community health. Therefore, there’s a need for a timely and trustworthy platform to provide stats and information on the COVID-19 virus to the public. In Australia, the federal and state governments’ public media releases every day since the beginning of the outbreak, including data of new case numbers and information on symptoms and prevention from the COVID-19 virus. However, there are some limitations with the government updates: First, Australian states report their status separately without national criteria, making the data types inconsistent for each other. There are also some conflicts between the state government data and federal government data from time to time. Second, suitable interactive data visualization is needed to display the information, rather than the current static, plain text. Third, updates are not frequent enough, i.e., once a day and at different times in each state, and many details are missing. As an alternative, social media updates COVID-19 related information more frequently with fine-grained detail, but these channels also include numerous rumours and misinformation and can sometimes spread even faster than the truth [15, 73]. Also, it’s hard to see a historical trend due to its high frequent update and limited content size. To bridge the gap and respond to this crisis, we developed a COVID-19 information dashboard1 aggregating the information from different sources with intuitive data visualizations and frequent updates for providing people with the latest and the most accurate information. Our dashboard includes the latest COVID-19 status in each state (e.g., numbers of new cases, recovery, deaths, and trend), flight search, infection map, symptoms and prevention information, and latest news and tweets (as seen in Fig 1) to address people’s information needs. To make the information more understandable, we apply different interactive data visualization techniques for different kinds of data with tables, line/bar charts, and also the advanced interactive map. There are some similar dashboards around the world (such as COVID-19 global map from JHU [76], 1Point3Acres COVID-19 tracking resource for North America [1], DX Doctor’s COVID-19 real-time report in China [19]), but our dashboard is the first one specifically targeting people in Australia with over 837K individual users and 14M page views. Through spontaneously and rapidly building this dashboard, we have accumulated much first-hand experience, including the requirement elicitation, user activity analysis, collaboratively coding and testing, and continuously releasing. Based on the challenges and the experience, we summarise 9 lessons that would be helpful for the developers, researchers, and instructors respectively. First, we discuss the usage of sensitive data, professional wording, calming user feelings, and task allocation as lessons for developers when developing the COVID-19 dashboard. Second, for the academic researchers, we talk about the lessons related to how they can elicit people’s information needs, analyse users’ interactions on different devices, and understand users’ interests in map visualizations by analysing the usage data and user feedback we collected. Third, we discuss how students can benefit from this project and how the instructors need to support the students from the perspective of software engineer instructors. The lessons aim to help software engineers better understand how to deal with the pandemic as different roles. In particular, they may guide software developers in developing similar applications for future crisis events, benefit researchers in conducting studies in this area, and inspire instructors in practical teaching about software engineering. The COVID-19 dashboard is a great example of the importance of deeply thinking through what we call human values in software design. Human values - such as inclusion, diversity, social responsibility - are things that we as a society value, but they have often been paid little attention in software engineering [60]. In the case of a dashboard presenting important data on an emerging pandemic, it is critical that the design of the system thinks through possible negative consequences - for example, presenting the information in one way versus another may influence citizens’ behaviours. The contribution of this work is summarized as follows: - This is a timely social-good project for developing a COVID-19 information dashboard within a limited time for solving information needs of the society during this global pandemic. - We document the first-hand development experience of an information dashboard for COVID-19 with great social impact on millions of people in Australia. - During the dashboard development, we distill important lessons for developers, researchers, and instructors based on our own experience, and these lessons may guide them in the software engineer area and deliver value to the public. The rest of the paper is organized as follows. Section 2 provides the background of the efforts the developers have made to fight against the pandemic, and some dashboards that have been released for the COVID-19. We introduce the dashboard characteristics, the huge impact it has made to the public, and the overall steps of how the authors developed it in section 3. In section 4, we summarize a total of 9 lessons learned during the development of the COVID-19 dashboard. We conclude our work in section 5 and discuss the improvements that could be made to the dashboard. 2 BACKGROUND Software systems increasingly impact our society. This is especially true for AI systems, which can replace humans as decision makers, but it is also true for more mundane software systems. Essentially, any software system has the potential for impact (positive or negative) on society and there is an increasing recognition that developers need to understand these impacts as part of the software design process [79]. During the COVID-19 pandemic, developers --- 1http://covid-19-au.com are mobilising around the coronavirus outbreak to find solutions to deal with the crisis using different software technologies. 2.1 Developers’ Efforts in Fighting the Virus The Information Technology community is one of the important forces in fighting with COVID-19. Various innovations and solutions ranging from contact tracing applications to data platforms were developed in response to different aspects of the pandemic. Researchers have also reviewed the proposed applications and taxonomies [10, 43, 78]. Based on our experience and the existing research, we categorised such applications into 5 types: - **Symptom Tracking** applications that analyse symptom data from suspected and confirmed patients. Governments of countries such as Australia [20], Singapore [34], and the US [13] have rolled out their Self Checkers applications to direct individuals to appropriate resources. Some governments of countries such as Iceland [39] and the UK [13] use mobile technologies to collect data on patient-reported symptoms and triangulate to reveal information like how the virus is spreading and people who might have a risk that was exposed to the virus. - **Crowd Detection** applications that reduce the risk of virus transmission by monitoring the crowd in public areas. The Californian government worked with mobile app company Foursquare to track if public areas such as beaches and parks, were getting too crowded. In Denver, the Tri-County Health Department utilised data from ad-tech startup to monitor counties where the population on average strays more than 330 feet from home [67]. In the UK, the University of Newcastle uses data generated from smart city technology such as pedestrian flow, car park occupancy, and traffic to measure social distancing during the lock-down [42]. - **Contact Tracing** applications identify and alert individuals who are close contacts of the confirmed patients. After Singapore launched the first COVID-19 contact tracing app “Trace Together” [35] in March 2020, over 47 countries [56] and territories have developed their own Contact Tracing app. Concerns and debates have arisen around the effectiveness of the software [9], privacy issues [38], and project management failures [11]. To tackle such problems, Apple and Google co-developed a joint API for contact tracing applications [2]. - **Quarantine Daily Life** applications that help users cope with their life during the pandemic. Taiwan government uses a system called eMask to imposes quotas on masks [18] to prevent hoarding. - **Quarantine Daily Life** applications that help users cope with their life during the pandemic. Taiwan government uses a system called eMask to imposes quotas on masks [18] to prevent hoarding. To help the self-employed people, financial technology professionals have created Covid Credit [30], a cloud-based tool developed with open banking technology to help people prove their income losses to the government. Microsoft’s videoconferencing tool Teams uses artificial intelligence to cut out of the users’ live photos and place them into a fixed position within a setting to create a more connected feel for the attendees [69]. Some developers even created applications that mimic office sounds [70] for users who miss working onsite. **Information Aggregation and Sharing** applications aggregate and share COVID-19 data in real-time. Many applications collect and share COVID-19 datasets, such as COVID-19 Data Hub [37], DOMO tracker [21], Our World In Data [41] and Tableau COVID-19 global data [72]. The datasets were further visualised, analysed, and broadcasted. During December 2019, an AI company had sent the warnings of the outbreak by souring news reports and airline ticketing data [51]. In Europe, free live map of border crossing times for trucks was created to help Europe’s supply chains to evaluate expected delays [68] based on traffic data. Some visualization applications [16, 32] including our dashboard focus on presenting COVID case information to help to provide a foundation for public policy decisions [25]. 2.2 Information Dashboard about COVID-19 A dashboard is a visual display of the most important information needed to achieve one or more objectives. Information was consolidated and arranged on a single screen to be monitored at a glance [29]. There is a long history of using dashboards in response to disasters such as pandemics [77], Hurricanes Katrina and Rita in the US [71] and storms in Brazil [45]. Nowadays, dashboards are widely used to effectively communicate disaster information [33] such as earthquakes [23], hurricane [24], and bushfires [36] to the public. Since the COVID-19 outbreak, the information dashboard has also been adopted for displaying the COVID-19 related information. For example, Johns Hopkins University developed a global COVID-19 dashboard [22] to display the reported cases on a daily time scale around the world. A number of similar dashboards are also developed by different entities and countries globally [1, 7, 19, 27, 5, 46, 80, 83]. Other than the case number, dashboards were found to be used to display a variety of COVID data, including a clinical trial [74], preventive measures [82], social media sentiment level [59], county vulnerability index [50], and projection [31, 52]. Academic research in various disciplines has been generated based on these publicly available data dashboards [3, 5, 46, 47, 57, 58]. However, along with the rapid emergence of various dashboards, some concerns have been raised. One research proposed the idea of “dashboard pandemic”, stating that the dashboards are a “biopolitical technology of anxiety” and prompts national states of emergency, which lacks nuanced spatial, temporal, social, and epidemiological information. Thus not adequately addressing the uneven and unjust geographies of the present [26]. An article addressed geopolitical considerations in maintaining, calling developers accountable to readers [53]. Efforts to address these issues have been made. For example, the US county-level dataset [44] covers 300 variables from demographics to climate to make the dashboards more representative. The authors developed an information dashboard\(^2\) for displaying the latest status of COVID-19 in Australia in early March 2020. Besides the basic data statistics about COVID-19, we also add some additional features such as a rich information map, flight searching with confirmed cases, manually filtered latest news and tweets, etc. As the founders of this project, we share our first-hand experience and lessons which may inspire further research on developing similar information dashboard for other emergency disasters, and new ways of education during the pandemic. 3 AU COVID-19 DASHBOARD DEVELOPMENT In this section, we introduce the project characteristics, impact, and overall development process in steps. 3.1 Project Characteristic The first COVID-19 confirmed case in Australia was identified on January 25, 2020, and the increase was relatively slow in the next month. Since the beginning of March 2020, the number of new COVID-19 cases were increasing significantly in Australia. To keep people informed and calm, we started to develop an information dashboard to report the latest COVID-19 status in Australia on March 14, 2020, with a small team of the first three authors (one product manager and two developers). We officially released our dashboard on March 16 with basic functionalities and open-sourced our project on GitHub\(^3\). It has become one of the first COVID-19 informative dashboards in Australia. With the promotion and recruitment, our team increased from 3 members to 38 active members\(^4\) and over 200 volunteers from 12 different nations, most of whom are undergraduate/postgraduate students in Australia. According to participants’ expertise, we separated them into different groups, including web development, data/information/news collection, and communication. Note that this project is nonprofit, and all participants volunteer to contribute to it. After the development, based on the existing dashboards from other countries and analysing user feedback with feature requirements and behaviors, we kept adding features to the dashboard. The information dashboard contains functionalities as below: \(^2\)https://covid-19-au.com \(^3\)https://github.com/covid-19-au/covid-19-au.github.io \(^4\)https://covid-19-au.com/about-us **Figure 2: The visiting traffic of our dashboard** - The latest number of new/total cases, death, recovery, testing in each state and territory. - Data visualisation of historical data trend. - A map of case distribution in each city or suburb. - Flight details search with confirmed cases. - Basic information about COVID-19 including symptoms, prevention, and a list of hospitals doing coronavirus testing. - Latest news from online newsgroup and tweets from the Department of Health in State Government. 3.2 Impact Our project is a social-good open-source project to keep people informed and calm during the pandemic. Since the launch of this site, it has drawn a wide range of attention across Australia. From March 17, 2020 to July 16, 2021, there have been 837,958 individual users with 14,465,574 page views, as seen in Fig. 2. There are 4,337,250 sessions, and users spend over 2.6 minutes on average in each session. Among all the visitors, 21.7% of the users are returning users, whereas the rest of them are new visitors. Most of the users (78.3%) use mobile devices to access the dashboard, whereas 19.1% of them use Desktop. Only 2.6% of the users use a tablet to visit the website. Although most users are from Australia (over 90%), there are still some of them from other 184 different countries and areas around the world. From different channels (e.g., social media, email, online survey), we received much feedback from users aged from 10 to 80, around 81% of the users feel excellent or very good about our website. The feedback includes appreciation letters, bug/error reports, and feature requests. For example, we received an appreciation letter from a Canadian user who has an immunosuppressed daughter lives in Australia: “The information that your site has provided brings my family reassurance that my daughter is in safe hands; and for that we are truly grateful.” Furthermore, there is also feedback that expressed their appreciation while requesting more features like: “Thanks for all of your hard work to keep people informed about the spread of covid-19. Seeing the data each day really helps put everything in perspective and is an effective way to reduce the fear and panic that are being spread. The only addition I could think of..." would be to include a new version of the “Cases, Deaths and Recoveries” graph but allow it to be broken down by each state.” Seeing such feedback really motivated the team to keep delivering features to the product and having a positive impact on the users. ### 3.3 An Overview of Development Process In this section, we demonstrate the development process of the dashboard. Fig 3 shows the development cycle of how we build and maintain the dashboard. Our development cycle starts with team building. As most of our team members are volunteer students, they would need to focus on their class works first and then help with the development. So we have to constantly find new members to take place for some old volunteers who need to deal with their assignments first. Then, we adopt the Agile programming cycle in order to deliver value and response to the requirements frequently [6]. The development team meets virtually online to discuss which feature to develop in the next sprint, and we only pick the tasks that are actually needed. Moreover, inside each sprint, the developers report their daily scrum online, pick tasks from Kanban, and do extensive code reviews and tests. We discuss the details of each step in the following part. **Step-1 Team Building** To develop this dashboard, we constructed a team initialised with the first three authors of this paper as founders of this project and gradually expanded to over 200 volunteers from 12 different countries (e.g., Australia, China, Vietnam, et cetera) with different expertise (e.g., IT, business, health). Most of them are enrolled students who did not know each other before this project, and all of them are working as volunteers. We split the team into three groups: the data team (data collection and update), the development team (build and test the dashboard), and the communication team (manage the social media account and communicate with end-users). Each team collaborates closely with each other and keeps producing value during the development process. **Step-2 Requirement Elicitation** Different from conventional software development, we did not have a complete list of requirements before the project development and did not have enough time for user requirement analysis before we started the development due to the rapid change of the COVID-19 pandemic. Therefore, we designed the initial version of the website with basic functions by the inspiration from other dashboards developed in the counties with earlier cases (e.g., China, Singapore) and our development experience. After building and releasing the Minimum Viable Product (MVP) version of the website, the communication team keeps collecting feature requests from public users’ comments and feedback. They then summarised the requirements and discussed with the development team to make implement plans. The plans include the new feature development and the improvements on the existing ones. **Step-3 Data Collection** Data collection is a really important step to the information dashboard. The data needs to be accurate and trustworthy. The data collection team collects the data from different resources (e.g., Government websites, online newsgroups, social media) using a semi-automatic way to make sure the information users gained from our dashboard is correct and trustworthy. The automatic crawler extracts the data from the Internet, and volunteers double-check the results, including resolving the contradictory information, identifying the reliable resources, and make sure the numbers are correct. In terms of data trustworthiness, we only use the data from country and state government official release and their official accounts on social media. And for the online newsgroups, we use the news from mainstream online newsgroups and big newsgroups in the states of Australia. We have our data sources listed here:[5] **Step-4 Data Visualization** We understand that data visualisation is not just about display raw data directly to the public. With different types of data we collected in the previous step, we add different types of data visualisations. For example, we use the heatmap to show the case density in the suburbs and states, the line chart to show the historical COVID-19 trend in Australia and the other countries. We also use other charts like pie charts, bar charts, and stacked charts to display data, i.e., the age and gender distribution for each state in Australia. **Step-5 Web Development** We develop the website with React JavaScript, code is stored at Github for code management, and the website is hosted on AWS. The development team adopts the Agile programming model. The team members pick tasks from Kanban and chat virtually through Slack channels or Zoom meetings regularly. They also chat with the data team and communications team to understand the requirement. **Step-6 Testing & Release** After the implementation of each new feature, we manually test our web applications on different devices to make sure the features work on all popular operating systems and different screen sizes. We also ask a small portion of our users to test the features and send feedback to us. After passing the tests, we release the new features immediately to meet the public needs on time. ### 4 LESSONS LEARNED IN DASHBOARD DEVELOPMENT During the rapid developments, we have made some mistakes as well as conducting some experiments with our users. We also collect and analyse the user activities to learn how they are using the COVID-19 dashboard to continuously improve the website. With our first-hand experience and theories in software development, we summarise some lessons that are highly related to the pandemic itself. Furthermore, based on our work duties (developers, researchers and instructors), we categorise the lessons into these three aspects, which should be helpful with people who work in the same areas respectively. --- we also simplified the deployment process to adapt quickly update we published the data to the website for the public to view. Besides, As seen in (a) Fig 4, the red cross icons represent the geographic visualisation, entity naming, and prioritise development tasks. Though we were aware of the error soon after the release, we corrected the number and deployed the updated version as soon as possible, we still received a number of complaints (over 20) about the wrong number which resulting in users’ confusion, panic, and disappointment of our data in the dashboard, which brought a negative influence to the dashboard. To ensure the data accuracy, we then decided to adopt a human-centered semi-automatic mechanism to collect and verify sensitive data such as statistics and news, which kept both the data accuracy and maintenance update efficiency. In our approach, we first built the crawlers to fetch the latest stats from different trustworthy sources. Then, we involved human into the loop (HITL)[81] mechanism for having members from the data team to check the data accuracy and also resolving potential data conflicts. Finally, we published the data to the website for the public to view. Besides, we also simplified the deployment process to adapt quickly update so that if any unexpected errors happen, we can respond to them quickly. In such a way, we reduce the chances that errors might happen during the data collection process. Another example is when developing the cases map, we firstly use map markers to annotate COVID-19 virus stats in each city. As seen in (a) Fig 4, the red cross icons represent the geographic location of a COVID-19 clinic, and the grey markers represent the number of confirmed cases in that suburb. However, then we received feedback from users saying one of the markers was pointed right on his farm, which he was not happy with: “You have a case marked on our farm...”. Furthermore, we also received feedback like the pointer was pointed in a national park which confused them if there was a virus case in the park. So we changed it to the (b) of Fig 4. We use the shades of red to represents confirmed cases in a certain area to avoid the ambiguous and misunderstanding. **Lesson 2: Use domain-specific terms for a clear description** In the development of such domain-specific app, it is crucial to choose professional terms rather than some random words which may cause ambiguity, confusion, and resulting in losing trust in the product. In our development experience of the COVID-19 dashboard, we once used the term “Existing Case” to describe the confirmed cases that have not recovered yet. Though all of the developers in our team can understand this well, we received much feedback asking what does the Existing Case refers to as they thought the Existing Case is identical to Confirmed Case, some even suspect that we were using fraud data. We then realized that for this kind of cases, there is a more professional term as Active Case for it. We quickly change the wording of it and add an explanation under the column to explain to the users who are still not clear about it. Furthermore, adopting correct medical terms which is both accurate and easy to understand is difficult, so we also further checked all the other words that we were using, compared them with the ones on the government Department of Health website, and consult our team members with medical backgrounds to make sure we are using the right form. **Lesson 3: keep users calm during the pandemic** The COVID-19 virus not only has a physical impact on the patients but also brings heavy mental pressure, especially to people in lockdown or quarantine. There has been an increased number of reports of depression, anxiety, and distress across a number of medical staff and the public [51]. The social distancing, the isolated policies, and the fear of health and financial situations have negatively influenced people on their mental health. When developing the COVID-19 dashboard, we learned that the increasing number of death and confirmed numbers could cause people to feel anxious and worried. In order to avoid this, developers shall also consider keeping users calm when developing such dashboards. Since knowing the facts about COVID-19 can help reduce stress [14], in the COVID-19 dashboard, we develop the information page (seen in Fig 1) that contains an instructional video of what the virus is, general information, and frequently asked questions about the COVID-19, and Australian state regulations. Furthermore, we also add a daily distractions section to the page, which includes videos, images, and news that are either fun and relaxing or motivated people during the time. **Lesson 4: Develop different features for different phases of the pandemic** We develop the features that are only needed now [17]. Since the pandemic starts with no signs and it spreads around so quickly, there is no enough time for developers to develop all the features. Also, as our communication team keeps receiving feature requests from end-users, it is important to choose which features to develop under the current circumstances. In our practice, we chose the features that are needed the most based on different phases of the pandemic which keeps the continuous development, improves the efficiency of development, and increases developers’ motivation [17]. As can be seen in Fig 5, we firstly developed a Minimum Viable Product(MVP) [64], based on the inspiration from other dashboards developed in other countries (e.g., JHU, DXY, etc). Then, we noticed that the Australian government started to release policies such as some necessary information about the virus and the regulations to the public. Moreover, some online newsgroups also had detailed news behind those numbers. So we added the news and information features right after the MVP. As the COVID-19 pandemic was getting worse, we noticed that more than 60% for the cases are related to overseas traveling[55] so we updated the related flights and cruise ship information to the dashboard. As mentioned above, we also added the daily distraction part to keep people relax and calm during the pandemic. Finally, as the increasing curve was flattened, we noticed that the pandemic in other countries was still severe, so we added the global comparison to compare the pandemic in Australia with the rest of the countries to give the users a global view of the COVID-19 pandemic. In such a way, we managed to add new features in each new development iterations and keep delivering what is needed by the users at specific periods of the pandemic. Summary of lessons for developers: Software developers play an important role in fighting COVID-19. When rapidly developing an information dashboard for future crises, they should be careful about the sensitive data to avoid society panic, use domain-specific terms to avoid confusion, keep an eye on the mental health of users as well as delivering features based on different phases of the crisis. 4.2 Lessons for Academic Researchers Apart from the development lessons shared with developers, we also collect much information about users’ interactions and feedback to our information dashboard. In this section, we explore the data we collected to distill lessons that may benefit other researchers’ study and improve the development. Lesson 5: Understand people’s information needs about COVID-19 During the development of the dashboard, we have collected user feedback and their overall usage activities through Google Analytics. By analyzing this kind of data, our platform can help other researchers and Governments better understand people’s COVID-19 information needs to which they can work to cater to. Based on the data we collected from Google Analytics which helps collect end-user behaviour of the website, we learned that except the home page, state pages like Victoria (512,413 times), New South Wales (164,192 times) and Queensland (80,125 times) are the most visited pages, which are also the top three states that have the highest confirmed case number of COVID-19 in Australia. Note that the pandemic in Victoria is especially severe compared with the rest two, which also makes its page view significantly higher compared with the others. We also collect how users interact with page components. Table 1 shows the interaction frequency with components. We can see that the most popular component in our dashboard is the Case Map, as COVID-19 is spread by human and people are most concerned with the spatial data. For data from the user feedback, it is easier to figure out their information needs compares with the analytic tools, i.e. which part of the website do they like the most, what are the features they require. By September 2020, we have received a total of 315 feedback from users. As mentioned above, over 81% of the participants feel excellent or very good about the website we build. Some other details as can be seen in Fig 6, of all the features in the dashboard, users prefer the real-time stats of the detailed state data the most. Most of the users come to express their appreciation to the dashboard and leave their feature requests or bug reports of the dashboard. We further cross-compare the data with their age and gender and find out some facts, i.e. For users older than 40, they tend to raise bugs and data errors (37% of users older than 40) whereas the younger ones are more likely to ask for new features (44% of people younger than 40) such as adding the test number and the ICU number to the state table, introducing the log scale to the line charts, adding detailed age/gender distribution, etc. The data analysis from Google Analytics and users’ feedback helps us to make a better adjustment to the dashboard in order to improve their user experience. For example, we noticed that a number of our users are using the Case Map to check the data <table> <thead> <tr> <th>Component (actions)</th> <th>Portion</th> </tr> </thead> <tbody> <tr> <td>Case Map (click, zoom, etc)</td> <td>71.7%</td> </tr> <tr> <td>Case by State (choose state)</td> <td>10.5%</td> </tr> <tr> <td>Navigation (click)</td> <td>8.2%</td> </tr> <tr> <td>Global Comparison</td> <td>7%</td> </tr> <tr> <td>News (direct to original news)</td> <td>1.5%</td> </tr> <tr> <td>Flight Search (search)</td> <td>1%</td> </tr> </tbody> </table> Table 1: Users activities data collected from Google Analytics Figure 6: Results from the feedback --- 4.2 Lessons for Academic Researchers Apart from the development lessons shared with developers, we also collect much information about users’ interactions and feedback to our information dashboard. In this section, we explore the data we collected to distill lessons that may benefit other researchers’ study and improve the development. Lesson 5: Understand people’s information needs about COVID-19 During the development of the dashboard, we have collected user feedback and their overall usage activities through Google Analytics. By analyzing this kind of data, our platform can help other researchers and Governments better understand people’s COVID-19 information needs to which they can work to cater to. Based on the data we collected from Google Analytics which helps collect end-user behaviour of the website, we learned that except the home page, state pages like Victoria (512,413 times), New South Wales (164,192 times) and Queensland (80,125 times) are the most visited pages, which are also the top three states that have the highest confirmed case number of COVID-19 in Australia. Note that the pandemic in Victoria is especially severe compared with the rest two, which also makes its page view significantly higher compared with the others. We also collect how users interact with page components. Table 1 shows the interaction frequency with components. We can see that the most popular component in our dashboard is the Case Map, as COVID-19 is spread by human and people are most concerned with the spatial data. For data from the user feedback, it is easier to figure out their information needs compares with the analytic tools, i.e. which part of the website do they like the most, what are the features they require. By September 2020, we have received a total of 315 feedback from users. As mentioned above, over 81% of the participants feel excellent or very good about the website we build. Some other details as can be seen in Fig 6, of all the features in the dashboard, users prefer the real-time stats of the detailed state data the most. Most of the users come to express their appreciation to the dashboard and leave their feature requests or bug reports of the dashboard. We further cross-compare the data with their age and gender and find out some facts, i.e. For users older than 40, they tend to raise bugs and data errors (37% of users older than 40) whereas the younger ones are more likely to ask for new features (44% of people younger than 40) such as adding the test number and the ICU number to the state table, introducing the log scale to the line charts, adding detailed age/gender distribution, etc. The data analysis from Google Analytics and users’ feedback helps us to make a better adjustment to the dashboard in order to improve their user experience. For example, we noticed that a number of our users are using the Case Map to check the data with their mobile devices (over 80% of users are mobile users), and we have also received some feedback expressed that it’s hard to interact with the map on small screens. So, we added a full-screen option to the map for users to be able to better navigate on the map (as can be seen in Fig 4 as well). We also prioritised the feature requests based on the number of them accordingly. **Lesson 6: Understand users’ different interactions on mobile and desktop devices** The interactive COVID-19 case map, as illustrated in Fig 7, has been considered to be one of the most critical parts of our dashboard according to our user feedback (as Case map in Table 1). Epidemics of emerging infectious diseases such as COVID-19 are often observed as several clusters of disease at widespread locations [75], and its transmission is more likely to occur between individuals that are in close proximity [61]. Therefore, spatial data such as confirmed case numbers in different areas are quickly disclosed and broadcast to the public. When people perceive such data, they naturally interact with it as it is easy to understand. This is one of the reasons for the case map component is popular. However, due to the complexity of the spatial data and the characteristic of this pandemic, we hope to provide more insights to researchers on how users interact with the map especially in mobile platforms, which can help with their system design in future crises. Users can interact with the map by actions including zooming, panning, and clicking. We analyzed 779,018 records of our dashboard’s map interaction logs from August 10 to September 9, 2020. These logs were further aggregated into 61,322 sessions. Among these sessions, we found that more of them were generated by mobile users than desktop users. 43,503 sessions were carried out by mobile devices, which took 70.94% of all the sessions. Moreover, there was a clear difference between the interaction patterns of the two user groups. Mobile users spent less time interacting with the map. A mobile session’s average duration was 41.57 seconds, while it was 94.61 seconds for a desktop user. Correspondingly, mobile users generated fewer activities. Their average number of activities per session was 11.57 times, which was 25% less than desktop users. The reason might be that it was hard for mobile users to carry out complicated gesture actions on the small screen than desktop users with a mouse or touchpad. Navigation took up the majority of all the activities. As indicated in Fig 8, mobile users and desktop users spent 95.59% and 86.99% of their activities respectively on zooming and panning. After users locate an area, they can click on it to see the detail. Mobile sessions had a 0.51 average click volume, which means that only 50% of them click on any of the tiles. In comparison, desktop sessions had 2 average clicks. Most users were not enthusiastic about finding the tile detail, including history numbers and trends. 85.91% of all the map sessions had not clicked any tile on the map. However, when calculating the sessions with at least one click recorded, we found that those sessions had 4.2 clicks on average. This indicates that those who want to explore the details tend to select multiple places inside one session. **Lesson 7: Understand users’ interests in the map** Apart from the interactions, researchers can further tell users’ interest areas on the map by mining different interaction records. The results may help the Government make the policies accordingly, understand one area’s mental stress, etc. From the data we collected from the case map, we find that the hot area in the map is proportional to the number of active cases in the areas. Refer to Table 2, of all the 8 Australian states showing on the map the most clicked one is Victoria, which is the state that also has 74% of all the cases in Australia by October 2020. The Local Government Area (LGA) level data shows the same pattern. The most clicked tile is Wyndham Victoria, which has the most COVID-19 cases among all the other LGA areas. Out of the 14,168 sessions that recorded a click, 71.2% of them clicked on a tile that is 50km away from their IP locations, which indicates apart from where they are based, the users are also interested in the situation outside the place they live in or work at. This reveals that users show more interest in the hot spot area with more case numbers regardless they are the residents or not. Another factor leading to the hot area is not related to the COVID-19 case number, but the size of that area. The Northern Territory State is of the least cases and least population among all the other states in Australia, but it attracted more clicks than Tasmania and Australian Capital Territory because it is the third-largest state in Australia in size. It is 15.6 times larger than Tasmania and 602 times larger than the Australian Capital Territory. A similar situation happens in clicks on LGA level data too. Take the second most clicked LGA area, Yarra Ranges Victoria as an example. Compare to the Wyndham (the most clicked LGA with the highest confirmed number), Yarra Ranges has 90% confirmed cases less than Wyndham, but is more than 4 times larger than it. Fig 9 shows the clicks on Wyndham and Yarra Ranges, the red layers represent the confirmed case numbers, whereas the green represents the click numbers. The darker the color is, the higher numbers it has. So the larger area gets a higher chance to be clicked. The website also offers several data layer options for users to choose from (top left corner of Fig 7), i.e., active case, total case, total deaths, etc. However, only a few users appeared to have selected them. Excepting the default layer "active cases" which was designed to be displayed for every session, the 4 most displayed layers (total cases, new cases, recovered number and death number) took 11% of all sessions. A similar pattern was found in the history data periods filter and history data slider as well. Most sessions were not related to either of those functions. **Summary of lessons for researchers**: By analyzing users’ interactions and feedback to our information dashboard, we find that users always want to see more types of data and visualizations, they are interested in interact with case map the most, desktop users interact more compare with mobile device users, and they tend to focus on the area with high confirmed case numbers, etc. The conclusion may help other researchers understand people during the pandemic and decision-makers in the government to design their policies. ### 4.3 Lessons for Software Engineering Instructors Our dashboard is an open-source project initiated by Software Engineer (SE) instructors and run by volunteers, mainly university students. This section summarized the participants’ experiences and listed several suggestions that may help SE instructors teach software engineering principles and concepts during the pandemic through project-based learning. **Lesson 8: Students benefit from software engineering project-based learning in the pandemic** Although research shows that university students experienced heterogeneous disruptions during the pandemic [4, 12, 48], our volunteers unanimously expressed that participating in the project is a beneficial experience. One of the benefits is that participating in such projects prepares them for their future career. Many participants revealed the gap between the industry requirement and skill they acquired from tertiary education [62]. By participating in the project, they get a chance to apply their SE principles and knowledge to a real-world project. Our project is authentic, larger in scale, and more agile in pace compared to the capstone projects they were assigned from regular university courses. The site’s development can be traced through its GitHub repository7. There were 29 contributors submitted 604 pull requests with 2921 commits in 206 days, which is approximately 14 commits per day. The two peaks of the commit volumes are aligned with the two waves of outbreaks in Victoria Australia, where the majority of the developers based. The commits were mainly submitted during the night, 62% of the commits were submitted between 20:00 and 00:00 (GMT+11), as most of the major updates are deployed at night. The manual website updates last from morning to night, volunteers work in pair on shifts to submit and review data. The communication team runs multiple social media accounts, posts live data and write blogs to keep the public informed. Being able to work with a big community closely is another benefit. It helps the students cope with the social distancing and lockdown, by providing a sense of belonging and equipping them with useful soft skills, especially the communication and cooperation skills in the large development team. In the project, over 200 members communicate closely to plan, implement, test, and maintain the dashboard to keep it abreast of the pandemic via slack across 13 different channels as per Fig 10. The discussions are mainly work-related. We applied the Latent Dirichlet Allocation(LDA) [5] algorithm to all the chatting records and discovered the most frequently discussed topics are the data collection (includes news and case numbers), web page design, page testing, and requirements discussions. Therefore, instructors can use such a project-based learning approach to teach software engineering students under the epidemic allows students to collaborate within a large development group, and better understand the software development life cycle. **Lesson 9: Support students through the project process in the pandemic** We conducted with another research group, students stated that we believe that instructors can provide assistance in the following 16% of them. This shows the instructor’s attempt to use a positive has a 28% higher sentiment level than the ordinary members. Of overwhelming. An AFINN word list test shows the instructor analysis to the Slack messages to see the atmosphere in our project pressure to the participants who are closely following it, which do much during the pandemic apart from passively quarantined at home. However, the rapidly developing pandemic keeps causing the volunteer team is enlarged in size is because of the instructors’. Based our slack member analysis (Fig 11), we find that every time the instructor plays a role as the project manager. After completing the initial organization and helping the groups break the ice, the instructor guided the three student teams to independently arrange their rosters, schedule regular meetings, manage tasks and approach users. As a result, all the teams accomplished their works successfully and kept bringing values to the dashboard website. In a survey conducted with another research group, students stated that both their technical and non-technical skills grew after participating in this project. The most significant growth from these two categories are front-end development (34%) and working online skills (31%). A number of the participants also mentions other skills like UI/UX (32%), promotion (30%), and time management (24%). Instructors’ promotion can also help with the team building. Based our slack member analysis (Fig 11), we find that every time the volunteer team is enlarged in size is because of the instructors’ help includes posts on the university website, Information Technology department newsletter, and class promotion. Many of the students revealed that they would not know they could participate into the project without such promotions, and they are grateful for this. The sense of contributing to a great cause is the students’ largest motivation, according to the student volunteers. Some explained that the project relieved them from powerless for not being able to do much during the pandemic apart from passively quarantined at home. However, the rapidly developing pandemic keeps causing pressure to the participants who are closely following it, which requires awareness from the instructors. We applied sentiment analysis to the Slack messages to see the atmosphere in our project and our instructor’s strategy to keep members motivated while not overwhelming. An AFINN word list test shows the instructor has a 28% higher sentiment level than the ordinary members. Of all the Emojis in all the chatting history, the instructor alone sent 16% of them. This shows the instructor’s attempt to use a positive attitude to motivate the group. Such efforts provide a friendly and encouraging atmosphere, which reduces the stress for students. Furthermore, we observed that the instructor is the most responsive to all the members’ questions and achievements. This prevents the question owner’s anxiety from building up while making people feel appreciated. **Summary of lessons for software engineering instructors** The COVID-19 pandemic is changing the landscape of higher education, and instructors will have to adopt new ways to help students solve their challenges and create programs that are better suited for remote learning. Our experience has shown that organizing an open-source social-good software projects like ours is an good way for instructors to help students mitigate disruptive effects during the COVID-19 pandemic. By creating a positive environment and providing prompt support and feedback, instructors can help students gain experience and improve their skills, thus enhancing their motivation during development. ### 5 CONCLUSION AND FUTURE WORK In this project, we essentially followed an iterative process of understanding the users’ values as the project emerged. We share our experiences on the development of COVID-19 Information Dashboard. Most importantly, we summarize 9 lessons for developers, researchers, and software engineer instructors, which may help them with their works and further benefit the society. Many of the lesson descriptions in this paper are about taking into account a particular human value during design. For example, lesson 3 concerns being sensitive to adverse physiological reactions in users because of the way data is presented. In an ideal world, the relevant values for an application would be uncovered upfront during requirements engineering. However, this is difficult in practice and a more iterative approach is required, as followed in this paper. Research shows that software engineers do not naturally think about human values during development [40] and so the work here presents a case study from which useful insights may be drawn on how to properly understand and design for human values as the three roles a software engineer can be. In the future, we are going to further explore the project in two directions. On the one hand, we will further improve our site following the requirements from the public users and sharing more valuable data and experience with developers, researchers, and instructors. On the other hand, we will try to abstract our existing project into a general template that can be adapted to other emergency disasters like bush fire, flood, etc. We plan to release that template into an open-source platform for the community. ### REFERENCES [70] Spatial analysis in epidemiology. Veterinary Record 156, 8 (2005), 229–252.
{"Source-Url": "https://arxiv-export-lb.library.cornell.edu/pdf/2204.08674", "len_cl100k_base": 11306, "olmocr-version": "0.1.53", "pdf-total-pages": 12, "total-fallback-pages": 0, "total-input-tokens": 38935, "total-output-tokens": 17912, "length": "2e13", "weborganizer": {"__label__adult": 0.0013790130615234375, "__label__art_design": 0.004058837890625, "__label__crime_law": 0.0016956329345703125, "__label__education_jobs": 0.06243896484375, "__label__entertainment": 0.0006103515625, "__label__fashion_beauty": 0.0008339881896972656, "__label__finance_business": 0.0025196075439453125, "__label__food_dining": 0.001852989196777344, "__label__games": 0.00289154052734375, "__label__hardware": 0.0020847320556640625, "__label__health": 0.0187530517578125, "__label__history": 0.0012903213500976562, "__label__home_hobbies": 0.0008482933044433594, "__label__industrial": 0.0008673667907714844, "__label__literature": 0.0017957687377929688, "__label__politics": 0.002101898193359375, "__label__religion": 0.0011072158813476562, "__label__science_tech": 0.08770751953125, "__label__social_life": 0.0016183853149414062, "__label__software": 0.043426513671875, "__label__software_dev": 0.7578125, "__label__sports_fitness": 0.0006947517395019531, "__label__transportation": 0.0008640289306640625, "__label__travel": 0.000942707061767578}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 73576, 0.04456]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 73576, 0.32221]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 73576, 0.92525]], "google_gemma-3-12b-it_contains_pii": [[0, 5006, false], [5006, 11823, null], [11823, 17070, null], [17070, 22563, null], [22563, 28522, null], [28522, 34183, null], [34183, 41826, null], [41826, 46726, null], [46726, 51611, null], [51611, 57581, null], [57581, 65436, null], [65436, 73576, null]], "google_gemma-3-12b-it_is_public_document": [[0, 5006, true], [5006, 11823, null], [11823, 17070, null], [17070, 22563, null], [22563, 28522, null], [28522, 34183, null], [34183, 41826, null], [41826, 46726, null], [46726, 51611, null], [51611, 57581, null], [57581, 65436, null], [65436, 73576, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 73576, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 73576, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 73576, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 73576, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 73576, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 73576, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 73576, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 73576, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 73576, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 73576, null]], "pdf_page_numbers": [[0, 5006, 1], [5006, 11823, 2], [11823, 17070, 3], [17070, 22563, 4], [22563, 28522, 5], [28522, 34183, 6], [34183, 41826, 7], [41826, 46726, 8], [46726, 51611, 9], [51611, 57581, 10], [57581, 65436, 11], [65436, 73576, 12]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 73576, 0.03125]]}
olmocr_science_pdfs
2024-12-09
2024-12-09
c545af05de2edcc6768e5e21d0f8fdfb41849201
Haren: A Framework for Ad-Hoc Thread Scheduling Policies for Data Streaming Applications Downloaded from: https://research.chalmers.se, 2022-09-18 06:07 UTC Citation for the original published paper (version of record): N.B. When citing this work, cite the original published paper. Haren: A Framework for Ad-Hoc Thread Scheduling Policies for Data Streaming Applications Dimitris Palyvos-Giannas Chalmers University of Technology Gothenburg, Sweden palyvos@chalmers.se Vincenzo Gulisano Chalmers University of Technology Gothenburg, Sweden vinmas@chalmers.se Marina Papatriantafilou Chalmers University of Technology Gothenburg, Sweden prioranta@chalmers.se ABSTRACT In modern Stream Processing Engines (SPEs), numerous diverse applications, which can differ in aspects such as cost, criticality or latency sensitivity, can co-exist in the same computing node. When these differences need to be considered to control the performance of each application, custom scheduling of operators to threads is of key importance (e.g., when a smart vehicle needs to ensure that safety-critical applications always have access to computational power, while other applications are given lower, variable priorities). Many solutions have been proposed regarding schedulers that allocate threads to operators to optimize specific metrics (e.g., latency) but there is still lack of a tool that allows arbitrarily complex scheduling strategies to be seamlessly plugged on top of an SPE. We propose Haren to fill this gap. More specifically, we (1) formalize the thread scheduling problem in stream processing in a general way, allowing to define ad-hoc scheduling policies, (2) identify the bottlenecks and the opportunities of scheduling in stream processing, (3) distill a compact interface to connect Haren with SPEs, enabling rapid testing of various scheduling policies, (4) illustrate the usability of the framework by integrating it into an actual SPE and (5) provide a thorough evaluation. As we show, Haren makes it is possible to adapt the use of computational resources over time to meet the goals of a variety of scheduling policies. CCS CONCEPTS - Information systems → Online analytical processing engines; - Software and its engineering → Scheduling; Middleware. KEYWORDS Stream processing, Scheduling, Middleware 1 INTRODUCTION Data streaming is leveraged in applications dealing with heterogeneous data sources, variable input rates (and data distributions) as well as heterogeneous hardware (ranging from high-end servers to embedded edge devices). Stream Processing Engines (SPEs), the platforms running streaming queries (or simply queries), deploy the latter’s operators to multiple SPE instances (i.e., processes) existing within or across multiple computational nodes. In this context, resource scheduling [3, 13, 27–29] chooses how and to which SPE instances to deploy queries’ operators while thread scheduling, our focus, chooses how to allocate an SPE instance’s threads to the operators deployed to it to meet specific performance goals. Many related works have shown that custom thread scheduling (or simply scheduling) can reach better performance (e.g., lower processing latency) than that achieved when SPEs instantiate per-operator threads [7, 12, 24] which are scheduled by the Operating System (OS) [9]. Existing solutions discuss nonetheless specific scheduling policies (in combination with certain SPEs), without considering how to express the scheduling goals of a policy without the need to code its logic within an SPE. This observation forms the basis of our work, which aims at identifying and generalizing the logic of a general scheduler that can encapsulate existing policies while decoupling its internals from those of an SPE. Thus, our research question is the following: Is it possible to define an all-purpose SPE scheduling framework, which (i) allows the user to easily plug-in custom scheduling policies, (ii) transparently enforces those policies at runtime and (iii) requires minimal programming effort? These requirements can be crucial, especially in large cyber-physical systems (such as smart grids and vehicular networks) in which users and analysts can continuously deploy applications of different criticality, priority or latency sensitivity [19, 23] and SPEs themselves can perform adaptive live reconfigurations (e.g., operator fusion and fission [11]) to adjust resources to query loads and costs. We provide an affirmative answer and present Haren, a general tool which can be used in combination with an SPE with minimal modifications. We evaluate it in combination with Liebre, a lightweight SPE for edge-computing [14]. In summary, we make the following contributions: - We distill a compact set of primitives that can encapsulate the logic of the most common scheduling policies proposed in the literature, allowing users to define scheduling semantics without the need for altering the internals of the SPE. - Together with these primitives, we define the facilities that the SPE needs to provide for custom scheduling to happen. - We design and implement a framework that leverages such primitives in a lightweight fashion without dedicated threads but by sharing the job among threads running the analysis. 2 PRELIMINARIES Streams & Operators. A stream is an unbounded sequence of tuples sharing a schema composed by attributes \( \langle a_1, \ldots, a_n \rangle \). A query is a DAG of operators connected by streams. External data sources generate tuples to be processed by the operators of the query. These tuples, which are referred to as ingress tuples, are delivered to queries by Ingress operators (also called Sources or Spouts [7, 12, 24]), are pushed through the rest of the operators of the query, possibly resulting in new tuples, and are eventually delivered as egress tuples to Egress operators (also called Sinks [7]), which forward them to users or other applications. Streaming operators define at least one input stream and one output stream. The only exceptions are Ingress, which has no input and a single output stream, and Egress, which has one input but no output streams. The output tuples of an operator that are waiting to be processed by another operator connected to it are maintained in a queue shared between the two. Clock time attribute. We assume that, apart from the user-defined attributes, all tuples carry a clock time \( ta \) attribute\(^1\). This attribute carries the clock time at the moment in which the tuple is forwarded by the Data Source producing it\(^2\). If a tuple \( t \) is created by an operator of the query, its clock time is set to the respective value of the latest input tuple triggering the creation of \( t \) at the operator. By extension, each tuple \( t \) that is not an ingress tuple carries the clock time of the latest ingress tuple triggering its creation. Sample Query. Figure 1 presents a sample query composed by two operators (plus one Ingress and one Egress). For each input tuple, operator \( op_1 \) creates an output tuple carrying the same \( ta \) attribute of the input tuple plus an attribute \( c \) for the sum of \( a \) and \( b \). Operator \( op_2 \) produces tuples carrying, for each fixed window \([2]\) of 10 minutes, the attribute \( ta \) of the latest tuple contributing to the window, the attribute \( d \) containing the maximum value of \( c \) observed in the window and the attribute \( w \), to specify the start time of the window. The figure also shows the tuples currently present in each queue. Since attribute \( ta \) is set for each output tuple created by an operator to the value of the latest input tuple contributing to such output tuple, it can be observed that all the tuples in a queue of a particular operator have \( ta \) values that are smaller than or equal to those of the latter’s input queues. We use in the remainder the terms upstream and downstream peers to refer to the operators preceding and following an operator, respectively (e.g., \( op_1 \) is the upstream peer of \( op_2 \) while \( op_2 \) is the downstream peer of \( op_1 \)). Scheduling. An SPE instance running a set of operators (from one or more queries) has access to one or more CPU cores (mapped to hardware threads). In our work, scheduling refers to the process of periodically deciding which operators (possibly of different queries) should be run and in which order, within an SPE instance. A scheduled operator runs its code inside a hardware thread. At any moment, an operator can be run by at most one thread. A challenge in scheduling streaming operators is that, because of the varying rates and data distribution of data sources (which in turn affect the rates, data distribution and behavior of the queries’ operators), scheduling policies cannot be defined statically at compile time, but need to be continuously refined over time. The goal of custom scheduling for SPE instances is to control the performance characteristics of the queries. We quantify the performance of one or multiple queries as follows. Starting from the operator level, we quantify its performance over a period of time with the following metrics: 1. (1) Throughput, the number of tuples processed by the operator. 2. (2) Latency, the average clock time elapsed in between the operator’s processing of each tuple \( t \) and \( t \)’s clock time (i.e., the clock time of the latest ingress tuple triggering the production of \( t \)). 3. (3) CPU Utilization, the average CPU utilization (\%) of the operator. 4. (4) Memory Cost, the maximum amount of memory consumed by the tuples maintained in the operator’s input queues. Extending the performance characterization from operators to whole queries, we define (i) the query throughput as the average throughput of the query’s Ingress operators, (ii) the mean and max query latency as the average and maximum latency observed at its Egress operators, respectively, (iii) the CPU utilization as the sum of the CPU utilization of the query’s operators, and (iv) the memory cost as the sum of the memory costs of all the operators of the query. These definitions can be extended to multiple queries by means of the sums, averages, and maximums of all their operators. It should be noticed that these performance metrics depend on multiple aspects such as (i) the scheduling decisions, (ii) the arrival pattern of the incoming data, as well as (iii) the data distribution of the input values. For example, both the throughput as well as the memory cost depend on the CPU time allocated for a certain operator as well as the rate of the data source(s). With respect to the example of Figure 1, one can observe that (i) given the tuples currently stored in the operators’ queues and (ii) assuming that the next scheduled operator can process all its shown input tuples, the scheduling choice would depend on the desired performance metric. More concretely, scheduling the Egress operator would minimize the query’s latency, scheduling operator \( op_1 \) would minimize the overall memory used while scheduling the Ingress operator would maximize the query’s throughput. 3 GOALS AND SYSTEM MODEL We aim at designing and implementing a general purpose scheduling framework that allows users to define ad-hoc scheduling policies. More concretely, we want to allocate the threads of an SPE instance in a streaming-application-aware fashion that can meet --- \(^1\)Clock time is sometimes referred to as arrival time in the literature [6]. If the data source is generating (and not replaying) the data, clock time is equal to event time [2]. \(^2\)We assume that clocks of Data Sources and the processing node are synchronized with a time synchronization protocol such as NTP. complementary and richer performance goals than those enabled by the OS itself. Hence, we focus our study on a thread scheduling framework and assume that one or more query operators are deployed to a single SPE instance, where Haren also runs. Our goal is to shape Haren as a component (accessible to both the user and the SPE) that sits in-between the OS and the SPE. On the one hand, Haren should expose an interface that allows users to deploy queries and define scheduling policies, as well as SPEs themselves to perform adaptive runtime reconfigurations (e.g., operator fusion or fission [11]). At the same time, Haren should also orchestrate the execution of the SPE and retrieve over time any information needed from the SPE to enforce the user-defined scheduling policies. In summary, Haren’s aims at: G1 Distilling a compact interface for a scheduling middleware that can implement user-defined scheduling policies that optimize performance metrics agnostic to the OS (e.g., throughput, latency or memory utilization, among others). G2 Allowing the implementation of custom, user-defined rules for both inter-thread scheduling (i.e., specifying the assignment of operators to threads) and intra-thread scheduling (i.e., specifying the scheduling of operators within each thread). G3 Distributing and sharing scheduling overheads among available physical threads to take advantage of multi-core nodes. 3.1 System model Tuples, operators, and queries have various features that characterize their behavior and state. A general-purpose scheduling framework must be aware of the changing nature of these features to make informed decisions and orchestrate the execution of queries’ operators according to a user-defined scheduling policy. Not all features are equal in terms of how they change and in terms of how their changes can be observed. A first distinction can be made between static features (e.g., the type of an operator) and dynamic ones (e.g., the selectivity of an operator, which depends among other things on the data being fed to it). A second distinction can be made between features that are immediately derived from an operator (e.g., its number of input streams) and features that are derived from the input/output queues of an operator and/or the tuples maintained in such queues (e.g., the clock time of the earliest tuple (in the operator’s input queues)). This second distinction is crucial because it results in two critical observations. First, certain features can change over time independently of whether the operator is scheduled or not. This is the case, for instance, for the earliest clock time of any tuple in the input queues of an operator, given that it could change if any of its upstream operators are scheduled. Second, it might not be possible to update particular features of some operators unless these operators are executed (e.g., the average time needed by an operator to process one tuple, also referred to as the cost of an operator). Based on these observations, we introduce the following definitions. Definition 3.1. A feature $F$ of operator $o_i$ is independent if it can change only upon execution of $o_i$. Definition 3.2. An operator $o_j$ is feature-dependent on operator $o_i$ for feature $F$ if $F$ for $o_j$ can change upon execution of $o_i$. Definition 3.3. A feature $F$ of operator $o_i$ is dependent if it can change upon execution of $o_i$ as well as operators on which $o_i$ is feature-dependent. Definition 3.4. A feature $F$ of operator $o_i$ is execution-intrinsic if it can be updated only upon execution of $o_i$. Since operators, queues and tuples are accessed by the SPE, we assume the latter provides an interface (such as a metrics system [7, 12]) for Haren to retrieve up-to-date feature values. Although the features used by Haren can be arbitrarily complex, to keep the discussion tractable, we will focus on a specific set of them. These features, presented in Table 1, are required to implement most of the scheduling policies proposed in the literature, including the policies we later use in our evaluation. The table displays features along with their abbreviated id and type. For brevity, we do not include static features that can be trivially computed, such as the operator type. As aforementioned, the cost is the average time spent by an operator to process a single input tuple. The selectivity defines the average number of output tuples produced per processed input tuple. Observe that it can be higher than 1 for operators that generate multiple output tuples for every input tuple (e.g., an operator that splits a sentence into words). Cost and selectivity are used in many scheduling policies, to optimize for different metrics <table> <thead> <tr> <th>ID</th> <th>Feature</th> <th>Type</th> </tr> </thead> <tbody> <tr> <td>$c$</td> <td>Cost</td> <td>Dynamic, independent, execution-intrinsic</td> </tr> <tr> <td>$s$</td> <td>Selectivity</td> <td>Dynamic (except for Egress operators), independent, execution-intrinsic</td> </tr> <tr> <td>$t_h$</td> <td>Head clock time</td> <td>Dynamic, dependent on upstream and downstream peers, execution-intrinsic for Ingress operators</td> </tr> </tbody> </table> Table 1: Table of features considered in the paper. such as the average latency or the memory cost of the queries [23]. The *head clock time* is the earliest clock time of the tuples at the head of the input streams of an operator. This feature is also used in various scheduling policies (e.g., to optimize the maximum latency of a query based on its operators head latency, which is derived from their head clock time [6]). We assume in the remainder that the SPE instance has \( K \) active CPU cores which correspond to hardware Processing Threads (PTs). We refer to the \( i \)-th processing thread as \( PT_i \) \( i \in \{1, \ldots, K\} \) and to the \( i \)-th operator of the \( j \)-th query as \( op_j^i \) (but omit the query number if it is not essential for the discussion). 4 OVERVIEW Streaming applications have a live and changing nature, with vary- ing input stream rates and data distributions. In order to correctly enforce a scheduling policy, features and priorities that change over time need to be periodically updated. Since changes in features can depend on scheduling decisions (see § 3), information about scheduling decisions must also be collected over time. Figure 2 shows the two main tasks executed by Haren’s PTs, namely execution (\( T_E \)) and scheduling (\( T_S \)). PTs run task \( T_E \) during the majority of the time and switch periodically to task \( T_S \). These tasks isolate the portions of time during which scheduling information is gathered for priority updates (i.e., when PTs must synchronize) from those during which PTs can be dedicated to run- ing the operators deployed to the SPE instance. The separate tasks give fine-grained control over the scheduling overhead, which is proportional to the time spent gathering information about sched- uled operators and updating features and priorities. As stated in § 3, we aim at distributing and sharing the sched- uling overhead among all PTs (Goal G3). Because of this, Haren parallelizes the costly parts of \( T_S \) and lets all PTs (in a random fash- ion) take care of the portions of \( T_S \) that can be run more efficiently in a sequential fashion. We overview in the following tasks \( T_E \) and \( T_S \) and refer the reader to § 5 and § 6 for more detailed descriptions. ![Figure 2: Alternation of \( T_E \) (execution task) and \( T_S \) (scheduling task) during the runtime execution of Haren.](image) **Task \( T_E \):** PTs schedule operators (with the computed priorities). **Task \( T_S \):** PTs coordinate and take scheduling decisions for the next \( T_E \). **LEGEND:** - \( \square \) Parallel portion of \( T_S \) - \( \square \) Sequential portion of \( T_S \) The previous \( T_E \). In § 3, we distinguished features into independent and dependent (Definition 3.1 and Definition 3.3). Although it is easy for a PT to detect if an independent feature of its operators needs to be updated, the same is not true for dependent features, because such features might depend on the actions of multiple PTs. Haren reduces overheads by defining a sequential portion of \( T_S \) in which exactly one PT (chosen randomly) updates all the de- pendent features that have potentially changed and, subsequently, distributes the operators to all PTs. Then, each PT, in parallel, computes priorities for its operators and sorts these operators based on the recently updated priorities, concluding \( T_S \). Note that an operator might be assigned to different PTs in distinct executions of \( T_S \). To prevent situations where two PTs try to execute the same operator at the same time (see § 2), the sequential portion of \( T_S \) also acts as a barrier that marks, for all PTs, the end of the current \( T_E \) and the beginning of the next. For the same reason, no operator is executed during \( T_S \). 4.1 Inter-thread and intra-thread scheduling Since SPE instances can run on multiple threads, Haren allows users to specify how to (i) assign operators to PTs and (ii) decide the order with which each PT should schedule the operators assigned to it. It does this by means of an *inter-thread* scheduling function \( f \) and an *intra-thread* scheduling function \( g \). \( F \) being the set of available features and \( O \) the set of operators deployed to the SPE instance, we define these functions as follows. The *inter-thread scheduling function* \( f: R^{|F| \times |O|} \rightarrow \{1, \ldots, K\} \) identifies which PT should execute which operator, for all the operators deployed to the SPE instance. Note that, when computing which PT should be in charge of executing a certain operator, the features of all the operators deployed to the SPE instance are given as input to \( f \). Thus, \( f \) can be used to implement both simple thread assignment policies (e.g., assign the operators of queries to PTs in a round-robin fashion), as well as much more complex ones (e.g., assign operators so that the load is equal for all the PTs). The *intra-thread scheduling function* \( g: R^{F \times |O|} \rightarrow R^D \) maps the features of operator \( op_i \) to a \( D \)-dimensional priority vector \( p_i = (p_{i1}, p_{i2}, \ldots, p_{iD}) \). Also in this case, the features of all operators deployed to the SPE instance are input to \( g \) when computing the priority of each operator. Each element of the priority vector reflects a priority dimension. The execution of operators is priori- titized based on a lexicographic sorting of their priority vectors. For example, a possible priority vector might describe two dimen- sions (queryClass, cost) (each computed based on the operators’ features). In this case, operators with higher queryClass would be scheduled before others with lower queryClass, while operators with equal queryClass would be scheduled according to their cost. 4.2 Architecture Figure 3 shows the APIs coupling an SPE instance with Haren, used by the latter to schedule the operators deployed to the former. The user interested in running a set of operators belonging to queries \( Q_1, Q_2, \ldots \) with a particular scheduling policy can invoke the SPE’s deploy function\(^3\) and pass the queries’ operators to be executed. She also initializes Haren with the inter-thread and the intra-thread scheduling functions \(f\) and \(g\) and the runtime parameters \(P, b\) and \(d\) (described in the figure). For simplicity and without loss of generality, the figure and our following discussion focus on a single SPE instance. When the queries’ operators are deployed to either one or multiple SPE instances (see § 1), each SPE instance is coupled with one instance of Haren. The SPE instance notifies the associated Haren instance of the new deployment by calling update. Internally, Haren inspects the queries in order to identify the set \(O\) of operators to be scheduled (and their interconnections) at the coupled SPE instance. Once Haren identifies the set \(F\) of features used by \(f\) and \(g\), Haren’s PTs schedule the execution of the operators. This is done by invoking: - **SPE.run(i, j, b)**, to run \(op_i^j\), specifying \(b\) as the maximum number of tuples it can process during the function invocation (we refer to § 5 for more details about the role of \(b\) in scheduling). - **SPE.getFeature(i, j, F)**, to retrieve feature \(F\) for \(op_i^j\). The SPE instance can also invoke the function update when, due to runtime reconfigurations (e.g., operator fusion or fission [11]), the list of operators scheduled by Haren changes. ![Diagram](image) Figure 3: APIs coupling Haren, the user and the SPE instance. ### 5 EXECUTION TASK (\(T_E\)) In this section, we provide a detailed description of the actions performed by PTs during \(T_E\). More concretely, we discuss (i) how each PT chooses the next operator to run, (ii) how it backs-off if there is no operator to be scheduled, and (iii) how it takes care of running operators for which execution-intrinsic features (Definition 3.4) have not been updated for more than the user-defined \(d\) time units. The different variables accessed by each PT are presented in Table 2 while the main loop is shown in Algorithm 1. List \(A\) contains the operators assigned to each PT at the end of the previous \(T_S\) task. Before the first execution of \(T_S\), all operators are given the same priority and assigned randomly to PTs. This also applies for operators added, removed or changed at runtime due to adaptive reconfigurations triggered by SPE instances (their assignment to threads and priorities are then updated during the first \(T_S\) following the reconfiguration). Each PT traverses \(A\) until it finds the operator with the highest priority that can run, or until it reaches the end of \(A\) (lines 5-13). Here, we remind the reader that an operator can generally run (i) if <table> <thead> <tr> <th>ID</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td>(A)</td> <td>List with the operators assigned to the PT.</td> </tr> <tr> <td>(E)</td> <td>Set that contains the operators that were executed by the PT at least once during the last (T_E).</td> </tr> </tbody> </table> <table> <thead> <tr> <th>ID</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td>(LU)</td> <td>Array of size (</td> </tr> </tbody> </table> Here, we remind the reader that an operator can generally run (i) if ![Algorithm](algorithm) **Algorithm 1: Main loop of PT – \(T_E\)** 1. \(t_f \leftarrow \text{now}()\) 2. while true do 3. \(op^* \leftarrow \emptyset\) 4. run \(\leftarrow\) false 5. for \(op_i^j \in A\) do 6. if \((op^* \neq \emptyset \land g(op^*) > g(op_i^j)) \lor (\text{now}() - t_f > P)\) then 7. \(\text{break}\) 8. if \(\text{SPE.canRun}(i, j)\) then 9. \(\text{SPE.run}(i, j, b)\) 10. \(LU_i \leftarrow \text{time}()\) 11. \(E \leftarrow E \cup op_i^j\) 12. run \(\leftarrow\) true 13. end if 14. end if 15. end for 16. \(\text{backoff}()\) 17. if \((\text{now}() - t_f > P)\) then 18. // PT enters \(T_S\) 19. Haren.update() // Algorithm 2 20. // PT leaves \(T_S\) 21. \(t_f \leftarrow \text{now}()\) 22. // Run delayed operators 23. for \(op_i^j \in A\) do 24. if \((t_f - LU_i > d)\) then 25. \(\text{SPE.run}(i, j, b)\) 26. \(LU_i \leftarrow \text{time}()\) 27. \(E \leftarrow E \cup op_i^j\) 28. end if 29. end for 30. end if ![Table](table) **Table 2: Variables used during \(T_E\).** \[ \text{ID} \quad \text{Description} \] \[ \hline \] \[ A \quad \text{List with the operators assigned to the PT.} \] \[ E \quad \text{Set that contains the operators that were executed by the PT at least once during the last} \ T_E. \] \[ \text{Shared variables} \] \[ LU \quad \text{Array of size} \ |O| . \ LU_i \text{is the latest timestamp when an operator was executed.} \] it has tuples in its input queues as well as (ii) free space in its output queues (function SPE.canRun, line 9). If such an operator is found, it is executed and allowed to process at most $b$ tuples, where $b$ is one of the user-defined parameters (§ 4.2) which we refer to as batch size. Subsequently, the next operator in $A$ is scheduled only if (i) it has the same priority of the previously run operator (and it can run) and (ii) if the elapsed time is less than the scheduling period $P$. Intuitively, $b$ is defined to limit the execution time of a given operator, allowing other operators to be scheduled too. Although Haren does not interrupt operators during the processing of a tuple, it can enforce preemptive scheduling policies, with the batch size $b$ defining the preemption granularity. Smaller values of $b$ allow for more frequent preemption of the scheduled operators, at the price of higher context-switching overhead. If the PT reaches the end of the operator list $A$ and does not find any operator that can run, it invokes a back-off function to avoid spinning (lines 14–15). PTs sleep using a simple exponential back-off algorithm. More specifically, they start with a very small sleep duration and double it at every invocation. The back-off time never exceeds the remaining duration of $T_E$ and is reset every time a PT enters this task. Afterward (line 16), the PT checks if the time spent in the loop has surpassed the user-defined scheduling period $P$ and if so, it enters $T_S$ (line 17, later described in § 6). As discussed in § 4, if any execution-intrinsic feature of operator $op_i^j$ is used by $f$ and $g$, Haren needs to run $op_i^j$ if the latter has not been scheduled for more than $d$ time units in order (i) for its feature to be up-to-date, and (ii) for the scheduling policies to be enforced correctly. Because of this, PTs record the last execution time for each operator they schedule (line 10). Moreover, when task $T_S$ is completed, each PT checks if there are any operators in $A$ that have not been scheduled for more than $d$ time units and runs them if that is the case (lines 19–23). Lastly, observe that when PTs run an operator, they also add that operator to their set of executed operators $E$ (lines 11, 23). This allows PTs to selectively update only features of specific operators during the next $T_S$ task, based on the ones executed during $T_E$, as described in the following section. 6 SCHEDULING TASK ($T_S$) The purpose of the scheduling task is to produce, for each PT, a list $A$ of operators sorted by their priority vectors $P_i = (p_{i1}, p_{i2}, \ldots, p_{iD})$. This list of operators will then be used by each PT during the previous $T_E$ to pick operators for execution. As mentioned in § 4, Haren tries to minimize the scheduling overhead by parallelizing the costly steps of this task and splitting the work between all PTs. However, as we discussed before (and further elaborate in this section), $T_S$ also defines a sequential portion executed by exactly one (randomly selected) PT, which we denote as $t^*$. The sequential portion acts as a logical meeting point for PTs to synchronize their parallel work. In particular, the mechanics of $T_S$ can be broken down into four main steps: (1) Computing the up-to-date features, done partly in parallel (for independent features) and partly sequentially by $t^*$ (for dependent features). The actual implementation does not invoke $g$ but uses the priority value computed during the previous $T_S$. In the algorithm $g$ is used for compact notation. <table> <thead> <tr> <th>ID</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td>$F$</td> <td>Set of all the features used by the user-defined scheduling functions $f$ and $g$.</td> </tr> <tr> <td>$F_D$</td> <td>Set of dependent features.</td> </tr> <tr> <td>$F_C$</td> <td>Set of constant features.</td> </tr> <tr> <td>$D$</td> <td>Number of dimensions of the scheduling function $g$.</td> </tr> <tr> <td>$K$</td> <td>Number of PTs.</td> </tr> <tr> <td>$PT$</td> <td>Array of dimension $K$, of all the available PTs.</td> </tr> <tr> <td>$P$</td> <td>Matrix of size $</td> </tr> </tbody> </table> Table 3: Additional variables used during $T_S$. | (2) Assigning operators to PTs using the inter-thread scheduling function $f$, done sequentially by $t^*$. (3) Updating the priority vectors $P_i$ using the intra-thread scheduling function $g$, done in parallel by all PTs. (4) Sorting the operators based on their priority vectors $P_i$, done in parallel by all PTs. In the following, we discuss the challenges of the above steps and outline Haren’s solutions to each one. All the new variables related to this task are presented in Table 3. Updating the features: To begin with, this step is needed in order for Haren to compute the new priorities of the operators, since for the latter it needs to access the latest values of those operators’ features. As previously discussed in § 3, these features can differ in how frequently they change, with some of them being static and others dynamic. Moreover, features can differ on how they change, with some being independent or dependent and execution-intrinsic or not execution-intrinsic. This heterogeneity of the features presents an opportunity to reduce the cost of the feature update. More specifically, Haren tries to selectively update only the values of (operator, feature) combinations which can have potentially changed since the last $T_S$. In order to facilitate such selective updates and improve performance, Haren stores, for every operator, the latest feature values it has retrieved in an $|O| \times F$ matrix denoted by $P$, shared between PTs. When PTs execute $T_S$, they use their knowledge about possible feature dependencies to only update (operator, feature) combinations whose value can have potentially changed. Updating features is a two-step process, the first executed in parallel by all PTs and the second executed sequentially by one PT at each $T_S$. **Independent Features.** In this first part of the feature update, each PT updates the independent features of each operator in its (local) set of executed operators, $\mathbb{E}$. This step is shown in Algorithm 2 (line 2). Updating independent features can be done safely in parallel. This is because the values of an operator’s independent features can change only if that operator is scheduled by the PT responsible for it. Since no scheduling of operators happens during $T_S$, Haren can be certain that any update to an independent feature of any operator will be final (for this $T_S$). **Dependent Features.** As discussed in §4, dependent features might change based on the scheduling decisions of more than one PT. Haren avoids concurrent attempts to update the value of the same feature for the same operator by multiple PTs, since deciding on a correct ordering of these concurrent updates would require the use of a synchronization protocol and thus add overhead to the system (e.g., `SPE.getFeature()` would need to return the value of the feature and the timestamp of its invocation atomically). At the same time, PTs would waste CPU cycles, since all updates to the same position of $\mathcal{F}$, except the last one, would be replaced. For these reasons, the second step of updating the features in Haren is done sequentially by $t^*$. This procedure is shown in Algorithm 3, lines 3-5. $t^*$ decides which operators need to have their dependent features updated, using the shared bit array $U$. This array is initialized during the previous, parallel step, with each PT marking (i) the operators they executed (Algorithm 2, line 3), as well as (ii) the feature-dependent operators of the executed operators (lines 4-5). For (ii), each PT needs to know which operator(s) are feature-dependent on each operator they executed. This knowledge is encoded in bitmap $D$, which is initialized once, at the beginning of the execution, based on the structure of the streaming queries and the dependent features used in the scheduling policy. For this phase to work correctly, all updates to $U$ by PTs must have finished and be visible to $t^*$. To ensure this, PTs are forced to wait at the entryBarrier (Algorithm 3, line 1) before the update of the dependent features can begin. When all PTs arrive at that barrier, they are allowed to pass it, and immediately afterward, all PTs, except $t^*$, are blocked at the exitBarrier (line 11). The PTs will wait there until the dependent features have been updated by $t^*$. The need for the second barrier is explained in the next paragraph. Since the only requirement for choosing a PT to become $t^*$ is that there can be only one at every $T_S$, the PT is chosen arbitrarily: the last PT that leaves the entryBarrier is appointed to be $t^*$ (line 2). **Assigning operators to PTs.** After the features have been updated, $t^*$ assigns operators to PTs, using the inter-thread scheduling function $f$, as seen in Algorithm 3 lines 6-8. Care is needed in this step so that the updated mapping of operators to PTs takes effect at the same time for all PTs. This ensures that Haren avoids situations where, for example, the same operator (which could be mapped to two distinct PTs in two distinct $T_S$) is executed concurrently by two different PTs. Such situations are avoided having all PTs except one block at exitBarrier (introduced above). Only when $t^*$ has finished its work (and has called `await()` at the barrier), can all PTs move forward to update the priorities. If a reconfiguration was triggered by the SPE during the previous $T_S$, Haren’s data structures will be resized during this step, and any new operators will be randomly assigned to PTs. After the operator assignment, the two final parts of $T_S$, namely the calculation of the new priority vectors and the sorting of operators, are done in parallel by all PTs. **Priority Update.** As discussed in §4.1, the intra-thread scheduling function $g$ can use features of any deployed operator to compute the priority vector $p_i = (p_{i1}, p_{i2}, \ldots, p_{iD})$ of operator $op_i$. To maintain simplicity without sacrificing performance, Haren performs the feature and priority updates separately, but executes them both in parallel in all PTs. To do the priority update, each PT applies the intra-thread scheduling function $g$ to all operators in its operator list $\mathcal{A}$ (Algorithm 2, lines 7-8). This process begins immediately after the assignment of operators to PTs. The resulting priority vectors are stored in a thread-local $|O| \times D$ matrix denoted by $P$. --- **Algorithm 2: Haren.update() - $T_S$ (Parallel Steps)** ```plaintext // Update independent features for $op^*_j \in \mathbb{E}$ do $F_i \leftarrow$ SPE.getFeatures($i, j, F - F_D - F_C$) $U_i \leftarrow 1$ for $op^*_k \in \mathbb{O} | D_{i,k} = 1$ do // Mark feature-dependent ops for update $U_k \leftarrow 1$ Haren.coordinate() // Algorithm 3 // Compute priorities for $op^*_l \in \mathcal{A}$ do $F_i \leftarrow g(i, j, F)$ // Sort based on priorities sortOperators($\mathcal{A}, F$) ``` **Algorithm 3: Haren.coordinate() - $T_S$ (Coordination Step)** ```plaintext if last then // Start sequential (only $t^*$ enters) // Update dependent features for $op^*_j \in \mathbb{O} | U_i = 1$ do $F_i \leftarrow$ SPE.getFeatures($i, j, F_D$) $U_i \leftarrow 0$ // Inter-thread scheduling for $op^*_k \in \mathbb{O}$ do $t \leftarrow f(i, j, F)$ $A_t$.append($op_i$) // End sequential exitBarrier.await() else exitBarrier.await() ``` Note that many of the priority functions in the literature can be defined recursively, i.e., the value of the function for an operator can depend on its respective value for other operators. Haren is optimized for such cases by taking advantage of the dependencies in the query DAG to update the priorities in an efficient order. **Sorting.** After a PT has updated the priorities of all operators in $A$, the only task that remains before PTs can enter $T_E$ is to sort these operators by their priority. Thus, sorting is the final step of $T_S$, which once again is done in parallel by all PTs (Algorithm 2, line 9). The operators in $A$ are lexicographically sorted according to the values of their priority vectors. More precisely, an operator $op_m$ is considered to have higher priority than $op_n$ if $$\forall k < l : p_{mk} = p_{nk} \land (p_{ml} > p_{nl})$$ After the sorting is complete, each PT can immediately enter $T_E$ without the need to synchronize with the other PTs. ## 7 EVALUATION We evaluate Haren by integrating it with a real-world SPE, implementing several scheduling policies of different complexities and studying their behavior and performance. We utilize small, low-end devices usually found at the edge of cyber-physical systems. We chose them because, while Haren can provide custom scheduling facilities to SPEs running in any kind of node, scheduling decisions can have a higher impact on performance when processing resources are limited. We first describe the experimental setup, then cover the various scheduling policies we use and present results for different complexities of the latter. ### 7.1 Experiments setup **Hardware/software.** We use Odroid-XU4 [17] devices (or simply Odroid) with Samsung Exynos5422 Cortex-A15 2Ghz and Cortex-A7 Octa core CPUs and 2 GB of RAM, running Ubuntu 18.04.2 LTS and Java HotSpot(TM) Client VM 1.8.0_201-b09. Haren’s PTs run on the four big cores (i.e., $K = 4$). CPU consumption is measured with ps and memory usage is retrieved from the JVM Runtime. **Haren Implementation.** We evaluate a fully-featured version of Haren, implemented in Java, and integrated with Liebre, a lightweight SPE for edge-computing [14]. The integration builds on Haren’s API (§ 4) with few changes in the SPE’s implementation. **Queries.** We evaluate Haren using synthetic queries, each consisting of a chain of operators with custom cost and selectivity (see Table 1). The source data is artificially generated. Each chain has one Ingress operator that retrieves data from a Data Source, which runs independently of the SPE. All chains have the same length $L$. The selectivity and cost values of operators are chosen using a strategy inspired by [23]. More specifically, selectivity and cost are chosen at two levels: query-level and operator-level. Regarding selectivity, each query $j$ is assigned a selectivity value $s^j$, which expresses the number of egress tuples produced for every ingress tuple, chosen uniformly at random from $[0.01, 1]$. Then, to satisfy the query selectivity, each operator of the query gets a selectivity equal to $s^j / L \geq 10\%$. For the cost selection, each query $j$ is assigned a cost class $z$ in $[0, 4]$ and then the query’s cost is computed as $c^j = B \times 2^z$. The cost of a query is proportional to the minimum time required for an ingress tuple to be processed by all query’s operators. The cost of the operators is then set to $c^j \pm 10\%$. $B$ is the base cost parameter that allows us to vary the load and thus the utilization of the system. We use operator chains in our evaluation to stress-test Haren in a tractable manner by simulating an SPE with a heterogeneous load. However, it should be noted that Haren’s model can handle complex query graphs that contain forks or joins, without any alteration. The correct handling of such cases depends only on the implementation of scheduling functions $f$ and $g$. ### 7.2 Scheduling Policies As described in § 1, Haren is a general scheduling framework that can implement most scheduling policies defined in the literature. To give evidence of this, we evaluate three scheduling policies from the literature, each of which optimizes a different performance metric. We also study a custom policy that we define in § 7.4. Apart from these policies, we also evaluate the performance when the SPE runs without Haren, executing each operator in a dedicated thread instead. An overview of the features, dimensions and goals of each policy is given in the following (discussing how they define function $g$) and also in Table 4. In all experiments, the inter-thread scheduling function $f$ randomly distributes operators to all PTs. The queries are chains of operators with $L = 12$. The scheduling period $P$ is 100ms and the batch size $b$ is 10 tuples. Each experiment runs for at least five minutes and is repeated at least five times. **Dedicated Threads (OS),** the baseline policy, is the default for many SPEs. Haren is not used and, instead, each operator runs in a dedicated thread. Threads are thus scheduled by the OS. Since the OS is agnostic to specific streaming-related metrics, the metric this policy optimizes depends on the OS scheduler. **First-Come-First-Serve (FCFS)** has been shown to optimize the maximum latency of the queries [6]. Our implementation uses the inverse of the head clock time $1/t_{HH}$ (defined in § 3) as the operator priority. To minimize the maximum latency of the system, operators with higher head latency (earlier $1/t_{HH}$) are given higher priorities. **Highest Rate (HR),** presented in [21], aims at minimizing the average latency of the queries running in the system. The priority value of each operator is equal to its global output rate, which represents the number of egress tuples that would be produced per time unit if that operator and all its downstream operators were executed. This policy prioritizes operators that are more productive (higher selectivity) and less costly (lower cost). Since the priorities depend on the features of multiple operators, we expect this policy’s overhead to be higher than that of FCFS. **Chain** policy [5] tries to minimize runtime memory usage. It groups operators based on how many tuples they discard and how quickly they do so and prioritizes operators that belong to the <table> <thead> <tr> <th>Policy</th> <th>Features</th> <th># Dims</th> <th>Optimizes</th> <th>Sections</th> </tr> </thead> <tbody> <tr> <td>FCFS</td> <td>$1/t_{HH}$</td> <td>1</td> <td>Max Latency</td> <td>§ 7.3, § 7.4</td> </tr> <tr> <td>HR</td> <td>$c, s$</td> <td>1</td> <td>Mean Latency</td> <td>§ 7.3, § 7.4</td> </tr> <tr> <td>Chain</td> <td>$c, s, 1/t_{HH}$</td> <td>2</td> <td>Memory</td> <td>§ 7.3</td> </tr> <tr> <td>Multi-Class</td> <td>$c, s, 1/t_{HH}$</td> <td>2</td> <td>Custom</td> <td>§ 7.4</td> </tr> </tbody> </table> Table 4: Scheduling policies studied in the evaluation. groups that discard the most tuples for the least cost. If two operators have equal value of priority returned by the chain algorithm, the operator with the earliest head clock time is executed. Thus, the used intra-thread scheduling function \( g \) has two dimensions: the priority of the chain algorithm and the head clock time. **Multi-Class** is a combination of multiple of the previous policies, which are applied depending on the priority class of each query. It is described in detail and studied in § 7.4. ### 7.3 Single-Class Scheduling In this first part of the evaluation, we study the behavior of intra-thread scheduling functions \( g \) that assume that all the queries belong to the same priority class and only prioritize operators based on the value calculated by each specific policy. **Performance Comparison.** Figure 4 compares the performance of scheduling using dedicated threads or custom scheduling with the FCFS, HR and Chain policies. We evaluate the mean throughput at the Ingress operators, the mean and maximum latency at the Egress operators and the total number of queued tuples. We also evaluate the maximum memory consumption and the average CPU utilization of the SPE process, including the scheduling overheads. The comparison is made for 5, 10, 15 and 20 queries running in parallel. When the processing load is much lower than the maximum capacity of the system (5 queries), OS scheduling can be optimal in throughput and latency, since there is no contention for resources. In such cases, the OS scheduler can respond faster than Haren’s PTs which use an exponential back-off to conserve resources (Algorithm 1). However, OS scheduling’s advantage diminishes as utilization and resource contention increase (>5 queries). For throughput, the Chain policy always performs better, which is expected since it prioritizes operators closer to the Ingress operators. Moreover, HR and FCFS policies optimize for mean and maximum latency respectively, as expected, outperforming OS scheduling. The Chain policy meets its goal of minimizing the total number of tuples in operator queues. Although FCFS results in more queued tuples, its memory consumption is usually lower or equal to Chain. We believe this is because different scheduling strategies result in different behaviors of the garbage collector. The CPU utilization is almost always lower for Haren than for OS scheduling. **Scheduling Overhead.** Figure 5 shows a breakdown of the overheads introduced by the scheduling task \( T_S \). More specifically, it shows the percentage of time spent (i) calculating priorities using the intra-thread scheduling function \( g \) (Priority), (ii) sorting the operators based on their priorities (Sort), (iii) updating the independent features and marking operators that need dependent feature updates (Update), (iv) running coordinate (Algorithm 3) (Coord) Algorithm 3 (Coord in Figure 5). The time difference is due to the overhead is needed not only to coordinate the PTs entering and update the independent features is negligible (lower than 1%). The highest overhead of scheduling in most experiments is the duration of Algorithm 3 (Coord). In that phase, \( t^* \) runs the sequential part of \( T_S \) (Algorithm 3, L3-8), while all other PTs block. Figure 6 shows a breakdown of the sequential part, illustrating (i) the percentage of time spent updating the dependent features (Update), (ii) computing the inter-thread scheduling function \( f \) (Assign), and (iii) the total percentage of time spent in that part (Total). The figure shows that overheads usually increase with the number of queries. The HR policy has only an assignment overhead since it does not use any dependent features. On the other hand, FCFS and Chain also have an update overhead because they use the clock time, a dependent feature which needs updating. In all cases, the total time spent by \( t^* \) in the sequential part is less than the total duration of Algorithm 3 (Coord in Figure 5). The time difference is due to the synchronization overhead of the entryBarrier and exitBarrier. This overhead is needed not only to coordinate the PTs entering the different scheduling phases together but also to ensure memory visibility of actions happening before and after the barriers. Figure 7 shows the duration of Algorithm 3 for different \#queries and values of the scheduling period \( P \). It depicts executions of the same policy (FCFS); the size of the dots indicates the magnitude of overhead. 7.4 Multi-Class Scheduling In this section, we focus on a more complex scheduling scenario and (i) study scheduling queries that belong to different priority classes, giving higher priority to the queries of higher classes and (ii) apply different scheduling policies for the queries belonging to each priority class. Scheduling based on priority classes can be important in many use cases of stream processing. For example, in edge and fog cyber-physical systems, there are frequently many streaming queries with different levels of criticality deployed to a single processing node [18, 19]. A smart vehicle, for instance, can be running many different streaming queries. Some of the queries can be very urgent, such as a query that detects obstacles, while others can be less urgent, such as a query that checks if the fuel is running low. Motivated by the use-case above, we construct the following evaluation scenario: each query belongs to a user-defined priority class which is provided to Haren, and represents the criticality of the query. Several synthetic queries are deployed using Haren having one of two possible priority class values, HIGH or LOW. In our Multi-Class scheduling policy, queries of HIGH priority are always scheduled before LOW priority ones (objective 1). HIGH priority queries are scheduled using the FCFS policy that minimizes the maximum latency (objective 2) while LOW priority queries are scheduled with the HR policy, to minimize the average latency (objective 3). We run 3 HIGH and 10 LOW queries with different loads, comparing the behavior and ability of OS scheduling and Haren to meet the scheduling objectives. The base cost \( B \) is 600. Scenario 1 (steady state). In this experiment, there are adequate processing resources, and the SPE is at a steady state. The HIGH and LOW data sources emit at a constant rate of 500 t/s and 1000 t/s respectively. Figure 8 shows the throughput, mean and max latency for the two query classes. Both scheduling techniques match the throughput of the data sources. However, Haren achieves a much lower max and mean latency for the HIGH queries (objective 2), while keeping the mean latency of the LOW queries at similar levels as the OS (objective 1). The overall performance of HIGH queries is higher than that of the LOW queries (objective 1). Since the policy does not optimize for the maximum latency of LOW queries, this metric shows a higher increase. Scenario 2 (dynamic — high load). In this scenario, the source rate fluctuates and the system is in an overloaded state. The data sources of HIGH queries emit tuples at a rate of 5000 t/s for 5 seconds and then stop emitting for another 15 seconds. The data sources of the LOW queries emit at a constant rate of 1000 t/s, as before. Figure 9 shows the same performance metrics of the HIGH and LOW queries. Similarly to scenario 1, Haren prioritizes HIGH queries compared to the LOW ones, in contrast with OS scheduling (objective 1). More specifically, Haren achieves better throughput than OS for the HIGH queries, while it is slightly worse for the LOW ones. The figure shows that, for OS scheduling, the maximum latency of all queries keeps increasing. On the other hand, Haren dramatically reduces the maximum latency of HIGH queries (-17.4s) and at the same time keeps it at a near-constant level during the whole execution (0.1s), achieving objective 2. Moreover, the mean latency of the LOW priority queries increases but remains stable and at lower values (2.6s) than those achieved for HIGH queries by OS scheduling (3.5s), thus achieving objective 3. The max latency of LOW queries increases faster, which is expected since Haren’s custom policy does not have this scheduling objective. The results highlight that, especially in the presence of resource contention, Haren’s application-level scheduling allows the users to choose which metric (of which queries) they want to prioritize, until the load decreases or more resources become available. 8 RELATED WORK Scheduling in data streaming can refer to resource scheduling (how to deploy operators, from one or more queries, to SPE instances within and across computational nodes [3, 13, 27–29]) and thread scheduling (how to allocate threads to operators within each SPE instance). These complementary views can be joint to meet performance metrics (e.g., latency) from both a top-down (e.g., to decide which node should run a certain query or operator) and a bottom-up perspective (e.g., to customize CPU threads allocation to operators). Since we focus on thread scheduling, Haren’s approach is orthogonal to resource scheduling (see § 1) and can work in synergy with it. For a given resource allocation, Haren can take care of thread scheduling at each SPE instance (e.g., Flink TaskManager or Storm Worker [7, 24]) and run operators (that would otherwise be run by dedicated task/executor threads) based on the scheduling policies. The features can be retrieved either from the SPE’s API or from secondary monitoring components (e.g., Flink’s metric system). Haren is mainly orthogonal to existing work, since it does not rely on any hard-coded policy but rather distills the functionality required from a scheduler to implement general, user-defined scheduling policies. We believe ours is the first work proposing and evaluating a concrete implementation of such a scheduler. Many scheduling policies and metrics proposed in the literature aim at meeting the growing requirements that users have for streaming applications. The First-Come-First-Serve (FCFS) policy was first proposed in [6] to optimize for the maximum latency of streams of continuous requests, in the context of database and web servers, and has been further studied in the context of stream processing [22, 23]. The Rate-Based (RB) policy optimizes for the average latency of a single streaming query and was described in [25]. In [21], Sharaf et al. present an extension of the Rate-Based policy called Highest Rate (HR) that extends the former to multiple queries. Chandramouli et al. [10] introduce a metric called Mace (Maximum cumulative excess) and describe a scheduling framework for the StreamInsight SPE that uses this metric to accurately estimate the latency imposed by the stream processing pipeline. The Chain scheduling policy, described in [5], tries to minimize the runtime memory usage of multiple queries at the same time. It is proven to be near-optimal for many types of single-stream queries and also acceptable for multi-stream queries; it is also extended in [4] to take maximum latency into account. Aurora, a pioneer SPE, provided a detailed description of its scheduling policy [8, 9] based on two schedulers with different functionalities and goals. The first two-level scheduler schedules queries (superboxes) using Round-Robin, whereas operators (boxes) are scheduled with one of three policies that either optimize for average throughput (Min-Cost), average latency (Min-Latency, which is very similar to the Rate-Based policy) or available memory (Min-Memory). The second scheduler of Aurora aims at optimizing the QoS of the system by utilizing user-provided graphs that correlate the latency with the QoS of queries. The work explores various optimizations to minimize the scheduling overhead while matching user-defined goals. When many heterogeneous queries run in the same node, it can be crucial to achieve fairness, i.e., balance the degree of slowdown experienced by co-scheduled queries. One way to express this notion is the slowdown or stretch [1, 16] metric. The Longest Stretch First (LSF) metric has been shown to optimize the maximum slowdown [1]. Sharaf et al. propose operator scheduling policies to optimize for latency or slowdown or to balance both of these metrics, either in the average or in the worst case [22, 23]. Heterogeneous queries deployed in the same system can exhibit different QoS requirements. Scheduling queries based on different priority classes is explored in [15], with the Continuous Query Class (CQC) scheduler, a two-level scheduler relying on Weighted Round Robin and Highest Rate schedulers [23]. CQC aims to minimize the latency of high-priority queries and maintain reasonable latency values for the low-priority ones. Pham et al. extend this work and explore the relationship between scheduling and load management in [19, 20]. Their scheduler and load manager work in synergy, exchanging runtime information to consistently honor the user-defined priorities of the queries while increasing the system’s utilization. 9 CONCLUSIONS AND FUTURE WORK We study the problem of thread scheduling in stream processing, searching for a solution that is not bound to a specific SPE implementation nor scheduling policy. As a result, we propose Haren, an all-purpose scheduling framework that can be integrated into an SPE through a well-defined API and that allows users to define ad-hoc scheduling policies with minimal programming effort. Haren implements such policies efficiently by parallelizing the work to multiple processing threads in a transparent fashion. We thoroughly evaluate Haren and observe that its expressiveness and efficiency not only allow to define many of the scheduling policies in the literature but also perform wider-adapted approaches in which SPEs rely on the Operating System scheduler. Interesting future work studies include the possibilities given by the inter-thread deployment function of Haren to elastically adjust threads of an SPE and boost Haren’s adaptivity by means of autonomous adjustments of its configuration parameters (e.g., the scheduling period P). Other interesting directions include a more in-depth exploration of Haren’s behavior for complex queries that involve parallel branches [26] as well as for runtime changes of the queries or the policies used to schedule their operators. ACKNOWLEDGMENTS We thank the shepherd, Ruben Mayer, and the anonymous reviewers for their insightful comments and suggestions. The work was supported by the Swedish Foundation for Strategic Research, proj. ’FiC’ grant nr. GMT14-0032, by the Chalmers Energy AoA framework proj. INDEED and STAMINA and by the Swedish Research Council (Vetenskapsrådet) proj. “HARE” grant nr. 2016-03800.
{"Source-Url": "https://research.chalmers.se/publication/513694/file/513694_Fulltext.pdf", "len_cl100k_base": 13974, "olmocr-version": "0.1.49", "pdf-total-pages": 13, "total-fallback-pages": 0, "total-input-tokens": 48044, "total-output-tokens": 14804, "length": "2e13", "weborganizer": {"__label__adult": 0.0003235340118408203, "__label__art_design": 0.0004916191101074219, "__label__crime_law": 0.00033593177795410156, "__label__education_jobs": 0.0011510848999023438, "__label__entertainment": 0.00013566017150878906, "__label__fashion_beauty": 0.00019502639770507812, "__label__finance_business": 0.0005440711975097656, "__label__food_dining": 0.0003590583801269531, "__label__games": 0.0008273124694824219, "__label__hardware": 0.002506256103515625, "__label__health": 0.0005645751953125, "__label__history": 0.0004801750183105469, "__label__home_hobbies": 0.0001558065414428711, "__label__industrial": 0.0009088516235351562, "__label__literature": 0.0002734661102294922, "__label__politics": 0.0003795623779296875, "__label__religion": 0.0004856586456298828, "__label__science_tech": 0.324951171875, "__label__social_life": 0.00010752677917480467, "__label__software": 0.0225067138671875, "__label__software_dev": 0.64111328125, "__label__sports_fitness": 0.00029659271240234375, "__label__transportation": 0.0008120536804199219, "__label__travel": 0.00026297569274902344}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 61166, 0.01708]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 61166, 0.31479]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 61166, 0.91224]], "google_gemma-3-12b-it_contains_pii": [[0, 583, false], [583, 5594, null], [5594, 12099, null], [12099, 17226, null], [17226, 23308, null], [23308, 27965, null], [27965, 33819, null], [33819, 39616, null], [39616, 46358, null], [46358, 49254, null], [49254, 52705, null], [52705, 59697, null], [59697, 61166, null]], "google_gemma-3-12b-it_is_public_document": [[0, 583, true], [583, 5594, null], [5594, 12099, null], [12099, 17226, null], [17226, 23308, null], [23308, 27965, null], [27965, 33819, null], [33819, 39616, null], [39616, 46358, null], [46358, 49254, null], [49254, 52705, null], [52705, 59697, null], [59697, 61166, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 61166, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 61166, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 61166, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 61166, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 61166, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 61166, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 61166, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 61166, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 61166, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 61166, null]], "pdf_page_numbers": [[0, 583, 1], [583, 5594, 2], [5594, 12099, 3], [12099, 17226, 4], [17226, 23308, 5], [23308, 27965, 6], [27965, 33819, 7], [33819, 39616, 8], [39616, 46358, 9], [46358, 49254, 10], [49254, 52705, 11], [52705, 59697, 12], [59697, 61166, 13]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 61166, 0.08133]]}
olmocr_science_pdfs
2024-11-24
2024-11-24
4ed57c200fdfd74ac2e4a486a7569ed33be266bd
Automated Scanning of Oracle 10g Databases GSOC Gold Certification Author: Rory McCune, rorym@mccune.org.uk Adviser: Paul M. Wright Accepted: January 23rd 2007 Automated Scanning of Oracle 10g Databases Abstract One of the points raised on the course is that whilst there are a number of scripts and tools which can be used as part of an Oracle Security review there isn’t really a “security scanner” like tool which is available for free. This paper analyses the various areas of Oracle security covered by the course and seeks to propose details of which checks could be carried out automatically and how (for example what parameters to check, and what the various resultant values would indicate about the security of the database). Additionally as part of this, I expect to produce an initial beta copy of a scanning tool which implements the checks described in the paper. This beta would likely be implemented in the Ruby Object-Oriented Scripting Language. In terms of Oracle database versions, the paper would look to primarily focus on 10g as it is the latest version available, however it is expected that many, if not all, of the techniques would apply equally to earlier versions. This paper should be of interest to people tasked with auditing the security of Oracle databases and also with security tool authors who focus on Oracle. Rory McCune # Automated Scanning of Oracle 10g Databases ## Table of Contents 1. **Introduction** ............................................................ 5 2. Oracle Assessment ......................................................... 6 - Introducing RoraScanner ............................................. 7 3. Oracle file-system checks .............................................. 9 - Unix file permissions & ownership .............................. 9 - Windows file permissions & ownership ......................... 10 - Automated checking of Oracle file permissions - UNIX ...... 11 - Automated checking of Oracle file permissions - Windows ... 12 4. Oracle Initialization file checks ...................................... 13 - Automated checking of Oracle initialization files .......... 14 5. SQL Connection Checks .................................................. 15 - Default and easily guessed password checking ............... 16 - Oracle patch level checking .................................... 17 - Password profile checking ..................................... 20 - User rights checking ........................................... 22 - Database parameter checking .................................. 23 6. Reporting and persistence ............................................. 24 7. Conclusion & Alternatives ............................................ 25 - Appendix A - RoraScanner architecture overview .......... 27 - Anatomy of a Check ........................................... 28 Rory McCune Automated Scanning of Oracle 10g Databases Installation Instructions .................................................. 30 Rory McCune Automated Scanning of Oracle 10g Databases 1 Introduction Oracle’s database products are arguably the most popular in the world and are used in most, if not all, large corporate organizations in one role or another. Part of the reason for this popularity is the product’s flexibility and ability to fit into a number of roles from data warehousing applications to on-line transaction processing. However an inevitable consequence of increased flexibility and complexity is an increased “attack surface”, meaning that there are more ways in which the system can be attacked due to the larger number of installed features. Also as a result of the complexity of Oracle’s database product, it can be a daunting task to know where to start in auditing or securing the database. For example, in the default Oracle 10gR2 installation, there are over 50000 database objects and almost 24000 table permissions already defined. One way to help address this problem is to use automated tools which allow the auditor to focus more on the analysis of tool output and policy related issues that don’t lend themselves well to automation. This document is intended to look at the areas within the Oracle database which can be reviewed by automated tools to ascertain the current level of security of the database. 2 Oracle Assessment. In order to assess the security of an Oracle installation, there are a number of areas which can be analysed. This document will focus on the areas which are specific to the Oracle installation; however they are by no means sufficient to ensure the secure operating of an Oracle installation on its own. In particular, the security of the underlying operating system is vital, as if it is possible to get privileged access to the operating system through an unpatched vulnerability or poorly configured system daemon, then it will be subsequently possible to compromise the security of the database installed on that server. For the purposes of this document the potential Oracle security checks have been split into three areas, depending on the method used to perform the check 1. Checks carried out at the file-system level (e.g., permissions on Oracle program files) 2. Checks carried out on the Oracle Initialization files. 3. Checks carried out over an SQL connection to the database. In terms of sources for the checks which our automated auditing can carry out, there are two good checklists which can be used for this. First is the SANS SCORE checklist available from [http://www.sans.org/score/checklists/SCORE_Oracle_v3.1.xls](http://www.sans.org/score/checklists/SCORE_Oracle_v3.1.xls) and the Center for Internet Security's Oracle Benchmark is also available from [http://www.cisecurity.org/bench_oracle.html](http://www.cisecurity.org/bench_oracle.html). Rory McCune Introducing RoraScanner The tool being used to implement the checks described in this paper is called RoraScanner. It is written in the Ruby scripting language (http://www.ruby-lang.org/en/) which is an object-oriented scripting language originally developed by Yukihiro “matz” Matsumoto. Ruby has several characteristics which lend it to a project like this. The object-orientation lends itself to an extensible model, allowing new classes of checks to be added to the scanner without disturbing existing code. Ruby code also tends to be relatively readable unlike other some other scripting languages. Also, using Ruby allows for the potential to add a web based front-end to the project relatively easily using Ruby on Rails (http://www.rubyonrails.org). This would also allow easy integration with the ActiveRecord framework which could be used to create a database of previous scans allowing for auditing of security relevant changes over time. There are many excellent learning resources available online for those interested in learning more about ruby. Good starting points are: - Learn to program Ruby - http://pine.fm/LearnToProgram/ - Why’s poignant guide to Ruby - http://poignantguide.net/ruby/ RoraScanner currently provides a basic reporting & logging framework and allows for checks to be carried out over an SQL*PLUS connection to an Oracle database. Throughout the document, sections are included on how RoraScanner is implemented to cater for that class of check. In some cases (file-system scanning Rory McCune Automated Scanning of Oracle 10g Databases and initialization file parsing) a separate script, rora-file-scanner, is used as the mechanism required to complete the check differs from that required by the main script. Rora-file-scanner either parses the output of file listings to audit file permissions or Oracle initialization files to confirm values within these files are set appropriately. Information about the general architecture of RoraScanner can be found in section 7 of this document. The latest version of RoraScanner can be found at http://rorascanner.rubyforge.org/. The best way to get the latest version of RoraScanner is to use the subversion service available from RubyForge or download the latest release. Installation information for RoraScanner and its pre-requisites can be found in the README file included with the release. 3 Oracle file-system checks Ensuring that the correct permissions are set on installed Oracle programs and data files, helps to ensure that only authorised operating system users can modify or read those programs and can also help to minimize the impact of any mistakes by users of the system (’rm -rf *’ has way less impact if the user doesn’t have many rights!). In terms of classification, there are two major environments where Oracle is installed that need to be considered, Unix based operating systems and Windows based operating systems. The permission structures and commands used to view and modify these permissions are quite different on each of these types of system and should be considered separately. Unix file permissions & ownership On Unix, the files which constitute the Oracle installation are found under the $ORACLE_HOME directory (this environment variable is set when Oracle is installed) which by default will be /opt/oracle/10GR2 for the current version. The files under this directory should be accessible only to the Oracle database user, with read access allowed for any other local users who need to run the utilities installed in this area. There are two main requirements for file permissions specified in the CIS and SCORE checklists. The general rule is that files under $ORACLE_HOME should have rights of 750 or less (Additional information on Unix file permissions can be found... Automated Scanning of Oracle 10g Databases at [http://en.wikipedia.org/wiki/File_system_permissions](http://en.wikipedia.org/wiki/File_system_permissions). There is one exception to this general requirement, which is that files in $ORACLE_HOME/bin should be set to 755 or less, to allow users who are not in the oracle users group to run the utilities in that directory. In terms of ownership, the Oracle program and data files should be owned by the Oracle user (by default this is “oracle”) and the primary group of the Oracle user (by default this is “dba”). **Windows file permissions & ownership** The first key check on a windows installation of Oracle is to confirm that the file-system, that Oracle is installed onto, is NTFS and not FAT32, as FAT32 does not allow for the setting of file permissions. Windows file permissions should be set such that the Oracle User has full control of the files in the Oracle base directory and the “Everyone” windows group should have all permissions revoked from this directory tree. Automated checking of Oracle file permissions - UNIX On Unix, checking of file permissions automatically tends to be relatively straightforward due to the support of various scripting languages and the text readable output from the “ls” command. There is an existing script which can be used to carry out file permission audits where the auditor has shell access to the database server. Fileprobe.sh can be downloaded from: http://www.evdbt.com/fileprobe.sh An alternative approach, currently used by RoraScanner is to use the output of the command “ls -laR > <text file>” when run from the Oracle Installation directory (by default /opt/oracle/10gR2) as a root-level user will provide all the information needed to complete these checks. This approach also has the advantage that sysadmins do not need to run any custom scripts on their servers to get the output. There are 2 general rules that should be stated for this series of checks: 1. If the file checked has group permissions of greater than Read/Execute or there are “other” permissions on the file, it should be flagged as a problem. 2. If the file is owned by any user other than the oracle user or the oracle group, then it should also be flagged as a problem file. The main exception to these rules is that the files in the $ORACLE_HOME/bin directory, which should have rights of 755 or less. Automated checking of Oracle file permissions – Windows On Windows, it is a bit trickier to get access to permission information in a programmatic fashion, so initially RoraScanner uses a relatively simple check to confirm whether the “Everyone” group has any access to the files in the ORACLE_HOME directory. To provide a relatively straightforward way of doing this, a program called Dumpsec can be used (http://www.systemtools.com/somarsoft/index.html). This is a commonly used file-system auditing tool and allows us to create CSV output of all the rights assignments for a directory tree. The process of using Dumpsec to get the information we need in the correct format is: 1. Change the Report -> Permission Report Options setting to get Dumpsec to “show all directories and files”. 2. Then Run Report -> Dump permissions for File System. Choose the Oracle Base directory as the starting point for the report. 3. Once the report has completed running, choose the File -> Save Report As.. option and select Comma Separated columns as the file type to save. This provides us with a report which lists every file in the directory tree and each rights assignment for that file on a separate line which is a relatively easy format to process automatically. 4 Oracle Initialization file checks Oracle 10G uses a number of initialization files to control the settings of variables related to the configuration of the database and related systems like the TNS listener. The main log files that we’re interested in for the purposes of these audits, are listener.ora and sqlnet.ora. init.ora also contains several parameters but the easiest way to view these is by selecting information from v$parameter over a database connection. Within these three files there are a number of checks from the SCORE and CIS checklists that can be reviewed relatively easily by an automated tool. Automated checking of Oracle initialization files There are a couple of techniques required to review the contents of these initialization files depending on how the relevant sections are laid out. In some instances there are name/value pairs on a line by themselves. These lines can be easily parsed and the value extracted and compared against the desired value. Additionally there are bracketed sections which start with a "parameter =" for these we need to parse the multi-line statements however, the checks described in the CIS and SCORE checklists don’t require us to parse these. One point that has to be considered in these checks, is the default value of the parameter if it is not found in the file, as it is important not to flag a parameter that’s not found, if its default configuration is secure. Fortunately the CIS checklist provides some guidance on this. Currently, the rora-file-scanner script reads in the .ora file supplied as a parameter to the script, reads the lines in the file into an Array variable then passes this array to each of the tests to be completed. In order to maintain readability in the code, the checks for each initialization have been split into separate module files. Rory McCune 5 SQL Connection Checks This section is by far the largest of the three we outlined in the introduction, in terms of the number and types of checks that can be carried out and there are a number of sub-sections that will be considered: 1. **Default and easily guessed passwords.** One of Oracle's main problems traditionally has been the large number of default accounts which ship on the database with default passwords. 2. **Oracle patch level.** Oracle have released a large number of security patches for 10g which resolve a range of security related issues. These are currently released as quarterly Critical Patch Updates (CPUs). 3. **Password profiles.** Closely related to reviewing database passwords, is checking the password profiles assigned to database users to ensure that they meet good practice requirements. 4. **User rights.** It is possible to review the rights assigned to security critical database tables and also system rights. 5. **Database parameters.** There are a number of security related parameters that can be checked over a database connection including the ones from init.ora that were mentioned in the previous section. Automated Scanning of Oracle 10g Databases **Default and easily guessed password checking** One of the easier checks to implement is default password checking. It is relatively straightforward to extract the usernames and password hashes from a database and compare them with those contained in one of the lists available on the Internet. In RoraScanner, the list used comes from Pete Finnigan's site and can be found at [http://www.petefinnigan.com/default/oracle_default_passwords.csv](http://www.petefinnigan.com/default/oracle_default_passwords.csv). Assessing whether a user is using an easily guessed password is somewhat more complex. To do this we need a dictionary file and also an implementation of the Oracle password hashing algorithm. The details of the algorithm are well known, having been published in a paper by Joshua Wright and Carlos Cid (available here [http://www.sans.org/reading_room/special/index.php?id=oracle_pass&ref=911&portal=af19b59fe003baf8ff4d03f329fe480d](http://www.sans.org/reading_room/special/index.php?id=oracle_pass&ref=911&portal=af19b59fe003baf8ff4d03f329fe480d)). An automated scanner can either choose to implement the algorithm as described or use one of the existing password checking programs which are available. RoraScanner currently uses checkpwd from Red database Security ([http://www.red-database-security.com/software/checkpwd.html](http://www.red-database-security.com/software/checkpwd.html)) as it works from the command line and allows for results to be parsed easily. Automated Scanning of Oracle 10g Databases Oracle patch level checking Determining the patch level of an Oracle installation has two major components. Firstly, confirming the version of the software running, which is easily done by querying the v$version view and returning the results and secondly ascertaining what, if any, security patches have been applied to the system. One technique for doing this is based on the work described in Paul M. Wrights paper “Using Oracle Forensics to determine vulnerability to Zero Day exploits”. That paper describes a process for creating md5 hashes of the DDL of PACKAGE objects in the database using the DBMS_METADATA.GET_DDL function. By calculating the hashes for all appropriate objects in the database for each CPU level, it should be possible to come up with signatures which uniquely describe each level. A variation on this technique which is mentioned in “Oracle Forensics Part 4: Live Response” by David Litchfield, is to get the source from SYS.SOURCE$ but in principle the results should be the same. In order to enable this technique, the first step is to create a set of hashes for each patch level available. To do this, one way is to iterate over all the objects which have DDL selectable, using the GET_DDL process. From a review of an Oracle 10gR2 server, the following object type have DDL which can be selected :- CLUSTER, DIMENSION, FUNCTION, INDEX, INDEXTYPE, LIBRARY, OPERATOR, PACKAGEPROCEDURE, SEQUENCE, TRIGGER, VIEW Using the sample database, it is then possible to create a list for each CPU-level and run a comparison to establish which MD5 hashes change from one to the next, thus establishing the changed packages. Rory McCune Automated Scanning of Oracle 10g Databases One object type which does change frequently but which is not suitable for use, is the SEQUENCE object as the alteration in the DDL there is just the number to start. Following from this we get this sequence of changes for the various CPU levels from 10.2.0.1 with no CPUs installed through to the April 2006 CPU level. Changes from original level to January 2006 CPU <table> <thead> <tr> <th>Object Type</th> <th>Object Name</th> <th>SCHEMA OWNER</th> <th>ORIGINAL HASH</th> <th>NEW HASH</th> </tr> </thead> <tbody> <tr> <td>PACKAGE</td> <td>OWA_OPT_LOCK</td> <td>SYS</td> <td>378dc65d663566e15a3acd132048714a</td> <td>cb965c814e58518c01797cd5fa06f73b</td> </tr> <tr> <td>PACKAGE</td> <td>OWA_UTIL</td> <td>SYS</td> <td>fef91af3adac5ac00a2d800c62314bac</td> <td>b8feebd79e05a14ce4cf813d31ae481</td> </tr> <tr> <td>PACKAGE</td> <td>HTP</td> <td>SYS</td> <td>aceedee71f7a2dc864682cde548b93e03</td> <td>0737c8fe10c981896d232c457c564908</td> </tr> </tbody> </table> Changes from January 2006 CPU to April 2006 CPU <table> <thead> <tr> <th>Object Type</th> <th>Object Name</th> <th>SCHEMA OWNER</th> <th>ORIGINAL HASH</th> <th>NEW HASH</th> </tr> </thead> <tbody> <tr> <td>PACKAGE</td> <td>DBMS_EXPORT_EXTENSION</td> <td>SYS</td> <td>0b2761a5835ed97f683ac8bf3ad54dc3</td> <td>2f115cb22c80785c3c08e34642c8a67f</td> </tr> <tr> <td>PACKAGE</td> <td>DBMS_REGISTRY_SYS</td> <td>SYS</td> <td>82f759c1038eeba30bb56d8a887476e4</td> <td>dda8a5bebf3615eb0f200aedc061f78 18</td> </tr> </tbody> </table> Automated Scanning of Oracle 10g Databases Reviewing the changes for the later CPUs in July 2006, October 2006 and January 2007, reveals that the changes are primarily in PACKAGE objects with some changes in trigger objects. The exception to this is the application of the January 2007 CPU which doesn’t seem to make any changes that are picked up by reviews of DDL. From this it is obvious that this check on its own isn’t sufficient to determine patch level however, there are some other areas of the database that can be reviewed for corroborating data. One of these is the DBA_REGISTRY_HISTORY view which stores the current applied CPU level in the comment field. Another technique which could be used to augment this checking, is based on the The LAST_DDL_TIME field in the USER_OBJECTS view which stores a timestamp for modifications of the DDL for each object in the database. Combined with a process similar to the one described above for creating lists of packages DDL hashes, it is possible to determine the current patch level. Automated Scanning of Oracle 10g Databases Password profile checking With any Oracle database there can be a number of password profiles setup for different classes of user. These profiles specify security related parameters like the maximum lifetime of a password and the number of failed login attempts that can be made before the account is locked out. Automated checking of these profiles is primarily a matter of checking current values for each relevant setting and then flagging any exceptions compared to the values specified in the CIS and SCORE checklists. The only complication to this is that profiles other than the default one may have a setting of “DEFAULT” rather than a value, which means that they have the same setting as the DEFAULT profile. In those cases it is important to flag those parameters only where the DEFAULT profile is also being flagged. A listing of potential parameters to check based on the material in the SANS Securing Oracle course is: - password_life_time - password_reuse_time - password_reuse_max - failed_login_attempts - password_lock_time - password_grace_time - password_verify_function Of these parameters, the only one which falls outside of our base approach to Automated Scanning of Oracle 10g Databases checking is the “password_verify_function” as it is not set to a numeric value that we can check. Instead, the easiest check to perform would be whether this parameter is not null, to indicate that there is a password verification function present. This isn’t ideal of course, as it doesn’t attest to the strength or not of the function. User rights checking This is a potentially tricky area to evaluate automatically as the rights provided to users and roles will vary from database to database and what will be appropriate for one system may not be for another. There are however, some high level privileges that we can review that would give some indications that excessive rights have been granted. Firstly there is the area of default role assignments. There are several default roles which ship with Oracle which provide an excessive amount of permissions. The CONNECT role may be assumed to be required for authentication to the database but in reality provides additional privileges that aren’t required for most application users. Similarly, the RESOURCE and DBA roles shouldn’t be used as roles with only the privileges required but should be defined on a database by database basis. Secondly, it is possible to report back assignation of system privileges like “DROP ANY TABLE” or “ALTER ANY PROCEDURE” primarily as information for the auditor to review whether these are being used appropriately. Also reviewing access to sensitive tables like DBA_USERS where the password hashes are stored is a good idea. Database parameter checking There are a wide range of database parameters for the configuration of the database which can be checked across a sql*net connection. Within the v$parameter view there are a series of checks that can be made by comparing the values returned with the suggested values in the CIS and SCORE checklists. In terms of techniques for checking, the primary thing to be aware of is that (similarly to the process for checking values in initialization files) it is important to be aware of whether the default value is considered acceptable, for the purposes of reporting the result if that parameter is not set. 6 Reporting and persistence At a basic level, the techniques described in this document can be used for one-off reporting which would likely be suitable for the purposes of security auditors (either external to an organisation or internal). One of the key design elements that has been implemented in RoraScanner as it stands, is the consistent format that the results from each scan module are returned in. This allows for the reporting module to simply iterate over the listing of complete checks and apply whatever transformation is required to get the desired output format. At the moment, this takes the form of a basic HTML report which outputs results from the various plugins in HTML table format. However, for other use scenarios such as a security team monitoring, the security of a database server over time, it would be desirable to be able to compare results of previous scans to the current one. In this case, adding in functionality to save scan results to a database file will provide the best solution. In the case of RoraScanner, the easiest way to do this is to make use of an existing Object-Relational Mapping (ORM) framework such as ActiveRecord. This allows for easy translation of the output arrays from the scanner into a variety of different relational databases. 7 Conclusion & Alternatives From this paper it is possible to see that by automating the process of auditing the security of an Oracle database, significant results can be produced which allow the auditor to focus on other areas of the security of the installation which don’t lend themselves to automation, such as reviewing the administrative processes for handling removal of accounts from databases for users who have left. RoraScanner currently (June 2007) implements a small number of checks in each of the categories mentioned however, the current intention is to, where possible, implement all of the checks listed in the CIS Benchmark for Oracle 10g. In terms of alternative products or tools which could be used to achieve similar results, there are some free and proprietary options available. There are three main commercial options for database vulnerability assessment, each of which cover a variety of database engines in addition to Oracle. NGSSQuirrel from NGSSoftware (http://www.ngssoftware.com), AppDetectivePro from AppSecInc (http://www.appsecinc.com/products/appdetective/) and IpLocks (http://www.iplocks.com/html/p/capabilities_va/). There are also some other free options available as listed below - Scuba (http://www.imperva.com/application_defense_center/scuba/) - This is a free database security scanner recently released by Imperva. It covers several database engines (DB2, Oracle, MS SQL and Sybase) and creates HTML reports. Scuba focuses on checks carried out over an SQL connection. - CIS Oracle Database Benchmark (http://www.cisecurity.org/bench_oracle.html) - At the moment this tool Rory McCune Automated Scanning of Oracle 10g Databases only covers version 1.2 of the CIS Oracle benchmark and is restricted to the scanning of Oracle 8i databases. - Oscanner (http://www.cqure.net/tools.jsp?id=20) - GPL java based Oracle Security scanner. At the moment this project doesn’t seem to be very active. Oscanner is focused on enumeration of security relevant information over an Oracle database connection. Appendix A - RoraScanner architecture overview RoraScanner is a series of ruby scripts designed to audit an Oracle database installation for security related information and provide a report of relevant findings back to the user. There are a couple of key design goals which have influenced the setup of the system. 1. Extensibility - With any security scanner, one of the key attributes needs to be the ability to add new security checks to the program easily. 2. Minimal database rights - RoraScanner tries to minimize the quantity of database rights required to complete its checks, in order to ease the process of being granted approval to run scans. Specifically, this has meant that using a lot of PL/SQL techniques that involve creating database tables have been ruled out, as have techniques requiring direct access to the underlying Operating System. There are essentially two groups of files within RoraScanner currently. Those that deal with file level scanning and those that deal with scanning done over the sql*net connection. With each group there is an initial script that deals with reading in command line objects and setting up the scanner object and then calling the appropriate methods to carry out the checks an generate the reports. Following on from that, there are Class and Module definition files. Where appropriate, these have been split up into separate physical files. As the check base grows it may be a good idea to split them up further. Rory McCune Anatomy of a Check Each check that RoraScanner carries out, has a number of variables setup in a specific format to allow for the reporting module to parse the results into the correct format. ```python def version_scan def find_version(version_string) version = version_string[\d+\.\d+\.\d+\.\d+]/ return version end @version_scan_source = "SCORE" @version_scan_description = "This check returns the version of Oracle in use on the database" @version_scan_sql = "select * from v$version" @version_scan_implications = "" @version_scan_column_names = %w[Component_Name Version_Number] @version_scan_results = Array.new @conn.exec('select * from v$version') do |r| if r[0]=~/Oracle/ @version_scan_results << ['ORACLE', find_version(r[0])] end if r[0]=~/PL/SQL/ @version_scan_results << ['PLSQL', find_version(r[0])] end if r[0]=~/CORE/ @version_scan_results << ['CORE', find_version(r[0])] end if r[0]=~/TNS/ @version_scan_results << ['TNS', find_version(r[0])] end if r[0]=~/NLSRTL/ @version_scan_results << ['NLSRTL', find_version(r[0])] end end @completed_checks << "version_scan" end ``` In this example, the check is designed to pull the version information out of the database for information (and also so it can be used in later checks if needed). Once these variables have been specified, we can execute the sql required for the check using the existing Oracle connection which is setup when we created the RoraScanner object. The results from this are passed into a ruby block and the relevant information extracted. In this case the code looks through the results for Automated Scanning of Oracle 10g Databases certain keywords and if found, adds them to the results array. At the end of the check, the @completed_checks array is updated to include the check name. It is important to note that the text added to the @completed_checks array must be the same as the naming used for the check variables, as this is used in the reporter module. Automated Scanning of Oracle 10g Databases Installation Instructions Note that all the components of RoraScanner only need to be installed on a scanning workstation, it is not necessary to install anything on the target server. Windows Install instructions - Install the RoraScanner scripts - http://rorascanner.rubyforge.org - Install Ruby on scanning machine - http://rubyforge.org/projects/rubyinstaller/ - Install ruport from a command line - ”gem install ruport” - Run RoraScanner (usage instructions are in the README) Linux Install Instructions - Install the RoraScanner scripts - http://rorascanner.rubyforge.org - Install Ruby and rubygems on the scanning machine using the package manager for your distribution eg, Fedora Core - yum install ruby, yum install rubygems - Install ruport from a command line - ”gem install ruport” - Run RoraScanner (usage instructions are in the README) ## Upcoming SANS Training Click here to view a list of all SANS Courses <table> <thead> <tr> <th>Event Name</th> <th>Location</th> <th>Dates</th> <th>Type</th> </tr> </thead> <tbody> <tr> <td>SANS Cairo February 2020</td> <td>Cairo, EG</td> <td>Feb 15, 2020 - Feb 20, 2020</td> <td>Live Event</td> </tr> <tr> <td>SANS Brussels February 2020</td> <td>Brussels, BE</td> <td>Feb 17, 2020 - Feb 22, 2020</td> <td>Live Event</td> </tr> <tr> <td>SANS Scottsdale 2020</td> <td>Scottsdale, AZUS</td> <td>Feb 17, 2020 - Feb 22, 2020</td> <td>Live Event</td> </tr> <tr> <td>SANS San Diego 2020</td> <td>San Diego, CAUS</td> <td>Feb 17, 2020 - Feb 22, 2020</td> <td>Live Event</td> </tr> <tr> <td>Open-Source Intelligence Summit &amp; Training 2020</td> <td>Alexandria, VAUS</td> <td>Feb 18, 2020 - Feb 24, 2020</td> <td>Live Event</td> </tr> <tr> <td>SANS Training at RSA Conference 2020</td> <td>San Francisco, CAUS</td> <td>Feb 23, 2020 - Feb 24, 2020</td> <td>Live Event</td> </tr> <tr> <td>SANS Zurich February 2020</td> <td>Zurich, CH</td> <td>Feb 24, 2020 - Feb 29, 2020</td> <td>Live Event</td> </tr> <tr> <td>SANS Secure India 2020</td> <td>Bangalore, IN</td> <td>Feb 24, 2020 - Feb 29, 2020</td> <td>Live Event</td> </tr> <tr> <td>SANS Manchester February 2020</td> <td>Manchester, GB</td> <td>Feb 24, 2020 - Feb 29, 2020</td> <td>Live Event</td> </tr> <tr> <td>SANS Jacksonville 2020</td> <td>Jacksonville, FLUS</td> <td>Feb 24, 2020 - Feb 29, 2020</td> <td>Live Event</td> </tr> <tr> <td>SANS Secure Japan 2020</td> <td>Tokyo, JP</td> <td>Mar 02, 2020 - Mar 14, 2020</td> <td>Live Event</td> </tr> <tr> <td>Blue Team Summit &amp; Training 2020</td> <td>Louisville, KYUS</td> <td>Mar 02, 2020 - Mar 09, 2020</td> <td>Live Event</td> </tr> <tr> <td>SANS Northern VA - Reston Spring 2020</td> <td>Reston, VAUS</td> <td>Mar 02, 2020 - Mar 07, 2020</td> <td>Live Event</td> </tr> <tr> <td>SANS Munich March 2020</td> <td>Munich, DE</td> <td>Mar 02, 2020 - Mar 07, 2020</td> <td>Live Event</td> </tr> <tr> <td>SANS St. Louis 2020</td> <td>St. Louis, MOUS</td> <td>Mar 08, 2020 - Mar 13, 2020</td> <td>Live Event</td> </tr> <tr> <td>SANS Prague March 2020</td> <td>Prague, CZ</td> <td>Mar 09, 2020 - Mar 14, 2020</td> <td>Live Event</td> </tr> <tr> <td>SANS Dallas 2020</td> <td>Dallas, TXUS</td> <td>Mar 09, 2020 - Mar 14, 2020</td> <td>Live Event</td> </tr> <tr> <td>Wild West Hackin Fest 2020</td> <td>San Diego, CAUS</td> <td>Mar 10, 2020 - Mar 11, 2020</td> <td>Live Event</td> </tr> <tr> <td>SANS Doha March 2020</td> <td>Doha, QA</td> <td>Mar 14, 2020 - Mar 19, 2020</td> <td>Live Event</td> </tr> <tr> <td>SANS Norfolk 2020</td> <td>Norfolk, VAUS</td> <td>Mar 16, 2020 - Mar 21, 2020</td> <td>Live Event</td> </tr> <tr> <td>SANS Kuwait March 2020</td> <td>Salmiya, KW</td> <td>Mar 21, 2020 - Mar 26, 2020</td> <td>Live Event</td> </tr> <tr> <td>SANS Dubai February 2020</td> <td>OnlineAE</td> <td>Feb 15, 2020 - Feb 20, 2020</td> <td>Live Event</td> </tr> <tr> <td>SANS OnDemand</td> <td>Books &amp; MP3s OnlyUS</td> <td>Anytime</td> <td>Self Paced</td> </tr> </tbody> </table>
{"Source-Url": "https://www.sans.org/reading-room/whitepapers/application/automated-scanning-oracle-10g-databases-1851", "len_cl100k_base": 8388, "olmocr-version": "0.1.50", "pdf-total-pages": 32, "total-fallback-pages": 0, "total-input-tokens": 67862, "total-output-tokens": 10046, "length": "2e13", "weborganizer": {"__label__adult": 0.00045680999755859375, "__label__art_design": 0.00041031837463378906, "__label__crime_law": 0.0015392303466796875, "__label__education_jobs": 0.00574493408203125, "__label__entertainment": 0.00010079145431518556, "__label__fashion_beauty": 0.00019609928131103516, "__label__finance_business": 0.0010862350463867188, "__label__food_dining": 0.00028967857360839844, "__label__games": 0.0006070137023925781, "__label__hardware": 0.0020008087158203125, "__label__health": 0.0006012916564941406, "__label__history": 0.0002884864807128906, "__label__home_hobbies": 0.00015461444854736328, "__label__industrial": 0.0009765625, "__label__literature": 0.000301361083984375, "__label__politics": 0.0003018379211425781, "__label__religion": 0.00046372413635253906, "__label__science_tech": 0.08966064453125, "__label__social_life": 0.0002002716064453125, "__label__software": 0.05950927734375, "__label__software_dev": 0.83447265625, "__label__sports_fitness": 0.0002503395080566406, "__label__transportation": 0.0003688335418701172, "__label__travel": 0.0001596212387084961}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 38258, 0.03154]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 38258, 0.1836]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 38258, 0.86721]], "google_gemma-3-12b-it_contains_pii": [[0, 0, null], [0, 164, false], [164, 1370, null], [1370, 2928, null], [2928, 3065, null], [3065, 4368, null], [4368, 5875, null], [5875, 7478, null], [7478, 8330, null], [8330, 9754, null], [9754, 10788, null], [10788, 12152, null], [12152, 13416, null], [13416, 14037, null], [14037, 15268, null], [15268, 16428, null], [16428, 17958, null], [17958, 19664, null], [19664, 21187, null], [21187, 22229, null], [22229, 23448, null], [23448, 23830, null], [23830, 25016, null], [25016, 25649, null], [25649, 26943, null], [26943, 28583, null], [28583, 28993, null], [28993, 30482, null], [30482, 32261, null], [32261, 32636, null], [32636, 33910, null], [33910, 38258, null]], "google_gemma-3-12b-it_is_public_document": [[0, 0, null], [0, 164, true], [164, 1370, null], [1370, 2928, null], [2928, 3065, null], [3065, 4368, null], [4368, 5875, null], [5875, 7478, null], [7478, 8330, null], [8330, 9754, null], [9754, 10788, null], [10788, 12152, null], [12152, 13416, null], [13416, 14037, null], [14037, 15268, null], [15268, 16428, null], [16428, 17958, null], [17958, 19664, null], [19664, 21187, null], [21187, 22229, null], [22229, 23448, null], [23448, 23830, null], [23830, 25016, null], [25016, 25649, null], [25649, 26943, null], [26943, 28583, null], [28583, 28993, null], [28993, 30482, null], [30482, 32261, null], [32261, 32636, null], [32636, 33910, null], [33910, 38258, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 38258, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 38258, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 38258, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 38258, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 38258, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 38258, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 38258, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 38258, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 38258, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 38258, null]], "pdf_page_numbers": [[0, 0, 1], [0, 164, 2], [164, 1370, 3], [1370, 2928, 4], [2928, 3065, 5], [3065, 4368, 6], [4368, 5875, 7], [5875, 7478, 8], [7478, 8330, 9], [8330, 9754, 10], [9754, 10788, 11], [10788, 12152, 12], [12152, 13416, 13], [13416, 14037, 14], [14037, 15268, 15], [15268, 16428, 16], [16428, 17958, 17], [17958, 19664, 18], [19664, 21187, 19], [21187, 22229, 20], [22229, 23448, 21], [23448, 23830, 22], [23830, 25016, 23], [25016, 25649, 24], [25649, 26943, 25], [26943, 28583, 26], [28583, 28993, 27], [28993, 30482, 28], [30482, 32261, 29], [32261, 32636, 30], [32636, 33910, 31], [33910, 38258, 32]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 38258, 0.15306]]}
olmocr_science_pdfs
2024-11-27
2024-11-27
d23a9f6a7ad00f3c710ef94922b4f0642d17e730
These notes provide a quick introduction to the Coq system and show how it can be used to define logical concepts and functions and reason about them. It is designed as a tutorial, so that readers can quickly start their own experiments, learning only a few of the capabilities of the system. A much more comprehensive study is provided in [1], which also provides an extensive collection of exercises to train on. 1 Expressions and logical formulas The Coq system provides a language in which one handles formulas, verify that they are well-formed, and prove them. Formulas may also contain functions and limited forms of computations are provided for these functions. The first thing you need to know is how you can check whether a formula is well-formed. The command is called Check. Here are a few examples, which use a few of the basic objects and types of the system. Check True. \texttt{True : Prop} Check False. \texttt{False : Prop} Check 3. \texttt{3 : nat} Check (3+4). \texttt{3 + 4 : nat} Check (3=5). \texttt{3=5 : Prop} Check (3,4). \texttt{(3,4) : nat * nat} Check ((3=5)/\True). \texttt{3 = 5 /\ True} Check nat -> Prop. \(\text{nat} \to \text{Prop} : \text{Type}\) Check (3 <= 6). \(3 \leq 6 : \text{Prop}\) The notation \(A : B\) is uniformly used to indicate that the type of the expression \(A\) is the expression \(B\). Among these formulas, some can be read as propositions (they have type \(\text{Prop}\)), others may be read as numbers (they have type \(\text{nat}\)), others may be read as elements of more complex data structures. You can also try to check badly formed formulas and in this case the Coq system returns an informative error statement. Complex formulas can be constructed by combining propositions with logical connectives, or other expressions with addition, multiplication, the pairing construct, and so on. You can also construct a new function by using the keyword \texttt{fun}, which replaces the \(\lambda\) symbol of lambda calculus and similar theories. Check (fun x:nat => x = 3). \(\text{fun } x : \text{nat} \Rightarrow x = 3 : \text{nat} \to \text{Prop}\) Check (forall x:nat, x < 3 / (exists y:nat, x = y + 3)). \(\forall x : \text{nat}, x < 3 \lor (\exists y : \text{nat}, x = y + 3) \; : \; \text{Prop}\) Check (let f := fun x => (x * 3,x) in f 3). \(\text{let } f := \text{fun } x : \text{nat} \Rightarrow (x * 3, x) \; \text{in } f \; 3 : \text{nat} * \text{nat}\) Please note that some notations are overloaded. For instance, the \(*\) sign is used both to represent conventional multiplication on numbers and the cartesian product on types. One can find the function hidden behind a notation by using the \texttt{Locate} command. Locate ". <= .". \texttt{Notation Scope} "\_<\_\" := le x y \text{ : nat_scope} \((\text{default interpretation})\) The conditions for terms to be well-formed have two origins: first, the syntax must be respected (parentheses, keywords, binary operators must have two arguments); second, expressions must respect a type discipline. The \texttt{Check} command not only checks that expressions are well-formed but it also gives the type of expressions. For instance we can use the \texttt{Check} command to verify progressively that some expressions are well-formed. Check True. \(\text{True : Prop}\) Check False. \(\text{False : Prop}\) Check and. \[ \text{and} : \text{Prop} \rightarrow \text{Prop} \rightarrow \text{Prop} \] Check \((\text{and True False})\). \[ \text{True} \land \text{False} : \text{Prop} \] In the last example, \text{and} is a function that expects an argument of type \text{Prop} and returns a function of type \text{Prop} \rightarrow \text{Prop}. It can therefore be applied to \text{True}, which has the right type. But the function we obtain expects another argument of type \text{Prop} and it can be applied to the argument \text{False}. The notation \[ a \rightarrow b \rightarrow c \] actually stands for \[ a \rightarrow (b \rightarrow c) \] and the notation \( f \ a \ b \) actually stands for \((f \ a) \ b\). The last example also shows that the notation \(\land\) is an infix notation for the function \text{and}. Some constructs of the language have a notion of \textit{bound} variable. Among the examples we have already seen, the \texttt{forall} and \texttt{exist} logical quantifiers and the \texttt{fun} function constructor and the \texttt{let .. in} local declaration construct have this characteristic. When constructs have a bound variable, this variable can be used with some type inside some part of the construct called the scope. The type is usually given explicitly, but it may also sometimes be left untold, and the Coq system will infer it. At this point you should be able to perform exercise 2.5 (see at the end of this document), taking all numbers in the type \text{nat}. ## 2. Defining new constants You can define a new constant by using the keyword \texttt{Definition}. Here is an example: \texttt{Definition example1 := fun x : nat => x*x+2*x+1.} An alternative, exactly equivalent, definition could be: \texttt{Definition example1 (x : nat) := x*x+2*x+1.} ## 3. Proving facts The notation \(A : B\) is actually used for several purposes in the Coq system. One of these purposes is to express that \(A\) is a proof for the logical formula \(B\). This habit is usually referred to under the name \textit{Curry-Howard Isomorphism}. One can find already existing proofs of facts by using the \texttt{Search} command. Search True. I : True Search le. le_n : forall n : nat, n <= n le_S : forall n m : nat, le n m -> le n (S m) The theorem le_S uses a function S, this function maps any natural number to its successor. Actually, the notation \(3\) is only a notation for \(S(S(0))\). New theorems can be loaded from already proven packages using the Require command. For example, for proofs in arithmetics, it is useful to load the following packages: Require Import Arith. Require Import ArithRing. Require Import Omega. Search le. between_le: forall (P : nat -> Prop) (k l : nat), between P k l -> k <= l exists_le_S: forall (Q : nat -> Prop) (k l : nat), exists_between Q k l -> S k <= l ... plus_le_reg_l: forall n m p : nat, p + n <= p + m -> n <= m plus_le_compat_l: forall n m p : nat, n <= m -> p + n <= p + m plus_le_compat_r: forall n m p : nat, n <= m -> n + p <= m + p le_plus_l: forall n m : nat, n <= n + m ... There is a real notion of false formulas, but it is only expressed by saying that the existence of a proof for a false formula would imply the existence of a proof for the formula False. A theorem that proves an implication actually is an expression whose type is a function type (in other words, an arrow type). Thus, it can be applied to a term whose type appears to the left of the arrow. From the logical point of view, the argument of this theorem should be a proof of the implication’s premise. This corresponds to what is usually known as modus ponens. A theorem that proves a universal quantification is also an expression whose type is a function type. It can also be applied to an argument of the right type. From the logical point of view, this corresponds to producing a new proof for the statement where the universal quantification is instantiated. Here are a few examples, where theorems are instantiated and a modus ponens inference is performed: Check (le_n 0). le_n 0 : 0 <= 0 Check (le_S 0 0). le_S 0 1 : 0 <= 0 -> 0 <= 1 Check \((\text{le}_S \ 0 \ 0 \ (\text{le}_n \ 0))\). \[ \text{le}_S \ 0 \ 0 \ (\text{le}_n \ 0) : 0 \leq 1 \] New theorems could be constructed this way by combining existing theorems and using the \texttt{Definition} keyword to associate these expressions to constants. But this approach is seldom used. The alternative approach is known as \textit{goal directed proof}, with the following type of scenario: 1. the user enters a statement that he wants to prove, using the command \texttt{Theorem} or \texttt{Lemma}, 2. the Coq system displays the formula as a formula to be proved, possibly giving a context of local facts that can be used for this proof (the context is displayed above a horizontal line, the goal is displayed under the horizontal line), 3. the user enters a command to decompose the goal into simpler ones, 4. the Coq system displays a list of formulas that still need to be proved, 5. back to step 3. Some of the commands sent at step 3 actually decrease the number of goals. When there are no more goals the proof is complete, it needs to be saved, this is performed when the user sends the command \texttt{Qed}. The commands that are especially designed to decompose goals into lists of simpler goals are called tactics. Here is an example: \begin{verbatim} Theorem example2 : forall a b:Prop, a \& b \rightarrow b \& a. 1 subgoal ============================ forall a b : Prop, a \& b -> b \& a Proof. intros a b H. 1 subgoal a : Prop b : Prop H : a \& b ============================ b \& a split. 2 subgoals ... H : a \& b \end{verbatim} subgoal 2 is: a elim H; intros H0 H1. ... H0 : a H1 : b ============= b exact H1. 1 subgoal ... H : a /\ b ============= a intuition. Proof completed. Qed. intros a b H. split. elim H; intros H0 H1. exact H1. intuition. example2 is defined This proof uses several steps to decompose the logical processing, but a quicker dialog would simply rely on the intuition tactic directly from the start. There is an important collection of tactics in the Coq system, each of which is adapted to a shape of goal. For instance, the tactic elim H was adapted because the hypothesis H was a proof of a conjunction of two propositions. The effect of the tactic was to add two implications in front of the goal, with two premises asserting one of the propositions in the conjunction. It is worthwhile remembering a collection of tactics for the basic logical connectives. We list these tactics in the following table, inspired from the table in [1] (p. 130). <table> <thead> <tr> <th></th> <th>⇒</th> <th>∀</th> <th>∧</th> <th>∨</th> <th>∃</th> </tr> </thead> <tbody> <tr> <td>Hypothesis</td> <td>apply</td> <td>apply</td> <td>elim</td> <td>elim</td> <td>elim</td> </tr> <tr> <td>goal</td> <td>intros</td> <td>intros</td> <td>split</td> <td>left or right</td> <td>exists v</td> </tr> <tr> <td>−</td> <td>=</td> <td></td> <td></td> <td></td> <td></td> </tr> <tr> <td>Hypothesis</td> <td>elim</td> <td>rewrite</td> <td></td> <td></td> <td></td> </tr> <tr> <td>goal</td> <td>intro</td> <td>reflexivity</td> <td></td> <td></td> <td></td> </tr> </tbody> </table> When using the tactic `elim`, this usually creates new facts that are placed in the result goal as premises of newly created implications. These premises must then be introduced in the context using the `intros` tactic. A quicker tactic does the two operations at once, this tactic is called `destruct`. Some automatic tactics are also provided for a variety of purposes, `intuition` is often useful to prove facts that are tautologies in first-order intuitionistic logic (try it whenever the proof only involves manipulations of forall quantification, conjunction, disjunction, and negation); `auto` is an extensible tactic that tries to apply a collection of theorems that were provided beforehand by the user, `eauto` is like `auto`, it is more powerful but also more time-consuming, `ring` and `ring_nat` mostly do proofs of equality for expressions containing addition and multiplication (and `S` for `ring_nat`), `omega` proves formulas in Presburger arithmetic. One of the difficult points for newcomers is that the Coq system also provides a type `bool` with two elements called `true` and `false`. Actually this type has nothing to do with truth or provability, it is just a two-element type that may be used to model the boolean types that one usually finds in programming languages and the value attached to its two elements is purely conventional. In a sense, it is completely correct (but philosophically debatable) to define a function named `is_zero` that takes an argument of type `nat` and returns `false` if, and only if, its argument is 0. ## 4 Inductive types Inductive types could also be called algebraic types or initial algebras. They are defined by providing the type name, its type, and a collection of constructors. Inductive types can be parameterized and dependent. We will mostly use parameterization to represent polymorphism and dependence to represent logical properties. ### 4.1 Defining inductive types Here is an example of an inductive type definition: ```coq Inductive bin : Set := L : bin | N : bin -> bin -> bin. ``` This defines a new type `bin`, whose type is `Set`, and provides two ways to construct elements of this type: `L` (a constant) and `N` (a function taking two arguments). The Coq system automatically associates a theorem to this inductive type. This theorem makes it possible to reason by induction on elements of this type: ```coq Check bin_ind. ``` ```coq bin_ind : forall P : bin -> Prop, P L -> (forall b : bin, P b -> forall b0 : bin, P b0 -> P (N b b0)) -> forall b : bin, P b ``` The induction theorem associated to an inductive type is always named \textit{name}$_\text{ind}$. ### 4.2 Pattern matching Elements of inductive types can be processed using functions that perform some pattern-matching. For instance, we can write a function that returns the boolean value \texttt{false} when its argument is \texttt{N L L} and returns \texttt{true} otherwise. \begin{verbatim} Definition example3 (t : bin): bool := match t with N L L => false | _ => true end. \end{verbatim} ### 4.3 Recursive function definition There are an infinity of different trees in the type \texttt{bin}. To write interesting functions with arguments from this type, we need more than just pattern matching. The Coq system provides recursive programming. The shape of recursive function definitions is as follows: \begin{verbatim} Fixpoint flatten_aux (t1 t2:bin) {struct t1} : bin := match t1 with L => N L t2 | N t'1 t'2 => flatten_aux t'1 (flatten_aux t'2 t2) end. Fixpoint flatten (t:bin) : bin := match t with L => L | N t1 t2 => flatten_aux t1 (flatten t2) end. Fixpoint size (t:bin) : nat := match t with L => 1 | N t1 t2 => 1 + size t1 + size t2 end. \end{verbatim} There are constraints in the definition of recursive definitions. First, if the function has more than one argument, we must declare one of these arguments as the \textit{principal} or \textit{structural} argument (we did this declaration for the function \texttt{flatten_aux}). If there is only one argument, then this argument is the principal argument by default. Second, every recursive call must be performed so that the principal argument of the recursive call is a subterm, obtained by pattern-matching, of the initial principal argument. This condition is satisfied in all the examples above. ### 4.4 Proof by cases Now, that we have defined functions on our inductive type, we can prove properties of these functions. Here is a first example, where we perform a few case analyses on the elements of the type \texttt{bin}. 8 Theorem example3_size : \forall t, \text{example3 } t = \text{false} \rightarrow \text{size } t = 3. Proof. intros t; destruct t. 2 subgoals ================================= example3 L = \text{false} \rightarrow \text{size } L = 3 subgoal 2 is: example3 (N t1 t2) = \text{false} \rightarrow \text{size } (N t1 t2) = 3 The tactic \text{destruct } t actually observes the various possible cases for \( t \) according to the inductive type definition. The term \( t \) can only be either obtained by \( L \), or obtained by \( N \) applied to two other trees \( t1 \) and \( t2 \). This is the reason why there are two subgoals. We know the value that \text{example3} and \text{size} should take for the tree \( L \). We can direct the Coq system to compute it: \text{simpl.} 2 subgoals ================================= true = \text{false} \rightarrow 1 = 3 After computation, we discover that assuming that the tree is \( L \) and that the value of \text{example3} for this tree is \text{false} leads to an inconsistency. We can use the following tactics to exploit this kind of inconsistency: intros H. \hspace{1cm} H : true = false \hspace{1cm} \begin{align*} &\text{-----------------------------} \\ &1 = 3 \end{align*} discriminate H. 1 subgoal ... \begin{align*} &\text{-----------------------------} \\ &\text{example3 } (N t1 t2) = \text{false} \rightarrow \text{size } (N t1 t2) = 3 \end{align*} The answer shows that the first goal was solved. The tactic \text{discriminate } H can be used whenever the hypothesis \( H \) is an assumption that asserts that two different constructors of an inductive type return equal values. Such an assumption is inconsistent and the tactic exploits directly this inconsistency to express that the case described in this goal can never happen. This tactic expresses a basic property of inductive types in the sort \text{Set} or \text{Type}: constructors have distinct ranges. Another important property of constructors of inductive types in the sort \text{Set} or \text{Type} is that they are injective. The tactic to exploit this fact called injection (for more details about discriminate and injection please refer to [1] or the Coq reference manual [2]). For the second goal we still must do a case analysis on the values of t1 and t2, we do not detail the proof but it can be completed with the following sequence of tactics. destruct t1. destruct t2. 3 subgoals example3 (N L L) = false -> size (N L L) = 3 subgoal 2 is: example3 (N L (N t2_1 t2_2)) = false -> size (N L (N t2_1 t2_2)) = 3 subgoal 3 is: example3 (N (N t1_1 t1_2) t2) = false -> size (N (N t1_1 t1_2) t2) = 3 For the first goal, we know that both functions will compute as we stated by the equality’s right hand side. We can solve this goal easily, for instance with auto. The last two goals are solved in the same manner as the very first one, because example3 cannot possibly have the value false for the arguments that are given in these goals. auto. intros H; discriminate H. Qed. To perform this proof, we have simply observed 5 cases. For general recursive functions, just observing a finite number of cases is not sufficient. We need to perform proofs by induction. ### 4.5 Proof by induction The most general kind of proof that one can perform on inductive types is proof by induction. When we prove a property of the elements of an inductive type using a proof by induction, we actually consider a case for each constructor, as we did for proofs by cases. However there is a twist: when we consider a constructor that has arguments of the inductive type, we can assume that the property we want to establish holds for each of these arguments. When we do goal directed proof, the induction principle is invoked by the elim tactic. To illustrate this tactic, we will prove a simple fact about the flatten_aux and size functions. Theorem forall_aux_size : forall t1 t2, size (flatten_aux t1 t2) = size t1 + size t2 + 1. Proof. intros t1; elim t1. ============================= forall t2 : bin, size (flatten_aux L t2) = size L + size t2 + 1 subgoal 2 is: forall b : bin, (forall t2 : bin, size (flatten_aux b t2) = size b + size t2 + 1) -> (forall t2 : bin, size (flatten_aux b0 t2) = size b0 + size t2 + 1) -> size (flatten_aux (N b b0) t2) = size (N b b0) + size t2 + 1 There are two subgoals, the first goal requires that we prove the property when the first argument of flatten_aux is L, the second one requires that we prove the property when the argument is N b b0, under the assumption that it is already true for b and b0. The proof progresses easily, using the definitions of the two functions, which are expanded when the Coq system executes the simpl tactic. We then obtain expressions that can be solved using the ring_nat tactic. intros t2. simpl. ... ============================= S (S (size t2)) = S (size t2 + 1) ring_nat. intros b IHb b0 IHb0 t2. ... IHb : forall t2 : bin, size (flatten_aux b t2) = size b + size t2 + 1 b0 : bin IHb0 : forall t2 : bin, size (flatten_aux b0 t2) = size b0 + size t2 + 1 t2 : bin ============================= size (flatten_aux (N b b0) t2) = size (N b b0) + size t2 + 1 simpl. ... ============================= \begin{align*} \text{size} \ (\text{flatten} \_\text{aux} \ b \ (\text{flatten} \_\text{aux} \ b0 \ t2)) &= \\ S \ (\text{size} \ b + \text{size} \ b0 + \text{size} \ t2 + 1) \end{align*} \text{rewrite IHb}. \text{...} \begin{align*} \text{size} \ b + \text{size} \ (\text{flatten} \_\text{aux} \ b0 \ t2) + 1 &= \\ S \ (\text{size} \ b + \text{size} \ b0 + \text{size} \ t2 + 1) \end{align*} \text{rewrite IHb0}. \text{...} \begin{align*} \text{size} \ b + (\text{size} \ b0 + \text{size} \ t2 + 1) + 1 &= \\ S \ (\text{size} \ b + \text{size} \ b0 + \text{size} \ t2 + 1) \end{align*} \text{ring} \_\text{nat}. \text{Proof completed}. \text{Qed.} \section{4.6 Numbers in the Coq system} In the Coq system, most usual datatypes are represented as inductive types and packages provide a variety of properties, functions, and theorems around these datatypes. The package named \texttt{Arith} contains a host of theorems about natural numbers (numbers from 0 to infinity), which are described as an inductive type with 0 (representing 0) and S as constructors. It also provides addition, multiplication, subtraction (with the special behavior that \(x - y\) is 0 when \(x\) is smaller than \(y\). The package \texttt{ArithRing} contains the tactic \texttt{ring} \_\texttt{nat} and the associated theorems. The package named \texttt{ZArith} provides two inductive datatypes to represent integers. The first inductive type, named \texttt{positive}, follows a binary representation to model the positive integers (from 1 to infinity) and the type \texttt{Z} is described as a type with three constructors, one for positive numbers, one for negative numbers, and one for 0. The package also provides orders and basic operations: addition, subtraction, multiplication, division, square root. The package \texttt{ZArithRing} provides the configuration for the \texttt{ring} tactic to work on polynomial equalities with numbers of type \texttt{Z}. The tactic \texttt{omega} works equally well to solve problems in Presburger arithmetic for both natural numbers of type \texttt{nat} and integers of type \texttt{Z}. There are a few packages that provide descriptions of rational numbers, but the support for these packages is not as standard as for the other one. For instance, there is no easy notation to enter a simple fraction. In a paper from 2001, I showed that the rational numbers could be given a very simple inductive structure, but encoding the various basic operations on this structured was a little complex. The support for computation on real numbers in the Coq system is also quite good, but real numbers are not (and cannot) be represented using an inductive type. The package to load is \texttt{Reals} and it provides descriptions for quite a few functions, up to trigonometric functions for instance. 4.7 Data-structures The two-element boolean type is an inductive type in the Coq system, `true` and `false` are its constructors. The induction principle naturally expresses that this type only has two elements, because it suffices that a property is satisfied by `true` and `false` to ensure that it is satisfied by all elements of `bool`. On the other hand, it is easy to prove that `true` and `false` are distinct. Most ways to structure data together are also provided using inductive data structures. The pairing construct actually is an inductive type, and `elim` can be used to reason about a pair in the same manner as it can be used to reason on a natural number. A commonly used datatype is the type of lists. This type is polymorphic, in the sense that the same inductive type can be used for lists of natural numbers, lists of boolean values, or lists of other lists. This type is not provided by default in the Coq system, it is necessary to load the package `List` using the `Require` command to have access to it. The usual `cons` function is given in Coq as a three argument function, where the first argument is the type of elements: it is the type of the second argument and the third argument should be a list of elements of this type, too. The empty list is represented by a function `nil`. This function also takes an argument, which should be a type. However, the Coq system also provides a notion of implicit arguments, so that the type arguments are almost never written and the Coq system infers them from the context or the other arguments. For instance, here is how we construct a list of natural numbers. ``` Require Import List. Check (cons 3 (cons 2 (cons 1 nil))). 3 :: 2 :: 1 :: nil : list nat ``` This example also shows that the notation `::` is used to represent the `cons` function in an infix fashion. This tradition will be very comfortable to programmers accustomed to languages in the ML family, but Haskell addicts should beware that the conventions, between type information and cons, are inverse to the conventions in Haskell. The `List` package also provides a list concatenation function named `app`, with `++` as infix notation, and a few theorems about this function. 5 Inductive properties Inductive types can be dependent and when they are, they can be used to express logical properties. When defining inductive types like `nat`, `Z` or `bool` we declare that this constant is a type. When defining a dependent type, we actually introduce a new constant which is declared to be a function from some input type to a type of types. Here is an example: ``` Inductive even : nat -> Prop := even0 : even 0 | evenS : forall x:nat, even x -> even (S (S x)). Thus, `even` itself is not a type, it is `even x`, whenever `x` is an integer that is a type. In other words, we actually defined a family of types. In this family, not all members contain elements. For instance, we know that the type even 0 contains an element, this element is even0, and we know that even 2 contains an element: evenS 0 even0. What about even 1? If even 1 contains an element, this element cannot be obtained using even0 because 0 \( \neq 1 \), it cannot be obtained using evenS because 1 \( \neq 2 + x \) for every x such that 0 \( \leq x \). Pushing our study of even further we could see that this type, seen as a property, is provable if and only if its argument is even, in the common mathematical sense. Like other inductive types, inductive properties are equipped with an induction principle, which we can use to perform proofs. The inductive principle for even has the following shape. Check even_ind. even_ind : forall P : nat -> Prop, P 0 -> (forall x : nat, even x -> P x -> P (S (S x))) -> forall n : nat, even n -> P n This principle intuitively expresses that even is the smallest property satisfying the two constructors: it implies every other property that also satisfies them. A proof using this induction principle will work on a goal where we know that even y holds for some y and actually decomposes into a proof of two cases, one corresponding to the case where even y was obtained using even0 and one corresponding to the case where even y was obtained using evenS, applied to some x such that y=S (S x) and some proof of even y. In the second case, we again have the opportunity to use an induction hypothesis about this y. When a variable x satisfies an inductive property, it is often more efficient to prove properties about this variable using an induction on the inductive property than an induction on the variable itself. The following proof is an example: Theorem even_mult : forall x, even x -> exists y, x = 2*y. Proof. intros x H; elim H. 2 subgoals \[ \begin{align*} x & : nat \\ H & : even x \\ exists y : nat, 0 = 2 \times y \\ \end{align*} \] subgoal 2 is: forall x0 : nat, \( even x0 \rightarrow (exists y : nat, x0 = 2 \times y) \rightarrow exists y : nat, S (S x0) = 2 \times y \) exists 0; ring_nat. intros x0 Hevenx0 IHx. ... IHx : exists y : nat, x0 = 2 * y exists y : nat, S (S x0) = 2 * y In the last goal, IHx is the induction hypothesis. It says that if x0 is the predecessor’s predecessor of x then we already know that there exists a value y that is its half. We can use this value to provide the half of S (S x0). Here are the tactics that complete the proof: destruct IHx as [y Heq]; rewrite Heq. exists (S y); ring_nat. Qed. In this example, we used a variant of the destruct tactic that makes it possible to choose the name of the elements that destruct creates and introduces in the context. If we wanted to prove the same property using a direct induction on the natural number that is even, we would have a problem because the predecessor of an even number, for which direct induction provides an induction hypothesis, is not even. The proof is not impossible but slightly more complex: Theorem even_mult’ : forall x, even x -> exists y, x = 2* y. Proof. intros x. assert (lemma: (even x -> exists y, x=2*y)/\(even (S x) -> exists y, S x=2*y)). elim x. split. exists 0; ring_nat. intros Heven1; inversion Heven1. intros x0 IHx0; destruct IHx0 as [IHx0 IHSx0]. split. exact IHSx0. intros HevenSSx0. assert (Hevenx0 : even x0). inversion HevenSSx0; assumption. destruct (IHx0 Hevenx0) as [y Heq]. rewrite Heq; exists (S y); ring_nat. tuition. Qed. This script mostly uses tactics that we have already introduced, except the inversion tactic. Given an assumption H that relies on a dependent inductive type, most frequently an inductive proposition, the tactic inversion analyses all the constructors of the inductive, discards the ones that could not have been applied, and when some constructors could have applied it creates a new goal where the premises of this constructor are added in the context. For instance, this tactic is perfectly suited to prove that 1 is not even: Theorem not_even_1 : ~even 1. Proof. intros even1. ... even1 : even 1 =============== False inversion even1. Qed. This example also shows that the negation of a fact actually is represented by a function that says “this fact implies \texttt{False}”. Inductive properties can be used to express very complex notions. For instance, the semantics of a programming language can be defined as an inductive definition, using dozens of constructors, each one describing a kind of computation elementary step. Proofs by induction with respect to this inductive definition correspond to what WynsKel calls rule induction in his introductory book on programming language semantics [3]. 6 Exercises Most of the exercises proposed here are taken from [1]. Exercise 2.5 Write a function that takes five arguments and returns their sum. Exercise 5.6 Prove the following theorems: \[ \forall A \, B \, C : \text{Prop}, \, A /\!/(B /\!/ C) \rightarrow (A /\!/ B) /\!/ C \] \[ \forall A \, B \, C \, D : \text{Prop}, \, (A \rightarrow B) /\!/ (C \rightarrow D) /\!/ A /\!/ C \rightarrow B /\!/ D \] \[ \forall A : \text{Prop}, \, \neg \neg (A /\!/ A) \] \[ \forall A \, B \, C : \text{Prop}, \, A /\!/ (B /\!/ C) \rightarrow (A /\!/ B) /\!/ C \] \[ \forall A : \text{Prop}, \, \neg \neg (A /\!/ A) \] \[ \forall A \, B : \text{Prop}, \, (A /\!/ B) /\!/ \neg A \rightarrow B \] Two benefits can be taken from this exercise. In a first step you should try using only the basic tactics given in the table page \[\Box\]. In a second step, you can verify which of these statements are directly solved by the tactic \texttt{intuition}. Universal quantification Prove \[ \forall A : \text{Set}, \forall P \, Q : A \rightarrow \text{Prop}, \] \[ \quad (\forall x, P x) /\!/ (\forall y, Q y) \rightarrow \forall x, P x /\!/ Q y. \] \[ \neg (\forall A : \text{Set}, \forall P \, Q : A \rightarrow \text{Prop}, \] \[ \quad (\forall x, P x /\!/ Q x) \rightarrow (\forall x, P x) /\!/ (\forall y, Q y). \] Hint: for the second exercise, think about a counter-example with the type \texttt{bool} and its two elements \texttt{true} and \texttt{false}, which can be proved different, for instance. Exercise 6.32 The sum of the first \( n \) natural numbers is defined with the following function: ```coq Fixpoint sum_n (n:nat) : nat := match n with | 0 => 0 | S p => S p + sum_n p end. ``` Prove the following statement: ```coq forall n:nat, 2 * sum_n n = n*n + n ``` **Sum of powers** Define a recursive function \texttt{nat\_power}. Find in the Coq documentation\(^1\) how to attach the notation \( x^y \) to this function. Then define a summation function that makes it possible to compute \[ \sum_{k=0}^{n} f(k) \] Prove the following theorem: \[ \forall x \; n : nat, 1 \leq x \rightarrow (x - 1) \sum_{k=0}^{n} x^k = x^{n+1} - 1. \] To perform this exercise, prove a few auxiliary lemmas about distributivity of multiplication over subtraction in \texttt{nat} and powers and comparison. Use the tactics \texttt{ring\_nat} and \texttt{omega}. **Square root of 2** If \( p^2 = 2q^2 \), then \( (2q - p)^2 = 2(p - q)^2 \), now if \( p \) is the least positive integer such that there exists a positive integer \( q \) such that \( p/q = \sqrt{2} \), then \( p > 2q - p > 0 \), and \( (2q - p)/(p - q) = \sqrt{2} \). This is a contradiction and a proof that \( \sqrt{2} \) is not rational. Use Coq to verify a formal proof along these lines (use \texttt{Z} as the type of numbers). **Sum of powers revisited** Try to redo this exercise with other number types, like \texttt{Z}, \texttt{R}, where powers and summations may already be defined and the condition \( 1 \leq x \) can usually be replaced by another condition. 7 Solutions The solutions to the numbered exercises are available from the internet (on the site associated to the reference \[\Pi\]). The short proof that \( \sqrt{2} \) is not rational is also available on the internet from the author’s personal web-page. Here are the solutions to the exercises on universal quantification. **Theorem ex1 :** \[ \forall A : Set, \forall P : A \rightarrow Prop, \\ (\forall x, P x \lor (\forall y, Q y) \rightarrow \forall x, P x \lor Q x). \] \(^1\)http://coq.inria.fr/ Proof. intros A P Q H. elim H. intros H1; left; apply H1. intros H2; right; apply H2. Qed. Theorem ex2 : \neg (\forall A : Set, \forall P Q : A \rightarrow Prop, \ (\forall x, P x \lor Q x) \rightarrow (\forall x, P x) \lor (\forall y, Q y)). Proof. intros H; elim (H bool (fun x:bool => x = true) \rightarrow (fun x:bool => x = false)). intros H1; assert (H2: false = true). apply H1. discriminate H2. intros H1; assert (H2: true = false). apply H1. discriminate H2. intros x; case x. left; reflexivity. right; reflexivity. Qed. References
{"Source-Url": "http://www.dc.fi.udc.es/staff/freire/md2-05/c06-07/coq_in_a_hurry.pdf", "len_cl100k_base": 9479, "olmocr-version": "0.1.53", "pdf-total-pages": 18, "total-fallback-pages": 0, "total-input-tokens": 40472, "total-output-tokens": 10692, "length": "2e13", "weborganizer": {"__label__adult": 0.0003709793090820313, "__label__art_design": 0.0005354881286621094, "__label__crime_law": 0.00043082237243652344, "__label__education_jobs": 0.003904342651367187, "__label__entertainment": 0.0001252889633178711, "__label__fashion_beauty": 0.00018930435180664065, "__label__finance_business": 0.00028777122497558594, "__label__food_dining": 0.000606536865234375, "__label__games": 0.0009465217590332032, "__label__hardware": 0.000881195068359375, "__label__health": 0.0006694793701171875, "__label__history": 0.0003829002380371094, "__label__home_hobbies": 0.000209808349609375, "__label__industrial": 0.0007576942443847656, "__label__literature": 0.0006561279296875, "__label__politics": 0.00036263465881347656, "__label__religion": 0.000762939453125, "__label__science_tech": 0.1068115234375, "__label__social_life": 0.00020313262939453125, "__label__software": 0.00968170166015625, "__label__software_dev": 0.8701171875, "__label__sports_fitness": 0.0003650188446044922, "__label__transportation": 0.0006785392761230469, "__label__travel": 0.0002288818359375}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 35270, 0.02891]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 35270, 0.57722]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 35270, 0.8492]], "google_gemma-3-12b-it_contains_pii": [[0, 1136, false], [1136, 3357, null], [3357, 5509, null], [5509, 7481, null], [7481, 9083, null], [9083, 10455, null], [10455, 13022, null], [13022, 15086, null], [15086, 17167, null], [17167, 18960, null], [18960, 20323, null], [20323, 23147, null], [23147, 26042, null], [26042, 28158, null], [28158, 30029, null], [30029, 32214, null], [32214, 34266, null], [34266, 35270, null]], "google_gemma-3-12b-it_is_public_document": [[0, 1136, true], [1136, 3357, null], [3357, 5509, null], [5509, 7481, null], [7481, 9083, null], [9083, 10455, null], [10455, 13022, null], [13022, 15086, null], [15086, 17167, null], [17167, 18960, null], [18960, 20323, null], [20323, 23147, null], [23147, 26042, null], [26042, 28158, null], [28158, 30029, null], [30029, 32214, null], [32214, 34266, null], [34266, 35270, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, false], [5000, 35270, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 35270, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 35270, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 35270, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 35270, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 35270, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 35270, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 35270, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 35270, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, true], [5000, 35270, null]], "pdf_page_numbers": [[0, 1136, 1], [1136, 3357, 2], [3357, 5509, 3], [5509, 7481, 4], [7481, 9083, 5], [9083, 10455, 6], [10455, 13022, 7], [13022, 15086, 8], [15086, 17167, 9], [17167, 18960, 10], [18960, 20323, 11], [20323, 23147, 12], [23147, 26042, 13], [26042, 28158, 14], [28158, 30029, 15], [30029, 32214, 16], [32214, 34266, 17], [34266, 35270, 18]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 35270, 0.0148]]}
olmocr_science_pdfs
2024-12-11
2024-12-11
17591761f8be723ff35bfbd342c58457e0147807
CHAPTER 9 Complementary functions and complementary views 9.1 Introduction At the end of Chapter 7, we took two branches. One was based on the "editing the object" approach and was followed up in Chapter 8. This essentially took the view that all our update commands are addressed to the underlying object and the display acts merely as a way of viewing the effects of those updates. The other branch was the "editing the view approach" and assumes that it is the user's view of the object that is primary. Updates are then addressed to the view, and the underlying object must keep pace with these changes. This is arguably a more user-centred approach, and is investigated in this chapter. I say arguably because if we are to have a good user interface the two approaches will converge. On the side of editing the object, the presentation attempts to uncover the object's structure on the display. On the side of editing the view, if the global effects of updates to the display are to be predictable, then again the map between object and display and the effects of updates must be transparent. Good design will probably consist of a blend of the two approaches, and it is hardly surprising that at the end of this chapter we end up using the pointer space designed out of the former strategy to model structures resulting out of the latter. In the rest of this section, we introduce the concept of a complementary function, which acts as a unifying concept for several problems in addition to editing the display. The problem addressed by the rest of this chapter can then be seen as one of finding suitable translations from update functions to their complements. We then look at some of the principles that we will wish to apply to translation strategies. In particular, predictability will play a pivotal role in driving the chapter. Researchers into database theory have already investigated this problem and we use their terminology. However, we will see that the databases normal to this field differ in several respects from those common in general interface design. That is, our structures are both dynamic, and subject to structural change. Despite this, we look principally at the case of static views, as these are far more tractable and at least give us the general flavour required for more complex cases. The databases with which we deal differ markedly from typical DP databases in their structural complexity and scale. For instance, we may be interested in program syntax trees, or a small set of numbers, rather than large homogeneous relations. This is particularly important since many of the views defined over databases are slices put together out of these large relations, whereas those in which we are interested may be far more complex (even when static). The first major section gives a short algebra of views, so as not to clutter up the succeeding sections with too many definitions. Of particular importance are the definitions of complementary and independent views. The reader could choose to skip this and refer to it as necessary. Section §9.3 reviews possible translation strategies, starting with a rough taxonomy of strategies based on the level of generality at which they operate. It then examines the advantages and disadvantages of ad hoc translation schemes and schemes based around product databases. Finding these wanting, we go on to discuss the use of a complementary view which stays constant as the view of interest is updated. This is seen to have many advantages and bridges the gap between totally ad hoc methods and the restraints of product database formulations. Although the use of complementary views allows a level of predictability over the updates to the underlying data, it has unpredictable failure semantics, and §9.4 introduces the new concept of a covering view that supplies sufficient information to predict failure. The security implications of this are discussed. 9.1.1 Complementary functions In addition to the problem of editing an object through its display, there are several other problems which, although differing markedly in some respects, all share a common structure: - We are viewing a representation of an object on a display and then change it (perhaps insert a character into a text file). We wish to update the display image by making small changes rather than completely recreating the picture. - We are editing some view of a large database; we wish the underlying database to change in a way consistent with the changes in the view. We will see that this is usually far simpler than editing the display. • We want to say that the changes to an object are confined to a locality. • We are editing several objects, all of which must remain consistent with one another. If one is changed, the rest must change to remain consistent. Each of the above problems reduces to the following: we have two sets \((A, B)\) representing the objects/views and a relation \((r)\) between them; we have a transformation function \(f : A \rightarrow A\) and wish to find a complementary function, \(cf : B \rightarrow B\), which is consistent in that: \[ a \leftarrow r \rightarrow b \iff f(a) \leftarrow r \rightarrow cf(b) \] That is, the following commutes: \[ \begin{array}{ccc} A & \xrightarrow{f} & A \\ \downarrow{r} & & \downarrow{r} \\ B & \xleftarrow{cf} & B \end{array} \] In cases (i) and (ii) the relation will often be directed: in case (i) \(A\) is the object, \(B\) the view and \(r\) is the viewing function \(A \rightarrow B\); in case (ii) the function is the other way round. We could call this the "spider’s legs" problem. The legs represent the various views and they are joined by the body (the relation): as we pull one leg the others must follow. Note that this is equivalent to the problem of polymodality in logic programming. The finding of a complementary function is sometimes called translation (Bancilhon and Spyropoulos 1981). ### 9.1.2 Principles Several problems may occur in defining such a translation scheme: • **Uniqueness** – Unless the relation is functional \(A \rightarrow B\) there will be many choices of \(cf\) for a given \(f\). • **Failure** – Again, unless \(r\) is a function \(A \rightarrow B\) there may be no complementary function possible that satisfies the constraints. Similarly, when we have chosen a particular translation scheme, we still have the same problems in new guises: • **Uniqueness** – If there are several updates that achieve the same effect on \(A\), do their complementary functions achieve the same effect on \(B\)? That is, for any pair of updates \( f, g \) and objects \( a, b \) such that \( a \leftarrow r \rightarrow b \), is it true that: \[ f(a) = g(a) \implies cf(b) = cg(b) \] - **Failure** – Even where there is a consistent choice of a complementary function, it may not be defined for a particular translation scheme. For example, we may disallow the editing of key fields in a record, perhaps forcing the user to delete and re-enter such records. Further, for a particular update the complementary function may be partial. We may allow the editing of the department field of an employee record, but insist that the new department should already exist, even though in principle it would be possible to create a new department spontaneously. We can relate these issues to the usability principles of predictability and reachability (Chapter 3) and to sharing properties (Chapter 4): - **Predictability** – Does the user know what translation scheme has been chosen? Does the scheme admit a model by which the user can infer its behaviour? Can the user predict whether a given update will fail? If not, what additional information is required? - **Reachability** – The choice of translation scheme will affect the updates that are possible to \( B \) via the complementary functions, and also, because of the choice of failed updates, those that are possible to \( A \). - **Sharing** – In the case of several views being edited, the choice of the translation scheme will affect sharing properties such as the commutativity of updates on different views. - **Aliasing** – Do the users know what they are seeing? That is, do they know what the viewing function is? If they do not, there is no way they can relate what is seen and manipulated in the view to the underlying state of the system. ### 9.1.3 Complementary views – what you can’t see Aliasing reminds us that it is important that the designer and user are agreed as to what is in a view. For example, my bank statement has a running account balance. My interpretation of this view is how much money I have got, so if the amount is always positive I think I am in the black. However, the bank regards monies from cheque deposits as being available only when the cheque has cleared, and thus although the amounts shown on my statement are always positive I get charged interest and transaction charges. The problem is partly one of observability: the statement does not tell me my available balance, and thus does not tell be whether I am "really" in credit. To obtain this information from the statement means I have to remember what proportion of my deposits are cash and which are from cheques. It is also an aliasing problem, as a bank statement based on the actual date of deposits and one based on available balance would both appear the same. That is, the content of the view does not tell us about the identity. Aliasing is a thorny problem and may only become apparent when a breakdown occurs (as when I was charged on my account). However, the designer and the user do at least have the common view before them and this can serve as a focus for thrashing out a common interpretation. We can characterise the problem of aliasing as knowing what you can see. A new issue that will arise as the chapter progresses is the importance of knowing what you can not see. Whereas for observability the important issue for designer and user is agreeing on what they do see, the crucial issue for update semantics is agreeing on what they do not see. This seems a rather surprising statement, but the thing that makes it possible to understand change is knowing that certain other things do not change. When we edit one file, we expect other files to remain unchanged. When we pull the plug out of the bath, we expect the water to stay in the sink. So, for each view we will look for a complementary view which remains constant through updates. It is hard enough to get over the problem of aliasing. The designer and the user have trouble agreeing on what they can see. It is clearly even more important that explicit effort is made in the design and documentation of systems so that the user knows about this often implicit but crucially important view. Knowing what stays constant, i.e. knowing what you do not see, is fundamental. 9.1.4 Extra complexity – the text editor The data handled by typical interactive systems turn out to be far more complex than a typical DP database. This is the case even for apparently simple data structures such as the text of a document. We’ll take a look at a text editor and the choice of complementary function for the two modalities. The text consists of an unbounded number of lines all of the same fixed length (for simplicity) and a cursor position within the text. The display consists of a fixed number of lines of the same length as the text and a cursor also. The invariant relation will be that the display should be identical to the portion of text it would cover if the cursors were lined up. - Editing the text, display following – Take, for instance, inserting a new blank line after the cursor. We are then faced with problem of non-uniqueness: should we lose the top line of the display, or the bottom? Usually the choice is different depending on the position of the cursor in the display. • *Editing the display, text following* – This case is more difficult. If we again consider inserting a line on the screen, and say the bottom line of the screen is scrolled away, would we expect it also to disappear from the text? If not, why not? It would certainly be consistent with the invariant: obviously, some choices of complementary function are better than others! Even more bothersome is the case of deleting a line. Usually a new line "appears" from the hidden text to fill the gap. We are hardly then editing the view. In fact, to describe this adequately (and line insertion), we need a slightly more complex idea of complementary function. When we insert into our (say) 80x25 screen we obtain a 80x26 screen, and deletion similarly gives an 80x24 screen; we then expect these to bear a relation to the actual new display. Thus our screen update is from the real display (D) to some sort of extended display (X). We get the following diagram: Given such complexity, is editing the view, rather than the object worth thinking about? For simple cases (like text!), probably not, as it is reasonable to expect the users to perceive the underlying object as the item with which they are interacting. However, as the underlying object and the map between it and the view get more complex, it becomes more and more likely that the user will manipulate a surface model. For instance, when editing a file one rarely thinks in terms of the reads and writes to the disk and the allocation algorithms for disk space that are going on underneath; the file system is just such a complex view of the disk. One other thing that is worth noting from the example is that we tend to think of the relation between text and display as functional: "this display is the text between the 53rd line and the 77th". This is a valid perspective and the one we will use for much of this chapter. However, in the case of the display of a text, the view moves. We want dynamic or semantic views, not static ones. Fortunately, in many situations the forms of view do not require this complexity. 9.1.5 Differences from standard databases The example above shows that we should not expect all the properties of DP-style databases to hold for the more general case. In most DP situations, the structure of the database is fixed for long periods of time, and changing that structure is seen as a major, expert task. If we consider general systems for which we may want to design an interface, this may not hold. For instance, we may want to design an interface for manipulating a file system. We clearly want to create and delete files as well as edit them. In addition to this structural change, we also may have far greater structural complexity. So for instance, a portion of a program syntax tree is far more complicated than a list of personnel records. 9.1.6 Summary The concept of a complementary function over a relation captures many diverse problems, but we here confine ourselves to the case where the relation \( r \) is a function and usually refer to it as \( v \), the principal view. We must be prepared to examine the cases of dynamic, structurally changing and structurally complex views. However, we initially look at the simple case of possibly complex but static views. Further, we assume until §9.5 that the database is structurally static. This means that all views are valid for all database states. 9.2 Algebra of views The rest of this chapter considers complementary functions on databases resulting from updates to views. This section gives a short exposition of those aspects of the algebra of database views that will be needed later. The definitions are not new; they can be found elsewhere (Bancilhon and Spyratos 1981). A view is regarded simply as a function on a database, \( v : Db \rightarrow \text{range} \). If the view is being used to produce some sort of output for the user, then the form of the map will be very important. However, as in the case of the definitions over PIEs, we do not consider fidelity conditions here. Other views will be wanted for their conceptual or definitional value, and are not intended to represent a user image. In these cases fidelity will be irrelevant and only the information content of the view is important. Hence two views would be equivalent if they had the same information content. 9.2.1 Information lattice Where we are interested only in the information content of views, we can define an information ordering on them. One view is considered a subview of another if the former can be derived from the latter: \[ \{ \text{subview} \}: \] \[ u \text{ is a subview of } v, \ u \leq v \text{ iff: } \exists g: \text{range} \to \text{range} \text{ st } \forall db \ g \circ v(db) = u(db) \] As when we considered PIES, definitions concerning information can be made using functions (as above) or more implicitly: \[ u \leq v \equiv \forall db, db' v(db) = v(db') \Rightarrow u(db) = u(db') \] That is, we can always work out what is in view \( u \) if we know what is in view \( v \). This clearly gives a partial order to the views. This partial order admits a least upper bound or supremum by using the product view: \[ \{ \text{product} \}: \] \[ (u \times v): \text{Db} \to \text{range} \times \text{range} \] \[ (u \times v)(db) = (u(db), v(db)) \] This is clearly the minimal view (with respect to \( \leq \)) of which both \( u \) and \( v \) are subviews. If the views are for the user, then this corresponds to a new view where both the originals are visible. So it would still be the least upper bound even if we added quite strict fidelity rules on the information order. There is also a maximal element, namely the identity function on the database, \( id_{db} \). In both the case of the supremum and the maximal element, whether they are acceptable or not as a "real" visible view depends on the set of views regarded as acceptable. In the case of normal databases the former is probably acceptable, whereas the latter, implying that the user can see all the database at once, is arguably not reasonable. For the case of display views of texts, even the supremum represents a display twice as large as is possible. However, we only need to use the supremum to make definitions, so it can be used even when unacceptable as a normal view. 9.2.2 Independent views It will be important later to know whether two views are interrelated or not, that is, whether the views can vary independently of one another. We can define independence of views: \[ \{ \text{independence} \}: \] \[u, v \text{ are independent iff:} \] \[\forall a \in \text{range}, b \in \text{range} \exists db \text{ st } a = u(db) \text{ and } b = v(db)\] That is, for any given pair of possible values for \(u\) and \(v\), we can find a database simultaneously yielding those views. As well as using this concept later when we consider translations of views, it is clearly important when we consider sharing. For example, consider two views being presented in two windows. The database is being manipulated by editing the views and we assume all updates to the views are possible. Clearly, the two windows cannot be display independent unless the views are. If the views were not independent then there would be circumstances when a change in one view would yield a situation where there would be no consistent database state yielding both views. As in the case of display independence in Chapter 3 and independence of blocks in the previous chapter, pairwise independence does not imply independence of more complex configurations. For example, consider a database consisting of three numbers, a stock level, an amount on order, and a minimum stocking level: \[db = \text{stock\_level, amt\_ordered, min\_stock}\] There is the sensible constraint that the actual stock level plus the amount on order must always exceed the minimum stock level: \[\text{stock\_level} + \text{amt\_ordered} \geq \text{min\_stock}\] If we consider the three views giving the three numbers separately, then each view is independent of the other two; however, they are clearly not independent as a group. Thus in this example (and in general): \[u \text{ independent of } v, \text{ and } u \text{ independent of } w \] \[\text{does not imply } u \text{ independent of } v \times w\] Similarly, we could create arbitrarily complex situations with \(n\)-way independence but not \(n+1\)-way independence. In this example, we could have "normalised" the views, to make them independent, by considering the view set: \{ stock\_level, amt\_ordered, stock\_level + amt\_ordered − min\_stock \} These views are independent in all configurations, but the last view is, of course, by no means sensible. For example, updating the stock level when an item was sold would implicitly reduce the minimum stock level! This example gives us some inkling of the complexity of view editing. 9.2.3 Complementary views In terms of the information lattice, the opposite of two views being independent is their being complementary. That is, together they contain all the information in the database: \{ complementary views \}: \[ u \text{ and } v \text{ are complementary iff: } \forall db, db' \quad u(db) = u(db') \text{ and } v(db) = v(db') \Rightarrow db = db' \] or, in terms of the supremum: \[ (u \times v) = id_{Db} \] A third, functional formulation is: \[ \exists f: \text{range } \times \text{range } \rightarrow Db \quad \text{st} \quad \forall db \quad f(u(db), v(db)) = db \] The function \( f \) is, of course, unique and is the inverse to the supremum, so we could say: \[ u \text{ and } v \text{ are complementary iff } (u \times v)^{-1} \text{ exists} \] In general there may be many views complementary to a given view. Consider a database consisting of two integers, \( x \) and \( y \), constrained so that \( x > y \). If we have one view giving \( x \) (call it \( X \)), then the view giving the value of \( y \) is complementary to \( X \), but then so is the view giving \( y \) cubed. These two views contain exactly the same information so could be said to be equivalent. But even if we consider information content, the view yielding \( x + y \) is also a complement to \( X \) but is different from \( Y \). Further, we may add information to either of the views, and they remain complements. In fact, view independence and complementarity satisfy the obvious conservation properties with respect to subviews: if \( u \leq u' \) and \( v \leq v' \) then \( u' \) and \( v' \) independent \( \Rightarrow \) \( u \) and \( v \) independent and \( u \) and \( v \) complementary \( \Rightarrow \) \( u' \) and \( v' \) complementary 9.2.4 Summary In summary, we have defined four basic concepts: - **Information or subview ordering** – This says when one view contains enough information to determine another. - **Supremum over this ordering** – This yields a view (\( u \times v \)) containing as much information as \( u \) and \( v \) put together. - **Independence** – This tells us when two views can take any pair of values. - **Complementary views** – This is when two views are sufficient to determine the entire database and, in particular, implies that there is an inverse to the supremum. 9.3 Translation techniques – complementary views This section reviews different ways of translating updates to views into updates on the underlying database. It starts off by recalling the translation problem, and putting it in terms of the notation that is used in the section. This is followed by a subsection which classifies translation strategies into different levels. Sections §9.3.3, §9.3.4 and §9.3.5 deal in turn with ad hoc translation, translation when the underlying database can be regarded as a Cartesian product of views, and finally, translation using a complementary view. 9.3.1 The view update problem – requirements To recap the situation, we are concentrating on a view \( v \) on a database \( Db \). We wish to find a complementary function for any updating function \( f \) on the view. In the terms used by the database community, this process of finding the complementary function is called translation. Thus the problem which we address is: \{ translation \}: given a view \( v \) and a function \( f: \text{range} \to \text{range} \), find a translation \( T_f : Db \to Db \) such that: \[ f \circ v = v \circ T_f \] If we think of the view update as giving us an explicit change for a part of \( Db \), the translation problem can be seen as determining what happens to the things that are not mentioned explicitly in the view, or are specified only partly by the view update. It is thus a form of the framing problem. \subsection*{9.3.2 Translation taxonomy} Two major determinants of the update strategy are: (i) What update operations are available as translations? (ii) How much information about the update is required to calculate the trans- lation? Dealing with point (i) first of all, it is clear that there may be limitations on the sorts of updates that are possible. For instance, in the case of updating a display in line with a text, there are the available terminal codes, and in the case of a view on a database, there may only be certain operations allowed on the data by its underlying implementation. It will often be assumed that any transition between consistent states is possible. This assumption may or may not be reasonable. On the positive side, we must assume the set of updates available are complete, in that any consistent state can be obtained via some series of updates; if this is not so then we must assume there is something seriously wrong with our implementation. It is fundamentally unreachable. On the negative side, even though in principle such a sequence exists, it may be arbitrarily complex and therefore hard to generate. Such complexity is potentially disastrous in a shared database, where a large part of the data may be locked during a very long transaction. An important practical consideration for any translation scheme, is that the complexity of the update should be of the same order as the complexity of the view function. Considering (ii), we need to clarify the level of instantiation at which we wish translate. Typically, updates are parameterised functions, for example: - "insert the character \_?\_ into the text" - "change date to \_?\_" - "delete the record with key \_?\__" Thus the general update is of the form:- level 1 – "add record": \( \text{param} \times A \to A \) We can then instantiate this for a given parameter: **level 2** – "add record Fred born on 29/2/60": \( A \rightarrow A \) and finally, for a given view instance, \( a \in A \): **level 3** – <table> <thead> <tr> <th>NAME</th> <th>DATE</th> <th>NAME</th> <th>DATE</th> </tr> </thead> <tbody> <tr> <td>Jill</td> <td>3/7/53</td> <td>Jill</td> <td>3/7/53</td> </tr> <tr> <td>Tom</td> <td>27/10/61</td> <td>Fred</td> <td>29/2/60</td> </tr> <tr> <td>Glenda</td> <td>15/4/47</td> <td>Tom</td> <td>27/10/61</td> </tr> <tr> <td>Glenda</td> <td>15/4/47</td> <td></td> <td></td> </tr> </tbody> </table> In the expression of the translation problem, we have dealt implicitly with level 2; however, if the translation function \( T_f \) is not a basic update operation on \( D_b \) but instead does different updates depending on the the exact value of the view, then it is operating at level 3. On the other hand, if it is generic over a parameterised class of update functions then it operates at level 1. When a translation scheme operates at level 1 or 2, giving for each update operation a fixed sequence of database updates irrespective of the database state, we can say it is **context independent**. For example, when keeping a text in line with a screen display, many operations yield context-independent updates; so that "insert _?_" at the cursor point on the display translates to "insert _?_" at the text cursor, irrespective of the current text and display states. On the other hand, some translators at level 3 may need the value of the view to decide on the update, but may not need to know the particular update function (e.g. add_record) used. That is, they have the property that they are not dependent on the type of the update, only on the previous and updated states. We could call such translations **process independent**. An example of this would be files as views of a file system. When an edit is finished, the update to the file system is dependent only on the final value of the edited file, not on the particular edits which were done to the file. Other translations will be hybrid: for instance, when keeping a screen display in line with a changing text, the update "delete the line below the cursor" may become something like: "delete the line below the cursor, then: if the cursor is near the bottom of the screen add the relevant line of the text to the bottom of the screen, otherwise add the relevant line of the text at the top." It should be noted that a translation may be either context or process independent at the behavioural level, yet have an implementation that does not possess this property. This is particularly the case if the update strategy is defined using operations that are not available on the database directly, but have to be simulated: in particular if one assumes free update of the database. 9.3.3 Ad hoc translation We can approach each task of update translation in a one-off way. In the short-run, this is the simplest translation strategy. For instance, we might supply an index of variables used in a program: ``` amount occurs 2 times amount is static variable in main declared line 3 used lines 7 and 8 amount is parameter to do_work declared line 73 not used ``` ``` total occurs 1 time total is static variable in do_work declared line 77 used lines 86, 87, 93 and 101 ``` We begin to ask what updating various fields might mean. We decide that updating the variable name `amount` in the "occurs" line would be regarded as a global renaming of all occurrences of the variable name. However, it would have to fail if this resulted in any name clashes. Similarly, we might want to allow editing the variable name in the "is static in main" line. This would rename the variable just in that context; again it might have name clash problems, but would also mean moving this to a new subheading. Editing the procedure name within which a variable is used could be interpreted as a renaming of the procedure; however, editing the line numbers where a variable is referenced makes no sense at all. Even where updates are allowed, we would need to be careful. For instance, if we wished to edit the variable `amount` to read `total` we would have an intermediate state which would lead to name clashes. The edits would therefore have to be committed in non-atomic units. Clearly it is a complex job deciding what is updatable, and what those updates mean. Features of translation that are apparent here are: - Only a subset of possible update operations are allowed. Further, this example has assumed that updates are the natural ones for the view. In fact, the set of updates will usually be defined more rigidly by the underlying data objects and are not necessarily sensible ones for the view. - Those updates that are allowed may fail sometimes. (This is a feature of all translation strategies, and of normal updates.) - The semantics of updates may have to be changed radically: for instance, editing a variable name in an individual use would relocate that use to a different variable heading. (Again, this is not solely a problem of ad hoc strategies.) Ad hoc strategies have several disadvantages: - **Predictability** – It may not be clear to the user what the effect of an update will be. In particular, it may be that different ways of achieving the same change in the view may have different effects in the underlying database. - **Reachability** – It may be very unclear what changes can be achieved through the view. - **Dishonesty** – It is easy to fool oneself and others that it is the view that is being edited, whereas this is really a subterfuge for editing operations on the underlying object. This is particularly a problem if the concentration is not on "what would editing this value mean", as in the example above, but instead on "what can we do with database updates". Perhaps the most important of the criticisms above is the predictability of the consequent changes in the unviewed parts of the database. For instance, in our stock control example, it would be sensible for any update of stock level to generate an order and hence change the number on order, but not reduce the minimum stock level. Making this sort of inference in an ad hoc system can be difficult. On the other hand, an ad hoc approach has important advantages: - **Generality** – There are no fixed limitations to the sort of view we can tackle. But it may be difficult! - **Task orientation** – It is designed for a particular task and can be fitted to it. For instance, it may be deemed inappropriate to edit procedure names via a variable names index. This form of task-specific limitation may be difficult to achieve using a more unified strategy, and even where it is possible, it is less likely to be noticed. Because of these disadvantages, and in spite of these advantages, we now look at more unified and generic approaches to translation. 9.3.4 Product databases The simplest case of view update is when \( Db \) can be expressed as a Cartesian product and the views as "slices" of this. That is, \( Db = \prod_{\mu \in M} A_\mu \) and: \[ \forall v \in V \exists \mu_1, \cdots, \mu_n \text{ st range } = \prod A_{\mu_i} \\ \text{and } v(<a_\mu>_{\mu \in M}) = <a_{\mu_i}>_{i \in \{1, \cdots, n\}} \] In this case, for any given \( v \) we decompose \( Db \) into a product \( A \times B \) where \( A \) is the product of the \( A_\mu \) "sliced" by \( v \) and \( B \) is the rest. Then we have simply \( v(<a, b>) = a \) and for any update \( f: a \rightarrow a' \) we have a translation to \( Tf: <a, b> \rightarrow <a', b> \). A simple (flat) file system is an example of a product database where the individual files are the views. If the situation is more complex and there are invariants to be preserved of the tuple, then it is tempting simply to amend this so that for any consistent pair \( <a, b> \) the update \( f: a \rightarrow a' \) has a translation \( Tf: <a, b> \rightarrow <a', b> \) if the latter is consistent, otherwise it fails. This strategy works quite well if the consistency relation is simple. An example of this is a relational database with the views being the relations. If we can normalise the relation so that the only consistency requirements are those of non-null key fields and existent or null alien keys, then the former is within a single relation and the latter is the only cross-relation (and hence cross-view) constraint on update. The reason why this particular relation is acceptable is that the reachability is preserved; in order to delete a tuple, we can simply go round the views nulling all references to it, and then remove it. Similarly, to add a set of mutually referencing tuples we can add them with nulled alien keys and then go round filling them in when all the tuples are in place. Not all cases are so simple, and it is easy to think of consistency requirements that totally disallow certain updates. One of the aims of normalisation is precisely to make these consistency requirements simple, and to push as much semantics as possible into the relational structure. In principle, any database with views could be regarded as the Cartesian product of those views with suitable consistency requirements, but unless these requirements are very simple (as above) there is not necessarily much to be gained in terms of update specification. The approach taken by Khosia et al. (1986) is considerably more complex, being based on modal logic. However, their view that a database should be specified first as a collection of views, has some of the characteristics of a constrained Cartesian product. Their update rules between views are \textit{ad hoc}. 9.3.5 Complementary views The general idea that, for a particular view, we can decompose the database into a product is more useful. In fact, the attempts to deal with the update problem are precisely along these lines. Essentially we look for another view (u say), such that between them v and u determine the database uniquely. This is precisely the condition that u is a complement to v. We can then say that for any db with a = v(db) and update f: a → a’ the translation is such that u(db) remains constant. If no such update is possible, then the original update to the view fails: \[ \begin{align*} \text{let } a &= v(db), \quad b = u(db) \quad \text{and } f: a \rightarrow a' \text{ be an update} \\ \text{if } \exists db' \text{ st } v(db') = a' \quad u(db') = b \\ \text{define } T_f: db \rightarrow db' \\ \text{otherwise fail} \end{align*} \] That is, the following diagram commutes or the update fails: \[ \begin{array}{c} \text{range} \quad f \quad \text{range} \\ \downarrow v \quad \downarrow v \\ Db \quad T_f \quad Db \\ \downarrow u \quad \downarrow u \\ \text{range} \quad id \quad \text{range} \end{array} \] Note that this is precisely the same situation as the simple product, as we can regard the valid database states as equivalent to the set of pairs <v(db), u(db)>. Alternatively, we could say the product database translation is a special case of this, where we choose for any view v with \(\text{range} = \prod A_\mu\), the complement u where \(\text{range} = \prod_{\mu \neq \mu} A_\mu\). Using complements is not only a nice way of obtaining a translation, it is essential (either implicit or explicit) to achieve reasonable properties. Bancilhon and Spyritatos (1981) show that any translation rule T that satisfies: \[ \{ \text{morphism} \}: \forall f, f': A \to A \quad Tf \circ Tf' = T(f \circ f') \] and \[ \forall f: A \to A \quad f(a) = a \Rightarrow Tf(db) = db \] where \(v(db) = a\), must be given by such a complement. Further translations generated by complements are process independent, which enhances their predictability. There are, of course, many such complement views for a given view. The bigger the view, the more updates it fails. It is therefore sensible to look for a "minimal" view. We can measure minimality using the information ordering, and then ask for a complement that is minimal with respect to this. However, even such a minimal complement cannot be guaranteed to be unique. The special case of the unconstrained product is obtained if the views are also independent. If a complement is independent, then it is automatically minimal although it is still not unique. However, Cosmadikis and Papadimitriou (1984) show that where the database is relational, there is a unique independent complement so long as we only look at monotonic views. (Here monotonic means that as one adds tuples to the database, tuples are added to the view.) This special case is not likely to be of general use for complex views, however, so we must be content with having a non-unique complementary view and telling the user what it is. Thus the procedural uncertainty of the user is reduced from the question of "What will this update do?" to "What will stay constant when I do this update?". The latter is static information and more easily conveyed and memorised than the former. It does depend somewhat on the users’ preferred learning strategy but at least they have the choice. **9.3.6 Discussion** Clearly, translations generated by complementary views have a lot of advantages in terms of predictability and the consistency of update semantics. The unique complementary independent view derived by Cosmadikis and Papadimitriou is based on assumptions unlikely to obtain for the majority of complex views found in general interface design. The choice of a complementary space becomes a major decision. In particular, it is where task knowledge can be brought into the design process. For instance, if we were trying to form a complimentary view for the variables’ index view in the example earlier, we would probably put the procedure names in the complementary view. In fact, this would be an especially interesting choice, as it deliberately makes the complement non-minimal, and is an indication that even where minimal or independent complements can be found, this is not necessarily what is wanted. Of course, this is hardly a novel point, as most operating systems distinguish between the permissions to view and modify data. Product databases have a lot of advantages: - All views have an independent complement, implying no failure for internally consistent view updates. - Reachability, as we can change components independently. - Procedural uncertainty is minimised, since the complement is obvious. However, they also have some disadvantages: - No complex, cross-database views, implying no views like indices, lists of cross-references, etc. - No hiding, formatting, etc., so all views give complete information on some part of the database. - No structural change: the product and its views are fixed. We can alleviate some of these disadvantages. The lack of complex views can be alleviated by having additional read-only views that are not necessarily projections. These could be used for navigation but not update. Hiding and formatting can be achieved by allowing several views of each primary view, whose update relative to the primary view is defined either ad hoc or using a complementary subview. The semantics of the subview updates can be cross-checked against the explicit view if they are unclear. The issue of structural change is difficult for complementary view translation as well as for product databases, and we consider it in a separate section (§9.5.3). The real problem with using product databases, is that it is not always easy, or meaningful, to express a design in that way. Having said that, the normalisation process in relational databases attempts to approximate a product database, so it is not an unreasonable goal. Still, for general interfaces we are likely only to approximate the product design in some places, and have to search for more complex complements elsewhere. For some views it is very difficult even to find a complement. For example, the proper complement for the variables index is not very obvious. If we find ourselves forced to use an ad hoc translation strategy, we can still impose a loose complementary view methodology. That is, we can concentrate on what is to be left unchanged in the database when a view is updated, and design our translation around that general idea. It is likely to be helpful for the user to know what is constant, even if this does not uniquely define the update that has occurred. This is an example of searching for a deterministic ground, as discussed in Chapter 6. In the next section, we consider further the properties of complementary views, in particular their sharing properties, and the predictability of update failure. 9.4 User interface properties and complementary views We have already noted how the use of a complementary view, where it is possible, increases the predictability of an update strategy, as the user need only know what the complement is and can then infer the result of view updates. In this section we look further at the interface properties of complementary views. We begin by looking briefly at aliasing problems with complementary views. After this we consider sharing properties and how these relate to sharing of windows as defined in Chapter 4. We then turn our attention to the predictability of update failure, and introduce the concept of a covering view. Finally, we assess the security implications of imposing a covering view as an interface requirement. 9.4.1 Agreeing upon the views: aliasing and worse The designer of a system presents a view to the user. The user sees the contents of the view as the system runs, and infers some idea of what the view is. Of course, as we have seen before, aliasing means that the user and the designer need not agree. Content does not determine identity. Two views may look the same and yet be different. Note that this form of aliasing is more complex than, say, knowing one’s position in a document. There we assumed that the user knew the kind of view, and the problem was knowing where in the document the view was. Here there may even be confusion about the nature of the view itself. Imagine we have a programming system that, when the user clicks upon an identifier, gives an index of other references in the program through which she can further navigate. One day, the programmer is looking at a paper listing and wants to get to the line containing the identifier sum. Coincidentally the variable sum is on the screen, so she clicks this. Unfortunately, it does not reference the line which she wants. Why? Well, the programmer had assumed that the indexing was lexical, to all variables with the given name. In fact, the designer’s model was that only the incidents of the same semantic variable were given. The form of the indices for the two views is the same, a list of references, but the views are very different. Note that this form of aliasing is closely linked to procedural uncertainty and conceptual capture, as discussed in Chapter 6. This can be attacked only partly through the immediate user interface; the full solution must involve both study of the natural models of users and the production of suitable documentation to explain the nature of the view. A much broader idea of the “interface” is required to address problems of aliasing that arise through procedural uncertainty than those that arise through data uncertainty. Now, if it is hard for the designer and the user to agree about what they do see, how much more difficult it is for them to agree about what they do not see. The complementary view is, by its nature, not presented in the interface, and thus misconceptions about what does not change may take a long time to emerge, and the possibility of confusion is enormous. Note that this is not just a problem when the designer explicitly uses a complementary view approach. Whatever view update strategy is chosen, the user is not and cannot be aware of all the hidden ramifications of their actions. In the simple case of a product database (if the user is aware of it) the user’s actions can be made local to the particular attribute. In a more complex setting, the notion of locality depends crucially on viewpoint and the problems are precisely akin to those of determining the complementary view. There is no easy answer to this issue of agreement between user and designer. The best hope lies in the designer being aware of the problem. 9.4.2 Sharing properties of complementary views We consider again the sharing properties of windowed systems, where each window is a view of an underlying database. In the section on the algebra of views, we said that if all updates succeed, then view independence guarantees display independence (§9.2.2). Of course, when we consider complementary-view-based translation, some view updates will fail. This means we can be more generous about the views that do not share, as some view updates that would have resulted in display interaction will now fail. Display independence says that the display of one window stays the same as commands are executed in another window. If all the commands are view updates and the complement to the view is constant, then if the first window is a subview of the complement we can guarantee display independence. That is, assuming the complement to the view v is u: \[ v' \leq u \] the window of v’ is display independent of the window of v \iff If v’ is not a subview of u, then we can find two database states \( db \) and \( db' \) such that: \[ u( db ) = u( db' ) \quad \text{and} \quad v'( db ) \neq v'( db' ) \] However, because v and u between them determine the database we must have: \[ u( db ) = u( db' ) \quad \Rightarrow \quad v( db ) \neq v( db' ) \] Note that the condition is not only sufficient but necessary. **Proof:** If v’ is not a subview of u, then we can find two database states \( db \) and \( db' \) such that: \[ u( db ) = u( db' ) \quad \text{and} \quad v'( db ) \neq v'( db' ) \] However, because v and u between them determine the database we must have: \[ u( db ) = u( db' ) \quad \Rightarrow \quad v( db ) \neq v( db' ) \] Thus the update: \[ f: \mathcal{v}( \mathit{db} ) \rightarrow \mathcal{v}( \mathit{db}' ) \] would succeed and would change the value of \( \mathcal{v}' \). Result independence is far more difficult. Consider the following example of two pairs of independent complementary views. We have a database consisting of three, unconstrained integers, \((x, y \text{ and } z)\). We will consider the two pairs of views: - \( x \) with complement \(( y, z )\) - \( y \) with complement \(( x, y \times (x + z) )\) These views are independent of one another and satisfy the conditions for display independence. We consider the two updates: \[ f_x : \quad x = 1 \rightarrow x = 2 \] \[ f_y : \quad y = 1 \rightarrow y = 2 \] If we start in the database state \(( x = 1, y = 1, z = 1 )\), we consider the effects of the translations of these two updates performed in different orders: \{ \( f_x \) first then \( f_y \) \}: \[ T_{f_x} : (1, 1, 1) \rightarrow (2, 1, 1) \] \[ T_{f_y} : (2, 1, 1) \rightarrow (2, 2, -\frac{1}{2}) \quad 1\times(2 + 1) = 2\times\left(2 - \frac{1}{2}\right) \] \{ \( f_y \) first then \( f_x \) \}: \[ T_{f_y} : (1, 1, 1) \rightarrow (1, 2, 0) \quad 1\times(1 + 1) = 2\times(1 + 0) \] \[ T_{f_x} : (1, 2, 0) \rightarrow (2, 2, 0) \] That is, the two updates do not commute, and hence windows based on these would not be result independent. This is all the more surprising, as our complements were independent and hence "good" ones with no failure. In this example, as the database was a simple product with no constraints, we could have defined the complements so that the updates to \( x \) and \( y \) did commute (though we might have good task-specific reasons for our definitions). In more complex databases such a choice may not only be inexpedient, but be impossible. We can give a sufficient (but not necessary) condition for result independence of two independent views \( \mathcal{v} \) and \( \mathcal{v}' \) with complements \( u \) and \( u' \), respectively: \[ \exists u_{glob} \quad \text{such that} \quad u_{glob} \leq u \quad \text{and} \quad u_{glob} \leq u' \quad \text{and} \quad u \leq (v \times u_{glob}) \quad \text{and} \quad u' \leq (v' \times u_{glob}) \] Informally, \( u_{glob} \) is complementary to \( v \times v' \) and thus all updates are observable from \( v \) and \( v' \). However, again, unless one is using a simple policy for finding complements (such as the product database), such a view may not be possible or desirable. 9.4.3 Predicting failure – covering views The big advantage of an independent complement is in terms of predictability. If the views are not independent then there are updates that are sometimes legal and sometimes not, depending on the value of the (invisible) complementary view. If we wanted to see all this complementary view in addition to the principal view, then by its definition we would be viewing the entire database; exactly what the views of the database are there to avoid. Clearly, we must look for a covering view \((w)\) that is small enough to present to the user along with the principal view, and yet has enough information to predict whether a particular update will succeed or fail. We can formulate the property of the covering view as follows: \[ \{ \text{covering} \}: \forall db_1, db_2 \text{ st } (v \times w)(db_1) = (v \times w)(db_2) \exists db_1' \text{ st } u(db_1') = u(db_1) \Rightarrow \exists db_2' \text{ st } u(db_2') = u(db_2) \text{ and } v(db_1') = v(db_2') \] That is, if for any two database states both the principal view and the covering view are the same, then any consistent update on the first database is consistent for the second. Note again that for any given view and complement, even a minimal covering view is not necessarily unique. Example Consider the case of a relational database with the following relations: <table> <thead> <tr> <th>employee</th> <th>department</th> </tr> </thead> <tbody> <tr> <td>EMP_NAME</td> <td>EMP_DEPT</td> </tr> <tr> <td>Diane</td> <td>Sales</td> </tr> <tr> <td>Fred</td> <td>Accounts</td> </tr> <tr> <td>Tom</td> <td>Sales</td> </tr> <tr> <td>Jane</td> <td>Clerical</td> </tr> <tr> <td>Helen</td> <td>Sales</td> </tr> </tbody> </table> The update view is employee, and every EMP_DEPT must be a valid DEPT_NAME. We try to enter a record for Gillian in the personnel department (just formed); this succeeds or fails depending on whether there is an entry in the department relation for Personnel or not. A suitable covering view for this is clearly the set of department names. Another example would be if $u$ were a statement in a Pascal program (and $Db$ the set of valid Pascal programs); then a possible covering view for $u$ might contain a list of all the variable names in the scope of the statement and their types. In fact, we can ask for a covering view even when the translation is not generated from a complement. In this case we have to amend the definition to say that $w$ is a covering view for an update $f$ to a view $v$ if: $$\forall db_1, db_2 \ st \ (v \times w)(db_1) = (v \times w)(db_2)$$ $$\exists db_1' \ st \ Tf: db_1 \rightarrow db_1' \Rightarrow (\exists db_2' \ st \ Tf: db_2 \rightarrow db_2')$$ That is information from $u$ and $w$ together is sufficient to tell whether a particular update to $u$ will succeed. NOTE: the covering view deals only with the data uncertainty about the complement’s effect on update failure. If users are unaware of what view they are manipulating, or what the constant complement is, then the covering view can only help but may not be sufficient to make this clear. In general, procedural uncertainty is very difficult to handle (viz. 200-page manuals!). ### 9.4.4 Security Of course, one of the reasons for restricting access to a view of the database is security. The covering view isn’t updatable, but might require information that is not intended to be available to the user. This is not such a drawback as it seems: the very fact that the updates on the view behave differently depending on the hidden information implies that, in principle, it is possible to infer some of the hidden information. It is precisely this information that is required in the covering view. Thus if one finds that there is some item of information in the covering view that is regarded as confidential, one should think hard about whether that information was indirectly available anyway. This is similar to the case of statistical queries to databases, where one is allowed to ask for summary statistics of the data but is not supposed to have access to the data itself. Depending on the queries allowed it may be possible to infer the raw data from the summary statistics, breaking confidentiality. (Jonge 1983) This argument should not be taken to its extreme: for example, if one enters a random user name and password to a system, then it will behave differently when they are valid and when they are not; however, it would not be reasonable to demand that all the user names and passwords be public! Clearly, one would trade off predictability against security in this case. Even so, predictability analysis and the creation of suitable covering views would actually form a powerful test of system security. 9.5 Dynamic views and structural change In most of this chapter, we have assumed implicitly that it is meaningful to talk of a view, which can be applied to any database state. Typically, views may be more dynamic than that. We can consider three types of dynamism: - **Content** – The view is defined by some feature of content: for example, the set of all records of people in the Personnel department. - **Identity** – The view is defined indicatively: for example, this collection of records which I want to deal with no matter how their content changes. (The collection may initially be defined by content but is not constrained by it.) Again, in editing text we want to display this region of text, whatever changes happen elsewhere. - **Structure** – Much of the discussion of database views assumes a constant database structure. In general systems this may change, and the set of views available at any time can change accordingly. Many database packages deal very badly with schematic changes to live databases. The first of these categories is included because it has been described elsewhere as a dynamic view. (Garlan 1986) However, that definition is in fact consistent with the definitions of static view given earlier in this chapter. The complication of it, compared with more syntactic views, is that update semantics are less clear. However, it can be dealt with using complementary views quite adequately. The second category is clearly related to the issue of dynamic pointers. We will reserve the title dynamic view for this category of view. The third category of structural change is very hard to deal with and we will see by example how easy it is to make a mess of this. 9.5.1 Dynamic views We look at general views where we want the semantic identity of the view to be preserved. As with pointer spaces we have two distinguishing factors, the set of views available changes with the object viewed, and the notion of "sameness" between views depends on the operations that caused the database change. The first of these can be captured by using a set of valid views for each database state, in a similar fashion to the valid pointers to an object we considered in the previous chapter. For the "sameness" property we can use the idea of a pull function again. For each update $F$, we associate a pull function $F \cdot pull$ which takes views to their "natural" equivalents: $$\forall db \in Db, \ v \in valid\_views(\ db)$$ $$let \ db', \ pull = F(\ db)$$ $$then \ pull(\ v) \in valid\_views(\ db')$$ When we discussed various update strategies, we regarded process independence as being a useful trait. That is, the form of the update was unimportant, only the initial and final states mattered. This will almost always not be the case for dynamic views. We may easily be able to perform two different series of updates which would yield the same final database state, but affect the dynamic views in a totally different manner. We must not only know what an update does, but how it does it. As an example of the importance of this, consider two records in a database: \(<\text{TOM}, 1973>\> \(<\text{FRED}, 1971>\> We start with a view looking at Tom’s record. We then edit the database exchanging first the names, and then the dates. A view defined by content would still look at \(<\text{TOM}, 1973>\>\), but a view based on identity would be of the record that now says \(<\text{FRED}, 1971>\>\). The problem of view update translation is now correspondingly more complex: given \(a = u(db)\) and \(f : a \rightarrow a'\) we want a translation \(Tf : db \rightarrow db'\) such that \((Tf . pull(u))(db') = a'\). It is similarly more complex to talk about complements for such views. We cannot talk about a complement of a specific view, but instead of a complement function from views to views. This complement function must of course be preserved by the pull functions. If we let the set of complement views be \(V_c : Db \rightarrow B\), a possibly different set of views than \(V\), we get the following condition: \[comp : V \rightarrow V_c\] \[\forall v \in V, F \in U, db \in Db\] \[comp(F . pull(db, v)) = F . pull(db, comp(v))\] For the map to define a complementariness relation, we need the view and its complement to determine the database state: \[\forall db, db' \in Db, v \in valid_views(db), v' \in valid_views(db')\] \[let\ u = comp(v),\ u' = comp(v')\] \[then\ v(db) = v'(db')\ and\ u(db) = u'(db')\ \Rightarrow\ db = db'\] That is, if we have a value for the view, and a value for the complement, there is only one possible set of database state and view with these as their values. We can then use this to define a translation scheme for update, and the new view to use. It does not give us the general pull function for other views. This may not matter if there is only one view of interest, but if this is not so we need more structure again to obtain the relevant function. Alternatively, we can use the existing knowledge of pointer spaces and model dynamic views using these. ### 9.5.2 Using pointer spaces to model dynamic views The properties one wants of dynamic views are clearly similar to those of dynamic pointers, so it is natural to consider using pointer spaces and subobject projections to give dynamic views. The notions of determinacy and independence generated by subobject projections are consistent with the definition of information ordering and independence for views. The only difference is that the subobject projection, as a function of a block \( b \), is defined only for objects with a given set of valid pointers. This is precisely what we expect for dynamic views. Again, even when a sequence of operations maps back to an object with the same valid pointers, there is no guarantee that statically identical blocks are semantically the same (i.e. pulled to each other). So, for instance, we might operate on the string "abcde" by `delete(3,_)` followed by `insert(2,"c",_)`: ``` abcde ----> delete(3) ----> abde ----> insert(2,"c") ----> abcde ``` However, \( pull((2,3)) \neq (3,3) \neq (2,3) \). As block pointers behave so much like the intended behaviour of dynamic views, it is natural to identify the object component of their subobject projection with the view. This approach is taken further in Dix (1987b) and demonstrates the usefulness of the dynamic pointer approach. However, the use of dynamic pointers cannot hide the fundamental complexity of dynamic views. When we considered static views, we saw how difficult it can be even for the designer and the user to retain a common understanding both of what they do see and of what they do not see. This is even more difficult and requires more care on the part of the designer when the views are dynamic and essentially "move about" the database. ### 9.5.3 Structural change Some years ago a colleague was demonstrating a powerful (and expensive) commercial relational database that he was evaluating. After seeing some of the basic operations, I asked how well it coped with changes to the database schema. Within seconds he added a new field to an existing relation. I was duly impressed. However, I noticed that the database manager had filled the empty fields with a special NULL entry. One of the options for a field was that NULLs were not allowed. What would happen if you asked it to add a new non-NULL field. He tried it and, sensibly enough, the database refused. Presumably you obtained a non-NULL field by first creating a normal field, filling it with non- NULL entries and then changing its attributes. What would happen if you made a mistake? One of the fields in the relation we were looking at had some NULL and some filled entries. Try changing that field to be non-NULL, I suggested. He did and the database complied. All the records with NULLs in them were removed! Structural change is hard. The designers of the above database had obviously thought about it but had not considered all of the consequences. Further, error recovery mechanisms may not be as good when updates involve structural change. A computer installation I once worked in used a large mainframe with the manufacturer’s standard operating system. One of the attributes of a disk file was the number of tape backups that would be made automatically when the file was updated. Apparently this afforded a high degree of data security. However, one day an old version of a large file was required, the tape was found and an attempt made to restore it. Unfortunately it failed. In order to restore a file it had to return it to the same device with the same attributes, such as block size and file type, as when the backup was made. These attributes had changed and the values when the backup was made had been forgotten. The number of possible attribute combinations was large, and the information was not explicitly available from the backup tape itself. The relevant data were recreated from paper records! The recovery mechanism above was designed to work only in the structurally static case. If the operating system’s designers had thought about the possibility of structural change, they could easily have added some standard tape header giving the necessary attribute and device information. If we have a structural view of some underlying data, the update semantics are clearly quite complex. The notion of a complementary view does not help us that much: the things we do not see may not change, they may simply cease to exist! A small part of the view, say a file icon, represents a vast and valuable piece of data. Small changes to the view may mean enormous changes to the data. In simple file manipulation systems this is recognised and often special dialogues are initiated if the effect of an action is gross. Most computer filing systems are configured as, at most, a simple hierarchy. With these, it is not too unreasonable to expect users to understand the impact of their actions and to expect systems to detect potential troublespots. If the organisation of data becomes more complex, say with an object-oriented database or a hypermedia system, it becomes harder for the user to appreciate the potential scope of their actions and harder for the system to tell which actions it should warn about and which it should not. For instance, in the Unix file system a single file may have several “links”, that is, it may have several access paths through the otherwise hierarchical file system structure. Removing any link but the last merely removes an access path: the file is still there and (if you can find it) can be recovered. Removing the last link destroys the file, yet there is no readily apparent difference between these two operations. The consistency is very useful at a systems programming level, but is potentially disastrous at the level of the user interface. As with simpler systems, if the designer is too zealous in producing dialogue boxes and confirmation messages the user will, of course, reply habitually, and the benefit is lost. Finding the appropriate balance is not easy, and there appear to be no easy formulae. The trouble with updating structural views is that they are powerful. On the one hand, this power can be of great value, allowing the appropriate structuring of information and adding to its usefulness thereby. For instance, the database described above allowed (albeit disastrously in some cases) structural change. If this were not supported, a costly copying process between the old and new formats would be needed. Of course, with that power comes also risk. Inevitably, powerful actions will occasionally go wrong, and this emphasises the need for equally powerful recovery systems. Recovery systems that work only when the data structure is static and assume that structural change will be performed only by faultless "wizards" are not worth a lot. The Macintosh wastebin is an example of a recovery mechanism for a structural view, so it is not impossible (however, even this tends to "empty itself" in certain circumstances). We come back to the fact that structural change is hard. This means that we have to think more about it. So many potential designs are considered only in structurally static scenarios; this may well represent a large proportion of the use, but side-steps some of the most difficult design issues, relegating them to a phase late in the production process when they may be fudged. 9.6 Conclusions We have investigated the problem of updating an object through views to it. Although ad hoc methods have some advantages, it is necessary to use some more predictable method to reduce procedural uncertainty. If the database can be seen as a product then the problems of update predictability and reachability are easy. Further, we can easily test for sharing and interference between updates. Traditional database theory tried as far as possible to simulate this position by the use of normalisation rules, and in a sense follows the route (strongly favoured in programming language design too) of pushing semantics into syntax. This often means trading power for predictability. This might be a good goal to aim for, but is unlikely to hold for many more complex views. We have seen that researchers into database views have used the concept of a complementary view, which stays the same whilst the principal view is updated, as a way of defining the update for the database. This is more likely to succeed as a strategy than searching for a product formulation, and is less restrictive, yet it retains some of the predictability properties. In particular, it is only necessary to know what the complementary view is, to know the effect of updates. Unfortunately, the failure semantics of updates are not in general predictable for complementary view updates and thus it is necessary to introduce the idea of a covering view. This contains sufficient information from the complement to predict which updates to the principal view will fail. The covering view would not be updatable in itself, and perhaps would have weaker sharing restrictions. We saw that both the primary view and its complement have aliasing problems. Agreeing on the view presented to the user has some difficulties, but at least there is a common reference and differences in interpretation are likely to become apparent. The complementary view, by its very nature, is unseen and thus agreement is far more difficult. In both cases the aliasing is a form of procedural uncertainty and thus difficult to address purely within the on-line system. Solutions are bound to encompass the whole analysis of user’s models and the production of documentation and training. Although DP databases tend to have fixed structures, and the views on them tend to be gross and static, the same is not true of more general databases (e.g. graphics, program syntax trees) and thus we need to look at the case of dynamic views and structural change. Both these problems are considerably more difficult than the static case, and even that is not straightforward. In conclusion, it is wise to search as far as possible for a product formulation of one’s problem space and, failing that, look for complementary views. Even where these fail and an ad hoc approach is necessary, it will probably be advantageous to take a complementary-view-flavoured approach, and concentrate on what is to be left unchanged by an update. There is little reason for not including covering views, unless the noise these cause far outweighs the annoyance of unpredictable failure, or if it involves an extreme and pedantic case such as that of passwords and user names. For two rules to sum up the chapter: - Make sure the users know what they see. - Make sure the users know what they do not see.
{"Source-Url": "https://www.hiraeth.com/books/formal/pdf/chap09.pdf", "len_cl100k_base": 16224, "olmocr-version": "0.1.53", "pdf-total-pages": 30, "total-fallback-pages": 0, "total-input-tokens": 74236, "total-output-tokens": 17747, "length": "2e13", "weborganizer": {"__label__adult": 0.0003421306610107422, "__label__art_design": 0.001140594482421875, "__label__crime_law": 0.00029087066650390625, "__label__education_jobs": 0.003662109375, "__label__entertainment": 9.92417335510254e-05, "__label__fashion_beauty": 0.00015676021575927734, "__label__finance_business": 0.0005173683166503906, "__label__food_dining": 0.00029850006103515625, "__label__games": 0.0007643699645996094, "__label__hardware": 0.0007801055908203125, "__label__health": 0.0004045963287353515, "__label__history": 0.0004835128784179687, "__label__home_hobbies": 0.00019466876983642575, "__label__industrial": 0.0004115104675292969, "__label__literature": 0.0007958412170410156, "__label__politics": 0.00021398067474365232, "__label__religion": 0.0005307197570800781, "__label__science_tech": 0.0609130859375, "__label__social_life": 0.00012421607971191406, "__label__software": 0.0282745361328125, "__label__software_dev": 0.89892578125, "__label__sports_fitness": 0.00019752979278564453, "__label__transportation": 0.0004627704620361328, "__label__travel": 0.00020778179168701172}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 71543, 0.01682]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 71543, 0.37174]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 71543, 0.93471]], "google_gemma-3-12b-it_contains_pii": [[0, 1846, false], [1846, 4605, null], [4605, 6585, null], [6585, 9182, null], [9182, 11898, null], [11898, 13748, null], [13748, 16229, null], [16229, 18235, null], [18235, 20358, null], [20358, 22387, null], [22387, 24150, null], [24150, 26462, null], [26462, 28766, null], [28766, 30940, null], [30940, 33243, null], [33243, 36019, null], [36019, 37774, null], [37774, 40512, null], [40512, 43012, null], [43012, 45724, null], [45724, 48461, null], [48461, 50865, null], [50865, 53030, null], [53030, 55760, null], [55760, 58295, null], [58295, 60734, null], [60734, 63297, null], [63297, 66432, null], [66432, 69390, null], [69390, 71543, null]], "google_gemma-3-12b-it_is_public_document": [[0, 1846, true], [1846, 4605, null], [4605, 6585, null], [6585, 9182, null], [9182, 11898, null], [11898, 13748, null], [13748, 16229, null], [16229, 18235, null], [18235, 20358, null], [20358, 22387, null], [22387, 24150, null], [24150, 26462, null], [26462, 28766, null], [28766, 30940, null], [30940, 33243, null], [33243, 36019, null], [36019, 37774, null], [37774, 40512, null], [40512, 43012, null], [43012, 45724, null], [45724, 48461, null], [48461, 50865, null], [50865, 53030, null], [53030, 55760, null], [55760, 58295, null], [58295, 60734, null], [60734, 63297, null], [63297, 66432, null], [66432, 69390, null], [69390, 71543, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 71543, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 71543, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 71543, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 71543, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 71543, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 71543, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 71543, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 71543, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 71543, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 71543, null]], "pdf_page_numbers": [[0, 1846, 1], [1846, 4605, 2], [4605, 6585, 3], [6585, 9182, 4], [9182, 11898, 5], [11898, 13748, 6], [13748, 16229, 7], [16229, 18235, 8], [18235, 20358, 9], [20358, 22387, 10], [22387, 24150, 11], [24150, 26462, 12], [26462, 28766, 13], [28766, 30940, 14], [30940, 33243, 15], [33243, 36019, 16], [36019, 37774, 17], [37774, 40512, 18], [40512, 43012, 19], [43012, 45724, 20], [45724, 48461, 21], [48461, 50865, 22], [50865, 53030, 23], [53030, 55760, 24], [55760, 58295, 25], [58295, 60734, 26], [60734, 63297, 27], [63297, 66432, 28], [66432, 69390, 29], [69390, 71543, 30]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 71543, 0.03373]]}
olmocr_science_pdfs
2024-12-09
2024-12-09
495b96be2a383d688b9b74078b157cc3cd51e752
Fast recursive ensemble convolution of haar-like features Daniel Wesierski, Maher Mkhinini, Patrick Horain, Anna Jezierska To cite this version: HAL Id: hal-00819740 https://hal.science/hal-00819740 Submitted on 2 May 2013 HAL is a multi-disciplinary open access archive for the deposit and dissemination of scientific research documents, whether they are published or not. The documents may come from teaching and research institutions in France or abroad, or from public or private research centers. L’archive ouverte pluridisciplinaire HAL, est destinée au dépôt et à la diffusion de documents scientifiques de niveau recherche, publiés ou non, émanant des établissements d’enseignement et de recherche français ou étrangers, des laboratoires publics ou privés. Fast Recursive Ensemble Convolution of Haar-like Features Daniel Wesierski, Maher Mkhinini, Patrick Horain Département EPH, Telecom SudParis {first.last}@it-sudparis.eu Anna Jeziorska Lab. IGM, Université Paris-Est anna.jeziorska@univ-paris-est.fr Abstract Haar-like features are ubiquitous in computer vision, e.g. for Viola and Jones face detection or local descriptors such as Speeded-Up-Robust-Features. They are classically computed in one pass over integral image by reading the values at the feature corners. Here we present a new, general, parsing formalism for convolving them more efficiently. Our method is fully automatic and applicable to an arbitrary set of Haar-like features. The parser reduces the number of memory accesses which are the main computational bottleneck during convolution on modern computer architectures. It first splits the features into simpler kernels. Then it aligns and reuses them where applicable forming an ensemble of recursive convolution trees, which can be computed faster. This is illustrated with experiments, which show a significant speed-up over the classic approach. 1. Introduction This paper addresses the problem of efficiently convolving an image with Haar-like features. The features have become very popular in computer vision during the last decade. They are reminiscent of Haar wavelets and can be thought of as simple, coarse image templates, e.g. edges or bars. When combined, they are able to capture efficiently sparse local image structure, e.g. for face detection [15]. They can serve as smoothing filters and first- and second-order derivatives at the feature corners. Here we present a new, general, parsing formalism for convolving them more efficiently. Our method is fully automatic and applicable to an arbitrary set of Haar-like features. The parser reduces the number of memory accesses which are the main computational bottleneck during convolution on modern computer architectures. It first splits the features into simpler kernels. Then it aligns and reuses them where applicable forming an ensemble of recursive convolution trees, which can be computed faster. This is illustrated with experiments, which show a significant speed-up over the classic approach. 2. Background In this paper, we adopt the following general definition of Haar-like features. The kernels of Haar-like features are matrices of coefficients obtained after double differentiating piecewise flat patterns. In 1984, Crow [4] introduced summed-area table (SAT) to the computer graphics community as a generalized method for mip-mapping. In [7], Heckbert used SAT for efficient convolution by repeatedly integrating differentiated box filters in 1D and 2D domains. This was formulated in mathematical terms as $f \ast k = f^{(n)} \ast k^{(-n)}$, where $f^{(n)}$ and $k^{(-n)}$ mean $n$-fold integration and $n$-fold differentiation of image $f$ and kernel $k$, respectively. Unlike [7], where the kernels $k$ were quantized, Simard et al. [12] quantized images $f$ forming boxlets. They were then also differentiated to produce trains of impulses along image axes. The coinciding impulses of neighbouring boxlets often cancelled out leading to a reduced representation of the image. Hence, it could be convolved with an arbitrary kernel more rapidly. The algorithm was formulated as $f \ast k = (f^{[-n]} \ast k^{[-m]})^{[n+m]}$. We note this is a general, efficient scheme, which boosts speed performance of convolution primarily by introducing a reduced representation $f^{[-2]}$ of the image $f$. In their paper, the authors actually do not differentiate the kernel $k$. This would require recursively integrating the response four times, instead of two, as implied by $f \ast k = (f^{[-2]} \ast k^{[-2]})^{[2+2]}$. However, should this be of no concern for any reason, the boxlets scheme could also be applied to the kernel. If the kernel consisted of e.g. an ensemble of Haar-like features, the scheme would create their second-order derivatives $k^{[-2]}$, which we deal with in this paper. Hence, our scheme takes boxlets one step further. Namely, it transforms the boxletization $k^{[-2]}$ of the kernel $k$ to an ensemble of recursive convolution trees of simpler kernels which eventually require less data to produce exactly the same result as the original kernel \( k \). Therefore, our trees can be well applied together with the boxletization \( f \) of the image \( f \), keeping in mind that the final result would then require recursive integration of the response four times. Later, Viola and Jones [15] rephrased SAT to integral image and showed how to compute several Haar-like features from it by summing weighted boxes. The attractiveness of the integral image comes from the fact that the sum of pixels under e.g. a rectangular area can be computed in constant time at any scale and location by reading the values at four corners of the rectangle. This approach is very simple and thus has become very popular. For example, it has been implemented in the OpenCV library in the framework for rapid object detection [9]. Due to the overall simplicity of this approach, little work has been done on efficient computation of Haar-like features. Since all features are composed of boxes, some approaches consist in first computing boxes and combining them to obtain more complex features [10, 14, 9]. In [10], the authors concentrated on reducing the number of arithmetic operations by introducing a strip sum data structure. However, it needs to be emphasized that nowadays the computation time is bounded primarily by memory accesses [6]. In this view of this, we focus on reducing input/output data transfer without regard to the number of required arithmetic operations and we show that this strategy leads to a faster algorithm. Previously, in [14] the authors also considered reducing the number of memory accesses for Haar-like features, though with regard to GPU architecture. While both these methods improve on the naive classic computation [15], they refer only to specific features and are embedded into other algorithms, whereas we give theoretical explanations behind practice and generalize to any Haar-like features. In this paper we propose a novel algorithm for convolving an image with any set and type of Haar-like features by reducing memory accesses jointly for all features. This is challenging when multiple arbitrary features are considered and no assumption is made on their mutual positions. In order to reduce memory accesses during convolution, our idea is to decompose the set of features into smaller kernels, thus forming multi-pass convolutions, and align the kernels within and between passes. This scheme results in an ensemble of recursive convolution trees which reuse previously computed responses of smaller kernels, possibly shared by some subset of features. 3. Problem formulation In this Section we present our model for reducing inputs and outputs of multiple features during pixel-wise convolution. An input \( I \) is a memory read operation, whereas an output \( O \) is a memory write operation. We first introduce the parameters and degrees of freedom of the problem. Then, we describe the actions which can be performed on kernels in order to reduce the total sum of inputs and outputs of the convolution. 3.1. Model Let \( \mathcal{K} = \{ k_i \}_{i=1}^N \) be a set of \( N \) convolution kernels of Haar-like features and \( W \) be a 2D scanning window with its own coordinate system and origin in the upper left corner, as we employ left-to-right topology on the memory layout. We require all kernels \( k_i \in \mathcal{K} \) to be computed explicitly within \( W \). For brevity, we restrict ourselves to case \( \text{rank}(k_i) = 1 \), but extending it to kernels of higher rank is straightforward. Kernel \( k_i \) is a one- or two-dimensional vector or matrix, respectively, parameterized by: - **input positions**, indicated by non-zero coefficients; - **size**, determined uniquely by the layout of non-zero coefficients; - **offset position** \( x_i \in \mathbb{N}^2 \) from the origin of \( W \), which we write as \( k_i(x_i) \). In the following, apart from \( \text{rank}(k_i) = 1 \), we have no assumptions concerning the cardinality of \( \mathcal{K} \), the number of inputs of \( k_i \), its size nor position in \( W \). We thus say that \( \mathcal{K} \) has arbitrary configuration. Consequently, we assign two relation properties to \( \mathcal{K} \). A pair of kernels \( k_i \) and \( k_j \), where \( i,j \leq N \), is: - **equivalent** if \( k_i = \alpha k_j \), where \( \alpha \in \mathbb{R} \); - **n-coinciding** if their \( n \) non-zero coefficients are at the same positions in \( W \), where \( n = 0, \ldots, \min(\eta(k_i),\eta(k_j)) \) and \( \eta(k_i) \) is an operator returning the number of non-zero coefficients of kernel \( k_i \). For instance, window \( W \) can contain two equivalent kernels \( k_i(x_i) \) and \( k_i(x_j) \), which are located at different positions in \( W \), such that \( x_i < x_j \). Also, none of their non-zero coefficients may coincide. We then call such kernels 0-coinciding. Let us now briefly review how to implement a multi-pass convolution scheme, obtained after decomposing a single kernel into \( P \) smaller kernels. A small kernel, which is assigned to the first pass, is convolved with the whole image. Then, the second small kernel is convolved with the response obtained after the convolution with the previous image. The process is repeated recursively with the remaining \( P-2 \) smaller kernels to produce the final response, which is equivalent to the convolution with the original kernel. One can observe this \( P \)-pass convolution has in total \( P \) outputs, whereas the single-pass convolution has 1 output. The last output, which writes the final result into memory, is unavoidable for both convolutions. Since we aim at comparing the efficiency of convolution schemes based on the total number of memory accesses required to compute the final result, the count of the final output is ignored in our I/O analysis. Within the context of memory accesses, which have the cost of several orders of magnitude higher than arithmetic operations on modern CPU architectures, a good strategy for realizing the above multi-pass convolution is to turn it into a buffered recursive single pass. That is, it becomes the single pass convolution over the image, but a multi-pass convolution over the buffer. Namely, in each iteration of the convolution (i.e. at each pixel), a result obtained by one kernel is stored in a temporary variable (ALU register) in order to be used twice in the same iteration between two consecutive passes: 1) it is taken as the last input of the next kernel, and 2) it is output to the buffer so that it can be input to the next kernel in subsequent iteration(s). Therefore, this multi-pass convolution over the buffer reduces the number of inputs of the multi-pass convolution over the image by \( P - 1 \) because it combines the output of the kernel in one pass with the input of the kernel in the next pass in the buffer \( P - 1 \) times. We note that accessing registers has negligible cost. We formalize the above discussion by introducing three actions which can be performed on a kernel \( k_i \) in order to reduce total I/O count of \( K \) while keeping the final results unchanged, namely decomposition, permutation, and alignment. Each action implies cost of \( c_I \) inputs and cost of \( c_O \) outputs, where \( c_I, c_O \in \mathbb{Z} \). The total I/O cost is \( c_{I/O} = c_I + c_O \). If \( c_{I/O} < 0 \), then the actions reduce the total number of inputs and/or outputs w.r.t. the initial configuration of \( K \). **Decomposition** of kernel \( k_i \) into \( P_i \) smaller kernels \( k_i = k_i^1 \ldots k_i^{P_i} \) generates a recursive, multi-pass convolution over the buffer, where \( p \) indicates the \( p \)-th pass (i.e. \( k_i^1 \) is convolved with the image as first). The input cost of this action is \( c_I = \sum_{p=1}^{P_i} \eta(k_i^p) - (P_i - 1) - \eta(k_i) \), whereas the output cost is \( c_O = P_i - 1 \). When \( P_i > 1 \), this action creates 1-coinciding kernels for \( p = 1, P_i \) and 2-coinciding kernels for the remaining passes. **Permutation** of smaller kernels, e.g. \( k_i^1 \ldots k_i^{P_i} = k_i^{P_i} \ldots k_i^1 \), is performed to assign them to specific passes thus changing their positions in \( W \). It has costs \( c_I = 0 \) and \( c_O = 0 \). It can lead to reduction of inputs only when combined with alignment with other kernels in the case of multiple features. Yet, if \( i \) equivalent kernels \((1 < i \leq N)\), unfolded across multiple features after their particular decompositions, are permuted to the same pass and preceded by equivalent kernels in previous passes, then a joint recursion is continued leading to the output cost \( c_O = 1 - i \) for this pass. **Alignment** of two kernels \( k_i \) and \( k_j \) is an action which shifts \( k_i \) rightwards (due to the left-to-right topology) until it coincides with \( k_j \) in at least one position. It is analyzed in two possible cases. 1° Single feature. In this case, one can only align last input of kernel \( k_i^p \) with the first input of kernel \( k_i^{p-1} \) to allow recursion. Aligning a kernel \( k_i^p \) with \( k_i^{p-1} \) reduces the number of \( k_i^p \) inputs by 1. However, this implies that \( k_i^p \) is detached from \( k_i^{p+1} \), what increases the number of inputs of \( k_i^{p+1} \) by 1. Therefore, this action does not introduce either loss or gain in the number of inputs, and hence it has cost \( c_I = 0 \). The output cost is \( c_O = 0 \) as it is not possible to reduce the number of outputs by aligning \( k_i^p \) with \( k_i^{p-1} \) there are two special cases. Firstly, shifting \( k_i^1 \) has cost \( c_I = 1 \), as it is not preceded by other kernel. Secondly, since we need to know the value of the feature at specific, predefined location in \( W \), aligning \( k_i^1 \) with already shifted \( k_i^{p-1} \) requires to assign an output to \( k_i^p \), which will be read with single input by additional delta impulse \( \delta(x_i) \), placed at the original location of \( k_i \). Hence, if the last kernel is moved, the \( I/O \) count increases as \( c_I = 1 \) and \( c_O = 1 \). Clearly, shifting a kernel from any pass may reduce total \( I/O \) count only in the case of multiple features. 2° Multiple features. This case is more involved for several reasons. Again, we note that it is possible to align kernels of different features only if they are in the same pass and are preceded by equivalent kernels in previous passes to yield recursion. Now, a kernel in a given pass can be initially \( n \)-coinciding, i.e. before being aligned with another kernel located elsewhere in \( W \). Therefore, if it is aligned with another kernel becoming \( m \)-coinciding, the input cost is \( c_I = n - m \). This implies that it is possible that aligning kernels may not lead to an improvement, even for equivalent kernels. The output cost for aligning kernels of different features is \( c_O = 0 \). Moreover, even in the simple case, where all kernels have 2 inputs, aligning them is an NP-complete problem. We motivate our argument by constructing a simple example. Let 4 kernels with 2 inputs have the following sizes: 1, 2, 4, 7. Clearly, there is only one best alignment as \( 1 + 2 + 4 = 7 \), which would result in total of 4 inputs. However, this generally requires to compute all possible sums of integers to decide which subset sum equals to another subset sum. Subset sum problem is NP-complete. So, we try all possible alignments to decide which one yields minimum number of inputs and outputs. ### 3.2. Example As a simple example supporting our discussion, consider two kernels of Haar-like features defined as \( k_1(1,0) = \begin{bmatrix} 1 & 1 & 0 & 0 & 0 & -1 \\ -3 & 0 & 0 & 0 & 0 & 3 \\ +3 & 0 & 0 & 0 & 0 & -3 \\ -1 & 0 & 0 & 0 & 0 & +1 \end{bmatrix} \) and \( k_2(0,5) = \begin{bmatrix} -1 & 0 & 0 & 0 & 0 & -1 \\ +2 & 0 & 0 & 0 & 0 & +2 \\ -1 & 0 & 0 & 0 & 0 & +1 \end{bmatrix} \), which are initially 0-coinciding in \( W^{8 \times 8} \), as depicted in Fig. 1(a). In classical computation, the number of in- puts corresponds to the number of non-zero coefficients in the matrices, what here amounts to 20 inputs. After decomposing the features into simpler kernels, we have \( k_1 = k_1^X(1, 3) \ast k_1^Y(1, 1) \ast k_2^Z(1, 0) = [+1 0 0 0 0 -1] \ast [+1 -2 1]^T \ast [+1 -1]^T \) and \( k_2 = k_1^2(3, 7) \ast k_2^Z(0, 7) \ast k_2^Z(0, 5) = [+1 0 0 0 -1] \ast [-1 0 0 +1] \ast [+1 -2 1]^T \), which amounts to 10 inputs and 4 outputs (Fig. 1(c)). Now, we observe that the features share two equivalent, i.e. one vertical \( k_2^Z \), which is explicit (directly indicates side size of two boxes in both features) and one horizontal \( k_2^Z \), which is implicit (does not directly indicate side size of any box(es) in feature \( k_2 \)). By permutation, we assign \( k_2^Z \) to the first pass, \( k_1^Y \) to the second pass, and the remaining kernels \( k_2^Z \) and \( k_2^Z \) to the third, last pass. Finally, we align the kernels within passes. The kernel \( k_1^Z(1, 3) \) is shifted rightwards to coincide fully with its equivalent kernel \( k_1^Z(3, 7) \) in the first pass. The same is repeated for the next equivalent kernel \( k_2^Z(1, 1) \) in the second pass. Since the remaining kernels are in the last pass and are not equivalent, it is not efficient to align them as it would increase the current total I/O count. Hence, the kernel \( k_2^Z \) remains at its original position. Concluding, these three passes require 7 inputs and 2 outputs to compute both features exactly (Fig. 1(d)). Theoretically predicted improvement translates into 2.1-fold speed-up. **Figure 1.** (a,b,c,d) illustrate the steps of decomposition, permutation, and alignment. Each black square indicates non-zero coefficient. The blue arrows incoming to the squares denote inputs from memory, whereas the red outcoming arrows denote outputs to memory. (a) is an example configuration of two features (top - \( k_1 \), bottom - \( k_2 \)), (b) their decomposition from 2D into 1D using SVD, (c) their further 1D decomposition which discovers two equivalent kernels, and (d) a recursive convolution tree of kernels after their assignment to and alignment between and within convolution passes. ### 4. Proposed algorithm In this Section, we first describe our algorithm. The input of the algorithm is an arbitrary set of Haar-like features assigned to arbitrary positions within a scanning window \( W \). The output is another signal representation of the features in the form of recursive collection of smaller kernels. The algorithm acts like a parser. It splits a particular set of features into smaller kernels, assigns them into passes, aligns them within passes, and creates joint recursions for features if they share equivalent kernels while counting at each step the number of inputs and outputs. We call such a parsed kernel representation an ensemble of recursive trees. In the last part of this Section, we propose a simple yet efficient buffering strategy for implementing the ensemble by increasing the locality of memory reference during convolution. #### 4.1. Parsing ensembles of recursive trees We propose an automatic, off-line formalism which creates recursive convolution trees of decomposed Haar-like features. They require in total less inputs and outputs to produce the same result as original configuration of the features. First, we procedurally describe our method. The idea is to create recursive multi-pass trees of kernels and align them within each pass in such a way that the total sum of inputs and outputs is minimal. This problem is NP-complete. However, since the number of features is typically not large, it is practical to solve it with a brute-force search. This suggests the following approach: 1. **Decompose** features into smaller kernels in all possible ways such that the number of inputs is reduced. 2. **Assign** kernels of each feature to passes by permuting them. 3. **Align** kernels of all features within and between subsequent passes. 4. **Choose** ensemble of recursive trees with minimal sum of inputs and outputs. We now describe each step of the procedure in detail. #### 4.1.1 Decomposing features into smaller kernels Feature decomposing transforms feature kernel \( k_i \in \mathbb{Z}^{X \times Y} \) into a convolution product of vectors \( a_{j,t} \), whose first element is equal to 1, last to \( j \in \{-1, 1\} \), and the other \((t - 2)\) elements are equal to 0, for instance \( a_{-1,3} = [+1 0 -1] \). We call vectors \( a_{j,t} \) as primitive kernels of size \( t \) \((t \geq 2, t \in \mathbb{Z}\)). P-decomposition of \( k_i \) exists if there exist \( a_{j_p,t_p} \) s.t. \( k_i = \alpha (a_{j_1,t_1} \ast \ldots \ast a_{j_p,t_p} \ast (a_{j_{p+1},t_{p+1}})^T \ast \ldots \ast (a_{j_{p+t},t_p})^T) \). --- --- --- --- where \( \alpha \in \{-1, 1\} \). The problem is then to find all existing \( P \)-decompositions of \( k_i \) s.t. \( P \leq \eta(k_i) \). In the following it is assumed that \( k_i \) is separable. Thus the SVD \( k_i = k_i^x \ast k_i^y \) exists, where \( k_i^x \in \mathbb{Z}^{1 \times X} \) and \( k_i^y \in \mathbb{Z}^{Y \times 1} \). For simplicity, further presentation concerns decomposition of a vector. We refer to \( k_i^x \ast y \) simply as \( k \). Let \( \phi(k, l) \) be an operator returning set \( S \), containing all \( a_{j,t} \) such that \( t \leq l \) and \( \varphi(k, a_{j,t}) = 1 \), where \[ \varphi(k_1, k_2) = \begin{cases} 1 & \text{if } \exists k' \text{ s.t. } \psi(k_1, k_2) = k' \\ 0 & \text{otherwise} \end{cases} \tag{1} \] and \( \psi \) denotes deconvolution operator i.e. \( \psi(k_1, k_2) = k' \iff k_1 = k_2 \ast k' \). We denote the cardinality of \( S \) with \( L \). Note that the \( P \)-decomposition of vector \( k \) exists if \( \max(t_p) + \min(t_p) > 2^{\lceil \log_2 \alpha k \rceil} \), where \( \{t_p\}_{p=1}^P \) is a size of \( p \)-th primitive kernel forming \( P \)-decomposition of \( k \). \( P \)-decomposition can yield multiple primitive kernels, e.g. \( a_{j_1,t_1} = a_{j_2,t_2} \). Thus we need function \( \theta(k, a_{j,t}) \) returning \( \max(m) \) s.t. \( \varphi(k, (a_{j,t})^m) = 1 \), where \( (a_{j,t})^m = a_{j,t} \ast \ldots \ast a_{j,t} \). Finally we introduce function: \[ \xi(S, \mathcal{M}) = (a_{j_1,t_1})^{m_1} \ast \ldots \ast (a_{j_L,t_L})^{m_L}, \tag{2} \] where \( a_{j,t} \in S \) and \( \mathcal{M} = \{m_i\}_{i=1}^{L} \). \( m_i = \theta(k, a_{j_i,t_i}) \). We then propose to apply to \( k \) the procedure summarized in Algorithm 1, returning \( R_P \) s.t. the convolution product of all \( P \) primitive kernels in \( R_P \) gives \( k \). Using the introduced notation we explain how to create signal \( s_{\text{full}} \) in each iteration \( i \) of Algorithm 1. Firstly, we update \( S^{(i)} \) with \( \phi(k^{(i-1)}, \eta(k^{(i-1)}) - p + 1) \). Then we set \( \bar{t} = \max(t') \) s.t. \( a_{j',t'} \in S^{(i)} \), and we remove the elements of set \( S^{(i)} \) whose size does not satisfy the condition \( t > 2^{\lceil \log_2 \alpha k^{(i-1)} \rceil} \). Then the set \( \mathcal{M}^{(i)} \) is updated using \( m_i^{(i)} = \theta(a_{j_i,k^{(i-1)}}, k^{(i-1)}) \). Finally, we calculate \( s_{\text{full}} \) as \( \xi(S^{(i)}, \mathcal{M}^{(i)}) \). One can observe that if \( \varphi(s_{\text{full}}, k^{(i-1)}) = 0 \), then \( P \)-decomposition of \( k \) does not exist. This simple test limits our search space and allows us to terminate before testing numerous combinations of convolution products of primitive kernels \( \in S \). If the test is successful, we find primitive kernels required to satisfy the condition \( \varphi(s_{\text{full}}, k^{(i-1)}) \). Since \( P \)-decomposition does not exist without these primitive kernels, we know that the resulting set \( R_P \) includes them. If there exists at least one primitive kernel without which the condition is not satisfied, the \( k^{(i-1)} \) is simplified and the procedure is repeated iteratively. If not, we are forced to test equality of \( k^{(i-1)} \) with all possible combinations of convolution product of \( P \) primitive kernels belonging to a set of elements \( a_{j,k_i} \in S^{(i)} \) occurring exactly \( m_i^{(i)} \in \mathcal{M}^{(i)} \) times. In practice, usually the combinations are tested when \( L \) is already small. **Algorithm 1** \( P \)-decomposition of \( k \) Set \( k^{(0)} \) to \( k \), \( p \) to \( P \), \( R_P \leftarrow \emptyset \) For \( i = 1 \ldots \eta(k) \) do 1. Create signal \( s_{\text{full}} \) knowing \( k^{(i-1)} \) and \( p \) 2. \( \varphi(s_{\text{full}}, k^{(i-1)}) = 0 \) 3. \( P \)-decomposition of \( k \) does not exist; break 4. Otherwise 5. \( m = \theta(s_{\text{full}}, k^{(i-1)}) \) 6. \( s_{\text{temp}} \leftarrow \psi(s_{\text{full}}, (k^{(i-1)})^{m-1}) \) 7. \( L \leftarrow |S^{(i)}| \) and \( Q \leftarrow 1 \) 8. For \( l = 1 \ldots L \) do 9. \( s_{\text{full}} \leftarrow \psi(s_{\text{temp}}, a_{j_{l,t}}) \) 10. If \( \varphi(s_{\text{full}}, k^{(i-1)}) = 0 \) 11. Add \( a_{j_{l,t}} \) into resulting set \( R_P \) 12. Decrease the number of searched primitive kernels \( p \leftarrow p - 1 \) 13. If \( Q \) is equal 1 or \( p \) is equal 0 14. Combinatorial update of resulting set \( R_P \) 15. \( P \)-decomposition finished successfully; break 16. Else 17. \( k^{(i)} = \psi(k^{(i-1)}, Q) \) The procedure given in Algorithm 1 is repeated for \( P = 1 \), \ldots, \( \eta(k) \) resulting with the set \( D \) of all possible \( R_P \), i.e. all possible \( P \)-decompositions of \( k \), which is used as input to the procedure described in the next Subsection. ### 4.1.2 Ensembles of trees This Subsection covers two steps of our parsing procedure, namely assignment of kernels to passes combined with their alignment within and between passes for \( N \) Haar-like features. Let \( D_{k_i} \) be the set of all possible \( P \)-decompositions of \( k_i \). We augment \( D_{k_i} \) by decompositions into kernels (not necessarily primitive kernels) resulting from all unique combinations of primitive kernels for each element in \( D_{k_i} \), s.t. their number of inputs \( \leq \eta(k_i) \). The problem now is to choose a single element from each \( D_{k_i} \), where \( 1 \leq i \leq N \), such that after their particular alignment the number of memory accesses is minimal, thus creating the best ensemble of recursive trees of kernels. We note it is not necessary to permute kernels in each element of \( D_{k_i} \) in all possible ways to enumerate all possible combinations of alignments. This would be straightforward but inefficient. It is possible to align kernels of some subset of \( N \) features within given pass only if all their kernels in the preceding passes are equivalent, so allowing a recursion. We call this a proper assignment. Otherwise, their alignment is not possible and the problem reduces to multiple cases of single features. Of course, all unique kernels... from all features can be aligned within the first pass of the convolution, but the alignments in the next passes depend on the above condition. The pseudo-code is given in Algorithm 2. **Algorithm 2** N-features assignment and alignment 1. Define ensemble \( E_1 \leftarrow \emptyset \) and label it open 2. Define set of ensembles \( S_E \leftarrow E_1 \) 3. Set merged trees \( (T^0_k)_{1 \leq k \leq N} \) 4. Label each first kernel \( E_k \in T^0_k \) with \( E_1 \) For \( p = 1 \ldots N \) - For each tree \( T^p_k \) - For each branch of tree \( T^p_k \) from leaf up to kernel with any \( E \)-label in pass \( p \) - Set \( n \) to number of unique kernels in branch - Replicate branch \((n - 1)\) times - Add new branches to \( T^p_k \) - Permute unique kernels of all branches to \( p \) - Merge all branches into single kernel in pass \( p \) which have equivalent kernels in pass \( p \) For each \( E_j \in S_E \) labeled as open - For each combination \( t \) of \( E_j \)-labeled kernels of different features in pass \( p \) - Create all possible alignments of kernels - Set \( n \) to number of alignments - Replicate \( E_j \) \((n - 1)\) times. Create set \( A \) with \( E_j \) - Add to each \( E_j \in A \) kernels in \( t \) with particular alignment - Update current cost I/O for each \( E_j \in A \) - \( S_E \leftarrow S_E \cup A \) If (Exist \( E_j \in S_E \) not having proper assignment) - For each \( E_j \) not having proper assignment - For kernels of \( E_j \) in pass \( p \) create all combinations of branches from leaf to pass \( p \) - Set \( n \) to number of combinations - Label \( E_j \) as closed - Replicate \( E_j \) \((n - 1)\) times. Create set \( A \) with \( E_j \) - Add a combination of branches to each \( E_j \in A \) - Compute total cost I/O for each \( E_j \in A \) - \( S_E \leftarrow S_E \cup A \) If (Exist \( E_j \in S_E \) having proper assignment) - For each \( E_j \) having proper assignment - Label children nodes of \( E_j \) kernels in pass \( p \) as \( E_j \) else break ### 4.1.3 Choosing the best ensemble After creating all possible unique ensembles of recursive trees \( E_j \), the one is chosen from \( S_E \) which yields minimal sum of inputs and outputs. However, it is possible that there will be multiple such ensembles. In this special case, we first choose a configuration which has minimal total number of inputs as they are more sparsely referenced than outputs (see Section 4.2 for details). If there are still multiple equal ensembles, we prefer ones with minimal number of inputs in the first pass, then which are more local in this pass, and finally which form buffer of smallest height. If there are any ensembles left after these heuristics, we propose to choose an arbitrary one. We emphasize that these detailed rules are seldom necessary though. ### 4.2 Implementation: B-channel buffer The parsed, best ensemble of recursive trees requires multiple outputs, say \( B \), at each iteration of the pixel-wise convolution with the image. Its straightforward implementation would consist of individual circular buffers storing individual outputs, which would be then reused as inputs in subsequent iterations. Buffer sizes would differ from kernel to kernel. For example, a buffer for a vertical kernel would have the height of this kernel and width equal to the image width. On the other hand, a buffer for a horizontal kernel would only have a height of one row and width equal to the width of the kernel. This buffer clearly would occupy less memory than the former. However, since each one would reserve different memory block, such a buffering solution would result in non-local memory reference and thus be cache-unfriendly. In view of this, we propose to reserve a single contiguous memory block for a buffer which, at each iteration, stores all \( B \) outputs of the ensemble of recursive trees in one \( B \)-element contiguous data array, similarly to RGB image data structure - hence the appellation \( B \)-channel buffer. The inputs defined by kernels parsed into the first pass are read from the image, while the inputs of kernels from the remaining passes are read from the buffer. The input locations are specified by the kernels’ positions computed after alignment. Additional predefined offset to particular channel is required for inputs in the buffer. Hence, the width of the buffer equals the image width, while its height depends on a particular alignment of kernels within passes. Indeed, such a buffer occupies more memory than actually required but, in the context of convolution, this is not prohibitive on modern CPU architectures, which suffer from limited memory bandwidth (memory wall) and not from limited memory space. Consequently, such a buffering approach increases locality of memory reference, thus making it a cache-more-friendly-strategy. ### 5. Results In this Section, we present the performance of ensembles of recursive trees of kernels parsed by our algorithm. We illustrate their behavior on two examples having practical importance in computer vision. The results are evaluated... in terms of time efficiency by comparing the proposed convolution method with the classical approach of Viola and Jones [15]. We use an integral image of size 4096 × 4096 in all experiments, though all the results are repeatable for other image sizes. The improvement between both methods is predicted theoretically as: \[ \text{Predicted Improvement} = \frac{I_{\text{class}} + 1}{I_{\text{prop}} + O_{\text{prop}} + 1} \tag{3} \] where \(I_{\text{class}}\) refers to the total number of inputs of the classical method, and \(I_{\text{prop}}\) and \(O_{\text{prop}}\) refer to the total number of inputs and outputs of the proposed method, counted per pixel. Classical method requires only inputs to compute all Haar-like features, whereas both methods require an additional output to store the final result. The performance tests were run on 2 Ghz Pentium 4 processor which was connected to 3.5 GB RAM unit through 32-bit data bus with the support of 4 MB cache. The code was compiled with VC++ compiler under Windows environment. **Example SURF.** First example illustrates behavior of our algorithm on Haar-like features approximating Hessian of Gaussians in SURF [1]. They are specified by an offset from the origin of the scanning window defined in image coordinate system. Their kernels have the following non-zero coefficients using standard matrix notation: 1. \(k_1(2, 0) \in \mathbb{Z}^{10 \times 6}\), where: \(k_{1,1} = +1, k_{1,6} = -1, k_{4,1} = -3, k_{4,6} = +3, k_{7,1} = +3, k_{7,6} = -3, k_{10,1} = -1, k_{10,6} = +1;\) 2. \(k_2(1, 1) \in \mathbb{Z}^{8 \times 8}\), where: \(k_{1,1} = +1, k_{1,4} = -1, k_{1,5} = -1, k_{1,8} = +1, k_{4,1} = -1, k_{4,4} = +1, k_{4,5} = +1, k_{4,8} = -1, k_{5,1} = -1, k_{5,4} = +1, k_{5,5} = +1, k_{5,8} = -1, k_{8,1} = +1, k_{8,4} = -1, k_{8,5} = -1, k_{8,8} = +1;\) 3. \(k_3(0, 2) \in \mathbb{Z}^{6 \times 10}\), where: \(k_{1,1} = +1, k_{1,4} = -3, k_{1,7} = +3, k_{1,10} = -1, k_{6,1} = -1, k_{6,4} = +3, k_{6,7} = -3, k_{6,10} = +1.\) The proposed approach parses the SURF features jointly, producing recursive trees illustrated in Fig. 2. Their kernels are listed in Table 1, where \(0_{[n]}\) denotes a zero vector of size \(n\). One can observe that the number of memory accesses is reduced from 32 to 19, which results in the theoretical time improvement of 1.65. The measured improvement is 1.63, hence confirming the theory. **Example FACE.** Similarly, the Haar-like features in the 1st stage of the face detection cascade [9] are defined as: 1. \(k_1(1, 2) \in \mathbb{Z}^{5 \times 10}\), where: \(k_{1,1} = -1, k_{1,7} = +3, k_{1,13} = -3, k_{1,19} = +1, k_{5,1} = +1, k_{5,7} = -3, k_{5,13} = +3, k_{5,19} = -1;\) 2. \(k_2(7, 1) \in \mathbb{Z}^{10 \times 16}\), where: \(k_{1,1} = -1, k_{1,16} = +1, k_{4,1} = +3, k_{4,16} = -3, k_{7,1} = -3, k_{7,16} = +3, k_{10,1} = +1, k_{10,16} = -1;\) Table 1. Kernels in recursive trees for SURF example. | \(k_x(2, 9)\) | \([+1 \ 0_{[4]} -1]\) | | \(k_x(2, 0)\) | \([-1 \ 0_{[2]} -3 \ 0_{[2]} +3 \ 0_{[2]} -1]\) | | \(k_x(2, 9)\) | \([+1 \ 0_{[2]} -1]\) | | \(k_x(5, 5)\) | \([+1 \ 0_{[2]} -1]\) | | \(k_x(1, 5)\) | \([+1 \ 0_{[2]} -1]\) | | \(k_x(6, 2)\) | \([+1 \ 0_{[2]} -2 \ 0_{[2]} +1]\) | 3. \(k_3(3, 7) \in \mathbb{Z}^{5 \times 15}\), where: \(k_{1,1} = -1, k_{1,15} = +1, k_{3,1} = +2, k_{3,15} = -2, k_{5,1} = -1, k_{5,15} = +1,\) which are parsed into recursive trees shown in Fig. 3, with kernels given in Table 2. The resulting representation reduces the number of inputs and outputs from 22 to 16, which translates into 1.35-fold speed-up. The measured time improvement is 1.36. The presented experiments are summarized in Table 3. As expected, the measured time improvement is proportional to the ratio between the sum of inputs of the classical approach and the reduced sum of inputs and outputs of our approach. The results clearly indicate that the ensembles of recursive trees, parsed for the above examples using our method, are computed more rapidly than with the classical Table 2. Kernels in recursive trees for FACE example. | \(k_x(12, 7)\) | \([+1 \ 0_{[3]} -1]\) | | \(k_x(1, 2)\) | \([-1 \ 0_{[3]} +3 \ 0_{[3]} -3 \ 0_{[3]} +1]\) | | \(k_x(1, 16)\) | \([+1 \ 0_{[4]} -1]\) | | \(k_x(1, 7)\) | \([-1 \ 0_{[2]} +3 \ 0_{[2]} -3 \ 0_{[2]} +1]\) | | \(k_x(12, 12)\) | \([-1 \ 0_{[1]} +2 \ 0_{[1]} -1]\) | | \(k_x(3, 7)\) | \([+1 \ 0_{[3]} -1]\) | for all features inside the scanning window, features of several multiple scales can be parsed jointly as well and convolved also with a differentiated image representation, which could be obtained using e.g. boxlets method developed by Simard et al. in [12]. The boxlets scheme would create second-order derivative kernels of Haar-like features, which we take as input to our parsing algorithm. Therefore, our method takes boxlets one step further with respect to multiple Haar-like kernels. Consequently, boxlets method cannot replace our scheme, as it stops at the point where our scheme starts. Whether our method can be applied efficiently also to the boxletized image remains an open problem. We leave it as an interesting future work. It is possible that future object detectors will require thousands of templates to cope with high variability of object categories [2, 17]. It is therefore desirable to provide tools for computing a set of templates jointly in efficient and rapid manner. We presented a parsing scheme which achieves this goal. Acknowledgments. This work was partly supported by European FP7 project 216487 CompanionAble and by ERDF project Juliette under CRIF convention 10012367/R. References
{"Source-Url": "https://hal.science/hal-00819740/document", "len_cl100k_base": 10711, "olmocr-version": "0.1.53", "pdf-total-pages": 9, "total-fallback-pages": 0, "total-input-tokens": 39666, "total-output-tokens": 12597, "length": "2e13", "weborganizer": {"__label__adult": 0.0005283355712890625, "__label__art_design": 0.0015430450439453125, "__label__crime_law": 0.0006299018859863281, "__label__education_jobs": 0.0008730888366699219, "__label__entertainment": 0.00021064281463623047, "__label__fashion_beauty": 0.000335693359375, "__label__finance_business": 0.0003085136413574219, "__label__food_dining": 0.0004897117614746094, "__label__games": 0.0011997222900390625, "__label__hardware": 0.0030879974365234375, "__label__health": 0.0012445449829101562, "__label__history": 0.0006170272827148438, "__label__home_hobbies": 0.00018084049224853516, "__label__industrial": 0.0008335113525390625, "__label__literature": 0.00041604042053222656, "__label__politics": 0.0004673004150390625, "__label__religion": 0.0009093284606933594, "__label__science_tech": 0.44140625, "__label__social_life": 0.00013935565948486328, "__label__software": 0.01299285888671875, "__label__software_dev": 0.5302734375, "__label__sports_fitness": 0.0004076957702636719, "__label__transportation": 0.0007643699645996094, "__label__travel": 0.0002796649932861328}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 41450, 0.04552]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 41450, 0.68105]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 41450, 0.85879]], "google_gemma-3-12b-it_contains_pii": [[0, 1070, false], [1070, 5251, null], [5251, 10919, null], [10919, 17471, null], [17471, 22262, null], [22262, 28437, null], [28437, 33624, null], [33624, 38015, null], [38015, 41450, null]], "google_gemma-3-12b-it_is_public_document": [[0, 1070, true], [1070, 5251, null], [5251, 10919, null], [10919, 17471, null], [17471, 22262, null], [22262, 28437, null], [28437, 33624, null], [33624, 38015, null], [38015, 41450, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 41450, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 41450, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 41450, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 41450, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 41450, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 41450, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 41450, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 41450, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 41450, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 41450, null]], "pdf_page_numbers": [[0, 1070, 1], [1070, 5251, 2], [5251, 10919, 3], [10919, 17471, 4], [17471, 22262, 5], [22262, 28437, 6], [28437, 33624, 7], [33624, 38015, 8], [38015, 41450, 9]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 41450, 0.0603]]}
olmocr_science_pdfs
2024-12-10
2024-12-10
5bb6ce1d82790ce92ebac11f1f25868e089f255e
CHAPTER 2 LITERATURE REVIEW 2.1 INTRODUCTION It has almost been a decade since the software industry has detonated. It has witnessed a remarkable growth and a tremendous escalation not only in the core activities but also in the IT enabled services. Despite the uninterrupted expansion, the software industry still has the highest number of project delays and failures. According to the Standish report [9], 44% of the software projects are challenged (late, over budget and/or with less than the required features and functions) and 24% have failed (cancelled prior to completion or delivered and never used). Thus, making a total of 68% (both challenged and failed) which is quite exponential. Boehm [10] found that 15-35% of all the software projects were cancelled outright while the remaining projects suffered either from schedule slippage, cost overruns or failure to meet the project goals. Software development projects are collections of larger programmes with many interactions and functional dependencies. It involves a creation of a product that has never been created before although the development processes are similar among other projects. As a result, software development projects have a dismal track-record of cost and schedule overruns and quality and usability problems [12]. Further, it becomes very difficult to predict the success of project because the scope of the project keeps changing depending upon the market; hence the resources have to be re-allocated leading to schedule slippage and cost overruns. Many software projects involve multiple entities such as companies, divisions, etc., that may have varying interests. There is often a feeling of disconnection between software developers and their management, each believing that the others are out of touch with reality resulting in misunderstanding and lack of trust [12]. According to Doherty and King [27] and Warkentin et al. [30] organizational risks stemming from organizational culture, structure and business processes impacts the technical software development issues, creating a wide range of potential trouble points. A study revealed that 65% of the project failures were due to management issues [67]. Literature Review Apparently, this implies that software project development is extremely risky. Therefore, managing the involved risks is of primary importance in software project development, especially in the large-scale software projects [68]. If the risks are not controlled at the early stages of the project, it will result in an exponential increase in the cost of the project as shown in Figure 2.1 [69] [70]. ![Figure 2.1: Relationship between Project Risk and Cost/Return](image) The extant literature has produced a number of conceptual frameworks to explain different types of software development risk, risk management strategies, the preferred organizational climate and measures of software project performance [24] [35] [71]. This chapter aims to enlist and critically review the studies that have been conducted in the area of software risk, organizational climate and software projects. ### 2.2 BASIC CONCEPTS #### 2.2.1 Project **Project**, by definition, is a temporary activity with a starting date, specific goals and conditions, defined responsibilities, a budget, a planning, a fixed end date and multiple parties involved [72]. According to Turner and Muller [73], a project is an endeavour in which human, material and financial resources are organised in a novel way, to undertake a unique scope of work, of given specifications, within the constraints of cost and time, so as to achieve beneficial change defined by quantitative and qualitative objectives. A software project is a project which encompasses a unique scope of work with given specifications which needs to be completed in a given time at a given cost [74]. The main stakeholder of a software project is the customer, the party that is going to use the delivered system to its business purposes and will benefit from the value added by applying the system to its business. The second most important stakeholder of a software project is the developer, the party that is building the system to be used by the customer. The success or the failure of the software project is broadly assessed in three dimensions as shown in Figure 2.2 [74] [75] [76]: a) Cost – refers to any or part of the project’s materials, supplies or external contracts. b) Time – refers to any part of the project schedule, including the duration of individual tasks, milestones and deadlines. c) Product performance – refers to the specifications, quality, scope or standards that part or the entire project is planned to achieve. ![Figure 2.2: Project’s Triple Constraint [77]](image) However, the project cannot be called successful or failed on the basis of these three parameters if viewed from the eyes of all the stakeholders involved in it. The same outcome of a project may mean different things to different people [78]. Management’s view of what constitutes a successful project may be different from that of a project manager, while developer and users may have different take on the success [79] [80]. The difference in viewpoint is due to different perspectives, motivation and responsibilities associated with the roles [78] [81] [82] [83]. Linberg [84] found that software developers considered a project successful albeit it got cancelled before arriving at a conclusive outcome because it resulted in substantial learning that could be applied to future projects. Baker et al. [85] has defined project success as follows: the project is considered an overall success if the project meets the technical performance specification and/or mission to be performed, and if there is a high level of satisfaction concerning the project outcome among the key people in the parent organization, key people in the project team and key users or clientele of the project effort. One of the studies identified two criteria namely project management criteria and product success criteria, for defining project success. It noted that project management success covers meeting time, cost and quality objectives, while product success deals with the ability of the project’s final product to meet the project’s owner’s strategic organizational objectives, satisfaction of users’ needs and satisfaction of stakeholders’ needs where they relate to the product [86]. The same was reiterated in other studies [79] [82]. According to Prifling [87] success of software project in literature has been defined from two perspectives - efficiency and the effectiveness perspective. He says that one school of researchers defines success from the efficiency perspective, pinpointing the measures of efficient management of a project, such as adherence to time, budget, and quality requirements. While the other school, by contrast, places more emphasis on the effectiveness of projects, i.e. fruitful overall project outcomes for the organization as a whole, such as future profits or improved business process performance [87] [88]. The Standish report also defines success of the software project as meeting time, cost and product performance [9] [87]. Hence, the literature has no comprehensive view on what constitutes the success of an IT project [89]. However, on the basis of the above definitions, the success of the software projects can be viewed on two different perspectives – one from the customer’s point of view and another from the developer’s point of view. The customer’s success criteria of the software project are: a) Keeping expenses within the budget, b) Meeting the schedule, c) Acquiring the product of acceptable functionality & quality. The developer’s success criteria of the software project are: a) Reaching customer satisfaction confirmed with timely payments, b) Matching the time to market demands, c) Building the product of high maintainability and reusability. d) Substantial learning that can be applied to the future projects. In principle, the success of a software project can be claimed only if both the perspectives have been successfully achieved. This sometimes becomes quite difficult to achieve due to various factors influencing the software development. These can be the internal or external risks that the software projects get exposed to during the software development lifecycle or various organizations climate factors that may either help or hamper the otherwise smooth development and execution of the software projects. Before proceeding to the risks and organization climate factors that impact the success of the software projects, it’s imperative to understand the stages of Software Development Life Cycle. 2.2.2 Software Development Life Cycle The Software Development Life Cycle (SDLC) is a framework that is used to understand and develop information systems and software successfully. It is a process used by almost all developers and software development companies as the standard in the software process development. SDLC has many models and each model has its own strengths, weaknesses, advantages and disadvantages [90] [91]. The typical activities involved in the software development life cycle include: Requirements Gathering Gauging the accurate set of requirements is the first step in software development process. System requirement may vary depending on the software product that is going to get developed. Therefore, a careful analysis has to be made about the system requirement needed for the development of the product. **Requirement Analysis** This step is marked by undertaking a feasibility study on software requirement gathered in the first step. In this phase, development team has to communicate with the customers and make analysis of their requirements and system. An exhaustive document is prepared in this phase which has details like project plan or schedule of the project, the cost estimated for developing and executing the system, target dates for each phase of delivery of system developed and so on. This phase is the pedestal of software development process since further steps taken in Software Development Life Cycle would be based on the analysis made in this phase. **Systems Analysis and Design** This is an important phase in software development. Here analysis is made on the design of the system that is going to be developed. In other words, database design, functional specification design, low level design documents, high level design documents and so on takes place. Care must be taken to prepare these design documents because the next phase, namely the development phase, is based on these design documents. If a well structured and analysed design document is prepared, it would reduce the time taken in the subsequent steps namely development and testing phases of the Software Development Life Cycle. **Code Generation** This is the phase where actual development of the software takes place. That is based on the design documents prepared in the earlier phase. Code is written in the programming technology chosen. Here, the code is converted into executables in this phase after code generation. **Testing** In order to ensure quality of the software it is extremely crucial to ensure that the software so delivered is defect free. This can be ascertained by testing the developed code. Various tools and techniques are available for testing at different levels such as regression testing, performance testing, stress testing etc. Based on the need, the testing methods are chosen and reports are prepared about bugs. After this process the system again goes to development phase for correction of errors and again tested. This process continues until the system is found to be error free. **Deployment** This is one of the last phases of software development cycle. This phase is marked by documentation of internal design of software for maintenance and enhancement. **Support, Maintenance and Enhancement** The last phase of the software development life cycle is to provide support and maintenance of the delivered software. This is an incessant process. With ever changing environment, new problems are discovered and new requirement are identified, new dimensions need to be added to the existing software. All this is covered under support and maintenance phase of software development cycle. The entire software development cycle is constantly exposed to both internal and external risks. The risks are present in all the stages of SDLC and it is the obligation of the project manager to either remove or reduce its impact on the project. The various kinds of risks that software project is exposed to is discussed below. 2.2.3 **Risk** Risk is any potential situation or event that could negatively affect a project’s ability. A risk is an exposure to loss or injury or a factor, thing, element, or course that involves uncertain danger [92] [93]. Risks specific to the software have been widely studied in the literature. An examination of the available literature reveals that software project risk has been conceptualized in several different ways. For instance, Charette [94] defines it as “the possibility of loss with some choice involved”, later he further worked on the definition of risk and stated that risk is “an event with a likelihood of occurrence and some potentially negative consequence” [95]. While, Barki et al. [96] [97] have defined risk as “the degree of exposure to negative events and their probable consequences” and “a combination of the probability of an undesirable event with the magnitude of each and every foreseeable consequence”. Higuera and Haimes [98] and Madachy [99] have defined risk as “a measure of the probability and severity of adverse effects. Furthermore, Lytytinen et al. [47] and Ropponen and Lytytinen [26] have stated that software risk is “a state or property of a development task or environment, which, if ignored, will increase the likelihood of project failure”. Keil et al. [15] have defined software risk as “a contingency that constitutes a serious threat to the successful completion of a software development project”. Recently, Benaroch [100] has defined software risk as “failure to respond to threats”. He has further defined it as “the downward or upward variation in expected outcomes” [101]. While Purao et al. [102] states that risk is “a particular aspect of the development task, process, or environment, which, if ignored, will increase the likelihood of project failure”. Gefen et al. [103] laid down “unforeseen contingencies related to changes and additions to the software specifications during the development period” as the definition of software risk while, Wallace et al. [33] defined it as “a set of factors or conditions that can pose serious threat to the successful completion of a software project”. Masri et al. [34] stated that software risk is “the probability that risk sources would lead to risk events that in turn increase the negative variance from expected outcomes with predetermined magnitudes as well as the degree of which risk management mechanisms influence risk sources and the variance of expected outcomes”. Thus, it can be clearly seen that valuable attempts have been made to specify definition of the software project risk. However, the most common definition of risk in software projects is in terms of exposure to specific factors that present a threat in achieving the expected outcomes of a project [36]. On this basis, risk in software projects is usually defined as the probability – weighted impact of an event on a project [19] [36] [94] [95]. Mathematically, it can be written as, $$R = P \times I$$ where $R$ is the risk exposure attributable to a particular risk factor, $P$ is the probability that the undesirable event will be realized and $I$ is the impact or magnitude of the loss if the event does occur. Risk exposure is usually measured in dollars or time in commercial projects. The general view as used today in software projects is to reduce the likelihood of an unfavourable project outcome. Therefore, all probable risk factors should be identified at the onset of the project. The risk exposure for each factor is then estimated (using the above formula) and the exposures are prioritized to identify the risks that embody the greatest threat to the project. Attention is then focused on the high risk factors to decrease the likelihood of their occurrence and/or the magnitude of impact if they are realized, through control measures such as mitigation strategies and/or contingency plans. A progressive status of identified risk factors is maintained and periodically updated [36]. However this concept of risk has certain flaws: First, even before software engineering adopted the definition, management research found that this approach does not match actual managerial behaviour. It was found that, in practice, the likelihood of outcomes and their impacts tend to enter into managers’ calculations of risk independently, rather than as their products. They believe that risks can be reduced or dissolved by using their managerial skills to control the dangers. That is, “managers look for alternatives that can be managed to meet targets, rather than assess or accept risks” [105]. A second limitation of this definition is that it is very difficult in practice to estimate the probability of impact of many risk factors, especially in software projects. Probabilities can only be significantly determined for activities that are repeated many times, under controlled circumstances. Since software projects are often about enabling change through new applications using new technologies in dynamic environments, the extent to which previous patterns are applicable to the future is essentially uncertain in these projects [36]. A third limitation of this definition is that it securely pairs the risk event with the risk consequence, ignoring the interceding influence of organization-specific susceptibilities and capabilities to mitigate and respond [36] [106]. The capability of the organization to respond to a threat may increase or decrease an organization’s exposure to a risk event. These variables are not explicitly accounted for in the traditional definition of risk. They are usually left to be implicitly considered during risk identification and evaluation processes. A fourth limitation is that the definition encompasses only known or foreseeable threats. It provides limited options for managing realized threats and it does not recognize unforeseeable threats. This is a consequence of defining risk in terms of probability of impact. To assess the probability of an impact one needs the ability to foresee an eventuality [36]. Despite all the flaws in the definition of risk, this is still the most widely acceptable definition by the software practitioners. 2.3 STUDIES RELATING TO RISKS AFFECTING THE SOFTWARE PROJECTS Considerable amount of research has been conducted in the areas of risk identification, analysis and management of software projects. Investigators in this area have tried to identify the various risk factors that affect the success of the software projects and have also proposed various risk management models for better supervision of these threats [19] [22] [24] [26] [35] [36] [42] [107] [108]. Inspite of all this, the success rate of software projects is not very positive. Risk researchers corroborate the high failure of software projects, estimating that one-third of software projects fail or are abandoned. The unacceptably high rate of system failure across the board regardless of the size or complexity of the project, has commanded investigations of why these problems occur and what can be done to prevent them [109] [110] [111]. Furthermore, recent evidence suggests that reports from project managers of on-going projects may be optimistically biased, distorted or even non-reported, thereby further exasperating managers efforts to detect potential project pitfalls [112] [113]. This section deals with various work done on identification of risks and their mitigation. The extant literature has produced a number of conceptual frameworks to explain different types of software development risk, risk management strategies and measures of software project performance [24] [36]. The majority of risk management studies deals with normative techniques of managing risk [47] [96]. Some empirical studies have tried to understand how one can effectively manage software risk. Using case study data they have discussed which risk management principles were not followed and tried to identify reasons for not following the same. Overall, these studies provide illuminating insights into risk management deliberations, but are weak in explaining the true impact of risk management in generalising from observations. A few studies have gone further to establish systematic models of risk management [47] [48]. They all conclude that risk management efforts reduce the exposure to software risk and can thereby increase software quality and improve software development. Some studies focus solely on project delays or deals indirectly with software risks [114] [115] Overall, the understanding of how software risk management can improve software development has remained fragmented and largely anecdotal. In terms of previous efforts to identify risk factor, **Boehm’s work [19]** has probably had more influence on practitioner’s community than any other [15]. Boehm [19] identified top ten list of software risks based on his experience in defence industry. According to him personnel shortfalls, unrealistic schedules and budgets, developing the wrong functions and properties, developing the wrong user interface, gold plating, continuing stream of requirements changes, shortfalls in externally furnished components, shortfalls in externally performed tasks, real-time performance shortfalls, straining computer science capabilities are the top risks that a software company faces. To manage these risks Boehm proposed theory “W: Make everyone a winner”. This theory worked on two subsidiary principles: “plan the flight and fly the plan and identify and manage your risks”. Accordingly, various mitigation strategies to counter the above risks were proposed such as staffing with top talent, requirement scrubbing, prototyping, reference checking, detailed multisource cost and schedule, compatibility analysis etc. Although, the study details out the risks and their mitigation but fails to convey the tools used to derive these risks other than the fact that Boehm [19] used his own experience and a survey of the experienced project managers to identify these risks. According to Ropponen and Lyytinen [26], the study lacks a theoretical foundation. It has multiple items which refer to the same phenomenon. **Sherer [116]** used a three dimensional framework to explain the software risks. She identified technical, organization and environment as three dimensions on which the software risks were explained. To combat these risks various risk mitigation technique were also proposed. In the study, technical risks were identified as the most important risks affecting the software projects. Use of HIPO charts, data flow diagrams, prototyping, simulation modelling, benchmarking, fault tolerant methods were some of the risk management tools proposed in the study. Her study fails to link these risks to the Software Development Life Cycle. Moreover, the study fails to provide constructive tools to mitigate the risks relating to software vendor relationships and outsourcing. **Field [117]** in his article states that, “projects fail too often because the project scope was not fully appreciated and/or user needs not fully understood”. He developed a comprehensive list of pitfalls that must be avoided to execute a successful software project. The list includes misunderstanding user requirements, project scope ill defined, poorly managed changes; change in the chosen technology, business needs change, deadlines unrealistic, resistant users, lost sponsorship, lack of experienced personnel, best practice and lessons ignored by managers. This list was re-used by Reel [118] to adduce various risk management strategies such as building the right team, giving team what they need, involving customers or user in the development, setting up procedures and expectations for high level of quality before the development, tracking the progress religiously and institutionalizing a process for learning from past mistakes. Keil et al. [15] employed a variation on the traditional Delphi survey approach to elicit opinions from a panel of experts through iterative, controlled feedback. Groups of experienced project managers from USA, Hong Kong and Finland were formed and list of top ten risks along with their mitigation were identified. The list includes the following key risk factors and their mitigation: a) Lack of top management commitment to the project, lack of adequate user involvement and failure to gain user commitment; can be mitigated by relationship management, trust building and political skills. b) Misunderstanding the requirements and lack of frozen requirements can be managed by educating the user/customer on the impact of scope changes in terms of project cost and schedule; tools such as multi-criteria decision making and function point analysis can also be used to mitigate these risks. c) Failure to manage end user expectations, lack of required knowledge/skills in project personnel, introduction of new technology and insufficient/inappropriate staffing can be mitigated by internal reviews coupled with external reviews, use of work-breakdown structure, development of contingency plans to manage personnel shortfall and use of new technology. d) Changing scope/objectives and conflict between user departments can only be managed by contingency and disaster planning. Inspite of such detailed analysis this study fails to link it with the software development cycle. Oz et al. [107] collected quantitative and qualitative data about reasons why software projects fail. They conducted a factor analysis of the survey and identified lack of corporate leadership, poorly communicated goals/deliverables, inadequate skills and means, poor project management and deviation from timetable/budget as the key risk factors. Ropponen and Lyytinen [26] using survey instrument on eighty project managers delineated six components of software development risk. These were: scheduling and timing risks, systems functionality risks, subcontracting risks, requirements management risks, resource usage and performance risks and personnel management risks. They proposed various risk mitigation strategies to extenuate the identified risk, mainly concentrating on the following: standardization of the process, making risk management an integral part of the project, hiring of experienced project managers and controlling or decomposing the size of the project. Schmidt et al. [119] developed a comprehensive list of fifty three factors affecting the software project, using inputs from multicultural set of forty one practicing project managers. Three panels were formed on the basis of their cultural background and Delphi technique of decision making was used to identify the critical risk factors affecting the software projects. The risks identified were lack of top management commitment, failure to gain user commitment, misunderstanding of requirements, lack of adequate user involvement, lack of required knowledge/skills in project personnel, lack of frozen requirements, changing scope/objectives, introduction of new technology, failure to manage end user expectations, insufficient/inappropriate staffing, conflict between user departments. Jiang et al. [120] made use of software risk measurement instrument pertaining to various characteristics of a software development projects developed by Barki et al. [97] and pointed out that project size, application complexity, technology acquisition, insufficient resources, lack of team expertise, lack of user support, lack of user experience, lack of clear role definition, intensity of conflicts are the top nine risk factors that a software project can be exposed to. According to the study conducted on the Indian software industry, the Indian software industry is not only facing the problem of attrition from the home front but is also facing problem from the client side as well. There were a number of cultural and political issues that US managers perceive as irritants or barriers. One such issue is the apparent unwillingness of Indian software professionals to point out potential problems up-front, and in general, an unwillingness to say no for fear of offending the clients. Another related weakness is the lack of familiarity of many Indian firms and professionals with the work culture and work norms in the west, and especially in the United States. Other difficulties include resistance within the US to foreign programmers, poor telecommunication infrastructure, and the delays in obtaining the required visas for Indian programmers [66]. Addison and Vallabh [121] conducted a three phase Delphi survey of the South African software industry and identified unclear or misunderstood scope/objectives, misunderstanding the requirements, failure to gain user involvement, developing the wrong software functions, unrealistic schedule and budgets, continuous requirement change, inadequate knowledge/skills, lack of effective project management methodology, gold plating as the key risk factors. They also studied the effectiveness of various controls or strategies to reduce the occurrence of risk factors. They found that experienced project managers use controls such as assigning of responsibilities to team members and stabilizing requirements and specifications more than inexperienced project managers. The study lacked in the area of data collection as the sample size taken was too small to generalize the risks and their mitigation strategy. DeMarco and Lister [122] identified schedule flaw, requirements inflation, employee turnover, specification breakdown and poor productivity as the core risk factors of software development projects. While Lu and Ge [123] analysed the risk of software development projects in two aspects - one for owners (project’s feasibility and knowledge management problem) and another for contractors (scope change risk and management risk) in China using AHP technique. In-depth interview with IT professionals from leading firms in Australia were undertaken by Baccarini et al. [37], to ascertain the IT risks and their mitigation. The top ten risks identified in the study were: personnel shortfalls, unreasonable project schedule and budget, unrealistic expectations, incomplete requirements, diminished window of opportunity due to late delivery of software, continuous changes to requirements by client, poor production systems performance, poor leadership, inadequate user documentation, lack of agreed user acceptance testing and sign-off criteria. Rich and valuable array of mitigation techniques were identified and categorised as avoidance, reduction, transfer or acceptance strategies. However, the study failed to provide any framework for software risk management. In a study conducted by Smith [124] in Africa, lack of top management commitment to the project, unclear/misunderstood objectives, schedule flaw, lack of client responsibility; ownership and buy-in of the project and its delivered systems, no planning or inadequate planning, project not based on sound business case, lack of available skilled personnel, not managing change properly, lack of adequate user involvement, poor risk management came out to be the major risk factors affecting the software project. Costa et al. [24] in their study presented a technique for assessing the risk level of a software project based on its systemic and specific risks. They introduced an approach to estimate the probability distribution of earnings and losses incurred by an organization according to its software project portfolio. This technique was supported by an empirical study to assess the relative importance of risk factors for software development projects. The following risk factors were keyed out: client risk, control risk, analysis risk, team risk, testing risk, policies/organization structure risk and design risk. However, no attempt was made in the study to address the issue of managing and mitigating these risks. **Dey et al. [42]** through a case study on TCPO in Barbados identified the key risk factors as: the unavailability of key personnel, employee turnover and incorrect/incomplete requirement. The study also developed an integrated framework for managing risk in software development with the involvement of the stakeholders in TCPO. To control risks in the project they proposed constant project monitoring, dynamic scope management plan, involvement of client in the development process and effective communication between developer and client as some of the strategies for mitigating the risks. **Verner et al. [126]** conducted an exploratory statistical analysis to identify determinants of project success and used logistic regression to predict project success. According to the study, success is more likely to happen if the project manager is involved in schedule negotiations, adequate requirements information is available when the estimates are made, initial effort estimates are good, take staff leave into account, and staff are not added late to meet an aggressive schedule. The study is quite comprehensive as far as prediction of project success is concerned but it does not cover all the factors that affect the success of the project. Defining success only from the perspective of estimation, staffing and scheduling is incomplete in itself. **Zhou et al. [41]** analysed ten case studies in the UK, USA and New Zealand to identify critical risk factors (scope creep, unwillingness of customer to accept final systems, poor project management, etc.) at the pre-implementation and implementation stage of the software project. The study is limited to identification of risks at pre-implementation and implementation stage and ignores the risk occurring in post-implementation stage of software projects. The study fails to provide any insight into the risk management and mitigation strategies. **Bannerman [36]** conducted a study in government agencies in Australia to investigate the practices of a state government in dealing with software projects. Analysis of the study uncovered ten categories of risk factors namely: project governance, project setup, partner engagement, business proprietorship, project management, change management, management of projects, recognition of red flags, management of risk and benefit realization. The study also identified the various risk management techniques used in these projects. Overall, the study aimed at reviewing and reassessing the status of risk management research in literature and practices in a sample of Australian public sector agencies. The study is helpful as it provides a complete understanding of risk and risk management in public sector. Whether the same can be applied in private sector software companies is not clear from the study. Iacovou et al. [124] identified lack of top management commitment, original set of requirements miscommunicated, language barrier in project communications, inadequate user involvement, lack of offshore project management know-how by client, failure to manage end user expectations, poor charge control, lack of business know-how by offshore team, lack of required technical know-how by offshore team and failure to consider all costs as the core risk factors. The study aimed at providing an insight into risks affecting offshore – outsourced development projects but fails on delivering the risk management techniques to combat these risks. Anudhe et al. [22] using case-based methodology and structured and semi-structured interviews with senior management of various Indian software companies keyed out various risk factors affecting the software projects. Schedule and budget management (developing a collaborative work culture with clients), client expectations (educating the client to involve deep level of association with the customer), requirements capture (elaborate data collection and proactive analysis), staffing (maintaining buffer resources, involving client in resource recruitment), changes in client’s corporate structure (transparency and adequate communication) are few of the risk factors and its mitigation mentioned in their study. However, the study fails to define any model for risk management. Thus, it can be clearly seen that numerous researches have been devoted to the identification and management of the software risk. Various methodologies have been used for keying out the list of major risk factors. As a result, there have been various lists of risk factors with some similarities and some differences [40]. Therefore, a comprehensive and exhaustive list encompassing all the risk factors affecting the software projects is prepared in the following section. 2.3.1 A Risk Classification Framework Many different risk factors impacting the success of the software projects have already been identified by various researchers. Some of these risk factors are quite detailed and affect only specific projects in specific conditions. Some factors are, however, reported as very commonly encountered and having strong impact on the project’s chance of success. Some of the risk factors are controllable while others cannot be controlled by the project manager [15]. While some risks are more important as they have a direct impact on the project’s outcome than compared to the other. Thus, on the basis of this proposition the risks identified by the researchers have been classified on the basis of importance and control as shown in figure 2.3 and have been explained in the following section. **Figure 2.3:** Risk Classification Framework 2.3.1.1 Stakeholder Management Risk As the name suggests, this quadrant captures the notion that successful projects are very often those that have the commitment of both senior management and the end-users i.e. those who will actually use the system. Without a clear charter, or mandate, the project is simply not viable [15]. Projects in which either top management or user commitment is lacking represent a high-risk proposition. But initial commitment is not enough. Once a project has started, project managers must periodically gauge the level of commitment from both top management and the user community to avoid being caught in a situation where support for the project suddenly evaporates. These risks fall under high risk and low control category as they cannot be controlled by the project manager, but they can be moulded. Project managers must take reasonable steps to ensure that they have the support and commitment needed to deliver a successful project. The list of risks that fall under this category are: 1. *Lack of top management* Project is disrupted from achieving its objectives owing to management playing politics within and between departments or external agents. Furthermore, users may not support the project if they perceive that there is a lack of top-level management sponsorship. Keil et al. [15] found that lack of senior management commitment is the most critical risk impacting the software projects. Studies have time and again empathized that the top management support is needed throughout the implementation and top management needs to publicly and explicitly identify the project as top priority [127] [128] [129] [130]. 2. *Corporate culture not supportive* Corporate culture may be project adverse owing to other hidden agendas, factions within the company, organizational culture under continuous change or threat of change, and other internal priorities. All this will result in weak management support for the project and consequential failure of meeting objectives [37] [127] [131] [132]. 3. *Inadequate user involvement* This risk has been repeatedly mentioned by various researchers. This risk features in the top ten causes of software failure list of many researches. If the client is not involved in the project it will result in wrong interpretation of scope and objectives of the project and thus may lead to loss of money, time and even life [15] [41] [121] [124]. 4. **Lack of client responsibility and ownership** This risk was also fundamental on the list identified by Keil et al. [15]. If the users are not involved, there is a risk that developers may assume detailed functionality and business requirements, leading to project objectives not being achieved. It also means laying the blame for ‘lack of client responsibility’ on the project manager rather than on the users [133]. 5. **Friction between clients and contractors** Personal animosity or enmity can occur between clients and software contractors as a result of misunderstandings, unanticipated changes in the scope of the contract, missed or delayed delivery, or some other item of dispute that polarizes clients and contractors into opposing camps [134]. ### 2.3.1.2 Requirement and Schedule Risk Many projects face uncertainty and turmoil around the product’s requirements. While some of this uncertainty is tolerable in the early stages, the threat to success increases if such issues are not resolved as the project progresses. If requirements-related risk factors are not controlled, it might result in either building the wrong product, or building the right product badly. Either situation results in unpleasant surprises and unhappy customers. The above statements clearly show how crucial this quadrant is. The risks in this quadrant can be largely controlled by the project manager, but do require skilful interfacing with the user or customer. The risks that fall under this quadrant are: 1. **Miscommunication of requirements** Sometimes it is seen that the client himself is not sure what he desires from the project. It has also been found through literature that conflict among the users further accelerate this problem of miscommunication of requirements. Infact, miscommunication of requirements is one of the biggest risk factors as miscommunication can complicate the transmission of the original set of requirements and subsequent information exchanges and change requests [125]. 2. **Unclear scope/objectives** Boehm [19] point out that the different stakeholders in a software development project have different objectives, which often conflict with the objectives of another stakeholder. For instance, users require a robust, user-friendly system with many functions that can support their tasks while on the other hand, development team members hope to encounter interesting technical challenges. These differing expectations create fundamental conflicts when simultaneously approached, resulting in unclear or misunderstood scope/objectives of the project. Furthermore, ill defined or ambiguous requirement specifications are equally dangerous and are likely to originate problems of usefulness and deviations from both timelines and budget [19] [41] [135]. 3. **Changing requirements** Stakeholders (includes users) continuously make changes to software functionality throughout the project life-cycle. As the users’ needs change, so do the requirements of the project. One of the researchers suggested that by freezing a part of the functionality and delivery date, completion of the system is enabled. While, on the other hand it has also been argued that requirements should not be frozen as in today's fast moving business environment, a frozen design does not accommodate changes in the business practices. With a frozen design, the developer has little flexibility in changing the specifications. Continuous and uncontrolled changes in requirements, however will inevitably lead to a delay in the project schedule [10] [15] [133] [134] [136] [137]. 4. **Improper change management** Without proper software change management, enterprises lack a full understanding of how software running in production automates their business processes. This includes management of changes to software in development, changes to software in production, and changes to associated artefacts like requirements, models, and test cases. This also includes management of both individual changes and the coordination of dependent changes. Researchers have mentioned that improper change management as one of the leading causes of software failure [124] [138] [139] [140] [141]. 5. **Unrealistic schedule and budget** The project is unable to realize its objectives owing to unrealistic restrictions placed on the projects budget, schedule, quality or level of performance. A project failing to meet its committed deliverables or being significantly over budget can result in termination of the project. A number of researchers have stated that the ‘scheduling and timing’ risk is a major complicating factor as it is difficult to estimate schedules with acceptable accuracy and consistency. Very often, organizations embark on a large project having underestimated its size and complexity. This risk leads to the difficulties in scheduling the project correctly. Ropponen and Lyytinen [26] believe that performance with scheduling and timing risks improves with project experience. A fixed schedule may lead to schedule pressures and people under pressure do not necessarily work better, resulting in the inability to produce satisfactory results or deliver any software at all [19] [136] [142] [143] [144]. 6. Misunderstanding of requirements It may be time consuming and difficult to collect and record all of the required details from all prospective users, resulting in the project team not knowing enough about what is required to complete the project successfully. This may lead to the possibility of developing a system that cannot be used, mainly because, a proper systems’ analysis to develop a complete and accurate set of requirements has not been performed. A number of researchers have identified misunderstanding of requirements as one of the top ten risks affecting the software projects [15] [117] [119] [121] [133] [145]. 7. Unrealistic expectations According to Keil et al. [15], problems with user expectations can occur whenever user expectations are not realistic. This happens due to inadequate planning and failure to gain sign off from the client. Sometimes the project team is also exposed to unrealistic expectations from the top management or from the project manager. This de-motivates the team thus leading to serious issues in software projects. 8. Gold plating Gold plating means that the team is focused on analyzing and generating excessive levels of detail while losing sight of the project’s objectives. Often developers and analysts think of additional capabilities or changes, known as gold plating, which they think would make the system better and more attractive in their view. These deviations may result in unsatisfied users and unnecessary costs [19] [146] [147]. 9. Inaccurate estimation of schedule or cost An inaccurate initial estimation can lead to inadequate allocations of budget, or time, or both, to the project, which can then cause it to fail. The estimate drives every aspect of the project, constrains the actions that can be taken in the development or upgrade of a product, and limits available options. It is believed that most impromptu estimates of project scope based on the engineering or management experience are incorrect and are often based on simple assumptions and over-optimism; or worse are made to accord with what others want to hear. Needless to say, such estimates often lead to disaster. If the estimate is unrealistically low, the project will be understaffed from its outset and, worse still, the resulting excessive overtime or staff burnout will cause attrition and compound the problems facing the project. In turn, overestimating a project can have the same effects as any other inaccurate estimate [93] [148]. 2.3.1.3 Project Management Risk The risks under this are related to the actual execution of the project. The project manager has reasonable control over these risks, and hence these risks are regarded as moderate. Under normal circumstances, these risks do not pose a serious threat to the project; hence, they fall under low risk category. But project managers cannot afford to become complacent in their handling of these risks. Failure to manage the risks in this quadrant can result in poor quality software that is delivered late and/or over budget. The following risks belong to this quadrant. 1. Inadequate plans and procedures Inadequate planning can cause the entire project to go haywire. Planning helps in identifying the loopholes in the project and also enables the project manager to provide tools and techniques to overcome these loopholes. As a matter of fact meticulous planning at the time of pre-project stage helps in identifying risks at early stages of implementation. This risk has also been mentioned as one of the top ten risks affecting the software projects. [124]. 2. Lack of project management methodology Poor project management is universally accepted as a major cause of risk and failure in software projects. A full and complete project plan may not necessarily be presented but a comprehensive and proper project management strategy with clear definition of roles and responsibilities must be initiated as soon as possible. According to researchers requirements are frequently not explicitly fixed in any reasonable document. Project management from the customer side is most often done by just forwarding e-mails (and forwarding them again, and again) until they reach suppliers. It is then difficult to figure out the chain of responsibility, management, and resourcing for each separate change request. Therefore, it is very important to define project member roles and establish proper communication liaisons [41] [149] [150]. 3. New technology being introduced This risk occurs by using new or ‘leading edge’ technology that has not been used successfully at other companies. This risk may be increased further if there is a shift in technology during the project. Studies have stated that stability and compatibility of hardware and software platforms is the major cause of problem. Unproven or unfamiliar technologies may cause disappointment and lead to under-performance or conflicts [41] [133]. 4. Lack of single point accountability It is typical of large software projects to have many team leaders but no single point of responsibility for deliverables, resulting in the project failing to meet its objectives. If there are multiple contact points with the client as well, it might create a situation wherein the client keeps on informing different things to different contact points thus delaying the project [151]. 5. Lack of technical knowledge Project personnel may not have adequate knowledge of the technology, or the business, or may just not have the experience to handle the project. McLeod and Smith [152] indicate that ‘people’ risk arises from inadequate skills (both technical and managerial) as well as level of experience. The lack of experience with technology also increases the likelihood of occurrence of this risk. Infact, this is again one of the major causes of delay and failure of the software projects. [15] [17]. 6. **Inappropriate staffing** Inappropriate project staffing leads to failure of software projects. One of the main reasons behind this is the lack of proper project planning and estimation. Excess staff will result in increase in cost to the project where as under-staffing will result in excessive overtime or staff burnout thus causing attrition and poor performance [153]. 7. **High level of attrition** Employee turnover during the project has tremendous negative impact, as it gets extremely difficult to get competent experienced technical persons within a short period and furthermore, it takes time for them to adjust in a new environment. These have negative impact on productivity of software development projects [41]. 8. **Lack of commitment from project team** Lack of commitment from project team results in poor performance and delivery of poor quality product. Studies have confirmed that lack of commitment from the team is due to lack of trust, lack of balance or diversity, poor socialization, and inadequate communication [45]. 9. **Lack of mechanism of validation and verification** System development and testing is probably the most critical phase of any software development project. Adequate programming and testing methods and techniques need to be adopted. The use of unstable and sometimes incompatible software and hardware platforms may pose significant risk to the project. Tools needed for testing and verifying the application or product are indispensable for a successful implementation and deployment of the software. If correct tools are not available on time, it may delay the deployment, thus affecting the overall project schedule [41]. 10. Inadequate tools for reliability Reliability is defined as the probability of failure-free software operation for a specified period of time in a specified environment. Reliability is an important attribute of software quality, together with functionality, usability, performance, serviceability, capability, installability, maintainability, and documentation. Software reliability is hard to achieve. The difficulty of the problem stems from insufficient understanding of software reliability and in general, the characteristics of software. Realistic constraints of time and budget severely limit the effort put into software reliability improvement [154]. 2.3.1.4 Environment risk Risks in this quadrant can be traced to the project environment that exists both within and outside the organization. Risks falling under this quadrant are those over which the project manager has little or no control. They have a low likelihood of occurrence and are, therefore, not viewed as being crucial. However, if they do occur, they can be serious threat to the project. These risks are most difficult to predict. The risks under this quadrant are: 1. Inadequate third party performance The contractor selected is not fit for the purpose of the project. The contractor is unable to provide a solution that meets time, cost, quality and performance objectives. This may gravely affect the overall performance of the project as any delay from the third party may derail the entire project schedule resulting in increase cost and time [142]. 2. Competition alters schedule Globalization has given rise to new challenges and one such challenge is to keep up with the competition. Competitors may build software solutions more quickly, with greater functionality at cheaper cost, aggressively deploy the final product within the same market space [36] [134]. 3. Change in scope due to change in business model With ever changing environment it is very important to keep up with the project schedule. Studies have found that sometimes due to changes in competitive environment the software becomes outdated and is no longer needed by the user. According to a number of researchers business return on investment in IT can be eroded owing to changing consumer market conditions or advancements in software engineering. Sometimes, the entire project may be scraped or terminated due to change in the business model. The top management may withdraw support to the project due to restructuring of the business or even client’s organization may suddenly become disinterested. These have been confirmed by various studies as well [37] [134] [136]. 4. Natural disasters Natural disaster has a very rare occurrence yet it is one of the most crucial risk factor. One it is uncontrollable and two it can cause a complete damage to the project resulting in loss of money, time and even life. After identifying and classifying the risks on the basis of control and importance, it is important to understand how these risks can be abrogated and success of the software project be ameliorated. One of the approaches towards increasing the rate of success of the software projects can be presence of strong, robust, open and free organizational climate in the software development companies. “What is an organizational climate?”, “How does it impact the software project?”, “Is there any relation of success of software project with the organizational climate?” The next section aims to answer these and present an overview of the organizational climate and its related work in the area of software projects. 2.4 ORGANIZATION CLIMATE The construct of climate was first introduced in the 1960s, primarily based on the “social climate” and “social atmosphere” variables proposed by Lewin et al. [155] [156] and followed by empirical research conducted in organizational settings [157] [158] [159] [154]. Since Likert’s [158] early empirical work, organizational climate has been viewed as a fundamental building block for describing and analyzing organizational phenomena [160]. Cumulative research demonstrates that employee climate perceptions have important effects on both individual and organizational outcomes, such as work attitudes and satisfaction, job performance, service quality, customer satisfaction, workplace accident rates, TQM outcomes, and organizational financial performance, among other things [161] [162] [163] [164] [165] [166] [167] [168] [169] [170]. 2.4.1 Definition Organizational climate has been studied quite elaborately and various researchers have defined climate in numerous ways. According to Kopelman et al. [171], organizational members are active perceivers and interpreters of their work environments, and employees tend to form their perceptions by observing how the daily operations of the organization are conducted and what goals the organization appears to be pursuing. Schneider and White et al. [172] noted that the organization transmits this information to employees through its policies, practices, and procedures (e.g., human resources policies, marketing practices, operations management procedures), which collectively send messages about what is important—what behaviours the organization rewards, supports, and expects. Based on these behaviours and activities, employees develop a summary sense of “what is important around here,” which represents climate. Climate represents the patterns or themes that employees perceive in what they experience; it is one way to conceptualize the totality of the experiences organizational members have of their workplace [172]. It can be viewed as subjective, temporal, and potentially subject to managerial manipulations [173]. Climate has also been defined as “the shared perceptions of employees concerning the practices, procedures, and kinds of behaviours that get rewarded and supported in a particular setting” [167]. According to Litwin et al. [159], organization climate can be defined as “the perceived attributes of an organization and its sub-systems as reflected in the way an organization deals with its members, groups and issues”. Isaksen et al. [174] defines climate as “the recurring patterns of behaviour, attitudes and feelings that characterize life in the organization. At the individual level of analysis, the concept is called psychological climate. At this level, the concept of climate refers to the individual perceptions of the patterns of behaviour. When aggregated, the concept is called organizational climate”. Ekvall [175] and Isaksen and Ekvall [176] have defined organizational climate in terms of the interplay of institutional policies, goals, strategies, tasks, workload, resources, technology and staff. They suggested that creative outcome is most likely to happen if the organizational climate does the following: 1) Challenges individuals with tasks, goals and institutional operations. Work must be meaningful and “the development and survival of the organization is important” to employees. 2) Employees must have opportunities and initiative. This may be apparent in communication within and outside the organization and in the methods available to obtain information. 3) There must be support for new ideas. They should be encouraged and rewarded. 4) Employees must be trusted and employees should feel that trust. Risk is minimal because employees know they are trusted and in turn trust the organization. 5) Risk taking is supported. Risk is viewed as a part of the creative process. They described a measure of organization climate that covers 10 areas: support for ideas, challenges, time for ideas, freedom, trust and openness, dynamism, risk taking, playfulness and humour, debates and conflicts and impediments. Yet another most widely used framework for identifying organization climate has been given by Litwin et al. [159]. This framework emphasises on motivational linkages and seems to be quite relevant for studying organizational climate [177]. The framework considers six dimensions of organizational climate that include: structure, responsibility, reward, risk, warmth and support. Thus, climate is a perceptual mediator through which the effects of the work environment on employee behaviour pass [171] [178]. It is necessary to distinguish climate from culture, because the term culture is often used when climate is the more appropriate term [179]. Climate is about experiential descriptions or perceptions of what happens; it can most accurately be understood as a manifestation of culture [179]. In contrast, culture is a deeper phenomenon based on symbolic meanings that reflect core values and fundamental ideologies and assumptions [180] [181]. 2.4.2 Organization Climate and Software Projects Ein-Dor and Segev [182] perhaps conducted the first study of climate in Information Technology. He examined the relationship between climate toward Management Information System and the quality of developer-user relationships, the degree of system use, and system integration in the Literature Review organization. Boynton et al. [183] developed a conceptualization of the overall “IT management climate”, which is related to managerial IT knowledge and IT management-process effectiveness. More recently, Watts and Henderson [184] explored the concept of innovative IT climate and discussed how it is related to IT innovation. Jia and Reich [71] developed a new construct, “IT service climate” and tried to establish relation between IT service climate and service quality. They also developed a theory–based framework to help project managers identify the causes of service failure. Hyvari [185] evaluated the critical success/failure factors and their relationship with organizational background variables such as project type, project size etc. using chi-square analysis. Huang and Trauth [186] conducted a cross-cultural study on how culture influences the globally distributed software development between U.S and China. They conducted in- depth interview with Chinese IT professionals and found improving language skills, fostering organizational culture of valuing diversity and generation of innovative ideas along with adaptation of such organizational culture will help in improving the software quality and overall software development. An empirical study examining the work climate within the software development teams was conducted by Acuna et al. [187]. Team selection inventory test and team climate inventory test were used to gauge the developer’s climate preference before and after the project and developer’s perception of the climate respectively. According to the study, participative safety and team vision preferences and perceptions fit correlated with improved software quality. Keil et al. [35] conducted a controlled experiment on 134 graduates and found information asymmetry and organizational climate to have significant indirect effects on the willingness of the employees to report negative project status information. Researchers have also studied the impact of organizational climate factor on software developer’s job satisfaction, job performance and project success [48] [49] [50]. Woodruff [48] studied organizational climate and its impact on job satisfaction and its impact on job satisfaction and job performance. His study included 202 software developers from 12 different organizations in United States. The studies identified management’s ability to make decisions, selection of personnel along with inter-group cooperation and receptiveness by management significantly affected the job satisfaction. Mclean et al. [49] studied the impact of compensation on job satisfaction of the software developers. A study by Rasch et al. [50] examined the relationship among self esteem, goal difficulty, goal specificity, role ambiguity, effort, achievement needs, locus of control and ability on individual software developer performance. They found that individual ability and achievement needs have a direct effect on software developers’ performance. There is also work on individuals’ psychological climates, such as creativity climate for IT professionals, climate for business process change, ethical climate of IT professionals, technical updating climate, climate for reporting bad news in software projects, climate for knowledge-sharing [188] [189] [190] [191] [192] [193] [194]. Besides this, a number of researchers have also have mentioned that organizational climate has an impact on technical software development issues; thus, creating wide range of potential trouble points in the project [27] [28] [29] [30] [87]. 2.5 PERSPECTIVES OF SOFTWARE PROFESSIONALS The concept that different stakeholders can perceive software projects in different ways is also well established in the literature [46]. Keil et al. [141] have demonstrated that users and project managers differ in terms of their project risk perceptions. While Warkentin et al. [30] [195] and Stephen et al. [196] have exhaustively studied the perception of risk among various demographic characteristics of software professionals and have suggested that professionals with more experience in project leadership were more likely to view projects, and their associated risks, more holistically and assign and resolve risk as if they were organizational in nature. Researchers have also studied the perceived importance of risk factors among the experienced and inexperienced project managers and concluded that experienced project managers perceived different risks to be important compared with inexperienced project managers [124]. Liu et al. [197] have compared the senior executive and project manager perceptions of IT project risk in Chinese software industry. They concluded that project managers tend to focus on lower-level risks with particular emphasis on risks associated with requirements and user involvement, whereas top management focus on higher-level risks such as those risks involving politics, organization structure, process, and culture. Besides this, studies have also been done on the perception of success of the software project among various stakeholders by [74] [78] [80] [84]. These studies have concluded that there is a marked difference in the perception of the success of the software projects among various stakeholders of the project. 2.6 CONCLUDING REMARKS Thus, it can be clearly seen that tremendous amount of research has been conducted on software risk management. Ample literature is available which explains how software projects can be successfully delivered and various studies have been conducted to study the organization climate and its impact on software quality, innovativeness, team satisfaction etc., yet the success rate of software projects remains a mere 32% [9]. This clearly shows that there exists a definite gap between the researchers and practitioners approach. Some of the gaps identified in the contemporary research are as under: - Most of the studies done on identification and management of software risk have been conducted in the developed countries but there are very few studies on the identification of risk dimensions affecting the software projects in India. - In the literature, affect of organizational climate on success is well documented but its impact on software risks is largely anecdotal. Further, the dynamics of organizational climate on software risks and success is missing in the Indian context. - It is also seen that there are few studies done on the perception of software risks among various groups of software professionals. There is a paucity of research on the study of perception of software risks and organizational climate factors among various groups of software professionals based on demographic and project characteristics. - There is a paucity of research on gauging the collaborative impact of organizational climate and risk factors on the success and the three success constructs namely budget, schedule and quality. In view of the above literature, this research is directed towards understanding the dynamics of organizational climate factors on software risks and success of the software projects in India. It also aims to gauge the perception of risk and climate factors among the various groups of software professionals based on the demographics and project characteristics.
{"Source-Url": "http://shodhganga.inflibnet.ac.in/bitstream/10603/2428/11/11_chapter%202.pdf", "len_cl100k_base": 12970, "olmocr-version": "0.1.53", "pdf-total-pages": 31, "total-fallback-pages": 0, "total-input-tokens": 75328, "total-output-tokens": 14602, "length": "2e13", "weborganizer": {"__label__adult": 0.0004169940948486328, "__label__art_design": 0.0003883838653564453, "__label__crime_law": 0.0003848075866699219, "__label__education_jobs": 0.0028285980224609375, "__label__entertainment": 6.490945816040039e-05, "__label__fashion_beauty": 0.00016009807586669922, "__label__finance_business": 0.0011653900146484375, "__label__food_dining": 0.0003483295440673828, "__label__games": 0.0006895065307617188, "__label__hardware": 0.0004200935363769531, "__label__health": 0.00041556358337402344, "__label__history": 0.00020885467529296875, "__label__home_hobbies": 8.249282836914062e-05, "__label__industrial": 0.00027751922607421875, "__label__literature": 0.00036454200744628906, "__label__politics": 0.0002727508544921875, "__label__religion": 0.0003376007080078125, "__label__science_tech": 0.00394439697265625, "__label__social_life": 0.0001220107078552246, "__label__software": 0.0052490234375, "__label__software_dev": 0.98095703125, "__label__sports_fitness": 0.0002541542053222656, "__label__transportation": 0.0003113746643066406, "__label__travel": 0.00017392635345458984}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 69907, 0.0215]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 69907, 0.38626]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 69907, 0.94882]], "google_gemma-3-12b-it_contains_pii": [[0, 2205, false], [2205, 3697, null], [3697, 4961, null], [4961, 7646, null], [7646, 9461, null], [9461, 11689, null], [11689, 13923, null], [13923, 16609, null], [16609, 18944, null], [18944, 21426, null], [21426, 24285, null], [24285, 26954, null], [26954, 29553, null], [29553, 32165, null], [32165, 34794, null], [34794, 37413, null], [37413, 38292, null], [38292, 40581, null], [40581, 42741, null], [42741, 45170, null], [45170, 47332, null], [47332, 49555, null], [49555, 51751, null], [51751, 53540, null], [53540, 55449, null], [55449, 57808, null], [57808, 60256, null], [60256, 62577, null], [62577, 65303, null], [65303, 67722, null], [67722, 69907, null]], "google_gemma-3-12b-it_is_public_document": [[0, 2205, true], [2205, 3697, null], [3697, 4961, null], [4961, 7646, null], [7646, 9461, null], [9461, 11689, null], [11689, 13923, null], [13923, 16609, null], [16609, 18944, null], [18944, 21426, null], [21426, 24285, null], [24285, 26954, null], [26954, 29553, null], [29553, 32165, null], [32165, 34794, null], [34794, 37413, null], [37413, 38292, null], [38292, 40581, null], [40581, 42741, null], [42741, 45170, null], [45170, 47332, null], [47332, 49555, null], [49555, 51751, null], [51751, 53540, null], [53540, 55449, null], [55449, 57808, null], [57808, 60256, null], [60256, 62577, null], [62577, 65303, null], [65303, 67722, null], [67722, 69907, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 69907, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 69907, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 69907, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 69907, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 69907, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 69907, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 69907, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 69907, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 69907, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 69907, null]], "pdf_page_numbers": [[0, 2205, 1], [2205, 3697, 2], [3697, 4961, 3], [4961, 7646, 4], [7646, 9461, 5], [9461, 11689, 6], [11689, 13923, 7], [13923, 16609, 8], [16609, 18944, 9], [18944, 21426, 10], [21426, 24285, 11], [24285, 26954, 12], [26954, 29553, 13], [29553, 32165, 14], [32165, 34794, 15], [34794, 37413, 16], [37413, 38292, 17], [38292, 40581, 18], [40581, 42741, 19], [42741, 45170, 20], [45170, 47332, 21], [47332, 49555, 22], [49555, 51751, 23], [51751, 53540, 24], [53540, 55449, 25], [55449, 57808, 26], [57808, 60256, 27], [60256, 62577, 28], [62577, 65303, 29], [65303, 67722, 30], [67722, 69907, 31]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 69907, 0.0]]}
olmocr_science_pdfs
2024-12-10
2024-12-10
86b9ff53b53c4dca407937f062a05e958cbd232a
Reversible programming a case study of two string-matching algorithms Glück, Robert; Yokoyama, Tetsuo Published in: Proceedings 9th Workshop on Horn Clauses for Verification and Synthesis and 10th International Workshop on Verification and Program Transformation DOI: 10.4204/EPTCS.373.1 Publication date: 2022 Document version Publisher's PDF, also known as Version of record Document license: CC BY Citation for published version (APA): Reversible Programming: A Case Study of Two String-Matching Algorithms Robert Glück DIKU, Department of Computer Science, University of Copenhagen, Denmark glueck@acm.org Tetsuo Yokoyama Dept. of Electronics and Communication Technology, Nanzan University, Japan tyokoyama@acm.org String matching is a fundamental problem in algorithm. This study examines the development and construction of two reversible string-matching algorithms: a naive string-matching algorithm and the Rabin–Karp algorithm. The algorithms are used to introduce reversible computing concepts, beginning from basic reversible programming techniques to more advanced considerations about the injectivization of the polynomial hash-update function employed by the Rabin–Karp algorithm. The results are two clean input-preserving reversible algorithms that require no additional space and have the same asymptotic time complexity as their classic irreversible originals. This study aims to contribute to the body of reversible algorithms and to the discipline of reversible programming. 1 Introduction Reversible computing is an unconventional computing paradigm in which all computations are forward and backward deterministic. It complements existing mainstream programming paradigms that are forward deterministic, but usually backward nondeterministic, such as imperative and functional programming languages [9]. Reversible computing is required when the deletion of information is considered harmful as in quantum-based computing and to overcome Landauer’s physical limit (for a summary see [6, 11]). Additionally, reversible computing is a sweet spot for studying non-standard semantics and program inversion, which concern fundamental questions regarding program transformation [7]. The contribution of this study is threefold: • Introduce reversible computing concepts by a program development in this unconventional paradigm. • Explain a new, efficient reversible version of the Rabin–Karp algorithm for string matching. • Contribute to the advancement of a reversible programming discipline. String matching is a fundamental algorithmic problem with a wide range of practical applications. The problem is stated in a few lines (we follow established terminology [4]): Let \( T[0..n-1] \) be a text of length \( n \) and \( P[0..m-1] \) be a pattern of length \( m \) (\( \leq n \)) where the elements of arrays \( T \) and \( P \) are characters drawn from a finite alphabet \( \Sigma \) of size \( d \). The arrays are also called strings of characters. A pattern \( P \) occurs with a valid shift \( s \) in text \( T \) if \( T[s..s+m-1] = P[0..m-1] \). The string-matching problem is to find all valid shifts of \( P \) in \( T \). Today there are various string-matching algorithms all of which are defined in conventional languages. In this study, we develop efficient reversible string-matching algorithms, namely, a naive algorithm and the more efficient Rabin–Karp algorithm [10]. Although the worst-case matching time of the latter is no better than that of the naive method, the Rabin–Karp algorithm is faster on average because it uses hash values for fast, approximate matches, and only in the case of a possible match, performs an exact comparison of the pattern and text at the current shift. The use of a hash-update function that computes the next hash value from the current hash value (rolling hash) makes the creation of an efficient and reversible Rabin–Karp algorithm more challenging than that of the naive algorithm. We develop the reversible string-matching algorithms to explain reversible-computing concepts and how to solve the challenge posed by Rabin–Karp’s hash-based method. Specifically, we use the standard reversible programming language, Janus, with syntactic sugar to define the algorithms. Once the algorithms are written in a reversible language, they are guaranteed to be reversible. More details about reversible computing can be found in the literature, e.g., [22]. This study contributes to the existing literature on clean reversible algorithms that do not rely on tracing (e.g., [2, 8]), including a reversible FFT [21], Dijkstra’s permutation encoder [22], and language processors [23, 1]. 2 A Reversible Naive String Matcher We begin with the naive matcher to demonstrate how to proceed with reversible programming. The naive matcher developed in this section will later be employed in the reversible Rabin–Karp algorithm. Advanced considerations, such as the injectivization of the hash-update function, are discussed in the next section about the Rabin–Karp algorithm. Algorithms written in a reversible language cannot delete information, but can reversibly update information. No deletion of information means that programs written in a reversible imperative language cannot contain assignments that overwrite values, such as \( x := y + z \), only reversibly update values, such as \( x += y \) (shorthand for \( x := x + y \)). Consequently, reversible languages can only be as computationally powerful as reversible Turing machines (RTMs) [3], which exactly compute the computable injective functions. This injectiveness constraint makes reversible Turing machines strictly less powerful compared to their traditional counterparts that are universal. This is a significant limitation of reversible computing; however, all non-injective functions can be embedded in injective functions. There are two approaches for implementing a function in a reversible language. The first approach is to begin from an implementation written in a conventional (irreversible) language and reversibilize it into a program written in a reversible programming language, e.g., by recording the information otherwise lost (often called garbage). The second and the preferred approach is to change (injectivize) the problem specification into an injective function, which can be directly implemented in a reversible language without functional changes. The string-matching problem has an injective specification although it is usually considered a non-injective problem that, given text \( T \) and pattern \( P \), computes all valid shifts: \[ \text{match}(T, P) = \text{valid-shifts}. \] (1) This function specifies that \( T \) and \( P \) are consumed (deleted) by \( \text{match} \) and are replaced by \( \text{valid-shifts} \). Considering the problem from a reversible-computing perspective, we notice that we usually do not delete \( T \) and \( P \), but preserve them. This means that the string-matching problem has an injective specification: \[ \text{match}(T, P) = (T, P, \text{valid-shifts}). \] (2) Because of the injective specification, a faithful reversible implementation of the string-matching problem exists. This specification is an input-preserving injectivization (\( T \) and \( P \) are preserved). \[1\] Any expression \( e \) can be used in \( x += e \). Generally, to be reversible, \( x \) must not occur in \( e \) (e.g., \( x += -x \) is not reversible). A naive string-matching algorithm compares \( P \) to \( T \) at all shifts in \( T \) from left to right. When a mismatch is found at a shift \( s \), the matching continues at the next shift \( s + 1 \). The worst-case matching time for this (irreversible) naive matching method is \( \Theta((n - m + 1)m) \). First, we consider certain standard technical details. We consider characters as integers such that alphabet \( \Sigma \) of size \( d \) is set \{0, \ldots, d - 1\}. Let \( T \) and \( P \) be integer arrays of length \( n + 1 \) and \( m + 1 \), respectively, with terminating values \( T[n] \neq P[m] \), where \( P[m] \notin \Sigma \). Thus, the end of \( p \) is always signaled by a mismatch. All valid shifts \( s \), found during the search are pushed on a result stack. Thus, valid-shifts in Eqs. (1, 2) is a stack, which consists of zero or more unique indices of \( T \). At first glance, the reversible naive string matcher in Fig. 1 looks like a C-like program. At the second look, we notice that the program uses no destructive assignments, such as \( := \), only the reversible updates \( += \) and \( -= \) that add to resp. subtract from a variable the value of an expression, and the conditional at lines 9 to 15 not only has an entry test at \( \text{if} \), but also an exit test at \( \text{fi} \), which is the point where the control flow joins after executing one of the two branches. Reversible languages comprise elementary steps that perform injective transformations of the computation state, that is each step performs a forward and backward deterministic transition. Because the operations are reversible on the microscopic level, the macroscopic operation of a program written in a reversible language is perfectly reversible. The composition of injective functions is also an injective function, thus reversible programs implement computable injective functions. This principle is the same for all reversible languages including the transition function of a reversible Turing machine [3], a time-symmetric machine [15], and extensions that operate on quantum data (for quantum circuits, e.g. [16]). **A Reversible Matcher** The reversible naive string matcher, shown in Fig. 1 consists of three procedures. The main procedure \( \text{naive}\text{search} \) is called with a text \( T \), a pattern \( P \), and an initially empty stack \( R \) as input. When it returns, all valid shifts are stored in \( R \), and \( T \) and \( P \) are unchanged (all three arguments are pass-by-reference). The procedure tries all the possible shifts from left to right by incrementing \( s \) from 0 to \( n - m \) and calling procedure \( \text{match} \) in the for-loop \( \text{iterate} \) in lines 19 to 21. As a shorthand, we write \( m \) and \( n \) for the size of the pattern and text, respectively. Procedure \( \text{match} \) begins with calling procedure \( \text{compare} \) to match \( P \) to \( T \) beginning at shift \( s \) with the initial index \( i = 0 \). If \( \text{compare} \) returns with \( i = m \) (end of \( P \) is reached), the match succeeds, and \( s \) is a valid shift; otherwise, the match fails (end of \( P \) is not reached). The then-branch pushes the valid shift \( s \) to \( R \) and resets \( i \) to zero. Line 11 is required to restore the last value of \( s \) from the top of \( R \) because the last push \( \text{moved} \) that value to \( R \) and thereby zero-cleared \( s \). (This point is explained below.) In the else-branch, after the match fails at \( i < m \), the computation of \( \text{compare} \) is undone by uncalling \( \text{compare} \) to reset \( i \) to its initial value 0. (This is also explained below.) A local scope for \( i \) is opened and closed at the beginning and end of \( \text{match} \) using a \text{local}\text{–}\text{delocal} declaration. Furthermore, this scope declaration asserts the initial and final values of local variable \( i \) (in both cases \( i = 0 \)). Procedure \( \text{compare} \) compares \( P \) with \( T \) at \( s \), beginning with index \( i = 0 \). The loop begins with an entry test at line 2 which asserts that initially \( i = 0 \), and ends at line 4 when \( T[s+i] \neq P[i] \). This loop always terminates because by convention the terminating value \( P[m] \) is not in \( T \). **Reversible Programming** Similar to the other language paradigms, reversible computing has its own programming methodology. We summarize the programming techniques relevant to the programs in this study and exemplify them with examples from the programs. This is related to three important reversible programming themes: control flow, reversible updates, and data structures. procedure compare (int T[], P[], s, i) from i = 0 loop // index assertion i += 1 // character-by-character comparison until T[s+i] != P[i] // loop terminates when a mismatch occurs procedure match (int T[], P[], s, stack R) local int i = 0 call compare (T, P, s, i) if i = m then // match succeeded push (s, R) // push s to stack R of valid shifts w/ clearing s s += top (R) // restore the value of s i -= m // clear i else // match failed uncall compare (T, P, s, i) // clear i fi s = top (R) // current shift s is valid delocal int i = 0 procedure naivesearch (int T[], P[], stack R) iterate int s = 0 to n-m // slide over text call match (T, P, s, R) // match at current shift s end Figure 1: Reversible naive string-matching algorithm. Control flow: Join points in the control flow of a program require assertions to make them backward deterministic. In reversible languages, each join point is associated with a predicate that provides an assertion regarding the incoming computational states. This suggests that we must identify a predicate that is true when coming from a then-branch and false when coming from an else-branch. For a loop, we must identify a predicate that is initially true and false after each iteration. These assertions regarding the incoming control flow (‘come from’) are evaluated at runtime, similar to the tests that dispatch the outgoing control flow (‘go to’). If a predicate does not have the expected truth value, the control-flow operator is undefined, and therefore the entire program. Examples are fi-predicates in reversible conditional (if-fi) and from-predicates in a reversible while-loop (from-until). Sometimes, these assertions are easy to find, such as the entry test in line 2 of the increment loop in Fig. 1, which checks that the loop begins from $i = 0$ and $i \neq 0$ after the first iteration. The exit test $s = \text{top}(R)$ in line 15 of the conditional uses the fact that the shifts in stack $R$ are unique. Thus, whenever a match fails, indicating that $s$ is not pushed to $R$, the current shift $s$ and the last shift $\text{top}(R)$ differ. An excerpt from the program highlights these two cases: \[ \begin{align*} \text{from } i &= 0 \text{ loop} \quad \text{if } i = m \text{ then } \text{push}(s,R) \ldots \\ i &+= 1 \quad \text{else } \ldots \text{no push } \ldots \\ \text{until } T[s+i] &\neq P[i] \quad \text{fi } s = \text{top}(R) \end{align*} \] However, these assertions are not always easy to find and may require a restructuring of the program. Only a few conventional control-flow operators are reversible and do not require additional assertions, such as for-loops that iterate for a fixed number of times, e.g., iterate in lines [19, 21]. Reversible updates: Data can only be reversibly updated. The usual computational resources for deleting data in one way or another are not available (e.g., forgetting local variables upon procedure re- We present several update techniques used in our programs starting from a straightforward initialization of a zero-cleared variable to the uncalling of a procedure to reset values. Readers interested in reversible updates defined in a more general form should refer to [21]. (i) Copying & zero-clearing. If variable $i$ is known to be zero, it can be set to a value, e.g., by addition. For example, $i += m$ has the effect of reversibly copying the value of $m$ to $i$. Similarly, if we know that $i$ has the same value as $m$, that is $i = m$, we can zero-clear $i$ using $i -= m$. However, the relationship between two variable values is not always known. Additionally, when it becomes known owing to an equality test in a conditional, we can exploit this knowledge in the then-branch to zero-clear the variable. This is used in line 12 to reversibly reset $i$ to zero: ```plaintext if $i = m$ then ... $i -= m$ else ... fi ... ``` These techniques are indirectly used in a local–delocal declaration, where the local variable is initialized and cleared at the beginning and end of its scope using an equality test (here, however, just a simple $x = 0$ in lines 7 and 16). In general, the declaration of a local variable, $i$, has the following form, where $i$ is initially set to the value of $e$ and in the end must have a value equal to the value of $e'$: ```plaintext local int $i = e$ ... delocal int $i = e'$ ``` (ii) Compute-uncompute. Reversible programs are forward and backward deterministic; thus, they can run efficiently in both directions. Many reversible languages not only provide access to their standard semantics, e.g., using a procedure call, but also to their inverse (backward) semantics, e.g., using a procedure uncall. An uncall of a procedure is as efficient as a call because a procedure is forward and backward deterministic. We employ this property to reset index $i$ after an unsuccessful match, which can occur at any position $i < m$ in a pattern. We cannot determine the subtrahend to zero-clear $i$ (and we cannot use the irreversible $i -= i$). Instead we undo the computation of $i$ by an uncall in the else-branch. This resets $i$ to its initial value 0. By combining the techniques seen so far, we ensure that $i$ is zero-cleared after the if-fi. In the then-branch, we use the equality $i = m$; in the else-branch we undo the computation: ```plaintext local int $i = 0$ call compare(...,$i$) if $i = m$ then ... $i -= m$ else uncall compare(...,$i$) fi ... delocal int $i = 0$ ``` The compute-uncompute method goes back to the first RTMs [3], where a machine is textually composed with its inverse machine to restore the original computation state (which doubles the size of the entire machine). The call–uncall method above shares the text of a procedure (here, compare). It just invokes the standard resp. inverse computation of the procedure. We could have used an uncall in the then-branch. Instead, we exploit the knowledge about $i = m$ from the entry test of the if-fi to zero-clear $i$ using $i -= m$, which takes constant time, whereas the uncall requires time proportional to the length of $P$. The conditional takes advantage of both techniques. Bennett used program inversion to obtain an inverse RTM, whereas the aforementioned method uses inverse computation. We could have used program inversion to invert the procedure compare into the inverse procedure $\text{compare}^{-1}$ and invoked the latter using call $\text{compare}^{-1}$ to reset $i$. Both methods, calling the inverse procedure $\text{compare}^{-1}$ and inverse computation of $\text{compare}$, are functionally equivalent. Because RTMs cannot access their inverse semantics, e.g., by an uncall, program inversion is the only choice to build RTMs that restore the input from their output, whereas in a reversible language typically both choices are available. We refer to them collectively as the compute–uncompute programming method. It is used in many forms at all levels of a reversible computing system from reversible circuits (e.g., [20]) to high-level languages (e.g., [14]). Data structures: The data structures in reversible languages are the same as in conventional languages, such as arrays, stacks and lists, only the update operations on the data structures must be reversible. In the case of a stack, the operations push and pop can be defined as inverse to each other by letting them swap in and out the value on top of the stack, which means that $\text{pop} = \text{push}^{-1}$ [23]: $$\begin{align*} \text{push} & \quad \Downarrow \quad \text{pop} \\ (v, v_n \ldots v_1) & \quad \xrightarrow{\text{push}} \quad (0, v v_n \ldots v_1) \end{align*}$$ This definition of a push has the unfamiliar property that push($s$, $R$) in line 10 moves the value $v$ of $s$ to the top of the stack $R$ and zero-clears $s$. Because we need the value that we have pushed to continue the search, the value is copied back to $s$ from the top of $R$ using $s += \text{top}(R)$ in line 11. We can now complete the body of procedure $\text{match}$ in lines 7–16 by adding the two statements to the then-branch and the exit test that we discussed above to fi: ```c local int i = 0 call compare(...,i) if i = m then push(s,R) s += top(R) i -= m else uncall compare(...,i) fi s = top(R) delocal int i = 0 ``` We remark that abstract data types and object-oriented features can be used in reversible languages provided that their update operations and methods are reversible. Ideally, they are designed such that call and uncall can be used. When operators are inverse to each other, only one of them needs to be implemented. The idea of code sharing by running code backward can be traced back to the 60s [18]. We have presented all reversible-programming techniques used in the procedures $\text{naivesearch}$, $\text{match}$, and $\text{compare}$. This completes the review of the reversible naive string-matching algorithm shown in Fig. [1]. 3 A Reversible Rabin–Karp Algorithm The Rabin–Karp algorithm \[10\] replaces exact matches with approximate matches, which are inexact but fast, and performs exact matches only if a successful match is possible. This makes the algorithm conceptually easy and fast in practice. This study refers to the version presented by Cormen et al. \[4\]. The algorithm extends the naive string-matching algorithm by performing at each shift \(s\), an approximate match by comparing the hash values of \(P\) and \(T\) at \(s\). An exact match (by procedure match) can only succeed if the two hash values are identical; otherwise, an exact match is impossible. In either case, the next hash value at \(s+1\) can be computed in constant time from the current hash value at \(s\) (rolling hash) using a hash-update function \(\phi_s\). Hash values typically fit into single words that can be compared in constant time. The initial hash values of \(P\) and \(T\) at shift 0 are computed at the beginning of the algorithm using a hash function (pre-processing). The subsequent hash values are then computed using the hash-update function. The key to an efficient clean reversible Rabin–Karp matcher is a reversible constant-time calculation of the rolling hash values. We have explained the reversible naive string-matching algorithm in the previous section, and we can reuse procedures match and compare from Fig.\[1\] for the reversible Rabin–Karp algorithm. In this section, we focus on the injectivization and implementation of the hash functions that show the considerations for the development of a more advanced reversible algorithm. A preliminary version of the reversible Rabin–Karp program has appeared as a technical report \[19\]. The reversible Rabin–Karp program in this study becomes more concise and modular because of the use of macros and iterate loops. **Hash Function** The Rabin–Karp algorithm requires a pre-process that calculates the hash values of the given pattern, \(P[0..m-1]\), and of the initial substring, \(T[0..m-1]\), of the given text \(T\). The initial substring has the same length \(m\) as \(P\). Recall that \(P\) and \(T\) are two integer arrays over the non-empty alphabet of \(d\) integers \(\{0,\ldots,d-1\}\). Let \(p\) denote the hash value of \(P\) obtained using a polynomial hash function with modulus \(q\): \[ p = (P[0]d^{m-1} + P[1]d^{m-2} + \cdots + P[m-1]) \mod q. \tag{4} \] Similarly, let \(t_s\) denote the hash value of the substring \(T[s..s+m-1]\) of length \(m\) at shift \(s\): \[ t_s = (T[s]d^{m-1} + T[s+1]d^{m-2} + \cdots + T[s+m-1]) \mod q. \tag{5} \] The polynomials can be computed in \(\Theta(m)\) using Horner’s rule. Preferably, modulus \(q\) should be as large a prime as possible such that \(dq\) fits into a single word: thus, all modulo operations are single-precision arithmetic. The following properties of the two hash values are important. If \(t_s \neq p\), \(T[s..s+m-1] \neq P[0..m-1]\): thus, shift \(s\) cannot be valid. If \(t_s = p\), it is possible that \(T[s..s+m-1] = P[0..m-1]\): thus, an exact match is required to determine if shift \(s\) is valid. Whereas hash value \(p\) of \(P\) is the same during the matching, hash value \(t_s\) of \(T\) must be calculated for each shift \(s\). In order to efficiently calculate hash values \(t_s\) for \(s > 0\), we calculate the hash value \(t_{s+1}\) at the subsequent shift \(s+1\) from the hash value \(t_s\) at the current shift \(s\), using a recurrence function. We use this function to reversibly update the hash values in constant time. For a reversible implementation, conditions are first determined under which the function is injective. Then the function is rewritten into a composition of modular arithmetic operators, each of which is embedded in a reversible update. **Hash-Update Function** We can compute $t_{s+1}$ from $t_s$ for $0 \leq s \leq n - m$ because $$t_{s+1} = \phi_s(t_s)$$ (6) where the recurrence function $\phi_s$ is defined as $$\phi_s(x) = (d(x - T[s]d^{m-1}) + T[s + m]) \mod q.$$ (7) The recurrence function calculates the subsequent hash value from the current hash value $x$ by canceling the old highest-order radix-$d$ digit $T[s]$ via subtraction, shifting the value via multiplication with $d$, adding the new lowest-order radix-$d$ digit $T[s + m]$, and obtaining its remainder when divided by $q$. We can compute $\phi_s(t_s)$ in constant time if factor $d^{m-1}$ is precomputed. For reversible computing it is problematic that $\phi_s$ is generally not injective because the modulo operation is not injective in its first argument for arbitrary integers. Determining the conditions under which a function becomes injective by exploiting its properties and specific application context is an important step in the development of a clean reversible algorithm. We exploit certain properties in the domain of arithmetic operations in $\phi_s$. The congruence of two integers $x$ and $y$ modulo $q$, $x \equiv y \pmod{q}$, is compatible with addition, subtraction, and multiplication. But unlike these operations, division cannot always be performed. To show the injectiveness of $\phi_s$ in the following lemma requires that $d$ and $q$ be coprime integers, which means their greatest common divisor is 1. For example, when $d$ and $q$ are not coprime, $e.g., d = 2$ and $q = 6$ then $2 \cdot 1 = 2 \cdot 4 \pmod{6}$, we cannot divide this congruence by 2 because $1 \not\equiv 4 \pmod{6}$. Whereas if they are coprime, $e.g., d = 2$ and $q = 3$, then $2 \cdot 1 = 2 \cdot 4 \pmod{3}$ and we can divide this by 2 to deduce $1 \equiv 4 \pmod{3}$. We exploit this constraint on the operands in Lemma 3 which establishes that $\phi_s$ is injective. For the cancelation of common terms in congruences modulo $q$, we use the following two lemmas in the proof. **Lemma 1 (e.g. [13] Prop. 13.3).** Suppose $x, y \in \mathbb{Z}$ and $x \equiv y \pmod{q}$. If $c \in \mathbb{Z}$ then $$x + c \equiv y + c \pmod{q} \implies x \equiv y \pmod{q}.$$ (8) **Lemma 2 (e.g. [13] Prop. 13.5).** Suppose $d$ and $q$ are coprime integers. If $x, y \in \mathbb{Z}$ then $$dx \equiv dy \pmod{q} \implies x \equiv y \pmod{q}.$$ (9) **Proof.** We assume that $dx \equiv dy \pmod{q}$. Therefore, $d(x - y)$ is a multiple of $q$. Because $d$ and $q$ are coprime, $(x - y)$ is a multiple of $q$, i.e. $x \equiv y \pmod{q}$. \hfill $\square$ **Lemma 3.** Provided that $0 \leq x < q$, $0 < d < q$, and $d$ and $q$ are coprime, recurrence function $\phi_s$ is injective, where $$\phi_s(x) = (d(x - T[s]d^{m-1}) + T[s + m]) \mod q.$$ (10) **Proof.** We show that for any $x_1$ and $x_2$, whenever $\phi_s(x_1) = \phi_s(x_2)$, we have $x_1 = x_2$. $$\phi_s(x_1) = \phi_s(x_2)$$ $$\implies d(x_1 - T[s]d^{m-1}) + T[s + m] \equiv d(x_2 - T[s]d^{m-1}) + T[s + m] \pmod{q}$$ $$\implies d(x_1 - T[s]d^{m-1}) \equiv d(x_2 - T[s]d^{m-1}) \pmod{q} \implies \text{Lemma 1}$$ $$\implies x_1 - T[s]d^{m-1} \equiv x_2 - T[s]d^{m-1} \pmod{q} \implies \text{Lemma 2}$$ and $d$ and $q$ are coprime integers $$\implies x_1 \equiv x_2 \pmod{q} \implies \text{Lemma 1}$$ $$\implies x_1 = x_2 \implies 0 \leq x_1, x_2 < q$$ \hfill $\square$ The condition that \( d \) and \( q \) are coprime is not a restriction in practice because \( q \) is usually selected to be a large prime number. Thus, if \( q \) is prime, any alphabet size \( 0 < d < q \) can be used. **Injective Modular Arithmetic** For efficient calculation of a hash value, it is preferable to perform modular arithmetic at each elementary arithmetic operation instead of first calculating a large value that may exceed the largest representable integer. Therefore, we define the injective recurrence function \( \phi \), using elementary modular arithmetic operators, each of which is sufficiently simple to be easily implemented in a reversible language (e.g., supported as built-in operators or by reversible hardware). We rewrite \( \phi_i(x) \) in Eq. (10) into a composition of modular arithmetic operators \( +_q, -_q, \) and \( \cdot_q \) using the distributivity of the modulo operation as shown in Eq. (11). Similarly, the hash functions in Eqs. (4) and (5) can be rewritten as Eqs. (13) and (14). The same transformation is required for implementation in conventional languages. Additionally, we inspect the injectivity of each operator such that a reversible implementation can be provided. The injective function, \( \phi \), comprises the following operators: \[ \phi_i(x) = d \cdot_q (x - q T[s] \cdot_q h) + q T[s + m] \] (11) where factor \( h = d^{m-1} \) (mod \( q \)) is precomputed by \[ h = d \cdot_q \cdots \cdot_q d \mod m^{-1}. \] (12) Hash value \( p \) of a given pattern \( P \) and initial hash value \( t_0 \) of a given text \( T \) can be obtained using Horner’s rule defined in \( \psi \): \[ p = \psi(P[0..m-1]) \] (13) \[ t_0 = \psi(T[0..m-1]) \] (14) where \[ \psi(X[i..j]) = X[j] + q d \cdot_q (X[j-1] + q d \cdot_q (\cdots + q d \cdot_q (X[i+1] + q d \cdot_q X[i] \cdots)) ) . \] (15) The identity between \( \psi \) applied to the final substring, \( T[n-m..n-1] \), at shift \( n-m \) and the hash update \( \phi_{n-m-1} \) is used to zero-clear the final hash value, \( t_{n-m} \), in the reversible program: \[ t_{n-m} = \psi(T[n-m..n-1]) \quad \text{\textbullet\textbullet\textbullet Eq. (15)} \] (16) \[ t_{n-m} = \phi_{n-m-1}(t_{n-m-1}) \quad \text{\textbullet\textbullet\textbullet Eq. (6)}. \] (17) The problem is that modular arithmetic operations are generally non-injective. However, under certain conditions, they are injective in one of their arguments. For example, they are injective in their first arguments: - Addition \( x +_q y \) and subtraction \( x -_q y \) are injective in their first arguments if \( 0 \leq x, y < q \). - Multiplication \( x \cdot_q d \) is injective in its first argument if \( 0 \leq x < q \), \( 1 \leq d < q \), and \( d \) and \( q \) are coprime. Note that \( x \cdot_q d \) is not injective in its first argument, unless \( d \) and \( q \) are coprime. Thus, the relationship between \( d \) and \( q \) is a necessary condition. Analogously, the same holds for the second arguments of \( +_q, -_q, \) and \( \cdot_q \). Recall that the composition of injective functions is an injective function. Thus, the injectiveness of operators \( x +_q y, x -_q y, \) and \( x \cdot_q y \) under the stated conditions demonstrates the injectiveness of Eq. (11) under corresponding conditions. --- 2A partial function, \( f : X \times Y \times \cdots \times Y \to Z \), is injective in its first argument if for all \( x_1, x_2 \in X, y_1, \ldots, y_n \in Y \): if \( f(x_1, y_1, \ldots, y_n) \) and \( f(x_2, y_1, \ldots, y_n) \) are defined, \( f(x_1, y_1, \ldots, y_n) = f(x_2, y_1, \ldots, y_n) \) \( \Rightarrow x_1 = x_2 \). Similarly, for other arguments [21]. Implementation of Modular Arithmetic A ternary function that is injective in its first argument \( f(x, y, z) \) can be embedded in the reversible update \( g(x, y, z) = (f(x, y, z), y, z) \). Arguments \( y \) and \( z \) are part of the result of \( g \). Thus, \( g \) is injective. Such reversible updates for \( x +_q y \) and \( x -_q y \) can be implemented in Janus. We write \[ \begin{align*} \cdot \quad x & =+_q y \quad \text{for} \quad g_1(x, y, q) = (x +_q y, y, q), \quad \text{and} \\ \cdot \quad x &=+_q y \quad \text{for} \quad g_2(x, y, q) = (x -_q y, y, q). \end{align*} \] In the implementation of these operators in a reversible language, \( x, y, \) and \( q \) are integers that cannot be larger than the largest representable integer in that language. Otherwise, the same restrictions as those for mathematical modular arithmetic apply. Thus, we assume that \( x \) and \( y \) range over 0 to \( q-1 \), except that \( y \) ranges from 1 in multiplication. It is the programmer’s responsibility to ensure \( y \) and \( q \) are coprime integers in \( x =_q y \). In practice, it is sufficient that \( q \) is prime, so that \( y \) and \( q \) are coprime. The subtraction, \( x -_q y \), can be realized using an uncall to \( x =_q y \), and is written as \( x =-_q y \). The variable on the left-hand side must not occur on the right-hand side of any of these operators. We assume that these operators perform in constant time. The \( n \)th power of \( b \) can be stored in a zero-cleared variable, \( z \), written \( z =_q b^n \), by initializing \( z \) with 1 and repeating \( n \)-times \( z =_q b \): \[ \text{z += 1 } \\ \text{iterate int i = 0 to n-1 } \\ \text{z *=_q b } \\ \text{end} \] For notational simplicity, we write \( z =-_q b^n \) as the inverse of \( z =_q b^n \) to zero-clear \( z \). In an implementation the arguments of modular arithmetic operators cannot be larger than the largest representable integer in a particular reversible programming language. A Reversible Rabin–Karp Matcher Figure 2 shows the program for the reversible Rabin–Karp algorithm. The program consists of three procedures and uses procedure match in Fig. 1. The main procedure rabinkarp is called with text \( T \), pattern \( P \), alphabet size \( d \) (including the dummy character terminating \( P \)), modulus \( q \), and an initially empty stack \( R \) as the input. When it returns, all valid shifts are stored in \( R \), and all other variables \( T, P, d, q \) remain unchanged. Therefore, it is an implementation of an input-preserving injectivization of the string-matching problem shown in Eq. 2. The main iteration in lines 18–23 corresponds to that in the main procedure of the naive string-matching algorithm, except that the hash value \( p \) of \( P \) and the hash value \( t \) of \( T \) at shift \( s \) are compared. Only if a match is possible, that is \( p = t \) is true in line 19 an exact match of \( P[0..m-1] \) and \( T[s..s+m-1] \) is performed in the then-branch by calling match in line 20. This exact match can update \( R \) with a valid shift depending on the outcome of the comparison. After the conditional, \( t \) at shift \( s \) is updated to the hash value at shift \( s+1 \) through a call to update. Subsequently, the iteration continues at the next shift. The pre- and post-processing before and after the main iteration are performed in lines 14–16 and lines 25–27 respectively. In pre-processing, the hash values \( p \) and \( t \) are initialized by the calls to init_h as defined in Eqs. 13, 14, and \( h \) is precomputed using \( h =_q d^{n-1} \) as defined in Eq. 12. Post-processing, a typical idiom of reversible programming to zero-clear variables, uncomputes the values of \( h, t \) and \( p \). Notably, the call of init_h in line 15 and the uncall of init_h in line 26 have different indices. The uncall uses the fact that the last value of \( t \) is the hash value of \( T \) in the last shift \( n-m \) (cf., Eq. 17), whereas the initial value of \( t \) is the hash value of \( T \) in the first shift 0. R. Glück & T. Yokoyama 1 procedure init_h (int x, i, j, X[], d, q) 2 iterate int k = i to j-1 // compute hash value by Horner’s rule 3 x *=q d // shift by one radix-d digit 4 x +=q X[k] // add the low-order radix-d digit 5 end 7 procedure update (int t, T[], s, h, m, q) 8 t -=q T[s]*h // remove the high-order radix-d digit 9 t *=q d // shift by one radix-d digit 10 t +=q T[s+m] // add the low-order radix-d digit 12 procedure rabinkarp (int T[], P[], d, q, stack R) 13 local int t=0, int p=0, int h=0 14 call init_h (p, 0, m, P, d, q) // store hash of P[0..m-1] in p 15 call init_h (t, 0, m, T, d, q) // store hash of T[0..m-1] in t 16 h +=q d^m-1 // precompute factor h 17 iterate int s = 0 to n-m // slide over text if p = t then // compare hash values call match (T, P, s, R) // match at current shift s fi p = t call update (t, T, s, h, m, q) // update hash value end 25 h -=q d^m-1 // clear h 26 uncall init_h (t, n-m, n, T, d, q) // clear t 27 uncall init_h (p, 0, m, P, d, q) // clear p 28 delocal int t=0, int p=0, int h=0 Figure 2: Reversible Rabin–Karp algorithm. Procedure update computes the subsequent hash value, \( t_{s+1} \) from \( t_s \), in constant time using Eq. (11). Line 8 removes the high-order radix-d digit from \( t \), line 9 multiplies \( d \), which shifts the radix-d number left by a one-digit position, and line 10 adds the low-order radix-d digit. All the operations are modulo \( q \). Procedure init_h computes in an initially zero-cleared variable \( x \), the hash value \( \psi(X[i..j-1]) \) of a substring \( X[i..j-1] \), using Horner’s rule as shown in Eq. (15). In addition to \( x \), the indices \( i \) and \( j \), array \( X \), alphabet size \( d \), and modulus \( q \) are used as inputs. The hash values \( p = \psi(P[0..m-1]) \) and \( t_0 = \psi(T[0..m-1]) \) are computed in \( \Theta(m) \). Space, Time, and Reversibilization Regarding the space consumption of the program, no extra arguments are passed to procedure rabinkarp to maintain garbage values. All local variables are allocated and deallocated in the body of the procedures, and neither stacks nor arrays are allocated. Therefore, no additional space is required compared with the irreversible original of the program [4]. The pre- and post-processing times are bounded by the running time of init_h, which is \( \Theta(m) \). The worst-case running time of matching is \( \Theta((n-m+1)m) \), which is the same as that of the irreversible Rabin–Karp algorithm. In the worst case, the iteration repeats the \( \Theta(m) \) steps of the exact match \( n-m+1 \) times. The shift \( s \) increases monotonically in the main iteration of procedure rabinkarp and a limited number of elements \( T[s..s+m-1] \) of the text is accessed at each iteration. Thus, just like the irreversible original, the proposed Rabin–Karp algorithm computes over bounded space. Notably, no extra space is required by the two reversible string-matching programs. The speedup gained by allowing deletion as a computational resource (at the expense of additional heat dissipation owing to entropy increase \([6, 11]\)) is a constant factor of approximately two (the uncall in procedure `match` in case of an unsuccessful comparison). Thus, if reversibility were removed and the two programs were turned back into C-like imperative programs, speed, but no space would be obtained. The reversible programs, developed in this study, are in contrast to what one obtains from mechanically reversibilizing the string-matching algorithms using Bennett’s method \([3]\). Bennett’s method has the advantage that it can be applied to any irreversible program; however, it requires additional space proportional to the length of the computation because of the recording of a trace (for reversible simulations with improved space efficiency, see \(e.g., [17]\)). Therefore, the entire run of a reversibilized string matcher, including all hash calculations and mismatches, is recorded in the computation history. Moreover, because of the uncompute phase added by Bennett’s method to clean up the trace after finding all valid shifts, the reversible string-matching program produced by this reversibilization method is no longer computing over bound space. 4 Conclusion In this study, we have designed and implemented the reversible versions of a naive string-matching algorithm and the Rabin–Karp algorithm. We have shown that the hash-update function with a reasonable restriction in the reversible Rabin–Karp algorithm is injective. The reversible versions of a naive string matching algorithm and the Rabin–Karp algorithm have the same asymptotic running time \(O((n - m + 1)m)\) and space usage \(O(n + m)\), as the irreversible versions. Because the original inputs preserved over the runs are not regarded as garbage, both reversible algorithms are clean, \(i.e., \) they produce no garbage as output. The main iteration monotonically increases the shift \(s\) from 0 to \(n - m + 1\). Thus, the proposed Rabin–Karp algorithm is a streaming algorithm. This property cannot be automatically obtained by the reversibilization of Bennett \([3]\) and Lange–McKenzie–Tapp \([12]\). It is expected that the reversible algorithms developed in this study can be a part of other algorithms, and the insights gained from constructing the reversible algorithms can be applied in future program developments. Verifying conventional programs is not always an easy task (\(e.g., [5]\)), and exploring the reversibilization and mechanical verification of reversible programs will be a challenge in future work. Acknowledgments The authors would like to thank Geoff Hamilton, Temesghen Kahsai, and Maurizio Proietti for their kind invitation to contribute to the workshop HCVS/VPT at ETAPS week 2022 in Munich and the anonymous reviewers for the useful feedback. The idea for the reversible algorithms in this study was brewed in joint work with Kaira Tanizaki and Masaki Hiraku. The second author was supported by JSPS KAKENHI Grant Number 22K11983. References
{"Source-Url": "https://static-curis.ku.dk/portal/files/330783778/Reversible_Programming.pdf", "len_cl100k_base": 11101, "olmocr-version": "0.1.50", "pdf-total-pages": 14, "total-fallback-pages": 0, "total-input-tokens": 51953, "total-output-tokens": 14133, "length": "2e13", "weborganizer": {"__label__adult": 0.0005793571472167969, "__label__art_design": 0.0004513263702392578, "__label__crime_law": 0.00047850608825683594, "__label__education_jobs": 0.0012331008911132812, "__label__entertainment": 0.0001239776611328125, "__label__fashion_beauty": 0.0002486705780029297, "__label__finance_business": 0.0003542900085449219, "__label__food_dining": 0.0005860328674316406, "__label__games": 0.001010894775390625, "__label__hardware": 0.0015878677368164062, "__label__health": 0.00130462646484375, "__label__history": 0.0004222393035888672, "__label__home_hobbies": 0.0001608133316040039, "__label__industrial": 0.0007052421569824219, "__label__literature": 0.0006432533264160156, "__label__politics": 0.0003781318664550781, "__label__religion": 0.0008974075317382812, "__label__science_tech": 0.11187744140625, "__label__social_life": 0.00014281272888183594, "__label__software": 0.0052032470703125, "__label__software_dev": 0.8701171875, "__label__sports_fitness": 0.0004410743713378906, "__label__transportation": 0.0009312629699707032, "__label__travel": 0.0002543926239013672}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 46955, 0.04764]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 46955, 0.40481]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 46955, 0.80738]], "google_gemma-3-12b-it_contains_pii": [[0, 880, false], [880, 4115, null], [4115, 7907, null], [7907, 12627, null], [12627, 15561, null], [15561, 18772, null], [18772, 21572, null], [21572, 25382, null], [25382, 28766, null], [28766, 32462, null], [32462, 36577, null], [36577, 39468, null], [39468, 43017, null], [43017, 46955, null]], "google_gemma-3-12b-it_is_public_document": [[0, 880, true], [880, 4115, null], [4115, 7907, null], [7907, 12627, null], [12627, 15561, null], [15561, 18772, null], [18772, 21572, null], [21572, 25382, null], [25382, 28766, null], [28766, 32462, null], [32462, 36577, null], [36577, 39468, null], [39468, 43017, null], [43017, 46955, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 46955, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 46955, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 46955, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 46955, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 46955, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 46955, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 46955, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 46955, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 46955, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 46955, null]], "pdf_page_numbers": [[0, 880, 1], [880, 4115, 2], [4115, 7907, 3], [7907, 12627, 4], [12627, 15561, 5], [15561, 18772, 6], [18772, 21572, 7], [21572, 25382, 8], [25382, 28766, 9], [28766, 32462, 10], [32462, 36577, 11], [36577, 39468, 12], [39468, 43017, 13], [43017, 46955, 14]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 46955, 0.0]]}
olmocr_science_pdfs
2024-11-29
2024-11-29
026a6706211fbe2cad6d4ccc00e5ae9e0f1eaaa5
On the Codd Semantics of SQL Nulls Citation for published version: Link: Link to publication record in Edinburgh Research Explorer Document Version: Publisher's PDF, also known as Version of record Published In: Proceedings of the 11th Alberto Mendelzon International Workshop on Foundations of Data Management General rights Copyright for the publications made accessible via the Edinburgh Research Explorer is retained by the author(s) and / or other copyright owners and it is a condition of accessing these publications that users recognise and abide by the legal requirements associated with these rights. Take down policy The University of Edinburgh has made every reasonable effort to ensure that Edinburgh Research Explorer content complies with UK legislation. If you believe that the public display of this file breaches copyright please contact openaccess@ed.ac.uk providing details, and we will remove access to the work immediately and investigate your claim. On the Codd Semantics of SQL Nulls Paolo Guagliardo and Leonid Libkin School of Informatics, University of Edinburgh Abstract. Theoretical models used in database research often have subtle differences with those occurring in practice. One particular mismatch that is usually neglected concerns the use of marked nulls to represent missing values in theoretical models of incompleteness, while in an SQL database these are all denoted by the same syntactic NULL object. It is commonly argued that results obtained in the model with marked nulls carry over to SQL, because SQL nulls can be interpreted as Codd nulls, which are simply marked nulls that do not repeat. This argument, however, does not take into account that even simple queries may produce answers where distinct occurrences of NULL do in fact denote the same unknown value. For such queries, interpreting SQL nulls as Codd nulls would incorrectly change the semantics of query answers. To use results about Codd nulls for real-life SQL queries, we need to understand which queries preserve the Codd interpretation of SQL nulls. We show, however, that the class of relational algebra queries preserving Codd interpretation is not recursively enumerable, which necessitates looking for sufficient conditions for such preservation. Those can be obtained by exploiting the information provided by NOT NULL constraints on the database schema. We devise mild syntactic restrictions on queries that guarantee preservation, do not limit the full expressiveness of queries on databases without nulls, and can be checked efficiently. 1 Introduction Query evaluation is a fundamental task in data management, and very often it has to be performed on databases that have incomplete information. This is especially true in applications such as data integration [7, 4], data exchange [1] and ontology-based data access [2, 6] that rely on the standard tools offered by existing relational database technology, in particular SQL, in order to take advantage of its efficiency. There is much theoretical research on query answering and its applications that uses well established models of incompleteness. However, there is an important and often neglected mismatch between theoretical models and real-life SQL, which has an impact on the semantics of query answers. Theoretical work traditionally adopts a model of incompleteness where missing values in a database are represented by marked (also called naive or labeled) nulls. In SQL, however, missing values are all represented by the same syntactic object: the infamous NULL. Marked nulls are more expressive than SQL nulls: two unknown values can be asserted to be the same just by denoting them with the same null. For example, in a relation $R$ with attributes name and age, one can put tuples (“Alice”, ⊥₁) and (“Bob”, ⊥₁) to express the fact that Alice and Bob have the same age, even though their actual age, represented by the null ⊥₁, is unknown. However, there is a standard argument often found in the literature: SQL nulls are modeled by Codd nulls, that is, non-repeating marked nulls. Then each NULL is interpreted as a fresh marked null that does not appear anywhere else in the database. But do Codd nulls properly model SQL nulls? It is sometimes argued (e.g., in [8]) that they are different, but this assumes a special type of evaluation – called naive [5] – under which marked nulls are simply viewed as new constants, e.g., ⊥₁ ≠ ⊥₂ etc. Under naive evaluation, the conjunctive query q(x) :- R(x, y), R(x, y′), y = y′ will produce {“Alice”, “Bob”}, while the same query in SQL, SELECT R1.name FROM R R1, R R2 WHERE R1.age = R2.age, will produce the empty set. This mismatch is due to the SQL’s use of 3-valued logic (3VL): comparisons involving nulls in SQL result in the truth value unknown, even if a null is compared to itself, which happens in the above example. But this is easy to fix by using the same comparison semantics for Codd nulls: every condition x = y or x ≠ y evaluates to unknown if x or y is a null. So, is this sufficient to reconcile the mismatch between Codd nulls and SQL nulls? The answer is still negative, because we have not taken into account the role of queries. If SQL nulls are to be interpreted as Codd nulls, this interpretation should apply to input databases as well as query answers, which are incomplete databases themselves. To explain this point, let codd(R) be the result of replacing SQL nulls in R with distinct marked nulls, e.g., for R = { (“Alice”, NULL), (“Bob”, NULL) }, we would have codd(R) = { (“Alice”, ⊥₁), (“Bob”, ⊥₂) }. Technically, codd(R) is the set of such relations, because we can choose distinct marked nulls arbitrarily (e.g., { ⊥₃, ⊥₄ } instead of { ⊥₁, ⊥₂ } ), but they are all isomorphic. To ensure that Codd nulls faithfully represent SQL nulls for a query Q, we need to enforce the condition in the diagram below: \[ \begin{array}{ccc} D & \xrightarrow{Q} & Q(D) \\ \downarrow{codd} & & \downarrow{codd} \\ D' & \xrightarrow{Q} & Q(D') \end{array} \] Intuitively, it says the following: take an SQL database D, and compute the answer to Q on it, i.e., Q(D). Now take some D' ∈ codd(D) and compute Q(D'). Then Q(D') must be in codd(Q(D)), i.e., there must be a way of assigning Codd nulls to SQL nulls in Q(D) that will result in Q(D'). Does this condition hold for queries in some sufficiently expressive language like relational algebra? Unfortunately, the answer is negative, even for very simple queries. Take for example a database D with T = { NULL } and S = { 1, 2 }, and consider the query Q that computes the Cartesian product of T and S. The answer to Q on D is Q(D) = { ( NULL, 1 ), ( NULL, 2 ) }. The Codd interpretation of D is a database \( D' \) where \( T = \{ \bot_1 \} \) and \( S = \{ 1, 2 \} \), and \( Q(D') = \{ (\bot_1, 1), (\bot_1, 2) \} \). Since \( \bot_1 \) is repeated, \( Q(D') \) cannot be obtained by replacing SQL nulls in \( Q(D) \) with Codd nulls. The culprit in the above example is that the query, evaluated on the Codd interpretation of the original SQL database, produces an answer that is not a Codd table, as it contains repeated nulls. While in this particular example it is easy to detect such an undesirable behavior, we show that in general the class of relational algebra queries that transform SQL databases into Codd databases is not recursively enumerable, and thus it is impossible to capture it by a syntactic fragment of the language. Given the lack of an effective syntax for queries that preserve Codd semantics in query answers, we can only hope for sufficient conditions, i.e., finding reasonable syntactic fragments that guarantee this property. However, simply choosing a subset of relational algebra operations will not give us a useful restriction: as we saw before, one of the problematic constructs is Cartesian product, and we obviously do not want a fragment that prohibits joins. Thus, we must look for a more refined solution. The idea is to consider database schemas with \textbf{NOT NULL} constraints, which are very common in practice: base relations in real SQL databases will almost always have a \textbf{PRIMARY KEY} declared on them. We then exploit these constraints to come up with mild restrictions on queries, which have the following properties: - they guarantee the preservation of Codd semantics of SQL nulls in query answers on all incomplete databases; - they can be checked efficiently; and - they do not restrict the full expressiveness of relational algebra queries on databases without nulls, where all attributes are declared as \textbf{NOT NULL}. ## 2 Preliminaries We assume three countably infinite and pairwise disjoint sets of elements: names (\( \text{Names} \)), constants (\( \text{Const} \)), and nulls (\( \text{Null} \)). Elements of Null are denoted by \( \perp \), possibly with sub- or superscripts, and we call a \textit{signature} any finite subset of \( \text{Names} \). A naive record is a map from some signature to \( \text{Const} \cup \text{Null} \). To be as close as possible to SQL’s data model, we define a naive table as a bag of naive records (which may occur multiple times) over the same signature. **Schemas and databases.** A relational schema consists of a signature of relation names and a function \( \text{sign} \) that maps each relation name \( R \) to a signature \( \text{sign}(R) \), whose elements are called the \textit{attributes} of \( R \). A naive database \( D \) associates each relation name \( R \) with a naive table \( R^D \) over \( \text{sign}(R) \). We denote the sets of constants and nulls occurring in \( D \) by \( \text{Const}(D) \) and \( \text{Null}(D) \), respectively. A Codd database (respectively, table) is a naive one in which nulls do not repeat, that is, there can be at most one occurrence of each element from Null. Note that a Codd database is a set of Codd tables, but the converse need not hold. SQL databases. We use the special symbol \( N \not\in \text{Const} \cup \text{Null} \) to denote SQL’s NULL value. SQL databases (as well as tables and records) are defined in a similar way as naive ones, but they are populated with elements of \( \text{Const} \cup \{N\} \) rather than \( \text{Const} \cup \text{Null} \). Query language. We use relational algebra on bags, with the usual operations of projection \( \pi \), selection \( \sigma \), Cartesian product \( \times \), union \( \cup \), difference \( - \), intersection \( \cap \), renaming \( \rho \), and duplicate elimination \( \varepsilon \). These are all defined in the standard way [3]. Selection conditions are Boolean combinations of comparisons \( x = y \) and \( \text{null}(x) \), where each \( x \) and \( y \) is either a constant or an attribute. The condition \( \text{null}(x) \), corresponding to IS NULL in SQL, tests whether the value of \( x \) is null. We use \( x \neq y \) and \( \text{const}(x) \) for \( \neg(x = y) \) and \( \neg\text{null}(x) \), respectively. This language captures the basic fragment of SQL: SELECT [DISTINCT] - FROM - WHERE queries, with (correlated) subqueries preceded by possibly negated IN and EXISTS, combined by UNION, INTERSECT and EXCEPT, possibly with ALL. The answer to a query \( Q \) on a (naive or SQL) database \( D \) is denoted by \( Q(D) \). Selection conditions are evaluated using SQL’s three-valued logic: (in)equality comparisons result in unknown if at least one of the arguments is null, and truth values are propagated through the connectives \( \land, \lor, \neg \) following the well known truth tables of Kleene logic. Then, for a table \( T \), the operation \( \sigma_\theta(T) \) returns all occurrences of each record \( r \) in \( T \) for which the condition \( \theta \) evaluates to true. 3 Codd Interpretation of SQL Nulls Differently from naive databases, where nulls are elements of Null, missing values in SQL are all denoted by the special symbol \( N \). To reconcile this mismatch, the occurrences of \( N \) in an SQL database are typically interpreted as non-repeating elements of Null. That is, an SQL database can be seen as a Codd database where each occurrence of \( N \) is replaced by a fresh distinct marked null. Obviously, these nulls can be chosen arbitrarily as long as they do not repeat, so an SQL database may admit infinitely many Codd interpretations in general. To make this notion more precise, let us denote by \( \text{sql}(D) \) the SQL database obtained from \( D \) by replacing each null (either \( N \) or an element of Null) with \( N \). Note that \( \text{sql}(D) \) is uniquely determined for any given (naive or SQL) database \( D \). Then, for an SQL database \( D \), we define \[ \text{codd}(D) = \{ D' \mid D' \text{ is a Codd database such that } \text{sql}(D') = D \} \tag{1} \] Even though this set may be infinite, its elements are all isomorphic. Thus, with some abuse of terminology, we can speak of the Codd interpretation of an SQL database, which is unique up to renaming of nulls. Answers to queries are tables, which may of course contain nulls. So, if SQL nulls are interpreted as Codd nulls, this should apply also to query answers, not just input databases. More precisely, when computing the answer to a query \( Q \) on an SQL database \( D \), there should always be a way of assigning Codd nulls to SQL nulls in \( Q(D) \) so as to obtain \( Q(D') \), where \( D' \) is the Codd interpretation of In other words, the Codd interpretation of $Q(D)$ should be indistinguishable from $Q(D')$, that is, isomorphic to it. This requirement was shown in the diagram in the introduction and it is formally defined below. **Definition 1.** A query $Q$ preserves Codd semantics if, for every SQL database $D$ and for every $D' \in \text{codd}(D)$, it holds that $$Q(D') \in \text{codd}(Q(D)).$$ The above definition can also be equivalently formulated as follows: a query $Q$ preserves Codd semantics if, for every Codd database $D$, 1. $\text{sql}(Q(D)) = Q(\text{sql}(D))$ (2a) 2. $Q(D)$ is a Codd table (2b) Intuitively, in order to preserve Codd semantics a query must (2a) preserve the occurrences of nulls, regardless of repetitions, and (2b) avoid repetitions of nulls in the answers. These two requirements are in fact independent of each other. For example, the query $Q = R \times S$ satisfies (2a) but not (2b), because on the Codd database $D$ where $R = \{ \bot_1 \}$ and $S = \{ \bot_2, \bot_3 \}$ the answer $Q(D) = \{ (\bot_1, \bot_2), (\bot_1, \bot_3) \}$ contains repeated nulls. On the other hand, the query $Q' = R \cap S$ satisfies (2b) but not (2a), because $\text{sql}(Q'(D)) = \emptyset \neq \{ \text{N} \} = Q'(\text{sql}(D))$. Can we syntactically capture the class of queries preserving Codd semantics? Unfortunately, the answer is no. **Proposition 1.** For every schema with at least one binary relation symbol, the set of queries that preserve Codd semantics is not recursively enumerable. To prove this, we can show that the set of preserving queries is not recursive, by reduction to the undecidability of emptiness of relational algebra expressions; since the complement of the set is clearly r.e., the result follows. Thus, we should look for syntactic restrictions that provide sufficient conditions for the preservation of Codd semantics. This is what we do in the next section. ### 4 Queries Preserving Codd Semantics Since the set of queries that preserve Codd semantics cannot be captured syntactically, we can only hope for syntactic restrictions that are sufficient to guarantee this property. However, simply choosing a subset of relational algebra operations would be too restrictive to be useful: as we have seen in the examples, Cartesian product is one of the operations causing problems with the preservation of Codd semantics, and we certainly do not want a fragment that forbids joins altogether. This suggests that, to come up with useful restrictions, we need some additional information beyond the query itself. Real databases typically must satisfy some integrity constraints, and when it comes to incomplete SQL databases the most basic form of constraint amounts to declaring some of the attributes in the schema as **NOT NULL**. The use of this kind of constraints is extremely common in practice, because each base table in a real-life SQL database has almost always a subset of its attributes declared as **PRIMARY KEY**, which implies **NOT NULL**. We model **NOT NULL** constraints as follows: the signature \( \text{sign}(R) \) of each base relation \( R \) is partitioned into two sets \( \text{sign}_{\text{null}}(R) \) and \( \text{sign}_{\text{¬null}}(R) \) of nullable and non-nullable attributes, so that \( \pi_{\text{sign}_{\text{¬null}}(R)}(R^D) \) contains only elements of \( \text{Const} \). That is, nulls are not allowed as values of the attributes in \( \text{sign}_{\text{¬null}}(R) \), while there are no restrictions on the values of the attributes in \( \text{sign}_{\text{null}}(R) \). We extend these notions to relational algebra queries as follows: \[ \begin{align*} \text{sign}_{\text{null}}(Q_1 \star Q_2) &= \text{sign}_{\text{null}}(Q_1) \cup \text{sign}_{\text{null}}(Q_2) \quad \text{for } \star \in \{ \times, \cup \} \\ \text{sign}_{\text{null}}(Q_1 \cap Q_2) &= \text{sign}_{\text{null}}(Q_1) \cap \text{sign}_{\text{null}}(Q_2) \\ \text{sign}_{\text{null}}(Q_1 - Q_2) &= \text{sign}_{\text{null}}(Q_1) \\ \text{sign}_{\text{null}}(\pi_\alpha(Q)) &= \text{sign}_{\text{null}}(Q) \cap \alpha \\ \text{sign}_{\text{null}}(\sigma_\theta(Q)) &= \text{sign}_{\text{null}}(\varepsilon(Q)) = \text{sign}_{\text{null}}(Q) \\ \text{sign}_{\text{null}}(\rho_{A \rightarrow B}(Q)) &= \begin{cases} \\ (\text{sign}_{\text{null}}(Q) - \{A\}) \cup \{B\} & \text{if } A \in \text{sign}_{\text{null}}(Q) \\ \text{sign}_{\text{null}}(Q) & \text{otherwise} \\ \end{cases} \\ \text{sign}_{\text{¬null}}(Q) &= \text{sign}(Q) - \text{sign}_{\text{null}}(Q) \end{align*} \] From the above definition we immediately obtain: **Proposition 2.** Let \( Q \) be a query and \( D \) be a database. Then, \( \pi_{\text{sign}_{\text{¬null}}(Q)}(Q(D)) \) consists only of elements of \( \text{Const} \). That is, independently of the data, the answer to a query \( Q \) can only have null values for the attributes in \( \text{sign}_{\text{null}}(Q) \). We say that a query \( Q \) is **non-nullable** if \( \text{sign}_{\text{null}}(Q) = \emptyset \). To explain the restrictions that ensure preservation of Codd semantics, we need two definitions. **Definition 2.** The parse tree of a query \( Q \) is constructed as follows: - Each relation symbol \( R \) is a single node labeled \( R \). - For each unary operation \( \text{op}_1 \), the parse tree of \( \text{op}_1(Q) \) has root labeled \( \text{op}_1 \) and the parse tree of \( Q \) rooted at its single child. - For each binary operation \( \text{op}_2 \), the parse tree of \( Q \ \text{op}_2 \ Q' \) has root labeled \( \text{op}_2 \) and the parse trees of \( Q \) and \( Q' \) rooted at its left child and right child, respectively. Note that each node in the parse tree of \( Q \) defines a subquery of \( Q \), so we can associate properties of such queries with properties of parse tree nodes. **Definition 3.** The base of a query is the set of relation names appearing in it. A node in the parse tree of a query satisfies: **NNC** (non-nullable child) if it is not a leaf and at least one of its children is a non-nullable query; NNA (non-nullable ancestor) if either itself or one of its ancestors is a query that is non-nullable; DJB (disjoint base) if it corresponds to a binary operation and the base of its left child is disjoint with the base of its right child. We now state the main result. **Theorem 1.** Let $Q$ be a relational algebra query whose parse tree is such that: (a) each $\varepsilon$, $\cap$, and $-$ node satisfies NNC; (b) each $\times$ node satisfies NNA; (c) each $\cup$ node satisfies NNC or DJB or NNA. Then $Q$ preserves Codd semantics. These conditions do not restrict the full expressiveness of relational algebra on databases without nulls: when all attributes in the schema are non-nullable, every query is such, hence the restrictions are trivially satisfied. **Corollary 1.** On database schemas without nullable attributes, every relational algebra query satisfies the conditions of Theorem 1. Also, the restrictions are easy to check: **Proposition 3.** Deciding whether a query satisfies the conditions of Theorem 1 can be done in linear time w.r.t. the number of nodes in its parse tree. We will now outline the main ideas behind the restrictions. If a query is non-nullable, then it trivially satisfies (2b). But there exist non-nullable queries for which (2a) does not hold: e.g., $\pi_A(\varepsilon(R))$ when $R$ has attributes $A, B$, of which only $A$ is non-nullable. Thus, non-nullability needs to be used more carefully, on the subqueries of $Q$. Duplicate elimination, intersection and difference cause problems with (2a). What these operations have in common is that they match nulls syntactically, i.e., as if they were constants. Now, SQL nulls are all syntactically the same, but this is not the case for Codd nulls. So, for these operations, it makes a difference whether we are using Codd nulls or SQL nulls. On the other hand, the remaining operations are not affected by this: projection, union and Cartesian product do not rely on syntactic matching of nulls, and nulls in selection conditions are not compared syntactically (equality and inequality conditions involving at least one null result in unknown). Thus, we only need to take care of $\varepsilon$, $-$ and $\cap$, and here is where the NNC condition comes into play. Requiring it for $\varepsilon$, $\cap$ and $-$ nodes is enough to ensure that the query satisfies (2a). Intuitively, when at least one of the input subqueries to each of these operations is non-nullable, no syntactic matching of nulls can occur, simply because one of the operands (the only one for $\varepsilon$) will not have nulls at all. **Proposition 4.** Let $Q$ be a query such that each $\varepsilon$, $\cap$ and $-$ node in its parse tree satisfies NNC. Then $Q$ satisfies property (2a). If in addition to the condition of Proposition 4 we also required the query itself to be non-nullable, then preservation of Codd semantics would be guaranteed. However, this is too restrictive, as it would forbid even the simple retrieval of a base relation whenever some of its attributes are nullable. So, we need more refined ways of ensuring (2b) by restricting only the problematic operations. Duplicate elimination, difference, selection and intersection always produce a table that is contained in at least one of the input tables, so their output may have repeated nulls only if these repetitions were already in the input. The same holds for projection, for a similar reason. The problematic operations w.r.t. (2b) are \( \cup \) and \( \times \). Both can create repetitions of nulls across records, and the latter can also create repetitions of nulls within a record. To restrict these operations appropriately, we use the \( \text{NNA} \) condition. Requiring this condition for each \( \times \) and \( \cup \) node is enough to ensure that the query satisfies (2b). Intuitively, repetitions of nulls that may be created by \( \cup \) and \( \times \) are allowed in the intermediate results of a query, but only as long as they will be eventually discarded, at the latest when the final output is produced. In fact, the \( \text{NNA} \) condition for \( \cup \) can be relaxed. We want to restrict a union operation when it may create “new” repetitions of nulls, but we need not do so when the only repetitions it may produce are those inherited from the input, which were introduced by the application of previous operations. There are two cases in which this happens: when one of the operands is non-nullable, or when the input tables are built from disjoint sets of base relations. The first is captured by the \( \text{NNC} \) condition, and the second by the \( \text{DJB} \) condition. We can then allow for these additional possibilities by requiring each \( \cup \) node to satisfy \( \text{NNA} \) or \( \text{NNC} \) or \( \text{DJB} \). This explains the need for the conditions of Definition 3. As an example, let us consider the query \((\rho_{B \rightarrow C}(R \cup S) \cup \rho_{D \rightarrow A}(\varepsilon(T))) - \pi_{A,C}(\sigma_{A=1 \lor B=C}(R \times T))\), whose parse tree is shown below: Next to each node we indicate the corresponding signature, where non-nullable attributes are underlined (for the leaves, this information is given by the schema). On the left side of the tree, we see that the innermost \( \cup \) node (lower in the tree) satisfies \( \text{DJB} \) (but not \( \text{NNC} \)), the \( \varepsilon \) node satisfies \( \text{NNC} \) and so is non-nullable, and in turn the outermost \( \cup \) node satisfies \( \text{NNC} \) too. On the right side, we see that the node satisfies NNA because its ancestor \( \pi \) is non-nullable, which also ensures that the root node "\(-\)" satisfies NNC. Thus, the query preserves Codd semantics. We conclude this section with an outline of the proof that checking the conditions of Theorem 1 can be done in linear time. Let \( n \) be the number of nodes in the binary parse tree of the query. First, we compute the base and the nullable attributes of each node by scanning the tree bottom up (\( n \) steps). We then mark all \( \varepsilon, \cap, \cup, \neg \) nodes satisfying NNC, all \( \cup \) nodes satisfying DJB, all \( \sigma, \pi, \rho \) nodes, and all leaves; for each node, we visit up to two child nodes, so this requires at most 2 \( \cdot \) \( n \) steps. Next, by traversing the tree breadth-first from the root, we remove the subtrees rooted in non-nullable nodes; in the worst case (when all nodes are nullable) this takes \( n \) steps. Finally, the query satisfies the conditions of Theorem 1 iff all nodes in the resulting tree are marked, which can be checked in one more pass (\( n \) steps). 5 Derived Operations and Further Refinements In our query language we have explicitly included intersection, even though this operation is expressible in terms of difference. While it may seem redundant to have \( \cap \) in the syntax of queries, this is not the case w.r.t. our restrictions for the preservation of Codd semantics. To see why, suppose we want the intersection of base relations \( R \) and \( S \), but we do not have \( \cap \) available as a primitive operation in our query language. Of course, we can always write \( R - (R - S) \) or \( S - (S - R) \); the problem is that, even though these queries are equivalent, the former satisfies the conditions of Theorem 1 iff \( R \) is non-nullable, while the latter satisfies them iff \( S \) is non-nullable. In either case, the requirement is stronger than the one for \( R \cap S \), which is in fact given by their disjunction: \( R \cap S \) satisfies the conditions of Theorem 1 iff \( R \) is non-nullable or \( S \) is non-nullable. This suggests that adding some derived operations explicitly to the syntax of queries may lead to milder restrictions, allowing us to capture more queries preserving Codd semantics. We will show two such refinements: constant selections and semi/antijoins. **Selections.** Looking at \( \sigma \) may seem counterintuitive as this operation did not need to be restricted in any way. However, consider the query \( \sigma_{\text{const}(A)}(R) \cap S \), for unary relation symbols \( R \) and \( S \) over a nullable attribute \( A \). This query does not satisfy the conditions of Theorem 1, because neither \( \sigma_{\text{const}(A)}(R) \) nor \( S \) are non-nullable. But even though \( \text{sign}_{\text{null}}(\sigma_{\text{const}(A)}(R)) = \{A\} \), we can rest assured that in fact no nulls will appear in \( \sigma_{\text{const}(A)}(R^D) \). Here the idea is to include in our query language the operation of constant selection \( \sigma_{\text{const}(\alpha)} \) which, for a table \( T \) and \( \alpha \subseteq \text{sign}(T) \), returns all occurrences of each record \( r \) in \( T \) such that \( r(A) \) is a constant for every attribute \( A \in \alpha \). Then, we define \( \text{sign}_{\text{null}}(\sigma_{\text{const}(\alpha)}(Q)) = \text{sign}_{\text{null}}(Q) - \alpha \). **Semijoins and antijoins.** The theta-join of two tables \( T_1, T_2 \) with disjoint sets of attributes is \( T_1 \bowtie_\theta T_2 = \sigma_\theta(T_1 \times T_2) \). Adding \( \bowtie_\theta \) to the language does not change anything, but two operations derived from it can be added: semijoin \( \kappa_\theta \) and antijoin \( \overline{\kappa}_\theta \). These essentially correspond to \textbf{EXISTS} and \textbf{NOT EXISTS} in SQL. For tables \( T_1, T_2 \) with disjoint sets of attributes, they are defined as: \[ T_1 \kappa_\theta T_2 = T_1 \cap \pi_{\text{sign}(T_1)}(T_1 \kappa_\theta T_2) \quad \quad T_1 \overline{\kappa}_\theta T_2 = T_1 - T_1 \kappa_\theta T_2 \] That is, \( T_1 \kappa_\theta T_2 \) returns all occurrences of each record \( r \) in \( T_1 \) for which there is a record \( s \) in \( T_2 \) such that \( \theta \) is true on \( r \cup s \). Similarly, \( T_1 \overline{\kappa}_\theta T_2 \) returns all occurrences of each record \( r \) in \( T_1 \) for which there is no record \( s \) in \( T_2 \) s.t. \( \theta \) is true on \( r \cup s \). We define \( \text{sign}_{\text{null}}(Q_1 \kappa_\theta Q_2) = \text{sign}_{\text{null}}(Q_1 \overline{\kappa}_\theta Q_2) = \text{sign}_{\text{null}}(Q_1) \). How do we restrict these operations to ensure (2a) and (2b)? Observe that \( \kappa \) is an intersection and \( \overline{\kappa} \) is a difference, and syntactic matching of nulls must be prevented in general for these operations. Here, however, one of the operands to this intersection/difference is always contained in the other, independently of whether SQL nulls or Codd nulls are used, so syntactic matching of nulls is not a problem in this case. In turn, we need no restriction on \( \kappa \) and \( \overline{\kappa} \) to guarantee (2a). As for (2b), observe that the output of both \( \kappa \) and \( \overline{\kappa} \) is always contained in their left input, so no new repetitions of nulls can be created and, in turn, we do not need any restriction in order to ensure (2b) either. Repetitions of nulls that might have been created in the right operand of \( \kappa \) or \( \overline{\kappa} \) are discarded. Thus we can use an alternative to NNA, called \textbf{RDS}: a node in a parse tree satisfies this condition if it is the right-descendant of a \( \kappa \) or a \( \overline{\kappa} \) operation. **Theorem 2.** Let \( Q \) be a query (extended with \( \kappa, \overline{\kappa}, \sigma_{\text{\text{const}}} \)) such that: (a) each \( \varepsilon, \cap, - \) node satisfies \textbf{NNC}; (b) each \( \times \) node satisfies \textbf{NNA} or \textbf{RDS}; (c) each \( \cup \) node satisfies \textbf{NNC} or \textbf{DJB} or \textbf{NNA} or \textbf{RDS}. Then, \( Q \) preserves Codd semantics. An analog of Corollary 1 follows, and simple modifications to the algorithm of Proposition 3 show that these conditions are still linear-time testable. ### 6 Conclusions The notion of Codd database we adopted in this paper only allows for constant tuples to occur multiple times, as nulls cannot repeat. Relaxing this requirement to allow for duplicates of non-constant tuples raises several questions: How do we interpret multiple occurrences of a tuple with nulls in an SQL database? What is preservation of Codd semantics in this context? Do our restrictions still guarantee it? Another interesting direction for future investigation concerns set semantics. Observe that a query \( Q \) can always be rewritten into a query \( Q' \) where duplicate elimination is suitably applied in each subexpression so that, on set databases (i.e., in which relations are sets), evaluating \( Q \) under set semantics is equivalent to evaluating \( Q' \) under bag semantics. If \( Q' \) satisfies our restrictions, preservation of Codd semantics is guaranteed on all (bag and set) databases and, in turn, \( Q \) preserves Codd semantics on set databases. However, this is too restrictive for even simple queries (e.g., \( R \cup S \)) and weaker conditions may be devised to deal specifically with set semantics. Acknowledgements Work partially supported by EPSRC grants EP/N023056/1 and EP/M025268/1. The authors would like to thank the anonymous reviewers for their useful comments. References
{"Source-Url": "http://www.research.ed.ac.uk/portal/files/45342183/paper23.pdf", "len_cl100k_base": 8489, "olmocr-version": "0.1.49", "pdf-total-pages": 12, "total-fallback-pages": 0, "total-input-tokens": 40809, "total-output-tokens": 9774, "length": "2e13", "weborganizer": {"__label__adult": 0.0004267692565917969, "__label__art_design": 0.00035834312438964844, "__label__crime_law": 0.000537872314453125, "__label__education_jobs": 0.0016145706176757812, "__label__entertainment": 0.00010013580322265624, "__label__fashion_beauty": 0.00022459030151367188, "__label__finance_business": 0.0004978179931640625, "__label__food_dining": 0.0006041526794433594, "__label__games": 0.0006437301635742188, "__label__hardware": 0.0007371902465820312, "__label__health": 0.0011053085327148438, "__label__history": 0.00035834312438964844, "__label__home_hobbies": 0.00017344951629638672, "__label__industrial": 0.0007205009460449219, "__label__literature": 0.000743865966796875, "__label__politics": 0.0003349781036376953, "__label__religion": 0.0005679130554199219, "__label__science_tech": 0.1319580078125, "__label__social_life": 0.0001596212387084961, "__label__software": 0.0161285400390625, "__label__software_dev": 0.8408203125, "__label__sports_fitness": 0.00030040740966796875, "__label__transportation": 0.00080108642578125, "__label__travel": 0.0002567768096923828}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 34173, 0.01153]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 34173, 0.56441]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 34173, 0.87433]], "google_gemma-3-12b-it_contains_pii": [[0, 1286, false], [1286, 4078, null], [4078, 7028, null], [7028, 10252, null], [10252, 13766, null], [13766, 16531, null], [16531, 19844, null], [19844, 22605, null], [22605, 25432, null], [25432, 29064, null], [29064, 32922, null], [32922, 34173, null]], "google_gemma-3-12b-it_is_public_document": [[0, 1286, true], [1286, 4078, null], [4078, 7028, null], [7028, 10252, null], [10252, 13766, null], [13766, 16531, null], [16531, 19844, null], [19844, 22605, null], [22605, 25432, null], [25432, 29064, null], [29064, 32922, null], [32922, 34173, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 34173, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 34173, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 34173, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 34173, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 34173, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 34173, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 34173, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 34173, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 34173, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 34173, null]], "pdf_page_numbers": [[0, 1286, 1], [1286, 4078, 2], [4078, 7028, 3], [7028, 10252, 4], [10252, 13766, 5], [13766, 16531, 6], [16531, 19844, 7], [19844, 22605, 8], [22605, 25432, 9], [25432, 29064, 10], [29064, 32922, 11], [32922, 34173, 12]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 34173, 0.0]]}
olmocr_science_pdfs
2024-11-27
2024-11-27
3b066191241b84494ed8924d6b5e0d590d85e9e4
Advances in Parallel-Stage Decoupled Software Pipelining Feng Li, Pop Antoniu, Albert Cohen To cite this version: Feng Li, Pop Antoniu, Albert Cohen. Advances in Parallel-Stage Decoupled Software Pipelining, WIR, Apr 2011, France. hal-00870687 HAL Id: hal-00870687 https://hal.archives-ouvertes.fr/hal-00870687 Submitted on 7 Oct 2013 HAL is a multi-disciplinary open access archive for the deposit and dissemination of scientific research documents, whether they are published or not. The documents may come from teaching and research institutions in France or abroad, or from public or private research centers. L’archive ouverte pluridisciplinaire HAL, est destinée au dépôt et à la diffusion de documents scientifiques de niveau recherche, publiés ou non, émanant des établissements d’enseignement et de recherche français ou étrangers, des laboratoires publics ou privés. Advances in Parallel-Stage Decoupled Software Pipelining Leveraging Loop Distribution, Stream-Computing and the SSA Form Abstract Decoupled Software Pipelining (DSWP) is a program partitioning method enabling compilers to extract pipeline parallelism from sequential programs. Parallel Stage DSWP (PS-DSWP) is an extension that also exploits the data parallelism within pipeline filters. This paper presents the preliminary design of a new PS-DSWP method capable of handling arbitrary structured control flow, a slightly better algorithmic complexity, the natural exploitation of nested parallelism with communications across arbitrary levels, with a seamless integration with data-flow parallel programming environments. It is inspired by loop-distribution and supports nested/structured partitioning along with the hierarchy of control dependences. The method relies on a data-flow streaming extension of OpenMP. These advances are made possible thanks to progresses in compiler intermediate representation. We describe our usage of the Static Single Assignment (SSA) form, how we extend it to the context of concurrent streaming tasks, and we discuss the benefits and challenges for PS-DSWP. Categories and Subject Descriptors D.3.4 [Programming Languages]: Processor-Compilers, Optimization General Terms optimization Keywords automatic parallelization, stream-computing, loop distribution 1. Introduction In recent years, the CPU manufacturers have embraced chip multiprocessors because of technology, power consumption and thermal dissipation constraints, and because of diminishing returns in instruction-level parallelism. The amount of performance gained by the use of multi-core processor depends highly on the software fraction that can be parallelized to run on multiple cores simultaneously. Multiprocessor programming leaves the burden to programmer who faces the extra complexity, heisenbugs, deadlocks and other problems associated with parallel programming. The situation is worse when dealing with the migration of legacy code. Decoupled Software Pipelining (DSWP) is an automatic thread partitioning method which could partition a sequential program to run on multiple cores, and Parallel-Stage DSWP (PS-DSWP) exposes data parallelism into task pipelines extracted by DSWP. These automatic thread partitioning methods free the programmer from manual parallelization. They also promise much wider flexibility than data-parallelism-centric methods for processors, aiming for the effective parallelization of general-purpose applications. In this paper, we provide another method to decouple control-flows of concurrent tasks, exposing pipeline and data parallelism. The power and simplicity of the method rely on the restriction that all streams should retain a synchronous semantics [8]. It amounts to checking the sufficient condition that the source and target of any decoupled dependence are control-dependent on the same node in the control dependence tree (this assumes structured control flow). This restriction may appear as a severe one for experienced parallel programmers; but at the potential expense of adding extra levels of nested parallelism, it does not restrict the degree of pipeline parallelism. In fact, any pair of computational statements can be decoupled and assigned to different concurrent tasks. The partitioning algorithms also handle DOALL parallelization within task pipelines, and arbitrarily nested data-parallel pipelines following the control dependence tree of a structured control flow graph. Unlike existing DSWP algorithms, our method does not explicitly copy conditional expressions and can handle arbitrary backward data and control dependences. We are using two intermediate representations. - A conventional SSA-based representation, annotated with natural loop and control dependence trees (for structured control flow). - And a streaming data-flow extension of the latter representation as a backend for our partitioning algorithm, still in SSA form but with explicit task boundaries (for single-entry single-exit regions) and multi-producer multi-consumer streams to communicate across tasks. The backend representation streamlines the decoupling of multi-producer multi-consumer data flow through explicit, compiler-controlled sampling and merging stages. Multi-producer multi-consumer semantics is absolutely essential to handle general decoupling patterns where data-parallel stages feature an unbalance in the number of worker threads. Sampling is handled transparently by nesting tasks into enclosing control flow. Merging is captured by $\Phi$ functions at task boundaries, introducing a minor variant of the SSA form satisfying the so-called task-closed property that multiple incoming flows targeting the same use in a given task should be explicitly merged by a dedicated $\Phi$ function at the task entry point. Relying on SSA avoids building the complete program dependence graph: with the exception of the array dependence graph, our method only processes linear-size data structures, as opposed to the worst-case quadratic program dependence graph in DSWP. 2. Related Work The most closely related work to this paper is decoupled software pipelining and loop distribution. We recall the state-of-the-art in both and present the original finding at the source of this work: by extending loop distribution with pipelining and asserting a synchronous concurrency hypothesis, arbitrary data and control dependences can be decoupled very naturally with only minor changes to existing algorithms that have been proposed for loop distribution [10]. 2.1 Decoupled software pipelining Decoupled Software Pipelining (DSWP) [13] is one approach to automatically extract threads from loops. It partitions loops into long-running threads that communicate via inter-core queues. DSWP builds a Program Dependence Graph (PDG) [7], combining control and data dependences (scalar and memory). Then DSWP introduces a load-balancing heuristic to partition the graph according to the number of cores, making sure no recurrence spans across multiple partitions. In contrast to DOALL and DOACROSS [4] methods which partition the iteration space into threads, DSWP partitions the loop body into several stages connected with pipelining to achieve parallelism. It exposes parallelism in cases where DOACROSS is limited by loop-carried dependences on the critical path. And generally speaking, DSWP partitioning algorithms handles uncounted loops, complex control flow and irregular pointer-based memory accesses. Parallel-Stage Decoupled Software Pipelining [16] (PS-DSWP) is an extension to combine pipeline parallelism with some stages executed in a DOALL, data-parallel fashion. For example, when there are no dependences between loop iterations of a DSWP stage, the incoming data can be distributed over multiple data-parallel worker threads dedicated to this stage, while the outgoing data can be merged to proceed with downstream pipeline stages. These techniques have a few caveats however. They offer limited support for decoupling along backward control and data dependences. They provide a complex code generation method to decouple dependences among source and target statements governed by different control flow, but despite its complexity, this method remains somewhat conservative. By building the PDG, DSWP also inculcates a higher algorithmic complexity than typical SSA-based optimizations. Indeed, although traditional loop pipelining for ILP focuses on innermost loops of limited size, DSWP is aimed at processing large control flow graphs after aggressive inter-procedural analysis optimization. In addition, the loops in DSWP are handled by the standard algorithm as ordinary control flow, missing potential benefits of treating them as a special case. To address these caveats, we turned our analysis to the state of the art in loop distribution. 2.2 Loop distribution Loop distribution is a fundamental transformation in program restructuring systems designed to extract data parallelism for vector or SIMD architectures [10]. In its simplest form, loop distribution consists of breaking up a single loop into two or more consecutive loops. When aligning loop distribution to the strongly connected components of the data-dependence graph, one or more of the resulting loops expose iterations that can be run in parallel, exposing data parallelism. Barriers are inserted after the parallel loops to enforce precedence constraints with the rest of the program. An example is presented in Figure 1. ```c for (i = 1; i < N; i++) { for (i = 1; i < N; i++) S1 A[i] = B[i] + 1; S1 A[i] = B[i] + 1; S2 C[i] = A[i-1] + 1; S2 C[i] = A[i-1] + 1; <barriers inserted here>} for (i = 1; i < N; i++) S2 C[i] = A[i-1] + 1 ``` **Figure 1.** Barriers inserted after loop distribution. 3. OpenMP Extension for Stream-Computing as a Code Generation Target A recently proposed stream-computing extension to OpenMP [14] allows the expression of pipeline parallelism by making explicit the flow dependences, or producer-consumer patterns, between OpenMP tasks. It provides a simple way for explicitly building dynamic task graphs, where tasks are connected through streams that transparently privatize the data. The extension consists of two additional clauses, input and output to the task construct, that define the producer-consumer relationships between tasks. The OpenMP language, with this extension, is a natural fit as a target for our code generation. It provides for dynamic task creation and connection in the task graph, it handles arbitrary nesting of pipelined tasks in control-flow, and it allows the hierarchical nesting of tasks. The task construct is extended with input and output clauses as presented on Figure 2. Both clauses take a list of items, each of which describes a stream and its behavior w.r.t. the task to which the clause applies. In the abbreviated item form, `stream`, the stream can only be accessed one element at a time through the same variable `a`. In the second form, `stream >> window`, the programmer uses the C++ flavoured `>>` stream operators to connect a sliding window to a stream, gaining access, within the body of the task, to horizon elements in the stream. One of the main issues that needs to be addressed in order to distribute a PDG to the OpenMP stream-computing extension is that, in the latter, the data flow bypasses the control flow. In other words, when a task produces values on an output stream, these values will all reach the consumers of the stream, even if, in the serial semantics, the values would have been overwritten before reaching the consumers. This means that the only case where a direct annotation scheme will work is if all tasks are in the same control flow. There are multiple ways this issue can be handled, the most systematic one being to always ensure that every producer-consumer pair share the same control dependence. This is achieved by sinking all control flow surrounding the tasks, and not shared by both producer and consumer, in the tasks. To avoid the loss of parallelization opportunities, each task’s body can be further partitioned into nested pipelines. The GCC implementation of the OpenMP extension for stream-computing has been shown to be efficient to exploit mixed pipeline-and-data-parallelism, even in dynamic task graphs [14]. It relies on compiler and runtime optimizations to improve cache locality and relies on a highly efficient lock-free and atomic operation-free synchronization algorithm for streams. 4. Observations It is quite intuitive that the typical synchronization barriers in between distributed data-parallel loops can be weakened, resulting into data-parallel pipelines. We aim to provide a comprehensive treatment of this transformation, generalizing PS-DSWP in the process. 4.1 Replacing loops and barriers with a task pipeline In the previous example, we could remove the barriers between two distributed loops with pipelining so that the two loops could run in parallel. ```c /* Initialize the stream, inserting a delay. */ void INIT_STREAM() { produce(stream, A[0]); } /* Decoupled producer and consumer. */ for (i = 1; i < N; i++) { S1 A[i] = B[i] + 1; produce(stream, A[i]); } for (i = 1; i < N; i++) { S2 C[i] = A[i-1] + 1; tap = consume(stream); S2 C[i] = tap + 1; } ``` **Figure 3.** Pipelining inserted between distributed loops. Initialize the stream (left), producer and consumer thread (right). Figure 3 shows that pipelined execution is possible: the `INIT_STREAM` function inserts one delay into a communication stream; the produce/consume primitives implement a FIFO, enforcing the precedence constraint of the data dependence on array A and communicating the value in case the hardware needs this information. When distributing loops, scalar and array expansion (privatization) is generally required to eliminate memory-based dependences. The conversion to a task pipeline avoids this complication through the usage of communication streams. This transformation can be seen as an optimized version of scalar/array expansion in bounded memory and with improved locality [15]. 4.2 Extending loop distribution to PS-DSWP The similarity between DSWP and distributed loops with data-parallel pipelines is striking. First, both of them partition the loop into multiple threads. Second, both of them avoid partitioning the loop iteration space: they partition the instructions of the loop body instead. But four arguments push in favor of refining DSWP in terms of loop distribution. 1. Loop distribution leverages the natural loop structure, where the granularity of thread partitioning can be easily controlled. Moreover, it is useful to have a loop control node to which to attach information about the iteration of the loop, including closed forms of induction variables; this node can also be used to represent the loop in additional transformations. 2. Using a combination of loop distribution and fusion, then replacing barriers with pipelining leads to an incremental path in compiler construction. This path leverages existing intermediate representations and loop nest optimizers, while DSWP relies on new algorithms and a program dependence graph. 3. Considering the handling of control dependences, a robust and general algorithm already exists for loop distribution. McKinley and Kennedy’s technique handles arbitrary control flow [10] and provides a comprehensive solution. The same methods could be applied for DSWP, transforming control dependences into data dependences, and storing boolean predicates into stream. After restructuring the code, updating the control dependence graph and data dependence graph, the code generation algorithm for PDGs [2, 5, 6] can be used to generate parallel code. This solution would handle all cases where the current DSWP algorithm fails to clone a control condition. 4. Since loop distribution does not partition the iteration space, it can also be applied to uncounted loops. Unfortunately, the termination condition needs to be propagated to downstream loops. This problem disappears through the usage of a conventional communication stream when building task pipelines. From this high-level analysis, it appears possible to extend loop distribution with pipelining to implement PS-DSWP and handle arbitrary control dependences. Yet the method still seems rather complex, especially the if-conversion of control dependences and the code generation step from the PDG. We go one step further and propose a new algorithm adapted from loop distribution but avoiding these complexities. 4.3 Motivating example Our method makes one more assumption to reduce complexity and limit risks of overhead. It amounts to enforcing the synchronous hypothesis on all communicating tasks in the partition [8]. A sufficient condition is to check if the source and target of any decoupled dependence is dependent on the same control node. Consider the example in Figure 4. S1 and S7 implement the loop control condition and induction variable, respectively. S2, S3 and S6 are control dependent on S1. S3 is a conditional node, S4, S5 and L1 are control dependent on it. In the inner loop, L2 and L3 are control dependent on L1. When we apply DSWP to the outer loop, the control dependences originating from S1 must be if-converted by creating several streams (the number of streams depends on the number of partitions). When decoupling along the control dependence originating from S3, a copy of the conditional node must be created as well as another stream. ```plaintext S1 while (p != NULL) { S2 x = p->value; S3 if(c1) { S4 x2 = p1->value/2; S5 ip1 = p1->inner_loop; L1 while (ip2 = \Phi(ip1, ip3)) { L2 do_something(ip2); L3 ip3 = ip2->next; } } S6 ... = x3; S7 p = p->next; } ``` Figure 4. Uncounted nested loop before partitioning. ```plaintext S1 while (p1 = \Phi(p0, p2)) { S2 x1 = p1->value; S3 if(c1) { S4 x2 = p1->value/2; S5 ip1 = p1->inner_loop; L1 while (ip2 = \Phi(ip1, ip3)) { L2 do_something(ip2); L3 ip3 = ip2->next; } } x3 = \Phi(x1, x2); S6 ... = x3; S7 p2 = p1->next; } ``` Figure 5. Uncounted nested loop in SSA form. ```plaintext //task0-0(main task) S1 while (p1 = \Phi(p0, p2)) { //persistent-task1-1 #pragma task firstprivate (p1) output(x1) { S2 x1 = p1->value; } //persistent-task1-2 #pragma task firstprivate (p1) output(c1, x2) { S3 if(c1) { //persistent-task2-1 #pragma task firstprivate (p1) output(ip1) lastprivate(x2) { S4 x2 = p1->value/2; S5 ip1 = p1->inner_loop; } //persistent-task2-2 #pragma task input(ip1) { L1 while (ip2 = \Phi(ip1, ip3)) { //parallel - task3-1 #pragma omp task firstprivate (ip2) { L2 do_something(ip2); } L3 ip3 = ip2->next; } } //persistent-task1-3 #pragma task input(c1, x1, x2) { x3 = \Phi(c1, x1, x2); } } } //persistent-task1-4 #pragma task input(p0, p2) { S6 ... = x3; } //persistent-task1-5 #pragma task input(p1, p2) { S7 p2 = p1->next; } } ``` Figure 6. Loops after partitioning and annotated with OpenMP stream extension. Figure 5 shows the conversion to SSA form. Just like GCC, we use a loop-closed SSA form distinguishing between loop-\Phi and cond-\Phi nodes. The latter take an additional condition argument, appearing as a subscript, to explicit the selection condition. The partitioning technique will build a stream to communicate this condition from its definition site to the cond-Φ node's task. We build on the concept of treegion, a single-entry multiple-exit control-flow region induced by a sub-tree of the control dependence graph. In the following, we assume the control flow is structured, which guarantees that the control dependence graph forms a tree. Every sub-tree can be partitioned into concurrent tasks according to the control dependencies originating from its root. Any data dependence connecting a pair of such tasks induces communication over a dedicated stream. We call taskM,N the M-th task at level N of the control flow tree. In Figure 5, after building the control dependence tree, one may partition it into 3 tasks (task1_1, task1_2 and task1_3) at the root level, and for task1_2, one may further partition this task into inner nested tasks task2_1 and task2_2. One may then check for data parallelism in the inner loops: if they do not carry any dependence, one may isolate them in additional data-parallel tasks, such as task2_1 in this example. Figure 6 shows the task and stream-annotated code using an OpenMP syntax. Figure 7 shows the nested pipelining and data parallelization corresponding to the partitioned code. The main task will be executed first, and a pipeline will be created for the main task and its inner tasks three task1_1, task1_2 and task1_3. Among these, the same variable x used to be defined in the control flow regions of both task1_1 and task1_2, to be used in task1_3. This output dependence must be eliminated prior to partitioning into tasks, so that task1_1 and task1_2 could be decoupled, while task1_3 may decide which value to use internally. Nested tasks are introduced to provide fine grained parallelism. It is of course possible to adapt the partition and the number of nesting levels according to the load balancing and synchronization overhead. The generated code will be well structured, and simple top-down heuristics can be used. In the execution model of OpenMP 3.0, a task instance is created whenever the execution flow of a thread encounters a task construct; no ordering of tasks can be assumed. Such an execution model is well suited for unbalanced loads, but the overhead of creating tasks is significantly more expensive than synchronizing persistent tasks. To improve performance, we use the persistent task model for pipelining, in which a single instance will handle the full iteration space, consuming data on the input stream and producing the output stream [14]. In Figure 7, all the tasks except task3_1 use the persistent model to reduce the overhead of task creation; task3_1 is an ordinary task following the execution model of OpenMP 3.0 (instances will be spawned every time the control flow encounters the task directive). All these tasks will be scheduled by the OpenMP runtime. One problem with the partitioning algorithms is the fact that the def-use edges (scalar dependences) can become very large, sometimes quadratic with respect to the number of nodes [9]. Figure 8 (left) presents an example that illustrates this problem. Statements S1, S2 define the variable x. These definitions all reach the uses in the statements S3, S4 by passing through S5. Because each definition could reach every use, the number of definition-use edges is proportional to the square of the number of statements. These dependences constitute the majority of the edges in a PDG. SSA provide a solution to this problem. In SSA form, each assignment creates a different variable name and at point where control flow joins, a special operation is inserted to merge different incarnations of the same variable. The merge nodes are inserted just at the place where control flow joins. Figure 8 (right) is the original program under SSA form. A merge node (Φ) is inserted at S5, and killed the definition of S1 and S2. We could see here, in the SSA form, we could reduce the definition-use edges from quadratic to linear. Figure 9. Control dependence graph of Figure 4. Express the definition of tregion. treegion2_4, treegion2_5 and treegion2_1, we could create sub-tasks by merging treegion2_4 and treegion2_5 as one sub-task and treegion2_1 (which is also the inner loop) as one sub-task, or just for part of them. To reveal data parallelism, we can reuse the typed fusion algorithm introduced by McKinley and Kennedy [11]: it is possible to fuse communicating data-parallel nodes to increase the synchronization grain or improve the load balancing. In this example, the loop in node L2 does not carry any dependence, and we need to decouple it from its enclosing task to expose data-parallelism. 5. Partitioning Algorithm In this section, we present our partitioning algorithm, based on the SSA and tregion representations. We define our model and the important constructs that will be used by our algorithm, then we present and describe our algorithm. 5.1 Definitions In this work, we are only targeting natural structured loops [3]. Such loops are single-entry single-exit CFG sub-graphs with one entry block and possibly several back edges leading to the header from inside of the loop. break and continue statements can be preprocessed to comply with this restriction, but we plan to lift it altogether in the future. Tregion The canonical definition of a tregion is a non-linear, single-entry multiple-exit region of code containing basic blocks that constitute a sub-graph of the CFG. We alter this definition to bear on the Control-Dependence Graph (CDG) instead, so we will be looking at single-entry multiple-exit sub-graphs of the CDG. Loop Control Node In the representation we employ later, we will use the loop control node to represent the loop. The loop control node include statements which will evaluate the loop control expression and determines the next iteration. Although control dependences in loops can be handled by the standard algorithm by converting them to a control flow graph, there are advantages in treating them as a special case with coalescing them in a single node (loop control node): not only the backward dependence is removed by building the loop control node so that the control dependence graph will form a tree, but also, this node can be used to represent the loop in all sort of transformations. Conditional Level The control dependence graph of the structured code is a tree after building the loop control node. The root of the tree is the loop control node at the loop’s outermost level. We define the conditional level for every node in the control dependence graph as the depth of the node in the tree. The root of the tree with depth 0 has conditional level 0. We define the conditional level for the tregion as the conditional level of the root node of the tregion (subtree). We define tregion2_M to identify a tregion where M is the conditional level of the tregion and M is the root node number of the tregion. 5.2 The algorithm The algorithm takes an SSA representation of a single function, and returns a concurrent representation annotated with tasks and communication streams. Step 1: Transform Conditional Statements to Conditional Variables To achieve fine-grained pipelining, conditional statements are split to conditional variables. As showed in Figure 10. Full conversion to three-address SSA form is also possible (as it is performed in GCC or LLVM, for example). if (condition(i)) //is transformed to c1 = condition(i) if (c1) Figure 10. Split conditional statements to expose finer grained pipelining. Step 2: Build the Program Dependence Graph under SSA By building the program dependence graph, the control dependence graph, data dependence graph (through memory) and scalar dependence graph (through registers) are built together. The control dependence graph for the structured code is a tree, the root of the tree is the loop control node. The leaves of the tree are non-conditional statements and the other nodes inside the tree are the conditional statements or the loop control node of the inner loops. We start from building the control dependence graph, and evaluate the conditional level for each node in the graph. Every node inside the control dependence graph is an statement from the compiler’s intermediate representation of the loop except for the loop control node. The loop control node will be built by searching the strongly connect component started from the loop header node (at each loop nest level) in the program dependence graph. The data dependence graph could be built by the array dependence analysis [9] for the loop. We should analyse every pair of data dependences to mark the irreducible edges in a later step if there are recurrence. Step 3: Marking the Irreducible Edges A partition can preserve all dependences if and only if there exists no dependence cycle spanning more than one output loop [1, 12]. In our case, for the tregion at the same conditional level, if there are dependences that form a cycle, we mark the edges in between as irreducible. If we have statements in different conditional level, we promote the inner one to its ancestor until both of them are in the same tregion, mark the promoted root node and the other root node as irreducible. The algorithms is presented in Figure 11. Step 4: Structured Typed Fusion Before partitioning, to reveal data parallelism, we type every node in the dependences graph as parallel or !parallel. If there are loop-carried dependence inside this node, then it should be typed as !parallel, otherwise, typed as parallel. The parallel type nodes are candidates for data parallelization. The goal is to merge this type of nodes to create the largest parallel loop, reducing synchronization overhead and (generally) improving data locality. Further partitioning can happen in the following step, starting from this maximally type-fused configuration. Given a DAG with edges representing dependences and the vertices representing statements in the loop body, we want to produce an equivalent program with minimal number of parallel loops. We want it to be as large as possible to balance the synchronization. level 0 for our partitioning algorithms, and for all of its child trees at conditional level 1, we should decide where to partition. The partition point could be any point between each of these trees at the same level except the irreducible edges that we have created in step 3. The algorithm may decide at every step if it is desirable to further partition any given task into several sub-tasks. Look at the example Figure 13: ```plaintext for(1...) for (1...) BEGIN task1_1 BEGIN task1_2 x = work(i) x = work(i) if (c1) if (c1) y = x + i; y = x + i; BEGIN task1_2 BEGIN task2_1 if (c2) if (c2) z = y*y; z = y*y; END task2_1 END task2_1 END task1_2 END task1_2 ``` Figure 13. Before partitioning (left), and After partitioning (right). Loop with control dependences. The code in Figure 13 (left) is partitioned into 2 tasks, and one task (task1_2) is partitioned further into 3 sub-tasks. ### 6. Code Generation After the partitioning algorithms, we have decided the partition point between the original trees, with the support of the stream extension of OpenMP. We ought to generate the code by inserting the input output directives. With the support of nested tasks, relying on the downstream, extended OpenMP compilation algorithm (called OpenMP expansion). But some challenges remain, especially in presence of multiple producers and consumers. We are using SSA form as an intermediate representation and generating the streaming code. #### 6.1 Decoupling dependences across tasks belonging to different trees Clearly if we decouple a dependence between tasks in the same treegion, the appropriate input and output clauses can be naturally inserted. But what about the communication between tasks at different level? Considering the example in Figure 14, if we decide to partition the loop to 3 main tasks: task1_1 with S1, task1_2 with (S2,S3), and task1_3 with S4, task1_2 is further divided to task2_1 with S3. If we insert the produce and consume directly into the loop, unmatched production and consumption will result. ```plaintext for (...) { for (i = 0; i < N; i++) { S1 x = work(i) S1 x = work(i) produce(stream_x, x) //task1_1 end S2 if (c1) S2 if (c1) x = consume(stream_x) x = consume(stream_x) produce(stream_x, x) //task1_1 end S3 y = x + i; S3 y = x + i; S4 ... = y; S4 ... = y; BEGIN task2_1 BEGIN task2_1 S2 if (c1) S2 if (c1) x = consume(?) x = consume(?) produce(?, x) //task2_1 end BEGIN task2_1 BEGIN task2_1 S3 y = x + i; S3 y = x + i; produce(?, y) //task2_1 end BEGIN task2_1 BEGIN task2_1 S4 ... = y; S4 ... = y; produce(stream_y, y) //task2_1 end BEGIN task2_1 BEGIN task2_1 S3 y = consume(stream_y) S3 y = consume(stream_y) produce(stream_x, y) //task2_1 end BEGIN task2_1 BEGIN task2_1 S4 ... = y; S4 ... = y; produce(stream_y, y) //task2_1 end BEGIN task2_1 BEGIN task2_1 ``` Figure 14. Normal form of code (left) and using streams (right). The answer comes from following the synchronous hypothesis and slightly modifying the construction of the SSA form in presence of concurrent streaming tasks. 6.2 SSA representation We are using the Static Single Assignment (SSA) form as an intermediate representation for the source code. A program in SSA form if every variable used in the program appears a single time in the left hand side of an assignment. We are using the SSA form to eliminate the output dependences in the code, and to disambiguate the flow of data across tasks over multiple producer configurations. Consider the example in Figure 15, if we partition the statements into (S1), (S2,S3), (S4), we need to implement precedence constraints for the output dependence between partition (S1) and (S2,S3), which decreases the degree of parallelism and induces synchronization overhead. Eliminating the output dependences with the SSA form leads to the introduction of multiple streams in the partitioned code. In order to merge the information coming from different control flow branches, a $\Phi$ node is introduced in the SSA form. The $\Phi$ function is not normally implemented directly, after the optimizations are completed the SSA representation will be transformed back to ordinary one with additional copies inserted at incoming edges of (some) $\Phi$ functions. We need to handle the case where multiple producers in a given partition reach a single consumer in a different partition. When decoupling a dependence whose sink is a $\Phi$ node, the exact conditional control flow leading to the $\Phi$ node is not accessible for the out-of-SSA algorithm to generate ordinary code. **Task-closed $\Phi$ node** In SSA loop optimization, there is a concept called loop-closed $\Phi$ node, which implements the additional property that no SSA name is used outside of loop where it is defined. When enforcing this property, $\Phi$ nodes must be inserted at the loop exit node to catch the variables that will be used outside of the loop. Here we give a similar definition for task-closed $\Phi$ node: if multiple SSA variables are defined in one partition and used in another, a phi node will be created at the end of the partition for this variable. This is the place where we join/split the stream. We need to make sure that different definitions of the variable will be merged in this partition before it continues to a downstream one. This node will be removed when converting back from SSA. **Task-closed stream** Our partitioning algorithms generate nested pipelining code to guarantee that all communications follow the synchronous hypothesis. For each boundary, if there are one or more definitions of a variable coming through from different partitions, we insert a consumer at this boundary to merge the incoming data, and immediately insert a producer to forward the merged data at the rate of the downstream control flow. 1. When partitioning from a boundary, if inside the treegion, there are multiple definitions of a scalar and it will be used in other treegions which has the same conditional level, we create a $\Phi$ node at the end of this partition to merge all the definitions, and also update the SSA variable in later partitions. 2. If there is a $\Phi$ node at the end of a partition, insert a stream named with the left-hand side variable of the $\Phi$ node. 3. At the place where this variable is used, which is also a $\Phi$ node, add a special stream-$\Phi$ node to consume. 4. To generate code for the stream-$\Phi$, use the boolean condition associated with the conditional phi node it originates from. Let us consider the SSA-form example in Figure 15 where we partition the code into (S1,S2,S3) and (S4,S5). A $\Phi$ node will be inserted at the end of the first partition, $r_{1_4} = \phi(r_{1_1}, r_{1_2})$. ![Figure 15. Normal form of code (left) and SSA form of the code (right).](image) ![Figure 16. Apply our algorithm to generate the parallel code.](image) ![Figure 17. Multiple producers with applied our algorithm, the generated code.](image) The $\Phi$ node in a later partition should be updated from $r_{1_3} = \Phi(r_{1_1}, r_{1_2})$ to $r_{1_5} = \Phi(r_{1_4})$. In the second step, we find out that in partition (S1,S2,S3), there is a $\Phi$ node at the end, so we insert a stream to produce there. And in partition (S4,S5), after the $\Phi$ node there is a use of the variable, so we insert a stream consume. The generated code will look like Figure 16. This example illustrates the generality of our method and shows how fine-grain pipelines can be built in presence of complex, multi-level control flow. If we decide to partition the statements into (S1), (S2,S3), (S4,S5), which is the case for multiple producers, the generated code will look like in Figure 17. **7. Conclusion** In this paper, we propose a method to decouple independent tasks in serial programs, to extract scalable pipelining and data-parallelism. Our method leverages a recent proposition of a stream-processing extension of OpenMP, with a persistent task semantics to eliminate the overhead of scheduling task instances each time a pair of tasks need to communicate. Our method is inspired by the synchronous hypothesis: communicating concurrent tasks share the same control flow. This hypothesis simplifies the coordination of communicating tasks over nested levels of parallelism. Synchrony also facilitates the definition of generalized, structured typed fusion and partition algorithms preserving the loop structure information. These algorithms have been proven to be essential to the adaptation of the grain of parallelism to the target and to the effectiveness of compile-time load balancing. These partitioning algorithms also handle DOALL parallelization inside a task pipeline. We are using a combination of SSA, control dependence tree and (non-)dependence graph as an IR. With the support of SSA, our method eliminates the nested multiple producer and multiple consumer problems of PS-DSWP. SSA also provides additional applicability, elegance and complexity benefits. This work is currently under development in a development branch of GCC, the partitioning algorithms is partially developed. For the code generation part, we first need to migrate the existing OpenMP expansion pass of GCC to work under SSA form, which has been a long-running challenge. When this work is complete, our method will leverage the array data-flow analysis of the Graphite polyhedral compilation pass of GCC to provide more precise data dependence information in loop nests with regular control flow. **Acknowledgments** This work was partly funded by the European FP7 project TERAFLUX id. 249013, http://www.teraflux.eu References
{"Source-Url": "https://hal.archives-ouvertes.fr/hal-00870687/file/A-462.pdf", "len_cl100k_base": 8721, "olmocr-version": "0.1.53", "pdf-total-pages": 9, "total-fallback-pages": 0, "total-input-tokens": 27754, "total-output-tokens": 10357, "length": "2e13", "weborganizer": {"__label__adult": 0.00033664703369140625, "__label__art_design": 0.0002727508544921875, "__label__crime_law": 0.00029754638671875, "__label__education_jobs": 0.00033020973205566406, "__label__entertainment": 5.668401718139648e-05, "__label__fashion_beauty": 0.00013828277587890625, "__label__finance_business": 0.0001697540283203125, "__label__food_dining": 0.0003361701965332031, "__label__games": 0.0006251335144042969, "__label__hardware": 0.0013914108276367188, "__label__health": 0.0004036426544189453, "__label__history": 0.00022041797637939453, "__label__home_hobbies": 8.165836334228516e-05, "__label__industrial": 0.0004487037658691406, "__label__literature": 0.00016391277313232422, "__label__politics": 0.0002593994140625, "__label__religion": 0.00048470497131347656, "__label__science_tech": 0.0205841064453125, "__label__social_life": 6.0617923736572266e-05, "__label__software": 0.005054473876953125, "__label__software_dev": 0.96728515625, "__label__sports_fitness": 0.00032782554626464844, "__label__transportation": 0.0005884170532226562, "__label__travel": 0.0002071857452392578}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 42399, 0.04678]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 42399, 0.60653]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 42399, 0.8674]], "google_gemma-3-12b-it_contains_pii": [[0, 881, false], [881, 6855, null], [6855, 13551, null], [13551, 19497, null], [19497, 23524, null], [23524, 29690, null], [29690, 32759, null], [32759, 39326, null], [39326, 42399, null]], "google_gemma-3-12b-it_is_public_document": [[0, 881, true], [881, 6855, null], [6855, 13551, null], [13551, 19497, null], [19497, 23524, null], [23524, 29690, null], [29690, 32759, null], [32759, 39326, null], [39326, 42399, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 42399, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 42399, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 42399, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 42399, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 42399, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 42399, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 42399, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 42399, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 42399, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 42399, null]], "pdf_page_numbers": [[0, 881, 1], [881, 6855, 2], [6855, 13551, 3], [13551, 19497, 4], [19497, 23524, 5], [23524, 29690, 6], [29690, 32759, 7], [32759, 39326, 8], [39326, 42399, 9]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 42399, 0.0]]}
olmocr_science_pdfs
2024-12-07
2024-12-07
0e8b8ab8c2f1c43900845b597ed30defd92e9e13
SLAMM — Automating Memory Analysis for Numerical Algorithms John M. Dennis¹,² Computational and Information Systems Laboratory National Center for Atmospheric Research Boulder, CO 80305, USA Elizabeth R. Jessup³,⁴ Department of Computer Science University of Colorado Boulder, CO 80309, USA William M. Waite⁵ Department of Electrical and Computer Engineering University of Colorado Boulder, CO 80309, USA Abstract Memory efficiency is overtaking the number of floating-point operations as a performance determinant for numerical algorithms. Integrating memory efficiency into an algorithm from the start is made easier by computational tools that can quantify its memory traffic. The Sparse Linear Algebra Memory Model (SLAMM) is implemented by a source-to-source translator that accepts a MATLAB specification of an algorithm and adds code to predict memory traffic. Our tests on numerous small kernels and complete implementations of algorithms for solving sparse linear systems show that SLAMM accurately predicts the amount of data loaded from the memory hierarchy to the L1 cache to within 20% error on three different compute platforms. SLAMM allows us to evaluate the memory efficiency of particular choices rapidly during the design phase of an iterative algorithm, and it provides an automated mechanism for tuning existing implementations. It reduces the time to perform a priori memory analysis from as long as several days to 20 minutes. Keywords: memory analysis, sparse linear algebra, source-to-source translation, MATLAB ¹ The work of this author was supported through National Science Foundation Cooperative Grant NSF01, which funds the National Center for Atmospheric Research (NCAR), and through the grants: #OCI-0749206 and #OCE-0825754. Additional funding is provided through the Department of Energy, CCPP Program Grant #DE-PS02-07ER07-06. ² Email: dennis@ucar.edu ³ The work of this author was supported by the National Science Foundation under grants no. CCF-0430646 and CCF 0830458. ⁴ Email: Elizabeth.Jessup@Colorado.edu ⁵ Email: William.Waite@Colorado.edu 1 Introduction Traditionally, numerical algorithms have been designed to achieve the best numerical accuracy for a given number of floating-point operations [26,31,30,1,25]. However, this approach is based on the assumption that the time to perform floating-point operations dominates the overall cost of the computation. This assumption is no longer true in general because the cost of memory access has risen in comparison to the cost of floating-point arithmetic. While the performance of microprocessors has been improving at the rate of 60% a year, the performance of dynamic random access memory has been improving at a rate of only 10% [28]. In addition, advances in algorithm development mean that the total number of floating-point operations required for solution of many problems is decreasing [19]. Thus, the time to solution can no longer be considered a function of the number of floating-point operations performed alone but must rather be described as a combination of the costs of both floating-point arithmetic and memory access [19]. Creating new algorithms that demonstrate both numerical and memory efficiency [35,7,2,5,6,37,14,20,17] is a difficult task that has not been addressed extensively or in a systematic fashion. The all-too-common approach is to ignore memory efficiency until after the implementation is complete. Unfortunately, retroactive retooling of code for memory efficiency can be a daunting task. It is better to integrate memory efficiency into the algorithm from the start. Manual analysis, which involves derivation of an analytical expression for data movement, requires extensive knowledge of computer architecture and software engineering. It is laborious, error-prone, and too complex to perform on a regular basis. Fortunately, we can automate the process by employing computational tools to quantify the memory traffic. A static analysis provides an estimate of memory use by counting variable references in the code itself; a dynamic analysis is performed as the code is run and so reflects actual data access. One general design strategy is to prototype an algorithm in MATLAB using different memory layouts and to determine how the final version will perform by making measurements on the prototypes. Creating useful prototypes with appropriate statistics-gathering code requires specialized knowledge; this method would thus not be widely available if we didn’t package that knowledge. We therefore developed the the Sparse Linear Algebra Memory Model (SLAMM) processor, a source-to-source translator that accepts MATLAB code describing the candidate algorithm and adds blocks of code to predict data movement [10]. Source-to-source translators have a long history in the development of numerical algorithms. In early 1970, Marian Gabriel reported on a translator that accepted a FORTRAN formula and produced a FORTRAN formula computing the derivative of the input formula [16]. That translator was part of a larger system of doing least-squares fits [15]. Gabriel’s rationale for providing the translator echoes ours for SLAMM: The curve-fitting program ... requires partial derivatives of the function to be fitted, and thus the user had to supply FORTRAN expressions for these deriva- SLAMM Memory Analysis for Body: BLGMRES <table> <thead> <tr> <th>Component</th> <th>Mbytes (SR)</th> </tr> </thead> <tbody> <tr> <td>TOTAL: Storage Requirement</td> <td>10.21</td> </tr> <tr> <td>TOTAL: Loaded from L2 -&gt; L1</td> <td>574.64 +- 6.16</td> </tr> <tr> <td>DGEMM</td> <td>0.00 +- 0.00</td> </tr> <tr> <td>Sparse Ops</td> <td>79.50 +- 6.16</td> </tr> </tbody> </table> Fig. 1. The result of a memory analysis tives. Finding them for a complicated function is, at best, a nuisance. At worst, it is a common source of errors. Over the years, tools have been developed to automate production of analysis and translation algorithms from declarative specifications [22]; using them, processors like SLAMM can now be constructed more easily. We used Eli [18,13], a public-domain compiler generator with sophisticated support for standard tasks such as name analysis, to generate the SLAMM processor. Section 2 explains how the SLAMM processor analyzes a prototype and translates it to a MATLAB program. In Section 3, we summarize our experiences in applying SLAMM to algorithm development. 2 The SLAMM processor SLAMM’s goal is to predict the amount of data moved by an algorithm to be implemented in a compiled language, given a MATLAB prototype for that algorithm. Figure 1 illustrates information that SLAMM provided to the user for an algorithm named BLGMRES, which is a sparse linear system solver for a matrix of order 25,228: - The sum of the storage required (SR) for all of BLGMRES’s variables is 10.21 Mbytes. - The working set load (WSL) size is the amount of data load from the memory to the processors, which for BLGMRES is 574.64 Mbytes. This figure may be in error by up to 6.16 Mbytes, due to the difficulty SLAMM has in predicting data movement for certain programming constructs. - There were no dense matrix-matrix operations that could be implemented as calls to the Basic Linear Algebra Subprogram (BLAS) DGEMM [12]. - Sparse matrix-vector operations account for 79.50 Mbytes of the total loads and all of the possible error. Both static and dynamic analysis of the prototype are necessary in order to obtain this information. SLAMM performs the static analysis directly, and also produces a copy of the prototype that has been augmented with additional MATLAB code blocks. The MATLAB interpreter executes the transformed code to provide the dynamic analysis. The SLAMM processor accepts a MATLAB prototype containing SLAMM directives. All SLAMM directives consist of the prefix \%SLM, a command, and a terminating semicolon. A command (Table 1) is a keyword followed by one or more arguments, separated by commas. Table 1 SLAMM Commands <table> <thead> <tr> <th>Command</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td>start name</td> <td>Mark the beginning of a body of MATLAB code to be analyzed, and give it the name name.</td> </tr> <tr> <td>end name</td> <td>Mark the end of the body of MATLAB code named name.</td> </tr> <tr> <td>FuncStart name</td> <td>Mark the beginning of a MATLAB function to be analyzed, and give it the name name.</td> </tr> <tr> <td>FuncEnd name</td> <td>Mark the end of the MATLAB function named name.</td> </tr> <tr> <td>print name</td> <td>Request that a memory analysis be printed for name.</td> </tr> <tr> <td>Func ident,...,ident</td> <td>Classify one or more identifiers as names of functions for which data movement is to be ignored.</td> </tr> <tr> <td>IncFunc ident,...,ident</td> <td>Classify one or more identifiers as names of functions that contain significant data movement.</td> </tr> </tbody> </table> In Section 2.1 we explain how the number of memory accesses corresponding to a variable reference in the prototype is related to the region in which it occurs. Unfortunately, not every variable reference has the same effect, as discussed in Section 2.2. The translation based upon a static analysis of the prototype is described in Section 2.3. 2.1 Regions and variable accesses In the simplest case, each occurrence of a variable in the prototype represents an access to that variable’s memory location by the final algorithm. However, the number of times the memory location is accessed depends on the execution path and the region containing the variable occurrence. As an example, consider the prototype shown in Figure 2. The conditional guarantees that either B2 or B3, but not both, will be executed. Similarly, variables occurring in a region controlled by an iteration will be accessed many times. SLAMM directives can also be used to delimit regions on which to perform memory analysis. In Figure 2, directives have been used to define the region B1 and give it the name foo. The print command causes an output similar to that described by Figure 1. Name analysis is the process used to discover and record all of the relationships among identifier occurrences within program regions. This process is well understood, and can be described in terms of a few simple concepts [23]: Range: A region of the program text. Each of the regions B0-B3 in Figure 2 constitutes a range. For each range, SLAMM calculates: the total storage requirement (SR), the amount of data loaded from memory, the working set load (WSL) size, and the amount of data stored to memory, the working set store (WSS) size. Defining occurrence: An occurrence of an identifier that would be legal even if it were the sole occurrence of that identifier. All identifier occurrences in SLAMM are defining occurrences. For each defining occurrence, SLAMM creates a new data structure by prepending \texttt{slm} to the identifier and captures type, extent, and required memory storage. **Binding:** A relationship between an identifier and a unique entity. **Scope:** The region of the program text within which a binding is valid. In SLAMM, a binding holds over the entire range containing a defining occurrence of the identifier. A defining occurrence for the same identifier in a nested range creates a new binding. Within the scope of that new binding, the old binding is invalid. The scope of the new binding therefore constitutes a “hole” in the scope of the old binding. **Name space:** A collection of ranges, occurrences, bindings and scopes. SLAMM has two name spaces: the \textit{variable} name space and the \textit{counter} name space. Every identifier occurrence has a binding in each name space. The only ranges that are relevant in the variable name space are those constituting files and functions. In Figure 2, the region B0 is the only range in the variable name space. The entity bound to an identifier in the variable name space represents the prototype variable named by that identifier. All of the ranges are relevant in the counter name space. The entity bound to an identifier in the counter name space represents the number of times the prototype variable named by that identifier is accessed in the scope of that binding. 2.2 Correcting the access count An occurrence of an identifier in the prototype does not necessarily indicate that the corresponding variable must be loaded from the memory hierarchy. Fortunately, it is possible to improve the accuracy of the base identifier counts through a series of corrections. These corrections capture properties of the translation from MATLAB to a compiled language. An efficient implementation of the expression \( n = \text{size}(A,1); \), which uses the built-in MATLAB function size to set the variable \( n \) to the row dimension of the matrix \( A \), does not require access to the entire matrix \( A \). The necessary functionality can be provided in a compiled language by accessing a single integer variable. The function call correction addresses the counting mismatch by decrementing the counts for those identifiers that occur within a function call argument list. We are careful not to decrement the count for those identifiers that occur in an expression in an argument list. For example, the function call correction does not apply to the vector identifiers \( r \) in \( m = \text{size}(r_m1' \cdot r); \). We describe our approach for memory analysis of function calls in the next section. The calculation of the dot product \( \alpha = r' \cdot r; \) shows the need for another type of correction. In this case, the identifier \( r \) occurs twice in a single expression. However, the vector \( r \) is only loaded once from the memory hierarchy. The duplicate occurrence of \( r \) within a single expression represents cache reuse that cannot be ignored in the memory analysis calculation. To address cache reuse, we decrement the identifier counts for any identifiers that occur multiple times within a single statement. For simplicity, this duplicate correction does not address the possibility of cache reuse between multiple statements. The expression \( r_m1 = r; \) copies the vector \( r \) to vector \( r_m1 \). Memory copies are necessary in MATLAB for renaming purposes because MATLAB lacks a pointer construct. Single variable assignments are implemented as either a memory copy or a pointer assignment in a compiled language. We assume that, for an efficiently implemented algorithm, variables with a large storage requirement (e.g., vectors) use pointer assignments. Variables with a small storage requirement, such as a single floating-point value, use memory copies. Because the cost of memory copy for small variables is insignificant, we assume for the purposes of memory analysis that the assignment of one variable to another is always a pointer assignment. The copy correction decrements the identifier counts to properly address pointer assignment. The corrections discussed so far involve decrementing counts to properly account for particular identifier occurrences. A different form of correction is required in \( r = A \cdot w; \). Here SLAMM needs additional information about the types of entity represented by \( A \) and \( w \). For example, \( A \) may be a sparse or dense matrix. Type information is only available to the MATLAB interpreter. We address our lack of type information by transforming certain operators into function calls. For example, to apply the special operator correction we transform the expression \( r=A \cdot w \) to the equivalent \( r=\text{mtimes}(A,w) \). A profiled version of \text{mtimes} calculates the data movement based on the determination of type at runtime. 2.3 Translating SLAMM to MATLAB Figure 3 illustrates the translation of Figure 2 by the SLAMM processor. The oval boxes in Figure 3 represent additional code blocks introduced to carry out the dynamic analysis. Note that the SLAMM directives, being MATLAB comments, can be copied into the output as documentation. Header contains the definitions and initialization of MATLAB structures used to accumulate the information for each scope and identifier. A SizeOf code block is inserted just after an assignment is made to a variable. It typically contains a single call to the MATLAB `whos` function. Here is the assignment and SizeOf block in scope B2 of Figure 3: ```matlab new = [r,b,3]; [slm_new] = whos('new'); ``` This captures the type, extent, and required memory storage for `new` in a generated variable (`slm_new`) named for the user’s variable. Field `bytes` of the structure created by the \texttt{whos(’new’)} call specifies the amount of storage occupied by variable \texttt{new}. The purpose of an exclusive memory analysis block is to accumulate information from a particular scope. Each range requires an exclusive memory analysis code block. The exclusive memory analysis block for B1 (shown in Figure 3) contains (among other things): \begin{verbatim} slm_foo.wsl = slm_foo.wsl + slm_new.bytes + slm_b.bytes; slm_foo.wss = slm_foo.wss + slm_b.bytes; \end{verbatim} This calculates the amount of data loaded from the memory hierarchy by the if-expression and the fetch of \texttt{new}, accumulating the result in field \texttt{wsl} of the structure \texttt{slm_foo}. Similarly, the amount of data stored to the memory hierarchy (in the assignment to \texttt{b} at the beginning of the block) is recorded in field \texttt{wss}. Each of these assignments has two components: the total amount loaded or stored before this execution of the code in B1 (e.g., \texttt{slm_foo.wss}) and the amount loaded or stored during this execution (e.g., \texttt{slm_new.bytes}). The former is initialized to zero in \texttt{Header}, the latter is a constant determined by \texttt{whos}. Note that this calculation accounts only for the accesses in the scope of the bindings of B1. Both \texttt{new} and \texttt{b} have defining occurrences in B2, and thus B2 constitutes a hole in the scope of the B1 bindings for those identifiers. Memory access information associated with the assignment in B2 is accumulated by code in the exclusive memory analysis code block B2. In general, each term defining a variable access is multiplied by the count of occurrences described in Section 2.2. This count is 1 for all variable accesses in Figure 3, and therefore SLAMM omits it. The purpose of an inclusive memory analysis block is to gather the data from all of the exclusive memory analysis blocks in a function or program. It is generated at the end of the text of that function or program, where it will be executed exactly once. The inclusive memory analysis block of Figure 3 contains (among other things): \begin{verbatim} slm_foo.wsl = slm_foo.wsl + slm_elseLn7.wsl; slm_foo.wsl = slm_foo.wsl + slm_ifLn5.wsl; \end{verbatim} Here \texttt{ifLn5} and \texttt{elseLn7} are SLAMM’s names for B2 and B3, respectively. \texttt{Print Memory Analysis} (\texttt{foo}) consists of a call to a library function called \texttt{SlmPrtAnalysis} with an appropriate structure as its argument. SLAMM differentiates between identifiers that correspond to functions and identifiers that correspond to variables. Functions are further classified into those that provide a significant contribution to data movement and those that do not. We refer to those functions that provide a significant contribution to data movement as \textit{profiled functions}. SLAMM maintains the proper classification in a manually constructed table for a collection of commonly used built-in MATLAB functions. For example, the MATLAB function \texttt{size}, which determines the extent of a variable, typically does not contribute to data movement but the function \texttt{qr}, which calculates the QR factorization of an input matrix, certainly does. Two types of code transformations are necessary for profiled functions. The first involves changing the function call, while the second involves changes to the function itself. SLAMM transforms a function call to a profiled built-in MATLAB function by prefixing the string SLM to its name and adding an output argument. The additional output argument is a MATLAB structure containing the SLAMM-calculated memory analysis. The profiled function’s contribution to data movement is subsequently accumulated in the appropriate exclusive memory analysis code block of the caller. For profiled functions that return multiple output arguments, the code transformation only requires the addition of one extra output argument. For profiled functions that return a single output argument, additional code transformation may be necessary. For example, a single expression that uses the output argument of a profiled function as an operand requires the generation of multiple sub-expressions. All sub-expressions are linked by temporary variables. The generated MATLAB for the expression $t = \sin(r) + \cos(z)$, where $r, z, t \in \mathbb{R}^n$ is: $$ \begin{align*} [\text{slm}_L1C5, \text{slm}_\sin\_L1C5] &= \text{SLMsin}(r); \\ [\text{slm}_L1C14, \text{slm}_\cos\_L1C14] &= \text{SLMcos}(z); \\ t &= \text{slm}_L1C5 + \text{slm}_L1C14, \end{align*} $$ Here the single original expression $t = \sin(r) + \cos(z)$ is broken into three separate statements. The temporary variables $\text{slm}_L1C5$ and $\text{slm}_L1C14$ are the original output arguments of the $\sin$ and $\cos$ functions respectively and are used to calculate the expected result $t$. The structures $\text{slm}_\sin\_L1C5$ and $\text{slm}_\cos\_L1C14$ contain the results of the memory analysis of the $\sin$ and $\cos$ functions respectively. The function call transformation requires the generation of new versions of the profiled functions. SLAMM provides a collection of profiled functions for all necessary built-in MATLAB functions. Each consists of a call to the original function and the assignment of the memory analysis structures. For a user-supplied MATLAB function, the SLAMM language processor generates the various memory analysis code blocks described above and alters the name and output arguments appropriately. ### 3 An Application of SLAMM Automated memory analysis provides both the ability to evaluate the memory efficiency of a particular design choice rapidly during the design phase and the ability to improve the memory efficiency of a pre-existing solver. We illustrate both applications by using SLAMM to reduce the execution time of the Parallel Ocean Program (POP) [32], a global ocean model developed at Los Alamos National Laboratory. POP, which is used extensively as the ocean component of the Community Climate System Model [8], uses a preconditioned conjugate gradient solver to update surface pressure in the barotropic component. Parallelism on distributed memory computers is supported through the Message Passing Interface (MPI) [34] standard. We used POP version 2.0.1 [29] to examine data movement in the preconditioned Table 2 <table> <thead> <tr> <th>Solver Implementation</th> <th>WSL_P</th> <th>version</th> <th>Ultra II WSL_M</th> <th>error</th> <th>POWER4 WSL_M</th> <th>error</th> <th>R14K WSL_M</th> <th>error</th> </tr> </thead> <tbody> <tr> <td>PCG2+2D</td> <td>4902</td> <td>v1</td> <td>5163</td> <td>5.3%</td> <td>5068</td> <td>3.4%</td> <td>5728</td> <td>16.9%</td> </tr> <tr> <td></td> <td></td> <td>v2</td> <td>4905</td> <td>0.1%</td> <td>4865</td> <td>-0.7%</td> <td>4854</td> <td>-1.0%</td> </tr> <tr> <td>PCG2+1D</td> <td>3218</td> <td></td> <td>3164</td> <td>-1.7%</td> <td>3335</td> <td>3.7%</td> <td>3473</td> <td>7.9%</td> </tr> <tr> <td>Reduction</td> <td>34%</td> <td></td> <td>39%</td> <td>34%</td> <td>39%</td> <td></td> <td></td> <td></td> </tr> </tbody> </table> conjugate gradient solver using the test and gx1v3 grids. The test grid is a coarse grid provided with the source code to facilitate the porting of POP to other compute platforms. POP with the gx1v3 grid, which has one degree separation between grid points at the equator, is higher resolution than the test grid and represents 20% of the total compute cycles at the National Center for Atmospheric Research (NCAR) [4]. POP uses a three-dimensional computational mesh. The horizontal dimensions are decomposed into logically rectangular two-dimensional (2D) blocks [21]. The computational mesh is distributed across multiple processors by placing one or more 2D blocks on each processor. The primary advantage of the 2D data structure is that it provides a regular stride-one access for the matrix-vector multiply. The disadvantage of the 2D data structure within the conjugate gradient solver is that it includes a potentially large number of grid points that represent land. In effect, a number of explicitly stored zeros are added to the matrix. An alternative 1D data structure that uses compressed sparse row storage would avoid the inclusion of land points but would introduce indirect addressing. Additional details concerning the changes in data structures are provided in [11]. We used SLAMM to evaluate the required data movement for conjugate gradient solvers based on 1D and 2D data structures. We describe two types of data movement, the predicted data movement (WSL_P) and the measured data movement (WSL_M). WSL_P is predicted by SLAMM, and WSL_M is measured using hardware performance counters and refers to data loaded from the L2 to the L1 cache. For the 1D data structure, we used the PCG solver routine provided by MATLAB. We wrote a new PCG solver in MATLAB which used the same 2D data structures as in POP. Using the SLAMM directives described in Section 2, we created a region for one iteration of each of the algorithms. WSL_P for the algorithm with the 2D data structure (PCG2+2D) and the 1D data structure version (PCG2+1D) for the test grid are provided in the second column of Table 2. We tested both a naive implementation of PCG2+2D (v1) and an optimized one (v2) described later in this section. The SLAMM prediction is the same for both. SLAMM predicts that the use of the 1D data structure reduces data movement by 34% versus the existing 2D data structure. Based on the expectation of a 34% reduction in data movement, we implemented the 1D data structure in POP. If SLAMM had predicted a minor reduction in data movement, or even an increase in data movement, the 1D data structure would have never been implemented. A priori analysis like this provides confidence that the programming time to implement Table 3 <table> <thead> <tr> <th>CPU</th> <th>Ultra II</th> <th>POWER4</th> <th>R14K</th> </tr> </thead> <tbody> <tr> <td>Company</td> <td>SUN</td> <td>IBM</td> <td>SGI</td> </tr> <tr> <td>Mhz</td> <td>400</td> <td>1300</td> <td>500</td> </tr> <tr> <td>L1 Data-cache</td> <td>32KB</td> <td>32KB</td> <td>32KB</td> </tr> <tr> <td>L2 cache</td> <td>4 MB</td> <td>1440 KB</td> <td>8 MB</td> </tr> <tr> <td>L3 cache</td> <td>–</td> <td>32 MB</td> <td>–</td> </tr> </tbody> </table> Fig. 4. A code block that implements a piece of the PCG algorithm for versions v1 and v2. To evaluate the quality of our implementations and to check the accuracy of the SLAMM-based predictions, we instrumented all versions of the solver with a locally developed performance profiling library (Htrace), which is based on the PAPI [27] hardware performance counter API. Htrace calculates data movement by tracking the number of cache lines moved through the different components of the memory hierarchy. We focus on three primary microprocessor compute platforms that provide counters for cache lines loaded from the memory hierarchy to the L1 cache: Sun Ultra II [24], IBM POWER 4 [3], and MIPS R14K [36]. A description of the cache configuration for each compute platform is provided in Table 3. The measured data movement ($WSL_M$) is also presented in Table 2 for the 2D data structure implementations (PCG2+2D v1 and v2) and the 1D version (PCG2+1D) on each of the compute platforms. We report average data movement across ten iterations. While the discrepancies between the measured and predicted WSL for the PCS2+2D v1 solver are minimal for both the Ultra II and POWER4 platforms, the measured value of 5728 Kbytes for the R14K is 17% greater than the predicted value of 4902 Kbytes. The difference in data movement between the three compute platforms may be due to additional code transformations performed by the Ultra II and POWER4 compilers. That the PCG2+2D v1 solver is loading 17% more data from the memory hierarchy than necessary on the R14K is an indication that it is possible to improve the quality of the implementation. While SLAMM provides an indication of a potential performance problem, it... does not isolate the source of the problem. Locating and addressing the problem is still the responsibility of the software developer. An examination of the source code for the PCG2+2D v1 solver indicates that a minor change to the dot product calculation reduces data movement. Code blocks for version v1 and v2 of the solver are provided in Figure 4. The function **operator** applies the local matrix product, and the array `LMASK` is an array that masks out points that correspond to land points. In version v1 of the do loop, a temporary array `WORK0` is created that contains the point-wise product of two vectors `Q` and `P`. Outside the do loop, the dot product of `LMASK` and the `WORK0` array is calculated by **global_sum**. If the size of data accessed in the do loop is larger than the L1 cache, then a piece of the `WORK0` array at the end of the do loop is no longer located in the L1 cache and must be reloaded to complete the calculation. In the optimized version v2 of the do loop, we employ a scalar temporary `delta_local` to accumulate each block’s contribution to the dot product of `Q` and `P`. We then use a function **local_sum** that applies the land mask to complete the dot product. Finally, we replace the function **global_sum** with a call to **gsum**. The subroutine **gsum**, when executed on a single processor, is an assignment of `delta_local` to `delta`. Because version v2 of the code block does not access `WORK0` outside the do loop, it potentially reduces data movement. The `WSL_M` values in Table 2 for the v1 and v2 versions of the PCG2+2D solver on the R14K indicate that the rearranged dot product calculations reduce data movement by 18%. Note, that data movement is also reduced on the Ultra II and POWER4 platforms but to a lesser extent. Table 2 also provides the relative error between predicted and measured data movement for the solvers. SLAMM predicts data movement to within an average error of 0.6% for the PCG2+2D v2 solver and within 4.4% for the PCG2+1D solver. (The deviation for the poorer quality PCG2+2D v1 is greater.) Table 2 indicates that the actual percentage reductions in data movement are very similar to the predicted reductions. The results in Table 2 clearly demonstrate that it is possible for automated memory analysis to predict the amount of data movement accurately and so to provide *a priori* knowledge of the memory efficiency of a particular design choice before implementation in a compiled language. Note that it is entirely possible to perform the same analysis manually without SLAMM. While the calculation for the 2D case would be straightforward, the 1D case would be more complicated. In particular, an accurate prediction of the amount of data movement for the 1D data structure would require detailed information about location of land points. It is possible to estimate the difficulty of manual memory analysis by comparing the lines of code associated with the MATLAB prototype to the memory analysis code. Table 4 shows the number of non-comment lines for the 1D PCG prototype in MATLAB. For the 1D PCG prototype, the prototype grew from 41 lines to a total of 48 lines with the addition of seven `%SLM` directives. The SLAMM generated output code (prototype and memory analysis code) is 290 lines. In this case, memory analysis requires approximately seven times the number of code lines required by the algorithm alone. This illustrates that manual calculations are generally onerous and error prone and thus may not be performed regularly (or at all). We next examine the impact of reducing data movement on execution time. The timestep of POP includes a baroclinic and a barotropic component. The barotropic component is composed of a single linear solver for surface pressure. We executed POP using the test grid on a single processor of each compute platform for a total of 20 timesteps. This configuration requires an average of 69 iterations of the PCG2 algorithm per timestep. Table 5, gives the barotropic execution time in seconds using the three implementations of the solver. We include the execution time for the initial implementation of the solver using 2D data structures to accurately reflect the overall impact automated memory analysis has on execution time. Note that the PCG1+1D solver consistently has a lower execution time than either of the 2D data structure based solvers. The last row in Table 5 contains the percentage reduction in barotropic execution time for the PCG2+2D v1 versus the PCG2+1D solver. Table 5 indicates that code modifications either evaluated or identified by automated memory analysis reduce execution time by an average of 46%. Curiously, a comparison of Tables 2 and 5 indicates that the percentage reduction in execution time is even larger than the percentage reduction in data movement. The reason for the discrepancy is unclear. We next examine the impact of the 1D data structures on parallel execution time on POWER4 platform using the gx1v3 grid. We focus on the execution time of POP on 64 POWER4 processors. This is a typical configuration of POP that consumes approximately 2.4 million CPU hours every year at NCAR. We wrote a generalized gather-scatter routine to provide parallel execution under MPI for the 1D version of the solver. Recently, an alternative preconditioned conjugate gradient algorithm that uses a single dot product [9] (PCG1) was added to POP. The PCG1 algorithm provides a performance advantage for parallel execution because it eliminates one of the distributed dot product calculations. We configured POP to execute a total of 200 timesteps on 64 IBM POWER4 processors, with an average of 151 iterations per timestep. Note that, while the cost of the solver is important, it --- <table> <thead> <tr> <th>Developer generated Source Lines</th> <th>SLAMM generated prototype and analysis code</th> </tr> </thead> <tbody> <tr> <td>original 41</td> <td>%SLM 7</td> </tr> <tr> <td></td> <td>290</td> </tr> </tbody> </table> --- <table> <thead> <tr> <th>Solver implementation</th> <th>Ultra II</th> <th>POWER4</th> <th>R14K</th> </tr> </thead> <tbody> <tr> <td>PCG2+2D v1</td> <td>21.17</td> <td>4.57</td> <td>8.58</td> </tr> <tr> <td>PCG2+2D v2</td> <td>20.49</td> <td>4.01</td> <td>7.97</td> </tr> <tr> <td>PCG2+1D</td> <td>12.74</td> <td>2.11</td> <td>4.61</td> </tr> <tr> <td>Reduction</td> <td>39%</td> <td>54%</td> <td>46%</td> </tr> </tbody> </table> Table 5 Barotropic execution time for 20 timesteps of POP in seconds using the test grid on a single processor does not dominate the total cost of a timestep. The execution time for the time stepping loop in seconds for the four solver implementations is provided in Table 6. These results indicate that use of the PCG1+1D solver versus the PCG1+2D solver reduces total POP execution time by 9%. A 9% reduction in total execution time of POP is significant because that model has already been extensively studied and optimized [21,33]; the additional 9% translates into a reduction of 216,000 CPU hours per year at NCAR. 4 Conclusion Data movement is an important characteristic of a numerical algorithm running on today’s computers, contributing significantly to that algorithm’s running time. The effects of design decisions on data movement should therefore be explored before undertaking a costly implementation. Predictions of data movement are possible by adding instrumentation to a MATLAB prototype of the algorithm. As in the case of the partial derivative calculation problem described by Gabriel nearly forty years ago, that process is at best a nuisance and at worst a common source of errors. SLAMM automates the process of modifying the MATLAB prototype, reducing the cost of a test from days to minutes. It encapsulates knowledge about the characteristics of variable access and about strategies for accumulating information during a prototype run. If more detailed knowledge and better strategies evolve over time, they can be incorporated into SLAMM without the need for user re-training. Most of the difficulty in automating the instrumentation process lies in the common tasks of analyzing the text of the prototype to select the appropriate instrumentation code. Because of advances in compiler technology, those analysis tasks can be described by declarative specifications from which code can be produced automatically. Doing so dramatically reduces the cost of developing a tool like SLAMM. We have shown that SLAMM can be used to guide the performance improvement of large codes that are in current use as well as in the design of new algorithms. It provides one more example of the utility of source-to-source translators taking over the tedious and error-prone aspects of software development. References
{"Source-Url": "https://core.ac.uk/download/pdf/82714359.pdf", "len_cl100k_base": 8609, "olmocr-version": "0.1.49", "pdf-total-pages": 16, "total-fallback-pages": 0, "total-input-tokens": 37765, "total-output-tokens": 11308, "length": "2e13", "weborganizer": {"__label__adult": 0.0003688335418701172, "__label__art_design": 0.0005125999450683594, "__label__crime_law": 0.0004243850708007813, "__label__education_jobs": 0.0010538101196289062, "__label__entertainment": 0.00012254714965820312, "__label__fashion_beauty": 0.00022912025451660156, "__label__finance_business": 0.0003783702850341797, "__label__food_dining": 0.0004189014434814453, "__label__games": 0.0007944107055664062, "__label__hardware": 0.0025787353515625, "__label__health": 0.0006823539733886719, "__label__history": 0.00057220458984375, "__label__home_hobbies": 0.00016486644744873047, "__label__industrial": 0.0009794235229492188, "__label__literature": 0.00033593177795410156, "__label__politics": 0.0004718303680419922, "__label__religion": 0.000629425048828125, "__label__science_tech": 0.369384765625, "__label__social_life": 0.00012010335922241212, "__label__software": 0.01111602783203125, "__label__software_dev": 0.60693359375, "__label__sports_fitness": 0.0004940032958984375, "__label__transportation": 0.0010833740234375, "__label__travel": 0.0002512931823730469}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 43633, 0.04106]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 43633, 0.55579]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 43633, 0.85908]], "google_gemma-3-12b-it_contains_pii": [[0, 2090, false], [2090, 5338, null], [5338, 7890, null], [7890, 10648, null], [10648, 12113, null], [12113, 15614, null], [15614, 16562, null], [16562, 19796, null], [19796, 22927, null], [22927, 26367, null], [26367, 28329, null], [28329, 31730, null], [31730, 34864, null], [34864, 37434, null], [37434, 41582, null], [41582, 43633, null]], "google_gemma-3-12b-it_is_public_document": [[0, 2090, true], [2090, 5338, null], [5338, 7890, null], [7890, 10648, null], [10648, 12113, null], [12113, 15614, null], [15614, 16562, null], [16562, 19796, null], [19796, 22927, null], [22927, 26367, null], [26367, 28329, null], [28329, 31730, null], [31730, 34864, null], [34864, 37434, null], [37434, 41582, null], [41582, 43633, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 43633, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 43633, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 43633, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 43633, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 43633, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 43633, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 43633, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 43633, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 43633, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 43633, null]], "pdf_page_numbers": [[0, 2090, 1], [2090, 5338, 2], [5338, 7890, 3], [7890, 10648, 4], [10648, 12113, 5], [12113, 15614, 6], [15614, 16562, 7], [16562, 19796, 8], [19796, 22927, 9], [22927, 26367, 10], [26367, 28329, 11], [28329, 31730, 12], [31730, 34864, 13], [34864, 37434, 14], [37434, 41582, 15], [41582, 43633, 16]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 43633, 0.15966]]}
olmocr_science_pdfs
2024-11-26
2024-11-26
ccfe660ffc152765ed7e869ff7236314d4870967
D7.5: Functional specifications for social semantic functions (incl. prototype description) <table> <thead> <tr> <th>Revision</th> <th>Draft</th> </tr> </thead> <tbody> <tr> <td>Date of submission</td> <td>31.03.2013</td> </tr> </tbody> </table> | Author(s) | Marlies Olensky, Humboldt-Universität zu Berlin Maarten Brinkerink, Beeld en Geluid Pieter Vijn, Beeld en Geluid Danny Sedney, Beeld en Geluid Antoine Isaac, Europeana | | Dissemination Level | Public | ### Revision History <table> <thead> <tr> <th>Revision No.</th> <th>Date</th> <th>Author</th> <th>Organisation</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td>Draft 1</td> <td>17.01.2013</td> <td>Marlies Olensky</td> <td>Humboldt-Universität zu Berlin</td> <td>First draft version</td> </tr> <tr> <td>Draft 2</td> <td>28.02.2013</td> <td>Marlies Olensky</td> <td>Humboldt-Universität zu Berlin</td> <td>With input from Maarten Brinkerink, Juliane Stiller and Antoine Isaac</td> </tr> <tr> <td>Draft 3</td> <td>04.03.2013</td> <td>Marlies Olensky</td> <td>Humboldt-Universität zu Berlin</td> <td>With input from Maarten Brinkerink, Juliane Stiller and Antoine Isaac</td> </tr> <tr> <td>Draft 4</td> <td>05.03.2013</td> <td>Marlies Olensky</td> <td>Humboldt-Universität zu Berlin</td> <td>With input from Maarten Brinkerink, Juliane Stiller and Antoine Isaac</td> </tr> <tr> <td>Draft 5</td> <td>14.03.2013</td> <td>Marlies Olensky</td> <td>Humboldt-Universität zu Berlin</td> <td>With PyBossa</td> </tr> <tr> <td>Draft 6</td> <td>25.03.2013</td> <td>Marlies Olensky</td> <td>Humboldt-Universität zu Berlin</td> <td>With feedback from Maarten Brinkerink and Antoine Isaac</td> </tr> <tr> <td>Version 1</td> <td>28.03.2013</td> <td>Maarten Brinkerink, Danny Sedney, Pieter Vijn, Marlies Olensky</td> <td></td> <td>Addition of prototype description</td> </tr> </tbody> </table> ### Statement of originality: This deliverable contains original unpublished work except where clearly indicated otherwise. Acknowledgement of previously published material and of the work of others has been made through appropriate citation, quotation or both. Contents Contents ........................................................................................................................................... 3 1. Scope of this document ................................................................................................................. 4 2. Use cases ...................................................................................................................................... 5 2.1. Waisda? ................................................................................................................................. 5 2.2. PyBossa .................................................................................................................................. 9 3. Prototype ..................................................................................................................................... 15 3.1. Waisda? for Europeana .......................................................................................................... 15 3.2. PyBossa for Europeana ........................................................................................................... 21 4. References ................................................................................................................................. 26 5. Annex ......................................................................................................................................... 28 1. **Scope of this document** The scope of this document is to provide functional specifications for social semantic functions in Europeana. These specifications complement the work being accomplished in Task 7.2, where innovative applications for user interaction and User Generated Content (UGC), in particular User Generated Meta Data (UGMD), will be developed, as it adds a semantic component to these applications. Based on a review of and inspiration from existing approaches (Carminati, Ferrari, & Perego, 2012; Choudhury, Breslin, & Passant, 2009; Garcia-Castro, Labarga, Garcia, et al., 2010; Kim, Scerri, Passant, et al., 2011; Marshall, 2009; van Hooland, 2006; Von Ahn & Dabbish, 2008; Zarro & Allen, 2010), this document specifies the functionality that will be implemented in the applications Waisda? and PyBossa. For both applications prototype code will be delivered and is described in the last section of the document. For the remaining project phase, a process of feeding back the user-generated metadata into Europeana will be dealt with as well as the extension of the prototype code with more SKOS vocabularies. Also, the representation of UGMD in EDM will be tackled. One way of accomplishing this that will be investigated is using the Open Annotation Model (Hunter et al., 2010; Haslhofer et al., 2011 & 2012). 2. Use cases Voss (2007) based on Marlow et al. (2006) formulates questions that need to be answered in order to classify the typology of tagging systems and that help to express use cases for tagging systems. The questions have been considered for describing both systems (the list of questions can be found in the Annex). 2.1. Waisda? Waisda? is a crowdsourcing video annotation software that has been released as an open source framework by Sound and Vision. Waisda? will be further developed mainly through choosing additional controlled vocabularies that allow for better contextualization of objects and experimenting with an “emotional” vocabulary. An instance of the application will be build with data from the Europeana API, which is a substantial infrastructural alteration. The idea for the future (after the project ends) is either for Europeana themselves to offer such a game application from their website or that contributing data providers make it available directly on their own website. Generally, it was agreed to have the game interface translated from Dutch into English. Further multilingual aspects will be taken into account in the second prototyping / development phase (starting April 2013). The following description contains the current state, marked with the round black bulleting points, as well as the alterations, additions, etc. of the functional specifications, marked with the arrowed bulletin points. The user browses to the website of the game. Every guest user can play the game; there is no need for registration. Yet, at the end of the game the user has the option to register in order to save his score. ➢ While this keeps a low entry barrier for the user, the game needs to encourage the registration more. Only registered users can be analysed and their trustworthiness of contributions can then be assessed in the future. On the game recap page (at the end of the game), there must be a clear link that takes the user to the registration page. A separate box prominently displayed should be added. (cf. Figure 1 depicting the recap page). The current configuration of the landing page loads five random videos to play the game with, for each respective 'channel' (a channel is a subset of the entire database of available videos, for instance based on a certain series of episodes or videos from a certain provider). If there are already game sessions with players ready to start, a pop-up will enter the screen to notify the user of the possibility of joining a game with other users. The users are still free to ignore this pop-up and can also start their own game, based on one of the five channels.) - No alteration foreseen. In Europeana, a channel is a collection. The user clicks on a video to start playing (they can start playing anonymously). - Cf. first comment. The user is referred to a ‘waiting room’ with a 20 second start-up time, that allows the game session to attract additional players and/or load previous sessions as ‘ghost players’ (in this ‘waiting room’ players also get the basic game instructions). - For the second development phase, a more efficient use of the waiting time, in particular for recurring users will be considered (e.g. fulfilling small tasks, the option to register). The game starts and the video plays from start to end. The user can immediately start tagging in the entry field below the video. When a user hits the [ENTER] button, the tag entry is added to the database. Tag entries include temporal information related to the video, based on the moment the player starts typing and the moment a tag is entered. - Each tag entry earns points for the players, according to the following schema: - Tag entry: 5 - Match (with another user’s tag): 50 - Introduction of a tag (once it is matched by another player): 100 bonus - Geographical name: 25 bonus - Person name: 25 bonus D7.5: Functional specifications for social semantic functions - If tag entries added by players match within a ‘window’ of 10 seconds, the players earn points. Following the Games with a Purpose principle as developed by Louis von Ahn (von Ahn & Dabbish, 2008), the assumption is that blind matches constitute relevant tags. - Introducing a word to be matched for the first time for a video item, earns the player points. - Thanks to the use of Cornetto (Dutch language version of Wordnet) in the background, players can also score points by matching with synonyms of words used by opponents. - Players get bonus points for tag entries that are: - Geographical names (matched against the GTAA thesaurus geographical names axis) - Person names (matched against the GTAA thesaurus person names axis) As semantic disambiguation is an important aspect of user-generated metadata, the system cannot rely on correctly matching the users’ tags to the correct concept in the vocabulary. This is especially true when a new concept is introduced for a video, as the system has no other context to rely on. In the second development phase, we will implement the following functionality for semantic disambiguation: On the game recap page, the user has the option to review tags that could not be matched unambiguously and then disambiguate the tags and “approve” automatic matches to the controlled vocabularies. 5-10 tags from opponent players will be presented to the user and the disambiguation will earn the user additional points (25 points per match analogously to the matching of a geographical or person name). As part of the second development phase, we also contemplate to experiment with a trustworthiness score of users and their tags respectively. Ideas for this phase include: possible cooperation with the SEALINCMedia project, age of the account, consistency in playing the game, average number of matches related to all tags entered, etc. In this phase, infrastructural issues will be important as well, such as when to calculate the trustworthiness score, how to store it (for each annotation? What are the implications on the system’s performance?), how to export it, etc. For the moment, a basic ratio should be stored for each user, after each game: ratio of simple (non-matched) tags vs. matched tags. Additionally (to the GTAA Thesaurus), the system should consider additional controlled vocabularies for checking users’ tags. The following table is based on the work from Work Package 2 in the EuropeanaConnect project and represents a list of controlled vocabularies that have been available in the “semantic data layer”: <table> <thead> <tr> <th>Vocabulary name</th> <th>Lang.</th> <th>Description/Type</th> <th>Comments/status</th> </tr> </thead> <tbody> <tr> <td>Pico</td> <td>lt</td> <td>Concepts</td> <td></td> </tr> <tr> <td>GTAA</td> <td>nl</td> <td>Concepts, Geo</td> <td></td> </tr> <tr> <td>SC Ran</td> <td>en</td> <td>Concepts</td> <td></td> </tr> <tr> <td>Lausanne musea thesaurus</td> <td>fr</td> <td>Concepts</td> <td></td> </tr> <tr> <td>Fondazione Zerri vocabularies</td> <td>it</td> <td>Concepts</td> <td></td> </tr> <tr> <td>SWD</td> <td>de</td> <td>Concepts</td> <td></td> </tr> <tr> <td>Cornetto</td> <td>nl</td> <td>Concepts</td> <td></td> </tr> <tr> <td>DISMARC</td> <td>en</td> <td>Concepts</td> <td></td> </tr> <tr> <td>Iconclass</td> <td>de,en,fr</td> <td>Concepts</td> <td></td> </tr> <tr> <td>LCSH</td> <td>en</td> <td>Concepts</td> <td></td> </tr> <tr> <td>AATNed</td> <td>nl</td> <td>Concepts</td> <td></td> </tr> <tr> <td>Unesco</td> <td>en,es,fr</td> <td>Concepts</td> <td></td> </tr> </tbody> </table> Table 1. Vocabulary selection from EuropeanaConnect <table> <thead> <tr> <th>Vocabulary Name</th> <th>Language</th> <th>Concepts</th> <th>Notes</th> </tr> </thead> <tbody> <tr> <td>Wordnet 2.0</td> <td>en</td> <td>Concepts</td> <td></td> </tr> <tr> <td>Geonames</td> <td>mul</td> <td>Geo</td> <td></td> </tr> <tr> <td>WOLF Wordnet</td> <td>fr</td> <td>Concepts</td> <td></td> </tr> <tr> <td>Wordnet 3.0</td> <td>en</td> <td>Concepts</td> <td></td> </tr> <tr> <td>Rameau</td> <td>fr</td> <td>Concepts, Geo</td> <td></td> </tr> <tr> <td>Austrian Mediathek thesaurus</td> <td>de</td> <td>Concepts</td> <td></td> </tr> <tr> <td>Amsterdam Museum Vocabularies</td> <td>nl</td> <td>Concepts, Geo, Persons</td> <td></td> </tr> <tr> <td>EUScreen</td> <td>ca, da, de, en, el, hu, it, nl, sv</td> <td>Concepts</td> <td></td> </tr> <tr> <td>Bibliopolis thesaurus</td> <td>nl</td> <td>Concepts</td> <td></td> </tr> <tr> <td>OSZK Thesaurus</td> <td>hu</td> <td>Concepts, Geo</td> <td></td> </tr> <tr> <td>Polish Subject headings (JHP BN)</td> <td>pl</td> <td>Concepts</td> <td></td> </tr> <tr> <td>GeonetPT</td> <td>pt</td> <td>Geo</td> <td>For exploitation and sharing within the Europeana network</td> </tr> <tr> <td>VIAF</td> <td>mul</td> <td>Persons</td> <td></td> </tr> <tr> <td>CSIC (Spanish subject headings)</td> <td>es</td> <td>Concepts</td> <td>only for use in Europeana</td> </tr> <tr> <td>Getty AAT</td> <td>en</td> <td>Concepts</td> <td>only for research purposes, in Europeana</td> </tr> <tr> <td>Getty ULAN</td> <td>mul (labels are not language-tagged)</td> <td>Persons</td> <td>only for research purposes, in Europeana</td> </tr> <tr> <td>Getty TGN</td> <td>mul (but labels are not language-tagged)</td> <td>only for research purposes, in Europeana</td> <td></td> </tr> <tr> <td>Joconde</td> <td>Fr</td> <td>Concepts, Geo, Persons</td> <td>only for research purposes, in Europeana</td> </tr> </tbody> </table> Even though most of these vocabularies are quite specific, it will be still useful to use them in connection with specific collections. Therefore, the application will support the possibility to configure individual tasks (which would be done by the institution employing the game application). Specific collections (more than one) can be chosen to be part of the tagging game and according to those, appropriate controlled vocabularies can be chosen to be used for matching. For the prototype code, the Open Images collection will be chosen and the EU screen vocabulary will be used to match the tagged terms. In general, a generic tool will be developed that will allow to add collections and --- 1 Gligorov et al. (2011) find that 59% of the users’ tags could not be verified or found in a vocabulary. It is obvious, that more matches were found in the general Cornetto than in the GTAA. That is why, it is important to choose an “appropriate” vocabulary, corresponding to the collection. vocabulary. For DBpedia, only the Wikipedia categories\(^2\) are available in SKOS\(^3\). Further discussion is needed whether DBpedia could still be used as well as other larger vocabularies that have been used for semantic enrichment of Europeana (Geonames and GEMET). As time period vocabulary, we will wait for the results from the Europeana 1914-18 project that will investigate a combination of DBpedia and LCSH. The methodology can then be re-used to extract further time periods from DBpedia that go beyond World War I. The prototype showcases the infrastructure for doing this with GTAA – the actual importing of SKOS vocabularies will be done as part of phase two. Moreover, we will experiment with an “emotional” vocabulary. So, in addition to tagging the game with terms, in the instructions, the user will be encouraged also to tag the video with emoticons. These will be matched against an “emoticon vocabulary” and the points will be handled the same way as with the other controlled vocabularies. This is especially useful for the multilingual user. The use of this metadata for the search (in the Europeana interface or other applications) can be investigated separately. An emoticon vocabulary has been compiled consisting of a list of standardised emoticons from Wikipedia (http://en.wikipedia.org/wiki/List_of_emoticons#cite_note-cool-smiley-4), complemented by input from an Emotion Ontology\(^4\). After the video is done playing, the user is redirected to a game recap page. This provides the user with a summary of the points that were gathered during the game session, how they performed in relation to the opponents during the game sessions and an overview of all tag entries that received points and the rationale behind this. - Users that want to save their score and compete for a spot in the leader boards can register an account by providing the system with an e-mail address, password and user name (they also have to comply with the Terms of Use); they will also receive their own profile page with a game history and personal statistics. - As mentioned before, the game recap page must have a clear link which encourages the user to register and save their score. Tags from recurring users with high scores could be treated differently in terms of trustworthiness of their contribution. Yet, this will not be part of the functional specifications or the prototype code but could be part of further research during the rest of the project. Users are also able to share their score on several social media networks (the AddThis Plugin\(^5\) is used). - No alteration foreseen. ### 2.2. PyBossa PyBossa is a platform for creating and running crowd-sourcing applications that utilize online assistance in performing tasks that require human cognition, knowledge or intelligence such as image classification, transcription, geocoding and more (Brinkerink, 2012). For this task, we take the instance of PyBossa that was created for the Amsterdam Museum as a baseline. \(^2\) http://downloads.dbpedia.org/preview.php?file=3.8_sl_en_sl_skos_categories_en.nt.bz2 \(^3\) http://wiki.dbpedia.org/Downloads38#categories-skos \(^4\) http://bioportal.bioontology.org/ontologies/1666 \(^5\) http://www.addthis.com/ and adapt it. In this sense, we understand and turn PyBossa into a generic platform for creating online tagging games for still images that lets users perform classification tasks. Analogously to Waisda?, an instance of the application will be build with data from the Europeana API. Also for this application, the idea for the future (after the project ends) is either for Europeana themselves to offer such a game application from their website or that contributing data providers can easily create their own instance of an online tagging game for still images, based on a selection of Europeana records. Europeana does not host the actual objects (in this case the still images) but only the metadata records. This requires that selected collections for an instance of the tagging game contain resolvable references to the actual online content, hosted by the data provider (Brinkerink, 2012). Generally, it was agreed to have the game interface translated from Dutch into English. Further multilingual aspects will be taken into account in the second prototyping / development phase (starting April 2013). The following description contains the current state, marked with the round black bulleting points, as well as the alterations, additions, etc. of the functional specifications, marked with the arrowed bulletin points. Editors (in this case the Amsterdam Museum) can create series and questions (tasks). In Figure 2 to the right, editors can select a collection set and preview the relevance of this set. To the left, the range of questions is presented and can be edited. - create new questions (= information needs) in the CMS - determine which tags are saved per task on basis of the responses. - search the linked collection database to create new sets of the collection (= series) - determine what questions within a set should be answered ![Figure 2. Editor Page](image) - Editors should be able to compile tasks that consist of a collection in Europeana, then select appropriate vocabularies (that can be used to describe the objects) for it and select specific tasks (described in the user section): linking documents, correct metadata, correct enrichments. The selection of collections can be limited to a certain data provider, but can also be a combination of several collections from different data providers or a thematic selection. The selected tasks can be combined to create a set of tasks – this functionality will be implemented in a later phase. The crux of making this work effectively is more about matching a collection with a certain ‘information need’ to a specific task that supports added value for this particular need. For each task editors can select one of the metadata profiles from the Europeana Portal (e.g. full, standard, search result profile) that will then be presented with the image(s) to the user. As part of the correcting metadata fields, the editor should have the possibility to choose specific metadata fields that will be “open for correction”. In the admin section editors can perform different tasks that are related specifically to the instance of the Amsterdam Museum which limited the game to specific user groups. In general, the game should be open to any user. So, we will not need the restriction to be part of a school or any specific group. We will not need the possibility of limiting the words that are saved as tags; also grouping of users will not be necessary. Users can: - visit the homepage of the tagging game - register - log in - view what % of the set (records) is tagged (desired) - see who did the most tags (desired) - can re-request their password - after log in choose which series (created by editors) to tag (cf. Figure 3) The above-mentioned “desired functionality” could be implemented for the prototype with a low priority. For a user to see the progress on his task should help keeping the drop-out-rate low. This could be implemented as a progress bar covering the % of how many tasks of a task set a user has already completed. Additionally, a scoreboard, as available for Waisda?, could be useful to stimulate competition and participation, but is not mandatory. The user will be presented with a set of tasks for a specific collection as specified by the editor (cf. section on editor for details on what constitutes a set of tasks). For the prototype, this will be a flat list of one collection and the three different tasks. Later on, the user should be able to choose between different collection as well as tasks (the order of this choice still needs to be determined). - The three different types of tasks are - Linking documents: PyBossa should use the information on the standard IR-similarity that the Europeana API transmits, to present two images to the user that are similar to each other. The user should also see some metadata – I would suggest the title of the object and the creator. The user will then need to judge the two images and be presented with the question underneath the two images “Are these two images similar to each other?” and the possibility to answer with “yes/no” (via a radio button); and then underneath it, it should ask “Can you specify what type of relationship these two images have?” and have a field where the user then can type in the specification of the type of relationship. Here, we can use the typology of clusters that was developed in the course of an experiment by Europeana and OCLC (Charles & Wang, 2012): - Same objects/duplicates - Part of another Cultural Heritage Object (CHO) - Views of the same CHO - Derivative work - Part of thematic cluster - Collections In the second development phase, there could be experiments with more than two images, e.g. presenting the user with clusters of images to comment on. An example could be this image: http://www.europeana.eu/portal/record/2023707/1024E4CE3FE5E4D9E99A5A27089A6C0D7DB49C49.html At the bottom of the metadata “similar content” is displayed and for example this image could be displayed as the second one. http://www.europeana.eu/portal/record/2023707/22958D7D4483DD4A5BB3217C5AB3D17F01FDF375.html Then the user is asked if he agrees that these images are similar to each other. And the type of relationship would be either there is the same person depicted or in both pictures there are women or the picture is about hats. - Correcting metadata: For the task of correcting metadata, the user will be presented with only one image at a time. The metadata fields he will see with the image should be determined by the editor compiling the task. So, selecting the metadata fields will be made an option in the admin section, when the editor selects the collection (re-using the metadata profiles). Only the metadata fields that were selected by the editor as “open to correction” will then have underneath or next to each field the question “Do you agree with the description of the image?” as well as the answer possibilities “yes” and “no” (also via a radio button). Then again, if the answer is no, the user should get the possibility to provide a correct tag. In the second development phase, experiments with OpenSKOS will be made to see if it could be used for the autocompletion functionality. If the answer is yes, we still should allow for additional tags and ask the user “Can you provide additional and/or more specific information?” and then provide the same box as if he would correct the metadata but store this one as enrichment. In the end, the question is how a quality control of these corrections and additional tags can be managed. A manual check by the editor could be implemented at a later stage as “meta-tasks” that will check user-generated metadata for accuracy. Again, similar to Waisda? this will be left for future research (taking the trustworthiness of the D7.5: Functional specifications for social semantic functions users into account). And we would need to consider (at least some of) these strategies for semantic and multilingual enrichments (Olensky, Stiller & Dröge, 2012) while matching tags to controlled vocabularies (Table 2). <table> <thead> <tr> <th>Level</th> <th>Areas of concern</th> <th>Strategic execution</th> </tr> </thead> <tbody> <tr> <td>Metadata</td> <td>Metadata quality</td> <td>Quality score for metadata, no enrichments below the score, data cleaning process</td> </tr> <tr> <td>Metadata</td> <td>Structure of metadata</td> <td>Data normalization e.g. surname forename, rules for syntax, validate fields against a schema, consistency check for field refinements</td> </tr> <tr> <td>Vocabulary</td> <td>Choice of vocabulary</td> <td>Choose domain-specific vocabulary or a subset of a vocabulary, exclusion of parts of the vocabulary</td> </tr> <tr> <td>Vocabulary</td> <td>Scope of enrichment</td> <td>Choose fields to be enriched with a specific vocabulary or even limit enrichment to subsets or specific collections</td> </tr> <tr> <td>Workflow</td> <td>Semantics</td> <td>Disambiguate metadata values and use context</td> </tr> <tr> <td>Workflow</td> <td>Named entities</td> <td>Apply automatic named entity recognition</td> </tr> <tr> <td>Workflow</td> <td>Cross-lingual ambiguities</td> <td>Metadata records and enrichment term need to have the same language</td> </tr> <tr> <td>Workflow</td> <td>Weighting of enrichments</td> <td>If multiple values in one metadata field are enriched, they should be weighted according to their relevance</td> </tr> <tr> <td>Workflow</td> <td>Matching rules</td> <td>Use exact matches, include variants from the controlled vocabulary, rule on how to enrich multiple values in a field</td> </tr> <tr> <td>Workflow</td> <td>Quality assurance</td> <td>Quality checks (automatically or manually) before enrichments “go live”</td> </tr> <tr> <td>Workflow</td> <td>Quality assessment</td> <td>Assess the scope of the enrichments with regard to their occurrence in search results</td> </tr> </tbody> </table> Table 2. Framework of strategies for semantic and multilingual enrichments Here an example could be this image: http://www.europeana.eu/portal/record/09405u/3A69262579AA18C34F2616C08AA8587922E954D7.html which holds the Creator “Root”. So basically the user would mark this as incorrect, he might have information on the correct creator; but in this case it is rather unlikely. - Correcting enrichments: This task is very similar to the previous one on correcting metadata. Only here the user will be presented some basic metadata information, like title of the object, date and creator and then he will see the metadata field(s) that have been enriched as well as the actual enrichment. The same principle as for the correcting metadata should be applied asking for the agreement of the user. In case of disagreement, he should be able to type in his suggestion – here an auto-completion box with the terms from the respective vocabularies used for enrichment makes sense: GEMET Thesaurus for dc:subject, dc:type, dcterms:alternative; DBpedia (or DBpedix\textsuperscript{6}) for dc:contributor, dc:creator; and GeoNames for dc:coverage, dcterms:spatial. Like Waisda?, we will use as Time Ontology something methodologically based on the results of the experiment from Europeana 1914-18 with DBpedia and LCSH. And the same considerations about the trustworthiness and the matching with the vocabularies need to be applied as described in the upper section on correcting metadata. As an example I take one the wrong enrichments from our evaluation: http://www.europeana.eu/portal/record/07202/49279933A922E75938223A44C27767724BC8E2F9.html. This image was enriched with Adolphe Mouron Cassandre, although the creator is Cassandre Guggiari. So, it is the wrong person and the reason behind this is that the matching tool did not consider the structure of the name (first vs. last) and accepted a partly match as correct match. The user would then be able to mark the enrichment as wrong and through DBpedix (with the autocompletion) try to find the correct creator. \textsuperscript{6} The use of DBpedix (http://europeanalabs.eu/browser/contrib/ait/trunk/dbpedix) would be worth experimenting with. DBpedix is a semantic Tag-Autocompletion component. It is a backend to help users disambiguate their tags using DBpedia as the underlying ontology (providing also the corresponding URI) and source of multilingual labels. 3. Prototype In order to demonstrate and test the suggested alterations in this document, prototype code has been delivered that already includes part of the alterations suggested in this document and will take aboard and further investigate them as part of the further development of the innovative applications that is part of Task 7.2. This section describes the current state of both prototype instances (Waisda? and PyBossa). Both prototypes have been translated into English as described in the functional specifications. 3.1. Waisda? for Europeana http://waisda.tuxic.nl:8080/ (prototype instance) https://github.com/beeldengeluid/waisda/tree/master-0.0.2-SNAPSHOT (prototype code repository) 3.1.1. Europeana Video Collection Importer To facilitate the Europeana Network in setting up an instance of the Waisda? Video Labeling game, a reusable Europeana Video Collection Importer was added to the codebase of Waisda?, to allow for importing video datasets via the Europeana API. Create a admin user To import Europeana data the user must log in with an admin enabled user first. To create an admin user, register a new user in Waisda? frontend and set corresponding User table record's admin flag to '1'. Enter a search query in import page When logged in, browse to URL http://waisda.host.name/europeanaimport/start. The screen shown provides the user with a search input box where the user can enter a Europeana search query. See image below: The items Europeana finds based on this search query are imported into the Waisda? database. After entering a search query and hitting the 'start' button, the import page feeds back the total number of items found (any type, not only VIDEO). See image below: If the search query doesn't meet the expectation, another query can be entered and the import page shows the total number of items to be imported again. If this number meets the expectation, hit the 'start' button again to actually start importing the items. See image below: Note that a search will be batched into one or more subsearches, with each subsearch fetching at most a configured number of items (see Config and Setup). **Search Query formats** Please have a look at Europeana API documentation to learn more about query formats. Basically, Europeana can query most fields it stores. For example, to look for a set of items of a given data provider one has to use the following search query: ``` provider_aggregation_edm_dataProvider:[Name of collection] ``` Where [Name of collection] is the name of the dataset to import (for example: 'Open Beelden') Import filtering The importer applies a filter to perform a best-effort importing only valid videos. A video is considered valid if: - imageUrl <= 1024 characters - sourceUrl <= 1024 characters - sourceUrl matches one of the 'accepted URL' expressions (see Config and Setup section) - the video source has duration filled in correctly\(^7\) - the video hasn't been imported yet. Videos that have been imported already will be updated instead Note that video source URLs are preferred to be read from the edm:isShownBy field. If not available, the importer analyzes the edm:WebResources field for a valid video URL. If none of these fields provides a proper video URL, the item is skipped. Import progress When an import is running, the importer page shows a summary that indicates the progress and the import log. The progress indication shows: - currently imported title - current index number - number of total items The import log shows the result of each imported item using the log levels INFO, WARNING and ERROR. So it logs when an URL is too long, no duration filled in etc. See image below: Beside the frontend logging, Waisda? also creates an import log file named europeanaimport.log. Stop the importer The importer can run only one process at a time. It does not allow to start more than 1 import (at least when deployed as a single active node). To stop a currently running import, hit the stop button. The import log will show that the stop command was issued. \(^7\) Format according to: http://en.wikipedia.org/wiki/ISO_8601#Durations 3.1.2. Waisda? for Europeana Prototype Instance To showcase the possibilities with the further developed Waisda? codebase, a publicly available prototype instance was set up and clearly branded as a Europeana related project outcome (Figure 4). As suggested in this document the prototype instance has implemented a call-to-action reminding unanimous guest players to register an account, as part of the game recap. This link directs them to a registration page and allows them to save points they have already gathered during their guest session (Figure 5 and 6). D7.5: Functional specifications for social semantic functions Figure 5. Game recap with a call-to-action for registration The current version of the prototype instance tries to match tag entries against two controlled-vocabularies, namely the GTAA person names and the GTAA geographical names. At a later stage this will be expanded with additional controlled vocabularies that can be added to the game using a generic importer for SKOS vocabularies. In the example below (Figure 7) the player scores points for using a term from GTAA person names (Salvador Dali) and a term from GTAA geographical names (Rotterdam). In the game recap (Figure 8) these matches with different vocabulary terms (called 'dictionary matches in the game') can be identified with their own icon (a puppet for the GTAA person names terms and a pin for the GTAA geographical names). 3.2. PyBossa for Europeana prototype code repositories: - Europeana client API: [https://github.com/mk270/europeana-search](https://github.com/mk270/europeana-search) - PyBossa “upstream” features: [https://github.com/PyBossa/pybossa](https://github.com/PyBossa/pybossa) - Bespoke PyBossa tools: [https://github.com/mk270/pybossa](https://github.com/mk270/pybossa) 3.2.1. PyBossa task importer and task presenter The Europeana Search client API is also available as “europeana-search” from [http://pypi.python.org](http://pypi.python.org), and thus by “pip install europeana-search”; it is a dependency of the Bespoke PyBossa tools. PyBossa upstream features include: - Heroku deployment support - Importer generalisation - Two major hygiene fixes to make code intelligible - Fixes to bugs in task generation templates Bespoke PyBossa tools: - Europeana API task importer - Multi-image task presenter support - Task presenters: - Metadata correction game There are lots of branches of code in the mk270/pybossa fork of PyBossa; the ones relevant to this project are: **culttag-redux** - this set of tools are specially made for the tagging game but of no interest for the users of the platform PyBossa, because they are too specific. **culttag-deployable** - the tools above, plus some Heroku-specific configuration information To understand the meaning of “task presenter” and “task importer”, see [https://github.com/PyBossa/pybossa/blob/master/doc/overview.rst](https://github.com/PyBossa/pybossa/blob/master/doc/overview.rst) **Licensing:** the source is under a mixture of GNU Affero GPL v3.0 and Apache Software License v2.0 licences. ### 3.2.2. PyBossa tagging app walkthrough **Sign up** Go to [http://culttag6.herokuapp.com](http://culttag6.herokuapp.com) Click “Sign In” (unless for some reason you already have an account that’s logged in) Ignore the input boxes and click “Create a New Account” Enter details and click “Create an account” (This should log you in) Create an app Click "Create" from the navigation bar at the top Fill in the form - note that “Short Name” should be lower case, no spaces; e.g., “myapp1” Click “Create the application”; you should get the app control panel Click “Edit the task presenter” Go the Cultural Tagging Game box and click “Use the image template” Ignore the HTML text and just click “Update [...] presenter”; you should be returned to the app control panel Click “Import tasks” Go to the Europeana box and click “Use the Europeana API” D7.5: Functional specifications for social semantic functions Add a search string, e.g., “rembrandt” Add your API key (you can use: j5x8xiiJE) Click “Import” once. Be prepared to wait a few seconds before the page refreshes You should be taken to the app landing page Try an app From the app landing page reached above, click “Start contributing now” D7.5: Functional specifications for social semantic functions **Settings** From the login menu (in the menu bar, most to the right) My Applications can be accessed. ![Application interface screenshot] Here you find the app control panel as described under ‘Create an app’. In the left menu you can find important features as export tasks (metadata), an oversight of tasks and statistics. 4. References 5. Annex Questions from Voss (2007) classifying the typology of tagging systems: Tagging Rights Who is allowed to tag resources? Can any user tag any resource or are there restrictions? Are restrictions based on resources, tags, or users? Who decides on restrictions? Is there a distinction between tags by different types of users and resources? Source of Resources Do users contribute resources and have resources been created or just supplied by users? Or do users tag resources that are already in the system? Who decides which resources are tagged? Resource Representation What kind of resource is being tagged? How are resources presented while tagging (autopsi principle)? Tagging Feedback How does the interface support tag entry? Do users see other tags assigned to the resource by other users or other resources tagged with the same tags? Does the system suggest tags and if so based on which algorithms? Does the system reject inappropriate tags? Tag Aggregation Can a tag be assigned only once to a resource (set-model) or can the same tag be assigned multiple times (bag-model with aggregation)? Vocabulary control Is there a restriction on which tags to use and which tags not to use? Are tags created while tagging or is management of the vocabulary a separated task? Who manages the vocabulary, how frequently is it updated, and how are changes recorded? Vocabulary Connectivity Are tags connected with relations? Are relations associative (authority file), monohierarchical (classification or taxonomy), multihierarchical (thesaurus), or typed (ontology)? Where do the relations come from? Are relations limited to the common vocabulary (precoordination) or can they dynamically be used in tagging (postcoordination with syntactic indexing)? Resource Connectivity How are resources connected to each other with links or grouped hierarchically? Can resources be tagged on different hierarchy levels? How are connections created? Automatic Tagging Is tagging enriched with automatically created tags and relations (for instance file types, automatic expansion of terms etc.)?
{"Source-Url": "https://pro.europeana.eu/files/Europeana_Professional/Projects/Project_list/Europeana_Version2/Deliverables/D7.5-%20Functional%20specifications%20for%20social%20semantic%20functions.pdf", "len_cl100k_base": 9793, "olmocr-version": "0.1.53", "pdf-total-pages": 28, "total-fallback-pages": 0, "total-input-tokens": 57627, "total-output-tokens": 11480, "length": "2e13", "weborganizer": {"__label__adult": 0.0004088878631591797, "__label__art_design": 0.0008420944213867188, "__label__crime_law": 0.0003919601440429687, "__label__education_jobs": 0.0021572113037109375, "__label__entertainment": 0.0002899169921875, "__label__fashion_beauty": 0.00017523765563964844, "__label__finance_business": 0.0003101825714111328, "__label__food_dining": 0.00036835670471191406, "__label__games": 0.0023632049560546875, "__label__hardware": 0.000499725341796875, "__label__health": 0.000255584716796875, "__label__history": 0.000690460205078125, "__label__home_hobbies": 9.948015213012697e-05, "__label__industrial": 0.0002269744873046875, "__label__literature": 0.00104522705078125, "__label__politics": 0.0003879070281982422, "__label__religion": 0.0004527568817138672, "__label__science_tech": 0.035491943359375, "__label__social_life": 0.0002536773681640625, "__label__software": 0.044677734375, "__label__software_dev": 0.90771484375, "__label__sports_fitness": 0.0002465248107910156, "__label__transportation": 0.00028252601623535156, "__label__travel": 0.00026726722717285156}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 46729, 0.0181]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 46729, 0.15636]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 46729, 0.85213]], "google_gemma-3-12b-it_contains_pii": [[0, 411, false], [411, 2224, null], [2224, 3698, null], [3698, 5036, null], [5036, 7127, null], [7127, 8928, null], [8928, 12719, null], [12719, 16588, null], [16588, 19835, null], [19835, 22073, null], [22073, 23999, null], [23999, 27668, null], [27668, 30801, null], [30801, 32173, null], [32173, 33896, null], [33896, 34766, null], [34766, 36322, null], [36322, 36889, null], [36889, 37012, null], [37012, 37748, null], [37748, 38796, null], [38796, 39828, null], [39828, 40342, null], [40342, 40695, null], [40695, 41087, null], [41087, 44285, null], [44285, 44552, null], [44552, 46729, null]], "google_gemma-3-12b-it_is_public_document": [[0, 411, true], [411, 2224, null], [2224, 3698, null], [3698, 5036, null], [5036, 7127, null], [7127, 8928, null], [8928, 12719, null], [12719, 16588, null], [16588, 19835, null], [19835, 22073, null], [22073, 23999, null], [23999, 27668, null], [27668, 30801, null], [30801, 32173, null], [32173, 33896, null], [33896, 34766, null], [34766, 36322, null], [36322, 36889, null], [36889, 37012, null], [37012, 37748, null], [37748, 38796, null], [38796, 39828, null], [39828, 40342, null], [40342, 40695, null], [40695, 41087, null], [41087, 44285, null], [44285, 44552, null], [44552, 46729, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 46729, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 46729, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 46729, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 46729, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 46729, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 46729, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 46729, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 46729, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 46729, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 46729, null]], "pdf_page_numbers": [[0, 411, 1], [411, 2224, 2], [2224, 3698, 3], [3698, 5036, 4], [5036, 7127, 5], [7127, 8928, 6], [8928, 12719, 7], [12719, 16588, 8], [16588, 19835, 9], [19835, 22073, 10], [22073, 23999, 11], [23999, 27668, 12], [27668, 30801, 13], [30801, 32173, 14], [32173, 33896, 15], [33896, 34766, 16], [34766, 36322, 17], [36322, 36889, 18], [36889, 37012, 19], [37012, 37748, 20], [37748, 38796, 21], [38796, 39828, 22], [39828, 40342, 23], [40342, 40695, 24], [40695, 41087, 25], [41087, 44285, 26], [44285, 44552, 27], [44552, 46729, 28]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 46729, 0.18405]]}
olmocr_science_pdfs
2024-12-07
2024-12-07
685db607fd6049394b08094f8fad9519c7c22731
[REMOVED]
{"len_cl100k_base": 8742, "olmocr-version": "0.1.53", "pdf-total-pages": 15, "total-fallback-pages": 0, "total-input-tokens": 40204, "total-output-tokens": 10483, "length": "2e13", "weborganizer": {"__label__adult": 0.0003578662872314453, "__label__art_design": 0.0002796649932861328, "__label__crime_law": 0.0002560615539550781, "__label__education_jobs": 0.0005488395690917969, "__label__entertainment": 4.4465065002441406e-05, "__label__fashion_beauty": 0.0001310110092163086, "__label__finance_business": 0.0001500844955444336, "__label__food_dining": 0.0003523826599121094, "__label__games": 0.0003974437713623047, "__label__hardware": 0.0008387565612792969, "__label__health": 0.0003740787506103515, "__label__history": 0.00018930435180664065, "__label__home_hobbies": 8.374452590942383e-05, "__label__industrial": 0.0003342628479003906, "__label__literature": 0.0002211332321166992, "__label__politics": 0.00022470951080322263, "__label__religion": 0.0004367828369140625, "__label__science_tech": 0.005367279052734375, "__label__social_life": 6.490945816040039e-05, "__label__software": 0.0027923583984375, "__label__software_dev": 0.98583984375, "__label__sports_fitness": 0.0002727508544921875, "__label__transportation": 0.0004780292510986328, "__label__travel": 0.00017762184143066406}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 42617, 0.00982]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 42617, 0.48893]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 42617, 0.88857]], "google_gemma-3-12b-it_contains_pii": [[0, 2801, false], [2801, 6333, null], [6333, 9318, null], [9318, 11899, null], [11899, 13673, null], [13673, 15985, null], [15985, 17660, null], [17660, 21183, null], [21183, 23734, null], [23734, 26601, null], [26601, 30165, null], [30165, 32868, null], [32868, 36415, null], [36415, 39411, null], [39411, 42617, null]], "google_gemma-3-12b-it_is_public_document": [[0, 2801, true], [2801, 6333, null], [6333, 9318, null], [9318, 11899, null], [11899, 13673, null], [13673, 15985, null], [15985, 17660, null], [17660, 21183, null], [21183, 23734, null], [23734, 26601, null], [26601, 30165, null], [30165, 32868, null], [32868, 36415, null], [36415, 39411, null], [39411, 42617, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 42617, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 42617, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 42617, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 42617, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 42617, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 42617, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 42617, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 42617, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 42617, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 42617, null]], "pdf_page_numbers": [[0, 2801, 1], [2801, 6333, 2], [6333, 9318, 3], [9318, 11899, 4], [11899, 13673, 5], [13673, 15985, 6], [15985, 17660, 7], [17660, 21183, 8], [21183, 23734, 9], [23734, 26601, 10], [26601, 30165, 11], [30165, 32868, 12], [32868, 36415, 13], [36415, 39411, 14], [39411, 42617, 15]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 42617, 0.02041]]}
olmocr_science_pdfs
2024-12-10
2024-12-10
304ae88c36aec432838343b8889b2e183fbab154
An Architecture for Automated Software Maintenance Alex Sellink and Chris Verhoef University of Amsterdam, Programming Research Group Kruislaan 403, 1098 SJ Amsterdam, The Netherlands alex@wins.uva.nl, x@wins.uva.nl Abstract We developed an assembly line to implement certain specific changes in a stockbroking system written in COBOL with embedded SQL. The changes were proposed by the maintenance team of the system. Using our architecture, it took a few hours to implement the conditional transformations from the code examples we obtained from the maintenance team. Then we could carry out the tasks completely automated. We report on the transformations, their implementation and the architecture we used. It is the intention of the company that owns the COBOL/SQL to use our architecture for similar tasks. This study was carried out in order to give the company that owns the code an indication of the effort it takes, the development process of the components that carry out such tasks, and the process to change software using our architecture. Categories and Subject Description: D.2.6 [Software Engineering]: Programming Environments—Interactive; D.2.7 [Software Engineering]: Distribution and Maintenance—Restructuring; Additional Key Words and Phrases: Reengineering, System renovation, Software renovation factory, Automated software maintenance, Automated redesign, COBOL, embedded SQL. 1 Introduction During software maintenance in large companies, it appears to be the case that many and diverse changes to entire systems have to be made on a daily basis. Those tasks may seem relatively simple, but not that simple that they can be automated using ad-hoc tools that have no knowledge of the grammar of the code that has to be changed. Due to this fact, this type of maintenance has to be done by hand. Consequently, such maintenance uses a lot of precious capacity. First, since the task has to be done by hand and, second, since it is easy to overlook a case or to make mistakes. Let us give a few examples of typical tasks. The addition of explicit scope terminators in COBOL applications is a task that improves the readability of code. We learned from reliable sources that someone at a Dutch bank worked a year on adding explicit scope terminators manually. To make a comparison, we added in a mortgage system approximately 27 END-IFs per minute using a component that took less than an hour to implement using our architecture. More important, the automated process does not miss cases, makes no typographical errors, has uniform layout, etc. Similar advantages have been reported on in [31]. Another example is the adaptation to new standards. It is our experience that large companies have evolving internal standards for coding. As a consequence, they have more than one standard simultaneously. Depending on the time the programmers are working for the company, a certain standard is used. So automated adaption to the latest standards is a useful automated maintenance process. It can also be the case that decision structures need an update, since during the evolution of the system more cases have been added. At the company that we looked at, the tenth bank of the world, such changes are made to their systems on a daily base. It is recognized by the teams working on these issues that these tasks are very time consuming, not very challenging, although its hard to do it in a correct way without tool support other than compile-link-edit cycles. Maintainers have to look for the problematic code throughout the entire system. This is time consuming and error-prone. Once they located this code they have a good local comprehension of what to do. We stress that for many of these daily tasks it is not necessary to completely comprehend such systems. Local comprehension suffices in order to specify tools that search for the typical patterns they are looking for and once they are found, we automatically change them according to their wishes. The search and replace process is 100% automated. It will be clear that tool support for carrying out such tasks saves money and makes the maintenance process less error prone [1]. Since many such tasks are very company specific, it is not realistic to assume the existence of tools that carry out these tasks. To give the reader an idea, a typical task that we carried out was to restructure code so that it invokes a company specific routine. We discuss this tool in more detail in Section 3. Obviously, such tools do not exist, hence the proposed architecture. Using the technology that we developed it is easy to implement such specific tasks by maintenance teams although we are convinced that a short course to learn the tools is necessary (we come back on this issue in Section 5). In order to give a idea of the process that can be carried out by maintenance teams in the future, we carried out such tasks. We report on them in this paper. We obtained from the bank a typical system: a 100 KLOC system written in OS/VS COBOL, a COBOL 74 dialect, that contains embedded SQL. Some parts are 20 years old, and some parts are brand new. Moreover, we obtained some typical tasks that had to be carried out on this system. The maintenance team selected representative tasks that were too difficult to construct an ad-hoc disposable tool for to carry out the task. We implemented the tasks using an architecture, that we call a software renovation factory in a few hours and we were able to carry out the tasks completely automated on the system. The specific tools we implemented are together called an assembly line. The advantages of our approach are that the changes are made in a controlled way: the tools that we made are in fact the requirement specification of the tasks. This means that it is now possible to follow the history of changes in detail, that the process can be reproduced, moreover the process can be applied to other systems as well. In this way it is possible to set up such maintenance in an automated, controlled, and documented manner. Moreover, the evolution of the system and the many changes are now not only known by certain maintenance teams but they are documented in an executable way that is accessible for other parties, that can reuse the tools as well. This approach has advantages over an approach where the change history is only in the mind of the programmer. **Organization of the paper** In Section 2 we start with an overview of the architecture of the software renovation factory. We also discuss the implementation technology. In Section 3 we elaborate treat the assembly line that we implemented. In Section 4 we discuss an input and output program in order to show the effect of the entire assembly line. In Section 5 we address peopleware issues that are concerned with our approach. In Section 6 we conclude. **Applications of our approach** The technology discussed in this paper has been applied in various other projects. We mention control flow normalization of COBOL/CICS legacy systems [10] and a difficult leap year correction transformation [44]. In [40] a nontrivial restructuring problem for a Swiss bank is solved using this architecture. In [13] a COBOL 85 to COBOL 74 transformation is carried out using this technology (for the same bank as the case study of the current paper). **Related work** In [31] also automated tools are implemented to carry out software maintenance tasks. In [46] an architecture for a reengineering workbench is discussed. In that paper the focus is on what functionality is desired, and in our paper the focus is on how to easily create such functionality. In [2] an organizational view on (component) factories is given that can be used as complement to the technical view presented by us. Related implementation platforms for software renovation factories are for instance TXL [14], REFINE [37] and COSMOS [19]. For a comparison of the parsing technology used by these approaches in comparison with our approach we refer to [11]. For a comparison of our implementation platform (the ASF+SDF Meta-Environment) and REFINE we refer to [16]. For an overview of related systems, their history, and comparisons of REFINE and the ASF+SDF Meta-Environment by users of both systems we refer to [7, Section 3.3]. This paper is part of a larger effort. We refer to [5, 27, 6, 18] for an overview of how this paper relates with other papers by the authors. # The Architecture In this section we give an idea of the architecture that we call a software renovation factory. In fact this is a development environment that is suited to implement maintenance and reengineering tasks to be carried out in an automated fashion. It consists roughly of two parts. There is one part that has to be set up by developers of such factories and there is the part that can be used by maintenance teams so that they can develop assembly lines for automated maintenance. In Figure 1, we depicted the architecture of the factory. We discuss Figure 1 from left to right. CALE stands for computer aided language engineering, and CALE-Tools help in constructing a grammar or even generating one from some electronic source, like a standard, or an on-line language manual. CALE-Tools can assess the quality of existing language descriptions, with CALE-Tools we can develop language descriptions, and we can reengineer them. In fact, CALE-Tools form a factory of their own. For a more thorough discussion on CALE-Tools we refer to [42, 45]. Depending on the existence of such documentation we benefit from CALE-Tools in the construction of grammars. In some cases we can generate a grammar from an electronically available language description manual. As soon as we have a grammar, we generate from this grammar its native pattern language. For our example system written in OS/VS COBOL and embedded SQL this means that a real program is also a pattern: the pattern that matches only this program. In the generated pattern language we have for all sort names that are present in the grammar the three kinds of variables available. For instance, Paragraph1 matches exactly one arbitrary paragraph in OS/VS COBOL possibly containing embedded SQL. Paragraph1+ matches one or more such paragraphs, and Paragraph1* matches zero or more such paragraphs. The * stands for zero or more occurrences. The generation process from a grammar to a native pattern language is implemented as a CALE-Tool, hence the connecting arrow. For more information on the generation process, a formal definition of native pattern languages, and an example of their use we refer to [44]. In this paper we will use native patterns as well to implement the requested changes of the maintenance programmers. We believe that native patterns are very helpful when the technology that we developed will be ported to companies that use it for maintenance and/or reengineering. Since those programmers know the language quite well, the learning curve for the native pattern language is minimal. In order to have access to the pattern language it is possible to generate the documentation from the executable specification of this pattern language. This is depicted in the arrow to Docs. For OS/VS COBOL with SQL this amounts to a 25 page document, with a table of contents, etc. We use existing technology to do this [12]. From the grammar we generate generic transformations and generic analyzers. Those parts form the basis for which the user, in this case a maintenance programmer, can plug in custom-made tools. In fact, as soon as the user described the requirements specification of a tool, it is immediately executable since the generic components take care of bookkeeping issues. This architecture enables easy, reusable, and robust development of tools. In particular, it ensures maximal reuse of tools in case of different dialects. This technology has been discussed in [8]. The dashed rectangle represents the part that the maintenance team is working with. On top of the so-called Tool-Basis, the tools can be implemented with the aid of documentation of the native pattern language. The Tool-Basis contains the infrastructure that can be shared in custom tools, and takes care of the fact that the grammar, the generic transformations, and the generic analyzers are known in the custom made tools. In this paper we treat a case study that delivers a number of typical tools. Implementation of the Architecture We used the ASF+SDF Meta-Environment [26] to implement the complete architecture. SDF stands for Syntax Definition Formalism [21], it can be used to define the syntax of a language. ASF stands for Algebraic Specification Formalism [3], it can be used to describe the semantics of a language. The combination is thus adequate for defining syntax and semantics of languages and the ASF+SDF Meta-Environment is the supporting environment for both formalisms. We note that a conference is devoted to this system (and similar systems). See the proceedings of ASF+SDF97 [39] for a snapshot of the state of the art. The ASF+SDF Meta-Environment is also used as a language prototyping environment, see [17] for an elaborate treatise. For an overview of some industrial applications of the ASF+SDF Meta-Environment we refer to [4, 6]. The ASF+SDF Meta-Environment is an interactive programming environment generator that takes a language definition as input (including a definition of the syntax of this language and optionally other operations on programs in the language such as, for instance, interpretation, compilation or transformation) and generates corresponding tools as output. From the syntax definition of a language in SDF various components are generated: a lexical scanner [23], a Generalized LR parser [22], a syntax-directed editor [28], a pretty printer [12], and optionally traversal functions and program analysis functions [8]. For the operations defined on programs, efficient term-rewrite engines are generated. We mention that Generalized LR parsing is particularly helpful for reengineering and maintenance, see [11] for details. We can combine tools to obtain larger tools with a more complex behaviour. Using this component based engineering [27] many tools can easily be reused. We glue these components together with a coordination language called SEAL [29]. SEAL stands for Semantics-directed Environment Adaptation Language; it not only takes care of the coordination but also of a graphical user interface [30]. It is possible to change the coordination run-time, and to add functionality run-time, which is helpful in rapid development of custom tools. In Figure 2 we give an idea of the look-and-feel of the ASF+SDF Meta-Environment in action. This screen dump shows the implementation of the maintenance tasks that we obtained from the maintenance team. The upper window is the ASF+SDF Meta-Environment. You can add and delete specifications. Specifications can be syntax descriptions of languages, or tools. They are called modules, and they can be edited via the edit-module window. We can also open editors that understand the syntax of a certain module. For instance the COBOL+ window is an editor that can parse OS/VS COBOL plus CICS plus SQL. The buttons at the left-side of the COBOL+ window are implemented using SEAL. Part of the coordination script can be seen in the upper-right window: it contains the functionality of some EvalSQA button. This editor understands the SEAL language. We pressed the Typecheck button, that checks for type errors in the SEAL script. The SEAL window below pops up and tells us whether there are errors. As an example, we also pressed the McCabe button of the COBOL+ window. This results in the small window with the 13 in it. We will discuss the functionality of the maintenance tasks in the next section. 3 A typical software maintenance assembly line We carried out the case study on part of a stockbroking system in order to show the usefulness of the architecture that we propose. The development of the case study can be characterized as evolutionary. The earliest parts are from before 1980. Today, 1998, still new functionality is added to it. The maintenance tasks we discuss are all in the vein of this evolutionary process. They are concerned with restructuring of the error handling process after an SQL statement has approached a DB2-table. The values of the exit status of an SQL statement are modified in the new release of the embedded SQL that is used in this system. In the current situation, some of the return codes are hard-wired coded into the stockbroking system. This information will now be stored in a separate program that should be called. So a transformation that we carried out implements the change from the coded constants to the call. Overtime, the structure of the error handling procedures themselves, has extended. At this moment the decision structure is not optimal anymore. The other transformation that we carried out turns those decision structures into structures that are now more natural. The remainder of this section is devoted to a more thorough description of the assembly line in order to illustrate the process of automated software maintenance. As we see it, any automated reengineering or maintenance process consists of a number of very small steps that—together—perform a complex task. Identifying those steps requires a factory approach towards the tasks. What exactly this factory approach is, is hard to say in general. One of the fundamental issues is, in our opinion, that the process consists of three major phases. We call them the preprocessing phase, the main phase and the postprocessing phase. It is our experience that whatever problem we had to solve, it always boiled down to these three phases. The phases themselves are combinations of small steps. It is also our experience that the small steps can be reused over and over again. For instance, a postprocessing step in a control flow normalization assembly line [10], has now been used as a preprocessing step in this maintenance process. The common situation is, however, that pre- and postprocessing steps can be reused for the reason they were constructed for in the beginning. During development of the assembly line we use the ASF+SDF Meta-Environment in an interactive way. In Figure 2 this is expressed. Once the individual steps have been identified and implemented, we use the SEAL coordination architecture to combine all the small steps into one large usually complex task. A glimpse of this can also be seen in Figure 2. In order to modify the complete system, the implemented task can be carried out batch oriented [13]. Next, we discuss the steps that are present in this particular assembly line. Formatting code A basic step in maintenance and reengineering is (re)formatting the code. This is also emphasized in [46]. We use generic technology to create a formatter, this technology already exists [12]. We generate from the grammar description a specification that we can adapt to company specific formatting standards. We use this formatter as a preprocessing step, in order to format the code properly. The other steps make use of the formatter in the sense that when the transformation is done the output will be showed in a text editor using this formatter. Constructing the formatter is not a maintenance programmers task. It is part of the development of a renovation or maintenance factory. We reused this formatter from other projects, with an hour effort to adapt it to this project. McCabe Since some of the restructuring should lead to more simple decision structures, we implemented McCabe's cyclomatic complexity index [33] for OS/VS COBOL plus SQL (We learned from Tom McCabe [34] that his company is working on an implementation for COBOL with embedded SQL). We use the measure to show that the restructuring that we carry out decreases the complexity of the code. We think that this measure should be part of a basic set of tools that are readily available to the maintenance group. So we do not see this as a task for maintenance programmers, although implementation of this measure is not at all hard, when using this architecture. It is not part in the strict sense that we use this tool to perform the tasks. We use it to test whether the transformations reduce complexity. So we measure, transform, and measure the resulting code. Normalize conditions The error handling is treated in IF phrases. They all contain variations of conditions for which transformations should be made. We could make a huge program that takes care of all the possibilities that we may find in the current system and that might occur in other systems that will need this type of maintenance as well. We do not do this. We start with restructuring the code so that we are sure that all the conditions have a certain form. Therefore, we normalize Boolean conditions so that we can be sure of their form. This reduces the complexity of the assembly line drastically. Let us discuss the tasks that we carry out during this preprocessing step. We have to recog- ize, for instance, the Boolean condition $SQLCODE = -818 \text{ OR } -904 \text{ OR } -911 \text{ OR } -922$. Let us first explain this code, since it may be the case that this code is not familiar for the reader. We recall that this is OS/VS COBOL code with em- bedded SQL. The product of IBM that processes embedded SQL is called DB2, which stands for DataBase 2 [24]. When DB2 processes an SQL statement, DB2 sets a return code in the $SQLCODE$ (and $SQLSTATE$) host variable of the so-called SQL communication area (SQLCA). The return code indicates whether the statement executed succeeded or failed. If $SQLCODE$ equals zero, execution was successful, if its larger than zero, execution was successful with a warning, and if it is less than zero, execution was not successful. For instance, $SQLCODE = 100$ means that no data was found. The error code $-818$ indicates that the database request module and the application program were not the result of the same pre- compile. This module contains SQL statements extracted from the source program during program preparation. Code $-904$ is caused when the resource required for the SQL statement was not available. Code $-911$ is returned when a unit of work was the victim of a deadlock or timeout, so it had to be rolled back. The application is rolled back to the previous COMMIT, which ends a unit of recovery and commits the relational database changes that were made in that unit of recovery. Return code $-922$ means that there was an authoriza- tion failure. In all the above cases the SQL statement could not be executed, hence the use of the OR connector. The abovementioned IF phrase takes care of the error han- dling. There are many ways to implement the above Boolean condition, so we normalize all of them to a particular format. Let us give an example, just to give the reader an idea. The tool converts NOT ( NOT ( $SQLCODE = -818$ OR $-904$ OR $-911$ OR $-922$ ) ) to $SQLCODE = -818$ OR $-904$ OR $-911$ OR $-922$. We display the two equations that take care of the above normalizations. There are more equations, but they are concerned with other normalizations like NOT $X \geq 1$ turning into $X < 1$, which are not relevant for the SQL issues that we discuss at the moment. \[ [5] \text{Norm-cond}_{\text{L-exp}}(\text{NOT}(\text{NOT}(\text{L-exp}))) = \text{L-exp} \] \[ [9] \text{Norm-cond}_{\text{L-exp}}(\text{(Id1)}) = \text{Id1} \] We called this tool $\text{Norm-cond}$ and on logical expressions, abbreviated $\text{L-exp}$ it is called $\text{Norm-cond}_{\text{L-exp}}$. We mention that the underscore notation is generated from the grammar as well. Details on the generation process can be found in [8]. Equation \([5]\) removes double negations, $L\text{-exp1}$ is a variable matching exactly one arbitrary logical expression. Equation \([9]\) removes superfluous parentheses around identifiers that are logical expressions. We note that in COBOL we can use predicates that are logical expressions that can be given a name. The value of $SQLCODE$ is such a predicate. It is not necessary to have a fixed ordering of the return codes. We take care of that in the next analysis function. Error handling analysis Of course, we do not want to have programs changed that do not contain the error handling patterns. We implemented an analysis tool to check this. In Figure 2 this tool is called $\text{ErrHandDB2}$. The idea of this tool is that it returns the number of occurrences of $SQLCODE = -818$ OR $-904$ OR $-911$ OR $-922$ in all its variants but then only in IF phrases, since when it occurs in another context a transformation is undesirable. This tool depends on the fact that Boolean conditions are normalized first. So it does not take optional brackets and NOTs into account. What do we treat in this tool is the degree of freedom that may occur in the ordering of the Boolean condition. Still, the tool is simple. We have two equations for the tool $\text{ErrHandDB2}$: one for the IF and one for the IF ELSE case. We use an auxiliary tool, check return code (crc), to check for the correct values of return codes. Let us display the IF case of $\text{ErrHandDB2}$ and two of the 5 equations of the auxiliary tool. The other equations of both tools are similar. \[ [1] \text{crc(Lit1 Lit2 Lit3 Lit4) = true} \] --- $\text{ErrHandDB2}_{\text{Sentence}}(\text{*,0},$ \(\text{Statement}*)$ $\text{if SQLCODE = Lit1 Lit2 Lit3 Lit4}$ \(\text{Sentence1}) = 1$ \[ [2] \text{crc(Lit1 Lit2 Lit3 Lit4)}$ \(\text{contains=-818(Lit1 Lit2 Lit3 Lit4)}$ \& \text{contains=-904(Lit1 Lit2 Lit3 Lit4)}$ \& \text{contains=-911(Lit1 Lit2 Lit3 Lit4)}$ \& \text{contains=-922(Lit1 Lit2 Lit3 Lit4)}$ \[ [3] \text{contains=-818(Lit1 Lit2 Lit3 Lit4)} \] Equation \([1]\) is a conditional one. Above the line, the condition is stated, and if it succeeds the equation below the line is executed. $\text{ErrHandDB2}$ is an analysis tool. In fact, this means that the output sort is fixed. In this case the output is an integer. We have three arguments to an analy- sis tool. The first one is the operation that should be used, the second is the default value, and the third is the pattern. Since we wish to count the number of occurrences we use + as operator. If we do not find the pattern we wish to return 0 as a default value. If we find the pattern the tool will return 1. This means that for an entire program every occurrence in any context will be counted and added to the default value. Now we discuss the pattern. It looks for a COBOL sentence that starts with zero or more statements (expressed with the variable $\text{Statement}*$), then an arbitrary IF phrase containing four arbitrary literals Lit1, Lit2, Lit3, and Lit4 in the Boolean condition. So $SQLCODE = -305 \text{ OR } -502 \text{ OR } -803 \text{ OR } -811$ matches. In order to prevent that incorrect $SQLCODE$ return codes are counted, we have a condition on this equation, which is above the double line. We check whether the return codes are the four we are looking for. The fact that the variables Lit1 – Lit4 are the same above and below the double line means that they are bound to the same value if the rule matches. So if in the code -305 is matched by the first variable Lit1, the crc tool will use -305. The crc tool only returns true if all four literals are correct. This is expressed in equation [2] where we use the & as Boolean connector. In equation [3] we check whether one of the four equals -818. The variable Lit1* matches zero or more literals, then the literal -818 and then again zero or more arbitrary literals matched by Lit2*. The other return codes are checked analogously. It is simple to see that crc returns true only if the four literals are the return values that we are looking for and that there ordering does not matter. We use the ErrHandDB2 and crc analysis tools as conditions for the actual transformations. We discuss them next. Modify data At this point we enter the main operation phase. It consist of two parts. In the DATA DIVISION we have to add some issues and we have to change the actual coding in the PROCEDURE DIVISION. Since both parts are not depending on each other as it comes to our transformations, we can split them up into two steps. If that was not the case we could have implemented a global pattern. In some cases this is necessary, such as in complex jump instruction eliminations, see [10] for examples of global patterns. The tool that we discuss in this paragraph modifies the DATA DIVISION if a check in the PROCEDURE DIVISION succeeds. Its functionality is that it adds to the WORKING-STORAGE SECTION a special variable and a COPY member, plus some comments. If there was not yet a DATA DIVISION, it will be created, if the WORKING-STORAGE SECTION did not exist, it will create it. Of course the transformation is only performed when there are more than zero occurrences of the error handling code using the SQILCODE, so that the transformation makes sense at all. We explain the five equations that implement this tool. [1] ErrHandDB2(Program1) = 0 --- Add+EM948_Program(Program1) = Program1 [2] ErrHandDB2(Program1) = 0, Program1 = COMMENT1* Ident-div1 Env-div1 Data-div1 Proc-div1 --- Add+EM948_Program(Program1) = COMMENT1* Ident-div1 Env-div1 Add+EM948_Data(div(Data-div1) Proc-div1 --- Add+EM948_Data(div( ) = DATA DIVISION. Add+EM948_Ws-sec( ) [4] Add+EM948_Ws-sec( WORKING-STORAGE SECTION. Data-desc1*) = WORKING-STORAGE SECTION. Data-desc1 01 L+EM948 PIC X(O9) VALUE 'EM948 L'. * FOR TESTING EM948 SQILCODES COPY A0046075. [5] Add+EM948_Ws-sec( ) = WORKING-STORAGE SECTION. 01 L+EM948 PIC X(O9) VALUE 'EM948 L'. * FOR TESTING EM948 SQILCODES COPY A0046075. Equation [1] is a conditional one. Above the line, the condition is stated, and if it succeeds the transformation be- Modify error handling We modify the error handling code in the PROCEDURE DIVISION. We do this with a tool called Use-EM948. It consists of two conditional equations, one dealing with an IF phrase and one dealing with an IF-ELSE phrase. We treat them both. [1] crc(Lit1 Lit2 Lit3 Lit4) = true --- Use-EM948_Sentence( Statement1* IF SQILCODE = Lit1 OR Lit2 OR Lit3 OR Lit4 Sentence1) = Statement1* Move SQILCODE TO SQILCODE IN LINKAREA=EM948 CALL 'U100' USING L+EM948 LINKAREA=EM948 IF RETURNCODE = '9' Sentence1 [2] crc(Lit1 Lit2 Lit3 Lit4) = true --- Both conditions reuse the auxiliary crc tool that checks whether we are dealing with the correct return codes. If those values are correct, the condition is satisfied and we can make the change. The changes that we have to make in the PROCEDURE DIVISION are very local: the largest structures that we modify are COBOL sentences. Therefore, our tool has only two equations on this level (of course all the other equations on other levels are generated, as explained in [8]). The tool Use-EM948 applied to a COBOL sentence is denoted Use-EM948_Sentence. The first sentence that we are interested in consists of zero or more arbitrary statements, matched by Statement1*, then the special phrase starting with IF SQLCODE = Lit1 OR Lit2 OR Lit3 OR Lit4 followed by exactly one Sentence1. Since OS/VS COBOL is a COBOL 74 dialect, the scope of the IF has to be ended with a separator period (there is no END-IF). We recall that a sentence is one or more statements ended with a dot. We explain the replacement pattern. We leave the context intact: the Statement1* and Sentence1 are reiterated. Before we change the original IF phrase, we insert some new code above it. First, the exit status variable is copied to an auxiliary data item SQL-CODE that is a subrecord of LINKAREA-EM948. Then a company specific CALL follows, which checks the exit status and modifies the data item RETURNCODE accordingly. Now we change condition of the original IF phrase: it is changed into RETURNCODE = '9'. The second equation is a variation of the first: the Boolean condition can also be contained in an IF ELSE phrase. So the only difference is the Cond-body1 that represents anything that can occur between an IF and an ELSE. The rest of this case is the same as the first equation. Here we turn two IF phrases into one. Two IF phrases cannot occur in one sentence, since the separator period is also an implicit scope terminator. So, the Eval-SQL-a works on zero or more sentences, which is denoted by Eval-SQL-a_Sentence*. The pattern consists of a list of arbitrary sentences containing the two IF phrases that we are looking for. This is expressed with the (context) variables Sentence1* and Sentence2*. In between we have the two sentences containing the special IF phrases. The first one starts with zero or more arbitrary statements (Statement1*), then the conditional IF NOT SQL-OK Sentence1 (the latter variable expresses that the body of the IF does not matter). Then another arbitrary conditional statement with fixed part IF SQL-OK. From the code examples we understood that the maintenance team wants this in an IF ELSE construct. The replacement pattern is conceptually simple. There is, however, a small complication with the scope termination of the IF. In the replacement pattern we use an auxiliary function rsp. This stands for remove separator period. For, the variable Sentence2 represents code that is ended with a period. But since this period is also is also an implicit scope terminator, we have to remove it from Sentence2. Of course the separator period of Sentence1 ends the scope of the new IF ELSE. Next, we discuss the second transformation. Here, three consecutive IF phrases are turned into one nested IF phrase. In this transformation we make use of design knowledge: SQL-OK and SQL-NOT-FOUND cannot be true at the same time. This information can also be found in the file that defines the SQL auxiliary data items that are used in the code examples that we obtained from the maintenance team. Redesigning SQL control structures Control structures that were adequate at the start of development, are extended or modified overtime and in the end the structure is not optimal anymore. With the aid of design knowledge about the system it is possible to redesign such control structures. From the maintenance team of the system we obtained a few code examples and special requirements on the desired form of the new control structures. We discuss four transformations that take care of the required changes. We cannot simply make one tool that carries out the transformations, since two changes have overlapping patterns. So, we have two tools to perform this task in the right order. We call them Eval-SQL-a and Eval-SQL-b respectively, since we evaluate the SQL control structure and change it when its not optimal. We start with the first one. This second equation also works on lists of sentences, for the same reason as the first one. Again we have the context variables Sentence1* and Sentence2*. The sentences in between start again with zero or more arbitrary statements (matched by Statement1*). Then we have three consecu- tive phrases containing the control structure that has to be changed. In the replacement pattern we use the rsip tool that removes separator periods in two cases for the same reason as in the previous equation. So its another pattern, but the approach to deal with it is completely analogous to the first one. We discuss the third equation. Although this one is very simple, it interferes with the other patterns if not applied in the right order. In order to demonstrate this to the main- tenance team of the system we used two buttons in the ASF+SDF Meta-Environment. We give it another name as mentioned above: Eval-SQL-b. Apart from updating the control structures there was a requirement to start with pos- tive conditions in all IF phrases. As we can see in the above cases, all replacement patterns satisfy this criterion already. So this next tool takes care of the remaining cases. This can be obtained by the following simple transformation: ``` [3] Eval-SQL-b_Sentence( Statement1* = IF NOT SQL-OK Sentence1 ) = Statement1* = IF SQL-OK NEXT SENTENCE ELSE Sentence1 ) ``` This transformation swaps the negative condition of the IF phrase. So Eval-SQL-b works on single COBOL sentences, which is denoted by Eval-SQL-b_Sentence. We see that the input pattern is exactly the same as part of the input pattern of the first transformation. Therefore, we apply it in this ordering, since otherwise the pattern above would be broken. The NEXT SENTENCE is an empty state- ment in COBOL comparable to the empty statements CONTINUE or EXIT. We discuss the next equation, which is a variation of the third: ``` [4] Eval-SQL-b_Sentence( Statement1* = IF NOT SQL-OK Cond=body1 ELSE Sentence1 ) = Statement1* = IF SQL-OK rsip(Sentence1) ELSE asp(Cond=body1) ) ``` Again it works on a COBOL sentence. The special condi- tion NOT SQL-OK is now part of an IF ELSE phrase. Since we swap both branches, we have to remove the separator period from Sentence1 in the ELSE branch, using rsip, and we have to add a separator period to the body of the IF branch. We have a variable Cond-body1 that matches anything that can be part of an IF branch. We have a special sort for that due to the difficult scope termination rules of COBOL, see [9] for more details on these issues. We use an auxiliary tool asp, add separation period, in order to end the scope of the swapped IF ELSE. We note that sloppiness towards separa- tor periods in COBOL 74 dialects can be disastrous, see [41] for details on a Y2K tool that is erroneous due to sloppiness with separator periods. 4 Transforming an example pro- gram Now that we have constructed the entire assembly line that carries out the various tasks that were communicated to us, we treat an example program and its output so that the reader gets an idea of the effect of the many small changes together. We modified a program of the system for this pur- pose. In order to fit the example in this paper, we removed parts of it that are not relevant for explanatory purposes, and we made certain issues anonymous. Here is the modi- fied input program: ``` IDENTIFICATION DIVISION. PROGRAM-ID. XXXX. AUTHOR. N.N. DATE-WRITTEN. APRIL 22, 1996. PROCEDURE DIVISION. 1010=DETERMINE-MAX-SERIALNR. MOVE SQLCODE TO W-SQL-CODE. IF SQLCODE = -616 OR (-904) OR -922 OR -911 PERFORM 9999-EN904-FILL ELSE IF IND-MAX-SERIALNR = -1 MOVE 1 TO HH-MAX-SERIALNR-MESSAGE ELSE IF SQL-OK ADD 1 TO HH-MAX-SERIALNR-MESSAGE ELSE MOVE 'XXXXXXXXMESSAGE' TO EM900-TABLENAME. END-IF ADD-TO-MESSAGE-CT599. END-IF END-IF EXEC SQL INSERT INTO XXXXXXXMESSAGE VALUE (:DCLXXXXXMESSAGE,TRANSCODE-ORIGIN :DCLXXXXXMESSAGE,EVENTTYPE :DCLXXXXXMESSAGE,SERIALNR-MESSAGE :DCLXXXXXMESSAGE,BUF-MESSAGE) END-EXEC. MOVE SQLCODE TO W-SQL-CODE. IF NOT (SQLCODE = -616 OR (-904 OR -911) OR -922) PERFORM 9999-EN904-FILL ELSE IF NOT SQL-OK MOVE 'XXXXXXXXMESSAGE' TO EM900-TABLENAME. END-IF IF NOT (NOT SQL-OK OR (SQL=NOT-FOUND)) MOVE 'FETCH' TO H-SQL-CODE PERFORM 9999-SQL-ERROR. END-IF IF SQL-OK IF WS-EMP-IND=01 = C-SQL-NUL MOVE SPACES TO DATE-INC. END-IF IF SQL-NOT-FOUND MOVE 'Y' TO SW-EMP-ORDERS. END-IF IF NOT (SQL-OK) MOVE 'OPEN' TO EM900-FUNCTION ``` PERFORM 9999-SQL-ERROR. IF SQL-OK PERFORM 2000-FETCH-TRANSACTION UNTIL STOP-FETCH. In our assembly line, we have also a button that carries out the complete maintenance task. It is the ApplyAll button in Figure 2. If we process the above program with our assembly line by pressing the ApplyAll button, we obtain the completely transformed program below. **IDENTIFICATION DIVISION.** **PROGRAM-ID. XXXX.** **AUTHOR. K.N.** **DATE-WRITTEN. APRIL 22, 1998.** **DATA DIVISION.** **WORKING-STORAGE SECTION.** O1 L-EM948 PIC X(09) VALUE 'EM948 L'. * FOR TESTING EM948 SQL-CODES COPY 00046075. **PROCEDURE DIVISION.** 1010>DETERMINE-MAX-SERIALNR. MOVE SQLCODE TO W-SQL-CODE. MOVE SQLCODE TO SQL-CODE IN LINKAREA-EM948. CALL 'UT100' USING L-EM948 LINKAREA-EM948. IF RETURNCODE = '9' PERFORM 9999-EM904-FILL. ELSE IF IND-MAX-SERIALNR = *1 MOVE 1 TO HH-MAX-SERIALNR-MESSAGE. ELSE IF SQL-OK ADD 1 TO HH-MAX-SERIALNR-MESSAGE. ELSE MOVE 'xxxxxxxxMESSAGE' TO EM900-TABLENAME. 1015>ADD+TCMESSAGE=CT5901. EXEC SQL INSERT INTO xxxxxxxMESSAGE VALUE (:DCLXXXXXMESSAGE,TRANSCODE-ORIGIN :DCLXXXXXMESSAGE,EVENTTYPE :DCLXXXXXMESSAGE,RELATED-MESSAGE :DCLXXXXXMESSAGE,BUF-MESSAGE) ENDEXEC. MOVE SQLCODE TO W-SQL-CODE. MOVE SQLCODE TO SQL-CODE IN LINKAREA-EM948. CALL 'UT100' USING L-EM948 LINKAREA-EM948. IF RETURNCODE = '9' PERFORM 9999-EM904-FILL. ELSE IF SQL-OK NEXT SENTENCE. ELSE MOVE 'xxxxxxxxMESSAGE' TO EM900-TABLENAME. PAR=1. IF SQL-OK IF WS=EMP-IND-O1 = C=SQL=NULL MOVE SPACES TO DATA=INC ELSE NEXT SENTENCE. ELSE IF SQL-NOT-FOUND MOVE 'Y' TO EM=EOF-ORDERS. ELSE MOVE 'FETCH' TO H-SQL-CODE. PERFORM 9999-SQL-ERROR. PAR=2. IF SQL-OK PERFORM 2000-FETCH-TRANSACTION UNTIL STOP-FETCH. ELSE MOVE 'OPEN' TO EM900-FUNCTION. PERFORM 9999-SQL-ERROR. As we can see, a DATA DIVISION, a WORKING-STORAGE SECTION is created, and the necessary data item and COPY statement are added. The IF SQLCODE parts are recognized, regardless extra parentheses, extra negations, and ordering of the SQL return codes. The code is changed to the new CALL and the IF uses the RETURNCODE instead. The control structure redesign is also insensitive to extra parentheses, etc. In the replacement program we can see the effect of equations [1] and [2] of Eval-SQL-a. So all the changes are performed in the right ordering. Finally, in order to carry out such tasks on complete systems, it is not desirable to do this in an interactive way; even not using the ApplyAll facility. We see the interactive part of the ASF+SDF Meta-Environment as the development environment of the assembly line. When the assembly line is designed and implemented, an entire system should be transformed. We use the batch version of the ASF+SDF Meta-Environment to do this. We note that in [13] an elaborate discussion can be found how batch oriented system-wide maintenance and renovation tasks are carried out using the ASF+SDF Meta-Environment. 5 Peopleware Issues It is hard to come up with an objective measurement for maintainability. In fact, what to one programmer appeals, could feel cumbersome to the other. This is maybe best illustrated by the religious wars between programmers about the use of 60 TUs, programming language, indentation style, choice of text editor, commenting style, variable naming conventions, etc [35]. So maybe we could argue that there is no such measure at all. Still, the wish from many companies is to improve maintainability—after all major part of the total cost of a system is due to maintenance, as is confirmed in many studies [32, 38]; [36] gives a recent summary of these findings. It is also known that programmers working on a system for some time, typically maintenance programmers, consider the code to be their own [47]. Due to this fact, special care should be taken towards code inspections in general [20], or temporarily outsourcing maintenance and renovation. So, when management decides to (temporarily) outsource maintenance or renovation of a system there is a serious danger that the maintenance team will reject the code that is returned to them. For, their code has been taken away, which is for them a sign that they are not doing their work properly. Then someone else fiddles around with it, and when it comes back it is broke. Harry Sneed mentioned during his keynote for the fourth Working Conference on Reverse Engineering that he experienced this phenomenon in an off-shore outsourced Year 2000 conversion. On the other hand, outsourcing can be quite effective, for instance, a recent study [25] reports that outsourcing averages about twice the productivity of in-house development in New England banking applications. In [15], a key to success for off-shore outsourcing reengineering projects appeared to be intensive communication. Note that our approach also included intensive communication. The approach that we propose tries to avoid the above-mentioned risks. First of all, the maintenance team provided us with individual changes that we carry out system wide. Second, it is planned that maintenance teams of our partners are going to make those changes themselves, thus avoiding some of the abovementioned problems and risks. This paper is the first step in this process: we do a study in order to show how such projects are carried out in general. After our presentation of the assembly line we obtained some new transformations that we carried out. A next project that has been carried out for this bank is the automation of a temporary maintenance task where COBOL S5 is transformed back to COBOL 74 (see [13] for details). Ideally, the situation could be that in-house teams can make massive changes in a cost effective way, using tools that make the task a challenge instead of a tedious error-prone time-consuming job. We have done our very best to gear the tools as much as possible towards the normal situation of programmers that are working at this bank, for instance by using native patterns [44] and a grammar that is geared towards their dialect [9]. Moreover the names of the sorts in the grammar are chosen as much as possible from their manuals. At the moment we are constructing a similar maintenance/renovation architecture for Ericsson for a number of their proprietary languages [45]. 6 Conclusions In this paper we proposed an architecture to carry out software maintenance in an automated way. We applied our approach to a real-world COBOL/SQL stockbroking system plus some real-world maintenance tasks to show its effectiveness. We were able to implement the tasks in a few hours so that we could make the changes in a completely automated fashion on the entire system. We believe that this approach towards automated maintenance is promising in the sense that it is easy to apply, fast, and less error sensitive than traditional hand-crafted maintenance. References
{"Source-Url": "http://www.cs.vu.nl/~x/asm/asm.pdf", "len_cl100k_base": 10434, "olmocr-version": "0.1.50", "pdf-total-pages": 11, "total-fallback-pages": 0, "total-input-tokens": 58231, "total-output-tokens": 14298, "length": "2e13", "weborganizer": {"__label__adult": 0.0002486705780029297, "__label__art_design": 0.0002751350402832031, "__label__crime_law": 0.00019502639770507812, "__label__education_jobs": 0.0005426406860351562, "__label__entertainment": 3.9577484130859375e-05, "__label__fashion_beauty": 0.00010639429092407228, "__label__finance_business": 0.00020873546600341797, "__label__food_dining": 0.0002384185791015625, "__label__games": 0.0003767013549804687, "__label__hardware": 0.0005960464477539062, "__label__health": 0.00029349327087402344, "__label__history": 0.00014865398406982422, "__label__home_hobbies": 6.633996963500977e-05, "__label__industrial": 0.0002846717834472656, "__label__literature": 0.00015938282012939453, "__label__politics": 0.00014472007751464844, "__label__religion": 0.0003180503845214844, "__label__science_tech": 0.006290435791015625, "__label__social_life": 4.905462265014648e-05, "__label__software": 0.0048675537109375, "__label__software_dev": 0.98388671875, "__label__sports_fitness": 0.00018930435180664065, "__label__transportation": 0.00032401084899902344, "__label__travel": 0.00015115737915039062}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 55690, 0.04609]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 55690, 0.43473]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 55690, 0.89245]], "google_gemma-3-12b-it_contains_pii": [[0, 5408, false], [5408, 9827, null], [9827, 14089, null], [14089, 20408, null], [20408, 27095, null], [27095, 30488, null], [30488, 34850, null], [34850, 39776, null], [39776, 44753, null], [44753, 51886, null], [51886, 55690, null]], "google_gemma-3-12b-it_is_public_document": [[0, 5408, true], [5408, 9827, null], [9827, 14089, null], [14089, 20408, null], [20408, 27095, null], [27095, 30488, null], [30488, 34850, null], [34850, 39776, null], [39776, 44753, null], [44753, 51886, null], [51886, 55690, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 55690, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 55690, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 55690, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 55690, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 55690, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 55690, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 55690, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 55690, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 55690, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 55690, null]], "pdf_page_numbers": [[0, 5408, 1], [5408, 9827, 2], [9827, 14089, 3], [14089, 20408, 4], [20408, 27095, 5], [27095, 30488, 6], [30488, 34850, 7], [34850, 39776, 8], [39776, 44753, 9], [44753, 51886, 10], [51886, 55690, 11]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 55690, 0.0]]}
olmocr_science_pdfs
2024-11-29
2024-11-29
31b06db673cb70a9dd21647ec6419ba21988c637
A survey on security in JXTA applications Joan Arnedo-Moreno\textsuperscript{a,}\textsuperscript{*}, Jordi Herrera-Joancomartí\textsuperscript{b} \textsuperscript{a}Estudis d’Informàtica, Multimèdia i Telecomunicacions, Universitat Oberta de Catalunya, Rambla de Poblenou 156, 08018 Barcelona, Spain \textsuperscript{b}Escola Tècnica Superior d’Enginyeria, Universitat Autònoma de Barcelona, Campus de Bellaterra, Spain Abstract JXTA is an open-source initiative that allows to specify a set of collaboration and communication protocols which enable the creation and deployment of peer-to-peer (P2P) applications. This paper provides a survey on its current state regarding the topic of security. The study focuses on the security evaluation of standard peer operations within the JXTA network, highlighting which issues must be seriously taken into account in those applications sensitive to security. Key words: peer-to-peer, security, peer group, analysis, evaluation, distributed systems, JXTA, Java. 1 Introduction Peer-to-peer environments provide a virtual network where all involved parties collaborate to supply basic services, such as content sharing, processing or messaging. It is also assumed [35] that all peers have equivalent capabilities, and a central server with more processing power is no longer necessary, ensuring a high degree of decentralization and autonomy to participants. Such environments have become highly popular in recent times due to its great potential to scale and the lack of a central point of failure. \textsuperscript{*} This work is partially supported by the Spanish Ministry of Science and Innovation and the FEDER funds under the grants TSI2007-65406-C03-03 E-AEGIS and CONSOLIDER CSD2007-00004 ARES. \textsuperscript{*} Corresponding author. Email addresses: jarnedo@uoc.edu (Joan Arnedo-Moreno), jherrera@deic.uab.cat (Jordi Herrera-Joancomartí). Preprint submitted to Elsevier 16 April 2009 Just as the popularity of P2P applications has risen, concerns regarding their security have also increased, specially since it is no longer possible to trust a central server which capitalizes all security operations. As P2P applications move from simple data sharing (such as Gnutella [21] or BitTorrent [13]) to a broader spectrum, they become more and more sensitive to security threats and it becomes capital to take into account which security mechanisms exist in current P2P platforms before deploying them. JXTA [22] (or ”juxtapose”) is a set of open protocols that enable the creation and deployment of P2P networks. JXTA protocols enable P2P applications to discover and observe peers, allow communication between them, as well as advertise and locate resources within the network. Such protocols are generic enough so they are not bound to a narrow application scope, but are adaptable to a large set of application types. For that reason, they are implementation independent, so they can be deployed under any programming language or set of transport protocols. As the popularity of JXTA has increased, not only it has become one of the main testbeds for P2P applications [40] (over 2,700,000 downloads, 120+ active projects, 18,000+ collaborators), but different companies already have taken advantage of the provided framework in order to develop products based on a P2P model [45]. Some of them are quite important ones, such as Verizon or Nokia. The former uses JXTA in a program which directs both voice and data traffic through its network, providing users with an advanced version of instant messaging with telephony tools. The latter uses a JXTA-based software system in its data centers as a means to network monitoring and management. Other companies which use JXTA in their products encompass Codefarm [12], which uses JXTA to distribute its artificial intelligence algorithms for solving problems, such as market financial analysis, across many resources, and SNSing, China’s most used social networking software. This paper provides a survey of the current state of security in JXTA. The survey analyses how JXTA can be affected by typical P2P network threats and it also describes how protection against them can be achieved. The study has been performed analyzing basic peer operations but regarding them not as in an isolated way, but taking into account the whole peer life cycle. Furthermore, the analysis also takes into account one of JXTA’s most particular trait: peer groups. 1.1 Related work A lot of research efforts in the field of P2P have mainly focused towards strictly functionality issues such as scalability [14], efficient message propaga- tion across the network [49] or access to distributed resources [31]. At present time, the maturity of P2P research field has pushed through new problems such as those related with security. For that reason, security starts to become one of the key issues when evaluating a P2P system and it is important to determine which security mechanisms are available, and how they fit to every specific scenario. Even at the cost of some impact on performance, a security baseline must be kept in any P2P system in order to ensure some degree of correctness even when some system components will not act properly. Comprehensive reviews regarding security issues in P2P systems can be found in [44,46]. Systems are compared from two different standpoints. On one hand, P2P security is examined based on system capabilities, such as routing or data storage, analyzing the security threats they imply. On the other hand, another approach is to perform a security analysis based on individual security goals, such as reputation, availability or access control. Some attempts to measure the security degree of a P2P system have also been proposed. For instance, in [37] a security framework for such purpose is proposed, but only regarding the hash table based resource location and distribution. Those generic P2P system security reviews analyze system capabilities or security goals in an isolated manner and for that reason, a more accurate security analysis, for instance based on the peer’s life cycle, can not be performed. By focusing on a single P2P system, instead of providing a generic approach were several ones are reviewed at once, it is possible to present a much more detailed account of every security aspect. In particular, such detailed analysis may assess security solutions as a global layer across all basic peer operations, clearly showing how such operations interrelate and which constraints arise on regards to the deployment of security mechanisms. Unfortunately, such detailed analysis must be performed for each P2P platform independently since the specifics of every P2P system imply different implementations and different security solutions. Regarding the JXTA P2P middleware, although the platform has been available for several years, studies have been mainly concerned with performance [16,24,3] but not many have discussed such a sensitive issue as the development of secure applications. The most complete effort to present available security mechanisms in JXTA can be found in [50]. However, it can be mainly considered as a statement of design goal achievements. It does not provide a thorough review of all available security mechanisms or a clear idea of how they really work, making it difficult to assess in detail which are the real vulnerabilities in JXTA. On the other hand, JXTA documentation on regards to security is scarce and, in many cases, source code has to be directly reviewed in order to understand how security mechanisms in JXTA really work. Consequently, the results of this study will benefit security-aware platform developers and designers which want to create JXTA applications, by providing them an up-to-date detailed list of which security related issues should be taken into account. JXTA users may also benefit by realizing which may be the limitations of their applications on the scope of security, so they may take additional measures in order to guarantee a completely secure environment. Finally, it is worth mention that, to our best knowledge, there is no security evaluation of any other P2P platform regarding peers life circle, similar to the proposed approach with JXTA. For that reason, it is not possible to compare the JXTA security level with other platforms until such detailed analysis has been performed for every platform. Obviously, the detailed security analysis of other P2P platforms and the comparison with the JXTA secure mechanisms analyzed in this paper is completely out of the scope of this review. 1.2 Paper organization The paper is organized as follows. In section 2, an overview of the JXTA platform is provided in order to understand its main characteristics and methods of operation. Following, in section 3, the basic evaluation model is described by categorizing basic peer operations and threats under the JXTA model. Section 4 presents the security analysis. This analysis includes both core JXTA security mechanisms and additional existing security improvement proposals that are not currently integrated into the base JXTA framework. The final conclusions and directions for new research are outlined in section 5. 2 An overview of JXTA This section provides a general overview of the main JXTA concepts and components in order to understand the peer operations explained in section 3 and their security concerns. A detailed description of JXTA can be found in [41,42]. The fundamental JXTA architecture is divided into three distinct layers, as shown in Figure 1. The Core layer contains the minimum and essential characteristics, common to all P2P networks. Such operations include peer creation, discovery and communication (even when behind firewalls or NAT), as well as basic security services. The Services layer includes all network services which are not absolutely necessary, but provide desirable capabilities such as resource search, indexing, storage and sharing. The top layer is the Applications one, which includes any application deployed using the JXTA framework, such as instant messaging, file sharing or content management. Notice that the distinction between services and final applications may not always be clear, since what a client may consider an application may be considered a service by another peer. For that reason, the system is designed in a modular way, letting developers to choose the set of services and applications which most satisfy their needs. All JXTA components are within these three layers. 2.1 Peers Each peer in the JXTA virtual network is identified by a unique Peer ID, operating in an independent and asynchronous manner regarding other peers. However, some dependencies may exist depending on which roles they partake. Usually, peers act as edge peers, which could be considered the standard peer type in any desktop application on most devices. They implement the JXTA Core and Services layers as shown in Figure 1 and may interact with any JXTA protocol. Edge peers may also partake two additional roles in order to avoid some specific network constraints: minimal and proxy. This decision usually depends on its hardware or bandwidth capabilities. Devices with specific resource constraints (memory, CPU) may act as minimal peers, which only implement the JXTA Core layer. They are usually simple devices such as sensors or domotics. In order to use any necessary service to operate within the network, they must rely on proxy peers. A proxy peer summarizes and answers requests on their behalf. A very important role is that of rendezvous peers, which maintain a global index of available resources and help other peers find network services. They also act as beacons which newly connected peers may use in order to join the network. For that reason, rendezvous peers are usually well-known ones, with a DNS name or a static IP address. Connectivity between peers physically separated from the JXTA network, because of firewalls or NAT, is achieved by means of relay peers. They provide the ability to store and resend messages for unreachable peers and, by exchanging route information, message transport across several relay peers is possible in a transparent manner. Nevertheless, peers always attempt direct connections before using a relay. 2.2 Protocols As explained, JXTA defines a set of protocols (six, specifically) which enable the deployment of P2P networks. Using these protocols, peers may collaborate in a fully autonomous manner by publishing and discovering available resources within the network. Peers may also cooperate in order to route messages, allowing full communication, without the need for them to understand or manage different network topologies. All JXTA protocols are asynchronous and based on a request/response model, which means that for any given request, zero, one or many responses may be received. A brief description of each protocol is given: - The Peer Discovery Protocol (PDP) allows peers to publish their own resources and make them available to other peers. Any kind of peer may send PDP messages. This protocol is the default discovery protocol, but it is possible for applications to implement and deploy their own protocols. - In order to obtain information about other peers, the Peer Information Protocol (PIP) is used. Using this protocol, it is possible to query peer capabilities or monitor its behavior. - Peers use the Peer Resolver Protocol (PRP) in order to send requests to one or several peers and manage responses. The PRP protocol uses an unique ID associated to every request, which is included in messages. Other core protocols, such as PDP, make use of PRP in order to create its own requests. - The Pipe Binding Protocol (PBP) establishes virtual communication channels between peers named pipes, acting as abstract endpoints above any physical network. - Routes between peers are found with help of the Endpoint Routing Protocol (ERP). Whenever some peer is about to send a message to a destination but does not know any path, an ERP message is sent to other peers asking whether they know a path. - Finally, the Rendezvous Protocol (RVP) is responsible for the efficient propagation of messages within a group of peers, allowing peers to connect to services and exchange messages. 2.3 Resource publication Any kind of resource available within the JXTA network, including peers, peer groups, pipes or services, is described by an advertisement. Advertisements are XML documents containing an unique ID and all information regarding that resource and how it may be accessed and exchanged between peers using the JXTA protocols. Peers cannot access a resource without previously retrieving its associated advertisement. Every peer maintains a local cache where all received advertisements are stored for a later use. The local cache directly makes use of the peer’s file system in order to organize its content via directories and files. A sample advertisement is shown in XML Listing 1. **XML Listing 1 - Peer Advertisement** <xs:element name="PA" type="jxta:PA"/> <xs:complexType name="PA"> <xs:sequence> <xs:element name="PID" type="jxta:JXTAID"/> <xs:element name="GID" type="jxta:JXTAID"/> <xs:element name="Name" type="xs:string" minOccurs="0"/> <xs:element name="Desc" type="xs:anyType" minOccurs="0"/> <xs:element name="Svc" type="jxta:serviceParams" minOccurs="0" maxOccurs="unbounded"/> </xs:sequence> </xs:complexType> Any peer may publish an advertisement to announce the availability of a particular resource by using two different methods: local and remote publication. In *local publication*, the advertisement is indexed and stored the peer’s local cache. Following, the advertisement’s index is pushed to a rendezvous peer and is then distributed and replicated between all rendezvous in the global supernetwork peers, using the Shared-Resource Distributed Index (SRDI) service [43,1]. The rendezvous network acts as a remote index cache. By using this method, it is possible for peers outside the local network (out of broadcast range) to retrieve group advertisements by asking a rendezvous peer. It also enables peers which were off-line for some time to retrieve advertisements published during its disconnection. Whenever a peer receives the advertisement, the latter is indexed, stored into the local cache and assigned an expiration date. The advertisement retrieval mechanism is outlined in Figure 2. ![Advertisement retrieval from Rendezvous peers](image) Fig. 2. Advertisement retrieval from Rendezvous peers It must be remarked that during the publication process, the original advertisement is always kept in the peers’ local cache, only its index is distributed. This means that in case the peer goes offline, the advertisement will become unavailable. That makes sense, since also the resource the advertisement publicizes will be unreachable. In remote publication not only indexes are distributed, but the full advertisement itself via the JXTA propagation mechanism. This method is useful in case that the advertisement must be reachable even when the publishing peer is offline. However, under the remote publication method, no assumptions can be made about which peers will really store the advertisement and for how long. In both methods, when the expiration date is reached, the advertisement is considered stagnant and flushed from the cache, unless the same advertisement is received again, which renews its expiration date. Advertisements may be periodically retransmitted in order to attain permanency or update parameter changes. As can be seen, advertisement publication and discovery are very important steps in JXTA’s peer operation. 2.4 Messaging JXTA peers use pipes in order to exchange messages and access available services. JXTA messages are XML documents with ordered message elements which may contain any type of payload. Messages are the basic data exchange unit in JXTA and all protocols are defined as a set of messages exchanged between peers. Pipes provide an asynchronous, unidirectional and unreliable communication channel by default. However, bidirectional reliable channels may be provided on top of them. They offer two operation methods: *unicast* pipes, which allow one-to-one communications, and *propagation* pipes, which allow one-to-many. JXTA pipes are an abstraction and are not bound to a specific IP address or port. They have a unique ID and are published just like any resource in the JXTA network, so any peer may update them whenever its physical location changes. Both input pipes, used for message reception, and output pipes, using for message sending, are considered *pipe endpoints*, an actual destination in the physical network. Endpoints are dynamically bound to peers via the PBP protocol. ### 2.5 Peer groups JXTA introduces the concept of *peer group*: a collection of peers with a common set of interests. This concept is one of the main foundations of the JXTA architecture and is prevalent throughout all its specification [42]. Offering the possibility to create different (but not necessarily disjoint) groups of peers operating under the same overlay network allows to segment the network and offers a context for peers to publish and access different services. Peer group boundaries provide a secure framework in order to grant or deny access to the offered services. Peer groups form logical regions whose boundaries limit access to group resources, in a way similar to a VPN [25], operating at the application layer. Other interesting uses are the ability to provide a scoping or monitoring environment, where different classes of traffic and advertisements are limited to only peer group members. Peer groups are published, discovered and accessed just like any other resource in the network, by means of advertisements. In order to allow peer group management, JXTA defines the basic primitives for group membership and access control: the Membership and the Access Service. Both are core services which make use of the base JXTA protocols specification in order to achieve their ends. However, JXTA only defines the primitives, while specific applications may implement their own Membership and Access Services depending on their needs. The Membership Service manages identities within a peer group, providing each group member a *credential*. Peers may include this credential in messages exchanged within a peer group in order to allow other members to know who is making a request. With this information, the JXTA Access Service may evaluate the credential when a service is accessed and decide whether the request will be granted or denied. A peer establishes its credential within a peer group by successfully *joining* it. Before a peer may join a group, it must be authenticated by providing a correct *Authenticator* to the Membership Service. An Authenticator contains all the required information in order for the Membership Service to check that some requested identity can be granted. Each different Membership Service specification provides its own definition of an Authenticator, suited to its needs and inner workings. The join process is divided in three distinct steps: - In the *setup* step, the peer chooses which authentication method will be used for the whole process. If all parameters are correct and the choice is feasible, the peer receives an Authenticator from the Membership Service. - Following, in the *application* step, the peer completes the Authenticator with all necessary information and tests its correctness. It will not be possible to join the group until the Authenticator is correctly initialized. - Finally, in the *validation* step, joining the group is possible if the Authenticator is correct. The Membership Service checks whether the peer may assume the claimed identity and creates a credential. In case that a peer decides to give up membership to a specific group, it is possible to *resign*. When this happens, the credential is discarded. Group resignation is voluntary, the Membership Service does not support active membership revocation triggered by other members. The Access Service provides a single primitive in order to check a credential for a privileged operation. The possible results are disallowed (access denied), permitted (access granted), permitted but expired (the operation would be permitted but the credential has expired) and undetermined (unrecognized credential). ### 3 Security evaluation model The first step in order to assess the security degree of JXTA applications is to identify which is the standard peer lifecycle, so that it becomes clear which are the most common operations and, consequently, which deserve better attention on regards to security. Once such operations have been identified, a list of usual security concerns in P2P environments is provided. Our security evaluation model will be based in the cross-reference of standard operations and such threats, in order to evaluate how the system is protected against each one. 3.1 Standard peer operation cycle This section describes the standard peer operations for a peer participating in a JXTA network. The order in which they are presented is a logical one for most scenarios. However, it must be taken into account that such order may vary depending on the peer’s role. 3.1.1 Platform startup This is the initial step in order to setup the platform in the physical device which will hold a JXTA peer. This process mainly consists in loading the required libraries and creating the necessary data structures for network connectivity. At startup, all peers automatically join a default bootstrap peer group named netPeerGroup. This peer group is well known to all peers, since it’s ID is hard coded into the platform distribution. Peers may decide to stay only in this group or join others once they are connected to the JXTA network. At this stage, edge peers may also try to reach relay or rendezvous peers depending on their local configuration. 3.1.2 Peer group joining A peer will join those peer groups formed by peers it wants to interact with. This step usually follows startup, so all later operations are only within the boundaries of those specific peer groups and not the whole network. The peer locates the peer group advertisement and joins it via the peer group’s Membership Service. In the case that such peer joins the group for the first time, it must locate the peer group advertisement via PDP. From that point onward, the advertisement is already stored in its local cache. A peer may join several groups, which means that this operation may be performed several times. 3.1.3 Resource publication Any resource that peer holds and wants to make available to the rest of peer group members is announced by creating and publishing an advertisement as described in section 2.3. This step includes announcing its own presence, by publishing a peer advertisement, or creating a new group, by publishing a peer group advertisement. ### 3.1.4 Resource discovery Available resources in a peer group are discovered by retrieving their advertisements via the PDP protocol. This includes discovering other peers and pipes in order to initiate message exchanges. Usually, pipe advertisements are embedded into other more generic advertisements such as service advertisements. ### 3.1.5 Message exchange This would be the most frequent operation during any peer operation cycle. Message exchanges may occur at core protocol level or at service access. At core protocol level, JXTA core protocols are directly used. At service access, two pipe endpoints are established between the communicating peers. An outbound pipe is created by the peer which acts as a client, in order to send requests, and an inbound pipe is created by the peer which acts as a server, in order to receive and process requests. ### 3.1.6 Disconnection The peer resigns from all peer groups and goes to offline state in a tidy manner. This list of operations takes into account some degree of abstraction, since each one actually represents a set of more basic steps. In Table 1, a breakdown of each operation into such basic steps is provided. A more detailed explanation can be found in [42]. Nevertheless, from a security assessment standpoint, the chosen degree of abstraction is enough to provide a clear idea of which are the possible scenarios during any peer’s full operation cycle, from startup to disconnection. ### 3.2 Security threats in P2P networks The standard security threats in the traditional client/server environment are still valid in P2P environments. Furthermore, the P2P paradigm shift introduces new concerns that must be taken into consideration when designing P2P frameworks. The move from a passive stance (client) to an active one (peer) in the network easily propagates such concern across all its members. Security attacks in P2P systems are classified into two broad categories: passive and active [23]. Passive attacks are those in which the attacker just monitors activity and maintains an inert state. The most significant passive attacks are: - *Eavesdropping (EvS)*, which involves capturing and storing all traffic between some set of peers searching for some sensitive information (such as personal data or passwords). - *Traffic analysis (TAn)*, where the attacker not only captures data but tries to obtain more information by analyzing its behavior and looking for patterns, even when its content remains unknown. In active attacks, communications are disrupted by the deletion, modification or insertion of data. The most common attacks of this kind are: | Platform startup | Load platform | | | Join *netPeerGroup* | | | Open network listeners | | | Open local cache | | Peer group joining | Retrieve group advertisement | | | Instantiate group | | | Fill in Authenticator | | | Join | | Resource publication | Create advertisement | | | Local publication | | | Remote publication | | Resource discovery | Locate advertisement | | | Store advertisement in local cache | | Message exchange | Open pipe | | | Send messages | | | Receive messages | | | Access Service check | | Disconnection | Close connections | | | Shutdown platform | Table 1 Basic operation substeps • **Spoofing (Spf)**, in which one peer impersonates another, or some outside attacker transforms communications data in order to simulate such an outcome. • **Man-in-the-middle (MitM)**, where the attacker intercepts communications between two parties, relaying messages in such a manner that both of them still believe they are directly communicating. This category includes data alteration between endpoints. • **Playback or replay (Pb)**, in which some data exchange between two legitimate peers is intercepted by the attacker in order to reuse the exact data at a later time and make it look like a real exchange. Even if message content is encrypted, such attacks can succeed so long as duplicate communications are allowed and the attacker can deduce the effect of such a repeat. • **Local data alteration (LDA)**, which goes beyond the assumption that attacks may only come from the network and supposes that the attacker has local access to the peer, where he can try to modify the local data in order to subvert it in some malicious way. Apart from security threats that take into account a malicious attacker, it is also very important to take into account **Software Security Flaws (SSF)** in a security survey. Specifically, which steps are taken by the developers in order to minimize the probability that a bug that may later jeopardize a deployed system. ## 4 Security evaluation From the standpoint of basic security requirements which are desirable in JXTA, they are very similar to those of any computer system: confidentiality, integrity and availability. In order to achieve them, these requirements should translate into an architecture that includes authentication, access control, audit, encryption, secure communication and non-repudiation. JXTA remains neutral to cryptographic providers or security schemes. In its initial conception it does not mandate any specific security solution, providing a generic framework where different approaches can be plugged in. Enough hooks and place holders are provided in order for each specific application to implement its own security solution. Nevertheless, in a present day P2P framework, relying in the fact that each application will build from scratch its own security solution is not enough, since it will usually mean that security will be overlooked, as its is often the case. It is very important that basic tools and functionalities are already available, providing a default degree of security but allowing further modularization if necessary. As such, basic security services (encryption, integrity and authenticity) should be provided, at least, at the **Core layer**, even though some applications may chose not to use them. In this section we will analyze whether the current iteration of JXTA (version 2.5) is up to this desiderata for each of peer basic operation and according to the standard threats to P2P networks. 4.1 Platform startup During the framework startup phase, since the networking capabilities are not operative yet, no threat related to a networked environment applies. However, it does make sense to take into consideration local data alteration on such libraries, since it is at this precise moment that JXTA libraries are loaded into the system. Due to the open nature of JXTA, the official project page protects software integrity with SHA1 digests [34], in order to avoid malicious distributions. For that reason, a local attack is necessary to actually deploy fake libraries into the system. The current Java distribution also uses code signing to provide a basis for integrity and authenticity checking of installed libraries. Specifically, it makes use of the Java jarsigner [38] tool when the source code is built. The necessary keystore information to sign the code, both the private key and certificate, is distributed with the source code. Unfortunately, this approach allows anybody to sign malicious the code, since it uses a self-signed certificate, and the keystore password is easily available in the build files (it is jxta.platform), meaning that the whole keystore content may be easily compromised. This is unavoidable if it must be possible for anybody to build the libraries. The only solution would be to have an official distribution, built by a trusted party, whose keystore information is not widely available. Apart from data alteration, it is worth analyzing JXTA’s libraries security from a Software Security Flaw standpoint. JXTA is an Open Source Software (OSS) project, which is a good indicator when specifically analyzing security [10]. Obviously, security through obscurity should not be applied, so any software security mechanism which depends upon secrecy tends to eventually fail, as bugs or security flaws are discovered. Since JXTA code is public [40], it has been audited by a large number of individuals all across the Internet. The use of an OSS approach not only ensures current security, but allows direct improvement from the JXTA developer community, maximizing the networking effect. Nevertheless, it is worth mention that opening the source code creates the opportunity for individuals to review security, but it cannot guarantee that such reviews will occur. There is also the fact that no guarantee can be made that a review will find any particular security flaw in a system, but that problem is also common to closed source projects. In any case, OSS allows developers with security concerns to directly assess whether the JXTA framework is up to their needs. 4.2 Peer group joining The first step in order to join any peer group is to retrieve its peer group advertisement. The implications of this specific substep will be explained in the next subsection. Therefore, we will focus here on the actual group instantiation and join operation. As described in subsection 2.5, the Membership Service is the key security mechanism for the group join operation. Through this service, peers claim identities by proving they are the legitimate owner. This service is defined as generic in the JXTA specification, so each application may implement it according to its own needs. However, the JXTA reference implementation, as far as version 2.5 [41], provides three available Membership Services which are ready to use. The None Membership Service is intended for peer groups which need no authentication. Since any peer may claim any identity, it is recommended that credentials should only be used within the group for purely informational purposes. This service is widely used in applications with no security concerns. The Passwd Membership Service relies on a Unix-like username and password pair for peer authentication. In order to claim an identity, the correct password must be provided. The list of pairs (username and password) is distributed to all group members, which means that the password file equivalent freely roams across the overlay network, which makes this method completely insecure. In fact, this group membership service was created as a sample and a means of testing and it is advised in the JXTA documentation that it should never be used in any serious application. The default Membership Service is PSE, which stands for Personal Security Environment. This service is the only one that is considered secure and the one that will be analyzed. PSE provides credentials based on PKIX [11] certificates. As shown in XML Listing 2, any number of such certificates may be included as Certificate elements in the PSE credential, together with the Peer Group ID and the subject’s Peer ID. The credential itself is also signed. The authentication procedure in order to join a PSE peer group can be summarized as follows: (1) The user introduces its personal password. (2) The peer initializes an Authenticator for the peer group the user wants to join, using the provided password and the peer’s ID. (3) Using this information, an encrypted keystore in the local cache is located and opened, or created if not already existing. (4) The user’s certificate chain is retrieved. (5) Such certificate chain becomes the group credential for that peer. (6) The peer may interact with other ones in the same peer group. (7) The private key in the keystore is used by the peer in secure protocols when needed. All the enumerated steps in the join process using the PSE Membership Service are completed via local calls to JXTA libraries. For that reason, peer group joining is not concerned with network-based attacks (eavesdropping, traffic analysis, MitM or replay), since there are no real network based operations. It also means that any vulnerability in the join process must be exploited by a local attacker. As we can see, three actors interact in this process: the final user (the human being in front of the computer screen, or some agent), the peer (the application) and the peer group (JXTA libraries which control group access). That means that two spoofing methods must be taken into consideration: - Impersonating the user: Unauthorized access to keystore content. This is equivalent to taking control of another user’s peer. - Impersonating the peer: Unauthorized identity claim and credential generation. This is equivalent to being able to claim any identity within a peer group. In the first case, all security relies on the strength of keystore encryption and its password. Unfortunately, the keystore is stored as a simple file, which may be easily copied and distributed, and no mechanisms exist in order to plug in more advanced methods of key management (such as cryptographic hardware tokens). Regarding peer impersonation, it is must be pointed out that peers under a PSE Membership Service are authenticated only by being able to access a local keystore. During the process, the Membership Service is not concerned with the validity of certificate chains (whether it is signed by proper Certification Authorities or not expired), and the certificate content is never checked. Credentials are actually checked during the message exchange operations, as will be explained in section 4.4. As a result, anybody with access to a private key and a certificate (a self-signed one would be enough) will be able to correctly join any group using PSE and initially claim any identity. For that reason, the default join scenario is easily threatened by peer spoofing attacks, since anybody may create a valid keystore using public domain tools [39]. There is no real security on peer identity claims on regards to the Membership Service. These kind of peers which hold the necessary information in order to generate a correct PSE Peer Group Authenticator, but are not really group members because their certificate is not properly signed are named interlopers. In this scenario, they can become an annoyance, but can be spotted and dealt with when accessing services. A further concern that developers should take into account when using the PSE Membership Service is the fact that no revocation mechanism is provided. JXTA takes into account the possibility that a group member voluntarily resigns from a peer group, but does not provide the capability to expel a group member for some reason such as malicious behavior. No primitives exist within the framework which may somehow allow this. Developers must create their own revocation schemes from scratch. To sum up, we can see that PSE is a kind of toolbox that allows the implementation of different models based on securing identities via digital certificates, but it does not provide a clear structure of how trust is managed in a peer group (whose signatures are trusted or which peers are allowed to sign certificates). To properly configure PSE, the application must define the real trust anchors and some method that guarantees key authenticity. Under this scenario, trust anchors may take the form of PGP trust chains [20], where every peer may issue certificates, or a Certification Authority (CA), a single entity able to issue digital certificates within the group. In the latter case, it may based on a fully centralized approach [11], where a single peer holds the CA private key, or a distributed one [15], where the private key is split between several peers, which must collaborate to issue certificates. In scenarios where each peer may generate certificates, PSE may not properly, since it is not possible to easily guarantee key authenticity with the provided primitives. This is a weakness developers of JXTA agree that should be addressed [51]. Even under this assumption, it must be remarked that correctly setting a trust anchor in a pure P2P environment is not an easy task. First of all, in-band certificate generation procedures are easy prey to MitM attacks. In addition, when peer equality must be preserved, the proposed solution should avoid that the peer group may become entirely reliant on some peer, which gets some extra power above the rest. One of the original creators of JXTA, Yeager, provides a specific trust model for the membership service in [51], which tries to solve the problems previously described. Without actually recognizing a specific CA for each peer group, he proposes that rendezvous peers become the system’s trust anchors, the main reason being that they are well protected. Each edge peer uses rendezvous certificates as root certificates in order to ensure key authenticity. Furthermore, to acquire a certificate the peer must be authorized via an LDAP (Lightweight Directory Access Protocol) [48] directory with a recognized protected password. Rendezvous peers may use a secure connection to the LDAP service to authorize requesting peers. The rendezvous peer’s root certificate is securely distributed out-of-band by being directly included into the JXTA libraries. However, developers should take into account that this proposal is ultimately based in a centralized approach and peer groups become heavily reliant on external entities, which makes the system unfeasible in ad hoc environments. Furthermore, the proposal does not specify who configures or manages the LDAP service. It is assumed that some group administrator will do it, which makes it a logical approach in an enterprise environment, but moves away from a pure P2P model. 4.2.1 Non-core JXTA group membership Due to its open project approach, the JXTA platform offers additional security mechanisms, not currently included in the standard distribution, that have been proposed in order to tackle some of the described issues, by providing additional Membership Service implementations. An initial proposal can be found in [30], but its similarity with the Passwd Membership Service inherits most of its pros and cons. For that reason, it cannot be considered completely secure either. Another proposal [29] is similar to the trust model proposed by Yeager, adding extra capabilities upon the basic Membership Service. This approach is based on a centralized PKI and a basic challenge-response protocol [36] as a means for authentication during the join process. Its main contribution is to provide a method which peers may use in order to authenticate the group itself. It also allows to check peer group membership during the join process and defines a trust anchor based on both an external centralized LDAP server and a sign server. Using this method, it is no longer possible to easily spoof peer identities. The LDAP server provides peer certificate management and the sign server deals with group authentication, keeping a secure copy of a private key which represents the whole group. Again, developers should take into account that this proposal becomes reliant on external entities and cannot be considered a pure P2P approach. More elaborated proposals are presented in [52,2], based on joint authorization by multiple peers under voting schemes in order to maximize decentralization. Under this approach, JXTA credentials are signed certificates issued by a group CA, however group access is based on an agreement reached between several group members, instead of being entirely up to the CA’s decision. The main difference between both proposals is that [2] includes a rank system, where peers who join the group (“newbies”) have the least privileges, but they may rise to higher positions as they contribute to the group. Finally, a proposal which moves away from a centralized PKI and uses a web-of-trust approach is described in [4]. This model is specifically concerned in providing proof of peer group membership, not peer identity, via trust relationships: whenever peer A creates a trust relationship with peer B, it is vouching for B’s group membership to other group members. The model defines two different sets of peers: those which are allowed to register new members, named patron peers, and those who are not. No initial assumption is made regarding the cardinality of both sets, how a peer becomes part of each set or which are the restrictions in order to do so. A peer may decide to switch sets at any time. Group management is achieved via additional services that take into account the idiosyncrasies of JXTA’s messaging capabilities: the Patron Discovery, Sign, Trust Path Discovery and Credential Retrieval services. An advantage of this proposal is that it is not constrained to the JXTA file-based keystore type, using an interface named CryptoManager which arbitrates the join process and acts as a proxy for any cryptographic provider (software or hardware based). This approach also takes into account the fact that not all cryptographic providers are accessed via plain text passwords (for example, using biometrics), providing developers with the capability to choose a suitable degree of security according to each environment. 4.3 Resource discovery and publication Resources provided by peers in the JXTA network are represented by XML documents named advertisements, as detailed in subsection 2.3. In order to access such resources, their advertisement must be somehow retrieved. Advertisement discovery and retrieval is achieved via message exchange using the PDP and PRP core protocols (see subsection 2.2). Since it is a network-borne operation, we can focus on all threat types. We will discuss both resource discovery and publication in this section, since both share the same security mechanisms (only data flow direction changes between both operations) In the current JXTA reference implementation, advertisements may be secured at two different levels: at transport layer and at advertisement layer. Since securing at transport layer means considering an advertisement as a standard message, the provided security methods will be explained in subsection 4.4, where security in messaging is analyzed. In this subsection we will focus on advertisement-specific methods. At advertisement layer, security is achieved by digitally signing advertisements at application level by using a special type of advertisement named Signed Advertisement. The direct use of digital signature on the advertisement makes it possible to support both local and remote publication (via propagation to multiple peers). As a precondition to use this special type of advertisement, it is mandatory to join a peer group that uses the PSE Membership Service, since the necessary cryptographic keys to generate and validate the signature are obtained from the keystore and credential associated to this service. Signed advertisements will only be sent to members of that group. In any peer group which does not use this service, signed messages cannot be exchanged between its members. As a result, any security concern related to PSE is inherited by signed advertisements, such as the lack of real authenticity without setting a trust anchor at application level. The XML schema definition for a Signed Advertisement is shown in XML List- ing 3. It contains the signer’s credential (the PSECred element, a credential for a PSE Membership Service), the signature and the original advertisement. The Advertisement element encapsulates the original XML advertisement as plain text encoded via the Base64 algorithm [26]. The content of the Signature el- ement is generated by applying the RSAwithSHA1 algorithm to the original advertisement, XML formatted (not its Base64 encoded form). In order to feed the algorithm, the XML data is processed as plain text. The result is hence- forth Base64 encoded in order to be represented as plain text into the XML document. Once a signed advertisement is received by a peer, the signature is validated, the actual advertisement extracted and then stored into the local cache. XML Listing 3 - Signed Advertisement XML schema ```xml <xs:element name="SA" type="jxta:SA"/> <xs:complexType name="jxta:SA"> <xs:sequence> <xs:element name="PSECred" type="jxta:PSECred"/> <xs:element name="jxta:Signature" type="base64binary"/> <xs:element name="jxta:Advertisement" type="base64binary"/> </xs:sequence> </xs:complexType> ``` 21 On regards to advertisements, JXTA does not currently seem concerned with passive attacks, since it offers no advertisement protection against them. They are freely exchanged between peers in plain text. In fact, since they are structured using XML, it is very easy for an eavesdropper to read search for specific content (no need to process binary structured data). A human being can directly interpret advertisements with a text editor. No effort is made either in order to masquerade advertisement traffic, so it is feasible that an attacker may obtain some interesting information by just analyzing traffic, specifically detecting which peers offer more resources (since they are the ones which publish more advertisements). Using this method, it is possible to find the most interesting peers when looking for potential victims to attack. In fact, since anybody may instantiate any peer group, acting as an interloper, and then discover advertisements bound to the group, this kind of attacks are easy to perform. It is not even necessary to tap the network. How easily advertisements are exchanged is both a bonus for open services and a bane for tight security environments. If we assume that applications which use PSE correctly set a trust anchor in order to guarantee certificate authenticity, then active attacks such as spoofing, MitM and replay attacks may be correctly countered by digitally signing advertisements. Using this method, false advertisements may still occur within the peer group, but because of the non-repudiation property of digital signatures, it is easy to pinpoint offenders. As far as resource publication is concerned, since every peer is completely reliant on its rendezvous peer in order to properly distribute the advertisement index to the rest of the network, and no control is made about which peer may become a rendezvous one, it is possible to pull off MitM attacks by masquerading as a one. No control mechanisms exist either to automatically detect a misbehaving rendezvous peer. For that reason, each application should always deploy some method in order for peers to be able to identify real rendezvous peers. Finally, since secure advertisements lose the signature when stored into the local cache, the threat of a local attacker still exists, since it is possible to modify the local cache content, inserting or modifying false advertisements which redirect group members to false services in malicious peers. 4.3.1 Non-core advertisement security Another approach to advertisement security which is not included in the core JXTA distribution, exists in [5]. The proposed method is entirely based on XML Signature [47] (xmlsig) and provides advertisement authenticity and non-repudiation in a lightweight manner, without the need of a trust anchor. This is achieved by using Crypto-Based Identifiers [33] (CBIDs), which will be detailed in the following section. The main contributions of this proposal are: - Keeping interoperability by maintaining the advertisements base format, instead of creating a completely new one. This approach makes it possible to seamlessly integrate peers which support advertisement security which those who do not (or simply chose not to for some reason). - Providing a method to efficiently publish CBID-key binding by taking advantage of JXTA's own capabilities, without the need of additional protocols. - Maintaining end-to-end advertisement security for its whole lifetime, not just during transport, providing protection against local data alteration attacks, in contrast with the core signed advertisement approach. A sample of the XML signed advertisement used in this proposal is shown in XML Listing 4 (some ID's and Base64 encoded data have been shortened to improve readability). **XML Listing 4 - Xmdsig based signed Advertisement** ```xml <jxta:PGA xmlns:jxta="http://jxta.org" xml:space="preserve"> <GID>urn:jxta:uuid-2AD...5F02</GID> <MSID>urn:jxta:uuid-EB76C91C20F49F685C...B381F206</MSID> <Name>SampleGroup</Name> <Desc>Sample Peer Group Advertisement</Desc> <ds:Signature xmlns:ds="http://www.w3.org/2000/09/xmldsig#"> <ds:SignedInfo> <ds:CanonicalizationMethod Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315"/> <ds:SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1"/> <ds:Reference URI=""/> <ds:Transforms> <ds:Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature"/> </ds:Transforms> <ds:DigestMethod Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/> <ds:DigestValue>Ko0R31wMpcJ17VAmtaUf7nS/KU4=</ds:DigestValue> </ds:SignedInfo> <ds:SignatureValue> nloCRUg4WB0H+DcEaULKGYhqsfdRCy4R... ...QYH8Czio3P AkvLIU0G0eOHRL2kA1= </ds:SignatureValue> <ds:KeyInfo> <KeyName>urn:jxta:uuid-596162...BCF0646C103</KeyName> <ds:SignatureValue/> </ds:KeyInfo> </ds:Signature> </jxta:PGA> ``` In the current JXTA reference implementation, messaging has been secured under the assumption that the Personal Security Environment (PSE) has been chosen as a group’s Membership Service. By using the PSE, JXTA messages may be secured at two different levels in core messaging: at the messaging level, by using the CBJX [7] protocol, and at the wire transport level, via its own definition of TLS [17]. The messaging level operates at a higher abstraction level, encapsulating data without knowledge of the real network topology. The encapsulated data is then sent via the transport level, which does take into account both network topology and available transport protocols at the peer’s node. The standard messaging level provides the capability to include any type of digital signature elements into messages to be sent across the network. However, current standard messaging protocols never make use of this feature. CBJX (Crypto-Based JXTA Transfer) is a JXTA-specific protocol which provides lightweight secure message source verification by including into messages its own self-defined digital signature element, providing data integrity and authentication. This approach provides protection against active threats. Even though CBJX is formally specified as a wire transport protocol, it can be truly considered to operate at the messaging level, or, more exactly, at a meta-messaging level. The main reason is that it lacks the capability to directly send messages between endpoints, which is what ultimately defines a wire transport protocol in JXTA. CBJX pre-processes messages in order to provide an additional secure encapsulation, creating a new message that is then relayed to an underlying wire transport protocol. For that reason, we classify CBJX as message level security. In addition to the original message’s digital signature, an information block, according to the definition shown in XML Listing 5, is also encapsulated with the secured message: a CbJxMessageInfo element, which contains the source peer credential (a PSE certificate), both the source and destination addresses, and the source peer ID. This cryptographic information block is digitally signed as well, generating two distinct signatures within the final CBJX message. The certificate inside the cryptographic information block is used to validate both signatures. In order to generate both signatures, XML data is serialized and then fed to the signature algorithm, processed as plain text. An overview of the final message encapsulation is shown in Figure 3. CBJX encapsulates signatures by using a single Signature element containing a Base64-encoded PKCS#7 [27] binary signature. Once the final CBJX message is complete, it is sent using any wire transport protocol, just like as a standard message. On reception, the CBJX information block is extracted and both signatures are validated, acting in a transparent manner as far as upper layer protocols is concerned by providing the original message. Apart from digital signatures, CBJX provides an additional lightweight authenticity method by using CBIDs [33]. The concept of CBIDs, or statistically unique and cryptographically verifiable IDs, was initially conceived for IPv6 addressing in order to solve the issue of address ownership, avoiding router supplantation attacks and binding update packet spoofing [6,8]. Using this mechanism, each address is automatically bound to a specific node. It is important to notice that by using this method, authentic messaging is provided without the need of certificates issued by a trust anchor. At wire transport level, JXTA provides its own definition of standard TLS, allowing private, mutually authenticated, reliable streaming communications. Thus, TLS protects against both passive and active threats. As a wire transport protocol, it is responsible for encoding message data and sending it across the network. The protocol is composed of two layers: the TLS Record Protocol and the TLS Handshake Protocol. The TLS Record Protocol provides connection security with two basic properties: - The connection is private. Symmetric cryptography is used for data encryp- tion (e.g., DES [18], RC4 [28], etc.) The keys for this symmetric encryption are generated uniquely for each connection and are based on a secret negotiated by the TLS Handshake Protocol. The Record Protocol can also be used without encryption. - The connection is reliable. Message transport includes a message integrity check using a keyed MAC. Secure hash functions are used for MAC computations. The Record Protocol can operate without a MAC, but is generally only used in this mode while another protocol is using the Record Protocol as a transport for negotiating security parameters. In the specific case of JXTA, messages are delivered securely between endpoints even when multiple hops across peers are necessary. Even though TLS is a binary protocol, JXTA implements some of its data exchanges using XML elements (which encompass binary content). Three element types are defined in order to implement the protocol: TLS Content, which encapsulates transmitted secure data, Acknowledgements, which acknowledge data reception, and Retries, when a message is sent because of an apparent failure at a previous transmission. The latter element will be always present with a TLS Content element. All standard binary data structures defined in TLS are included into the TLS Content element. By combining both CBJX and TLS, it is possible to trump both passive and active attackers by achieving data privacy, integrity and authenticity. Application developers may decide which protocol to use depending on their constraints (such as operating under a non-PSE peer group). It also must be taken into account that both types of transport methods do not support full advertisement propagation, they only support point-to-point communications. That means that applications which are based on multicast are still prone to security threats. 4.4.1 Service access When accessing a service peer credentials must be checked in order to decide whether some peer has real access to that service. This is necessary since, as we could see in subsection 4.2, actually everybody may instantiate a peer group and try to access resources, acting as an interloper. This may be achieved in JXTA by using the peer group Access Service. As far as the Access Service is concerned, the current JXTA reference implementation offers three kinds of access control, each one bound to each different membership service credential type: The Always Access Service, which does not really check for access control and allows any operation. It is the default Access Service for peer groups. The simpleACL Access Service uses Access Control Lists in order to establish which identities may perform each group operation. The access lists are distributed as parameters within the peer group advertisement. The PSE Access Service provides an interface to PKIX certificate path validation. A trust anchor is set for the validation process and all credentials are validated against this anchor in order to decide whether the operation is permitted or not. It must be pointed out that current Access Service approaches are strictly tied to ensure that some identity may access some service. Whether that identity really belongs to a legitimate peer group member is never checked, it is always assumed correct. Since the Membership Service is not up to the task of checking group membership either (any peer may claim any identity), as exposed in section 4.2, this is something JXTA application developers should heavily take into account. However, it is possible to implement an Access Service which also checks group membership, as it is the case of the non-core approach in [4], previously presented in subsection 4.2.1. Furthermore, the Access Service provides a single primitive which just checks credential content, but does use on any kind of authentication protocol. This is not sufficient to guarantee protection against spoofing, since credentials are freely exchanged across the network, being public. Some other method must exist which tests credential authenticity, such as TLS or CBJX, in order to guarantee authenticity. 4.5 Disconnection No real vulnerabilities threaten disconnection, apart from those which force an unintended shutdown due to unauthorized local access to the application. However, such problems are related to the operating system, so it can be considered outside the scope of this study. Disconnection was mainly included for the sake of completeness in formalizing the peer’s full lifecycle. 4.6 Security evaluation summary Table 2 summarizes the JXTA security evaluation, as far as core functionalities is concerned (non-core proposals are not included). For each JXTA basic operation, it is shown whether it is vulnerable to each of the typical threats and which security mechanism exists in order to counter it. The threats are those listed in section 3.2: Eavesdropping (Evs), Traffic Analysis (TAn), Spoofing (Spf), Main-in-the-Middle (MitM), Replay attacks (Rp), Local data alteration (LDA) and Software security flaws (SSF). \[ \begin{array}{|c|c|c|c|c|c|c|c|} \hline \text{Operation/Threat} & \text{Evs} & \text{TAn} & \text{Spf} & \text{MitM} & \text{Rp} & \text{LDA} & \text{SSF} \\ \hline \text{Startup} & \text{N/A} & \text{N/A} & \text{N/A} & \text{N/A} & \text{N/A} & \text{V(1)} & \text{P(OSS)} \\ \hline \text{Join} & \text{N/A} & \text{N/A} & \text{V(5)} & \text{N/A} & \text{N/A} & \text{P(Key Enc.)} & \text{P(OSS)} \\ \hline \text{Publish/Discover} & \text{V(2)} & \text{V(3)} & \text{P(Signed Adv.)} & \text{V(4)} & \text{P(OSS)} \\ \hline \text{Messaging} & \text{P(TLS*)} & \text{V(3)} & \text{P(TLS*/CBJX)} & \text{V(4)} & \text{P(OSS)} \\ \hline \text{Disconnect} & \text{N/A} & \text{N/A} & \text{N/A} & \text{N/A} & \text{N/A} & \text{N/A} & \text{P(OSS)} \\ \hline \end{array} \] According to Table 2, the main vulnerabilities in JXTA’s basic peer operations may be summarized in five different types as follows: - **V(1):** Code signing may be easily compromised. Malicious executable code can easily be built and cannot be automatically discovered when installed. - **V(2):** No encryption mechanism exists. Advertisements are transmitted in plain text. - **V(3):** No data flow masquerading mechanism exists. It is easy to identify important peers by its traffic. - **V(4):** No integrity check is enforced on the local cache. Changes by a local attacker are not discovered. - **V(5):** No real authentication is enforced. Any peer may ultimately join any group as an interloper. ### 4.7 Security cost analysis This subsection provides a brief overview of the overhead introduced by the security mechanisms detailed in this survey. In order to assess the impact on performance, two different sets of scenarios have been taken into account when running a set of experiments: advertisement publication and discovery, evaluating the Signed Advertisement mechanism, and message propagation, evaluating CBJX. We have focused exclusively on CBJX since thorough studies on JXTA’s TLS performance already exist [16]. A set of 50,000 tests have been run for each different scenario using a PC with a 1.20 GHz Intel Pentium M processor and 1 Gb of RAM under Ubuntu 8.10 and SUN’s Java Runtime Environment version 1.6.0.10 (which includes the Java Cryptographic Extension (JCE)) . We decided to use a computer... which is below today’s average standards to assess the impact of using JXTA’s security mechanisms on lower end machines. In the tests, messages of different sizes have been processed in order to measure the time needed for secure encapsulation (in the cases of advertisement publication and message transmission) and the time for extraction (in advertisement discovery and message reception). Different suggestions exist on regards to desirable data size in order to test message performance [16,3]. We have decided to chose the one in [16]: 1kb, 10Kb, 100Kb, 1Mb and 10Mb. No suggestions exist for advertisement size, but by analyzing their XML schema [42], we consider that a good estimation is about 1Kb for small sized ones, 3Kb for medium sized ones and 5Kb for the bigger ones. The total time for processing protected data (encrypted and/or signed) has been divided in three separate categories, namely crypto processing, XML processing and data processing. The first category measures the time needed to compute cryptographic operations, for instance digital signatures, validation, encryption, etc. The second category, XML processing, measures the time spent to process XML structures in order to provide secure encapsulation/extraction. Finally, data processing measures the time needed for raw data operations, mainly data serialization and Base64 encoding/decoding. The time spent in cryptographic operations mainly depends on the efficiency of the cryptographic provider or even the use of hardware implementations. As we have already mentioned, in our tests we have used the Java Cryptographic Extension (JCE) as a default cryptographic provider. The time dedicated to XML processing depends on the underlying XML parser (in this case, JXTA uses its own XML processing library). Finally, data processing is usually dependent on raw computer power (memory and input/output speed). The experiment results are presented in Table 3 regarding securing advertisements and Tables 4 and 5 regarding securing messages. Data shows that cryptographic operations are the heaviest burden when using JXTA’s security mechanisms. Furthermore, it is worth mention that the sender needs more processing time than the receiver to deal with cryptographic data. In order to provide a better idea of the magnitude of the time for securing data, measurements have been taken for processing time when no security is used. The estimated time for generating advertisements and messages is about 4ms and the time needed for reading discovered advertisements is about 2ms . These values are very small compared to the cost of cryptographic operations, such as 455ms in the worst case scenario (securing a 10Mb message). However, regarding a real scenario, we should have into account the required trip time between the communicating peers. This variable is dependant on many factors, but from the measurements in [16], its value goes from 100ms for 1Kb up to <table> <thead> <tr> <th>Operation</th> <th>Publication</th> <th>Discovery</th> </tr> </thead> <tbody> <tr> <td>Advertisement Size</td> <td>1Kb 3Kb 5Kb</td> <td>1Kb 3Kb 5Kb</td> </tr> <tr> <td>Crypto processing</td> <td>36.295 37.953 39.335</td> <td>2.199 2.637 3.04</td> </tr> <tr> <td>XML processing</td> <td>0.318 0.518 0.699</td> <td>0.621 1.266 1.877</td> </tr> <tr> <td>Data processing</td> <td>0.422 0.943 0.74</td> <td>0.032 0.032 0.032</td> </tr> <tr> <td>Total</td> <td>37.035 39.414 40.774</td> <td>2.852 3.395 4.949</td> </tr> </tbody> </table> Table 3 Average processing time for securing advertisements. Time in ms, up to three decimals <table> <thead> <tr> <th>Operation</th> <th>Transmission</th> </tr> </thead> <tbody> <tr> <td>Message Size</td> <td>1Kb 10Kb 100Kb 1Mb 10Mb</td> </tr> <tr> <td>Crypto processing</td> <td>34.277 44.758 51.33 99.96 455.579</td> </tr> <tr> <td>XML processing</td> <td>0.169 0.175 0.186 0.201 0.207</td> </tr> <tr> <td>Data processing</td> <td>0.061 0.062 0.076 0.1 0.11</td> </tr> <tr> <td>Total</td> <td>34.507 44.995 51.592 100.261 455.896</td> </tr> </tbody> </table> Table 4 Average processing time for securing messages. Time in ms, up to three decimals <table> <thead> <tr> <th>Operation</th> <th>Reception</th> </tr> </thead> <tbody> <tr> <td>Message Size</td> <td>1Kb 10Kb 100Kb 1Mb 10Mb</td> </tr> <tr> <td>Crypto processing</td> <td>0.969 1.315 4.764 41.051 394.623</td> </tr> <tr> <td>XML processing</td> <td>0.275 0.277 0.295 0.296 0.395</td> </tr> <tr> <td>Data processing</td> <td>0.009 0.013 0.066 0.573 6.001</td> </tr> <tr> <td>Total</td> <td>1.253 1.605 5.125 41.92 401.019</td> </tr> </tbody> </table> Table 5 Average processing time for validating secured messages. Time in ms, up to three decimals 10.000 ms for 10 Mb messages. Taking this values, the magnitude of the time for secure data processing is affordable regarding the total time, which includes processing and trip time. 5 Conclusions and further work Being an OSS project, JXTA has been intensely reviewed, and as a result, its security features have improved over time. It can be summarized that the current implementation of JXTA has evolved to include an acceptable level of security, fulfilling minimum requirements for present day applications. However, this is at the cost of being bound to a very specific group membership model: PSE. In the case that a custom model is chosen for some applications, we will find out that most of its security capabilities may no be directly used, only CBJX becomes still available. This is not always desirable in a framework that was conceptualized to be open and easy to adapt to any environment. It would be useful that any custom application security model could make use of as many as possible JXTA secure mechanisms such as TLS or advertisement signature. Another useful feature, right now constrained by the assumption that PSE will always be used, would be the capability to use different types of keystores, apart from that in each peer’s the local cache. Specially, being able to go beyond using the file system as cryptographic storage. However, it is not possible for now. It is also important to take into account when designing JXTA applications that, even though PSE provides a certificate-based secure environment, it is still necessary to chose some methods in order to guarantee key authenticity. PSE assumes no trust model, just provides the necessary tools in order to deploy it. Furthermore, it makes no effort to provide any method of group membership revocation. Finally, core JXTA still has some gaps pending to be filled even when all its security capabilities are fully used (see Table 2). First of all, no mechanism exists in the current version of JXTA in order to secure messaging for propagation mechanisms, specially one that provides some degree of privacy. In addition, no security exists for the local cache, even though very important data is stored inside. At least, some degree of integrity would be desirable, such as maintaining advertisement signatures. Fortunately, due to its open project approach, additional security proposals, though not currently included in the standard JXTA distribution, have been proposed in order to solve all of these issues. Once the state of security for JXTA has been clearly established, further research includes providing additional security services at core level without the need of PSE. Our main efforts will be twofold. First of all, creating a peer group environment where membership is really checked during the join process. Then, improving advertisement and messaging security, both in cache storage as well as during transport. Additional research may include comparing the current state of security of JXTA to that of other P2P middlewares, from both a qualitative and quantitative standpoint. References
{"Source-Url": "http://openaccess.uoc.edu/webapps/o2/bitstream/10609/8723/1/2009_JSS.pdf", "len_cl100k_base": 15455, "olmocr-version": "0.1.53", "pdf-total-pages": 35, "total-fallback-pages": 0, "total-input-tokens": 69072, "total-output-tokens": 19574, "length": "2e13", "weborganizer": {"__label__adult": 0.0004436969757080078, "__label__art_design": 0.0004458427429199219, "__label__crime_law": 0.0015783309936523438, "__label__education_jobs": 0.0015764236450195312, "__label__entertainment": 0.0002353191375732422, "__label__fashion_beauty": 0.00019240379333496096, "__label__finance_business": 0.0010204315185546875, "__label__food_dining": 0.0003113746643066406, "__label__games": 0.0018606185913085935, "__label__hardware": 0.0023746490478515625, "__label__health": 0.00046634674072265625, "__label__history": 0.0005106925964355469, "__label__home_hobbies": 0.0001380443572998047, "__label__industrial": 0.0005564689636230469, "__label__literature": 0.00044465065002441406, "__label__politics": 0.0005617141723632812, "__label__religion": 0.0004668235778808594, "__label__science_tech": 0.28076171875, "__label__social_life": 0.0002627372741699219, "__label__software": 0.12213134765625, "__label__software_dev": 0.58251953125, "__label__sports_fitness": 0.0003018379211425781, "__label__transportation": 0.0005869865417480469, "__label__travel": 0.00026488304138183594}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 80622, 0.03945]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 80622, 0.32604]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 80622, 0.91647]], "google_gemma-3-12b-it_contains_pii": [[0, 1951, false], [1951, 4640, null], [4640, 7708, null], [7708, 10003, null], [10003, 11556, null], [11556, 14082, null], [14082, 16355, null], [16355, 18088, null], [18088, 20575, null], [20575, 23063, null], [23063, 25022, null], [25022, 27012, null], [27012, 28768, null], [28768, 31481, null], [31481, 34205, null], [34205, 36479, null], [36479, 38446, null], [38446, 41434, null], [41434, 44249, null], [44249, 46950, null], [46950, 49775, null], [49775, 52580, null], [52580, 54729, null], [54729, 57465, null], [57465, 58898, null], [58898, 61464, null], [61464, 63823, null], [63823, 66248, null], [66248, 69198, null], [69198, 70719, null], [70719, 73580, null], [73580, 75674, null], [75674, 77943, null], [77943, 80169, null], [80169, 80622, null]], "google_gemma-3-12b-it_is_public_document": [[0, 1951, true], [1951, 4640, null], [4640, 7708, null], [7708, 10003, null], [10003, 11556, null], [11556, 14082, null], [14082, 16355, null], [16355, 18088, null], [18088, 20575, null], [20575, 23063, null], [23063, 25022, null], [25022, 27012, null], [27012, 28768, null], [28768, 31481, null], [31481, 34205, null], [34205, 36479, null], [36479, 38446, null], [38446, 41434, null], [41434, 44249, null], [44249, 46950, null], [46950, 49775, null], [49775, 52580, null], [52580, 54729, null], [54729, 57465, null], [57465, 58898, null], [58898, 61464, null], [61464, 63823, null], [63823, 66248, null], [66248, 69198, null], [69198, 70719, null], [70719, 73580, null], [73580, 75674, null], [75674, 77943, null], [77943, 80169, null], [80169, 80622, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 80622, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 80622, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 80622, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 80622, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 80622, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 80622, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 80622, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 80622, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 80622, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 80622, null]], "pdf_page_numbers": [[0, 1951, 1], [1951, 4640, 2], [4640, 7708, 3], [7708, 10003, 4], [10003, 11556, 5], [11556, 14082, 6], [14082, 16355, 7], [16355, 18088, 8], [18088, 20575, 9], [20575, 23063, 10], [23063, 25022, 11], [25022, 27012, 12], [27012, 28768, 13], [28768, 31481, 14], [31481, 34205, 15], [34205, 36479, 16], [36479, 38446, 17], [38446, 41434, 18], [41434, 44249, 19], [44249, 46950, 20], [46950, 49775, 21], [49775, 52580, 22], [52580, 54729, 23], [54729, 57465, 24], [57465, 58898, 25], [58898, 61464, 26], [61464, 63823, 27], [63823, 66248, 28], [66248, 69198, 29], [69198, 70719, 30], [70719, 73580, 31], [73580, 75674, 32], [75674, 77943, 33], [77943, 80169, 34], [80169, 80622, 35]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 80622, 0.09132]]}
olmocr_science_pdfs
2024-12-08
2024-12-08
b4d96213c7c26cf1e2feb00e62c61a60d1593eb6
Software Testing Process in a Test Factory From Ad hoc Activities to an Organizational Standard Rossana Maria de Castro Andrade1,*, Ismayle de Sousa Santos1,†, Valéria Lelli1, Káthia Marçal de Oliveira2 and Ana Regina Rocha3 1Federal University of Ceará, GREat, Fortaleza, CE, Brazil 2University of Valenciennes, LAMIH, CNRS UMR 8201, Valenciennes, France 3Federal University of Rio de Janeiro, COPPE, Rio de Janeiro, RJ, Brazil Keywords: Software Testing, Test Factory, Test Process. Abstract: Software testing is undoubtedly essential for any software development. However, testing is an expensive activity, usually costing more than 50% of the development budget. Thus, to save resources while performing tests with high quality, many software development companies are hiring test factories, which are specialized enterprises for the delivery of outsourced testing services for other companies. Although this kind of organization is common in the industry, we have found few empirical studies concerning test factories. In this paper, we report our experience in the definition, use, and improvement of a software testing process within a test factory. To support the implantation of the test factory, we applied the PDCA (Plan-Do-Check-Act) cycle using the lessons learned in the PDCA check phase to improve the testing process. As a result, we have decreased the number of failures found after the software delivery and thus a higher value for DRE (Defect Removal Efficiency) measure. We also present 12 lessons learned that may be applicable by other test factories. 1 INTRODUCTION Software testing is one of the most expensive and time-consuming activities during software development (Shamsoddin-motlagh, 2012). The costs associated with this activity can reach more than 50% of the total costs of producing software (Myers et al., 2011). This high cost is because test requires time, knowledge, planning, infrastructure, and skilled personnel (Myers et al., 2011). Also, as the software often has to be delivered as soon as possible, the time available for the testing activity is usually compromised. Besides, the testing of particular kinds of applications (e.g., mobile applications) can be challenging (Dantas et al., 2009; Bezerra et al., 2014). Currently, hiring testing services from independent organizations, named test factories (Sanz et al., 2009), has become common in the industry. Test factories can be seen as software factories specialized in software testing. By leveraging test factories services, a software development project can benefit from tests with high quality and low cost since a software project does not need to invest in its own test team. Therefore, we decide to implement a test factory to provide testing services not only for the Research and Development and Innovation (R&D&I) projects executed in our research group1 but also to external companies. With this belief in mind, we have been working in the software testing process definition in a test factory2 since 2013. We highlight that test factories should work in a close relation with their customers (other software organizations that develop the software system to be tested) to be efficient. Thus, the definition of roles, responsibilities and competencies should be clearly defined in both parties: the test factory and the customer (software organization). Moreover, the control and tracking of the correction of bugs detected should be made to ensure traceability. Unquestionably, a software process that defines all activities, roles, and artifacts (used and produced in the activities) is a good *Researcher Scholarship - DT Level 2, sponsored by CNPq †PhD Scholarship (MDCC/DC/UFC) sponsored by CAPES 2http://fabricadetestes.great.ufc.br/ practice to address all these requirements. We argue that the definition and institutionalization of a testing process should be performed on a continuous improvement cycle mainly in the case where two or more organizations should interact to assure the execution of the activities and their internalization in all parties involved. This paper presents how software testing activities were continually integrated using a process continuous improvement cycle based on the lessons learned collected. So, the main contribution of this work is to report our experience on a definition, use, and improvement of a standard test process within a test factory. We also present 12 lessons learned that can be applicable by other test factories or in-house test teams to improve their software testing process. The paper is organized as follows. Section 2 reports our experience in software testing process improvement from the ad hoc testing to the standard test process. Section 3 discusses the results achieved. Section 4 presents the related work and, finally, Section 5 presents our conclusion and future work. 2 SOFTWARE TESTING PROCESS DEFINITION, USE AND IMPROVEMENT IN PRACTICE To define software testing activities, we followed the well-known cycle for process continuous improvement proposed by Johnson (Johnson, 2002): the PDCA (Plan-Do-Check-Act). The PDCA has four steps. It begins with the planning and the definition of improvement objectives. Next, the planning is executed (Do) and then evaluated (Check) to see whether the initial objectives are achieved. Actions are taken based on what was learned in the check step. If the changes are successful, they are included in the process. If not, it is necessary to go through the cycle again with modifications in the original plans. Figure 1 shows the PDCA cycle used during the testing process improvement described in this paper. We highlight that the several Do in that figure represent the application of the planning in more than one testing project. We followed this strategy to acquire more data to support the Check phase. It is worth noting that we have applied our testing process on several software projects (e.g., mobile and web projects) from the same company, but they have different product owners and/or project managers. Thus, this scenario enabled us to collect feedback from several customer’s teams while we ran the Figure 1: PDCA Cycle used in the testing process improvement. PDCA cycle. Next section describes the study object, i.e., the testing process used before the improvement. Then, the following sections present the two cycles of the improvement performed. Each cycle was started by the definition of goal (planning), and finalized with the definition of actions to be carried out in the next cycle. These actions were defined by the analysis of lessons learned collected after the execution of the planning in different projects. 2.1 Before the Test Factory: Ad hoc Testing The creation of our test factory was motivated by the need of one mobile manufacturer company, our main client, who does not have expertise in software testing. Once this client worked with Scrum methodology (Schwaber and Sutherland, 2016), we have started by identifying how to integrate testing activities as a service in its agile process. Scrum works with the concept of sprint, a time boxed effort during which a potentially releasable product increment is created, and with three roles (Schwaber and Sutherland, 2016): (i) Product Owner, responsible for maximizing the value of the product; (ii) Development team, consisting of professionals who do the work of delivering a potentially releasable increment of “Done” product at the end of each sprint; and (iii) Scrum Master, responsible for ensuring Scrum is understood and enacted. In the Scrum, the testing (now “agile”) is integrated with development efforts, being required tests for each product backlog item (e.g., a software functionality) (Myers et al., 2011). Thus, our initial goal was to encourage our customer to incorporate more test procedures in the software development. To do so, a test analyst was allocated to work closely with the software development team performing test activities as required. Following the Scrum, the test an- alyist performed functional testing at the end of each sprint. Furthermore, the developers created both unit and system tests without planning or documentation. One complete software project with eight developers, named here P1, was developed and tested following this structure. The duration of this project was about ten months (August 2013 until May 2014). With regard to the system tests, most of them failed (47%) and the failures were classified as critical, i.e., bugs that block the software. This high percentage of failed tests and the delay to find critical bugs motivated us to investigate how to improve our test process to identify the bugs as early as possible. 2.2 First Cycle: Establishing Test Procedures As mentioned in Section 2.1, the analysis of the results obtained from the ad hoc testing approach motivated us to adopt some practices and to formalize our testing process. The first practice is to allocate the test analyst to support the implementation of both unit and integration tests performed by the developers. First, the test analyst pointed out the basic tests scenarios, which the developers should implement by using JUnit tool\(^3\). In some cases, the test analyst also performed “Pair Testing”\(^4\) with each developer until they can create good tests cases at both unit and integration level. The second practice is regarding the validation of the backlog items. For each activity from the sprint backlog, it was added a validation with the test analyst to get the status “done”. We also included in this backlog specific activities for creating unit tests, emphasizing their importance within the sprint. When the development activity did not generate executable code, a review of the application code was made. On the other hand, if it is possible to execute the code, then automated tests or manual tests were performed to validate the functionality implemented in the activity. For each development activity, 1 or 0.5 points were added in the activity estimation for the validation of the product increment developed. Additionally, it was also added in the sprint Backlog one activity for the system testing of all products developed in the sprint. The last practice concerns the test specification. The test scenarios were documented in spreadsheets that were frequently updated by the test team and shared among the client. For the sake of simplicity, the test case specification in such spreadsheets contains only three columns: test scenario, step-by-step procedure, and results. Regarding the testing process, it was defined according to the sprint phases of the Scrum. Figure 2 shows the test process defined in the first improvement cycle. In the Sprint Planning phase, the test team estimates the testing effort and defines the test strategy according to the product requirements. Next, in the Sprint Execution, the test analyst creates the test scenarios, which are used: (i) by the developers to create both unit and integration tests; and (ii) by the testers to create automated tests scripts or perform manual tests. After the execution of the tests, their results are documented. Once a bug is found and fixed, the regression tests should be run again. Finally, in the Sprint Revision, the test team discusses the lesson learned to improve the testing process. We applied (Do phase from PDCA) the test process defined and the practices aforementioned in two development projects, named here P2 and P3. The project P2 was conducted between July 2014 and September 2014 with 12 developers, while the project P3 had 10 developers and occurred from September 2014 to December 2014. In the project P2, the low failures rate (15% of the total number of system tests) at the end of sprint shown us the greater participation of all developers in the product quality. It is worth mentioning that were not implemented automated tests in P2. In project P3, despite the failed test rate of 28%, none of them were of the critical type, representing an improvement comparing with the results obtained in project P1. We highlight that in this project the test automatization with tools (e.g., Robotium tool\(^5\)) made easier the regression testing. Regarding the tests documentation, the test team report that it is easier to document, plan and prioritize the tests according to changes in the sprints and the customer requests. Furthermore, they also reported that a bug tracker is crucial to to follow the fixed bugs and thus perform the regression testing efficiently. The main benefits that we obtained in the first improvement cycle are: (i) greater participation of all developers in the product quality; (ii) greater integration between developers and testers; and (iii) greater integration between the code and its test, once the test has become a part of the development of a feature. The main lessons learned from the execution of Do phase of PDCA in two projects (P2 and P3) were: - LL01: Test Documentation is essential. Our experience in the project P1 corroborates with our \(^3\)http://junit.org/junit4/ \(^4\)It is a kind of “Pair Programming activity (Zieris and Prechelt, 2016) applied on the software testing. \(^5\)http://robotium.com/ feeling that the lack of test documentation makes it difficult to monitor, replicate and evaluate them; - **LL02**: There is no need for specialized roles, but it is essential both to follow a test process and to have a team of experts. During the testing of P1, where developers and testers do testing without planning, many of the defects found at the end of the sprint were critical. In projects P2 and P3, the participation of an expert test analyst and the use of a testing process enabled critical defects to be identified in the early stages of development; - **LL03**: It is not always possible to automate the tests, but it is advisable. Automating tests is interesting because it facilitates continuous feedback. The planned use of a systems test automation tool in P3 supported the fast defect identification; - **LL04**: Pair Testing is a good practice to exchange experience between novices and expert testers. The application of Pair Programming to implement tests during P2 had a very positive impact, resulting in qualified developers involved with test activities and better communication among testers and developers; - **LL05**: The client should be aware of the testing activities. When the customer cannot participate in a decision at some point, we realized as a good practice to document the decisions taken concerning the testing activity to confirm them with the customer afterward (e.g., regarding test prioritization). We employed this practice in the three projects P1, P2, and P3 and we obtain a good feedback from the clients. Based on the aforementioned lessons learned, the next step (i.e., the Action phase in PDCA) is to define a standard software testing process. 2.3 Second Cycle: Defining a Standard Software Testing Process Based on the previous experience, we decided to evolve the test procedures for a formal software testing process that establishes activities, responsibilities, roles, and artifacts to be used and produced. To that end, several specific policies were created based on the Reference Model for Brazilian Software Process Improvement (MPS.BR) (SOFTEX, 2006) For the test project management, we defined the following policies: - The project planning of the test factory results in the test plan and should be carried out by the test factory manager; - The test plan should have the approval by the stakeholders and client aiming to establish commitments to the project; - The test factory manager should monitor the project continuously, based on the test plan and schedule; - The final phase constitutes project milestones; - Any changes in the test plan and schedule can only be implemented after obtaining new commitments with the client and all involved in the test factory. For the requirements management, the policies establish that: - All the testing requirements should be evaluated by the client and the stakeholders of the test factory; - Any change in the testing requirements should have impact assessment before being approved; - The plans, artifacts, and activities of the testing requirements management process should be maintained to assure their consistency; - The specification of the testing requirements should have the approval and commitment of all stakeholders; - The change requests in testing requirements must be recorded in e-mail or meetings and should be stored. Finally, for the quality assurance, all the test factory projects should be audited for adherence to the process and product quality, and the non-compliance that are not resolved in deadlines (up to three days) should be scaled to higher hierarchical levels. The standard process is organized as a work breakdown structure where phases are decomposed in activities and those in their turn in tasks. Figure 3 gives an overview of the activities of our test factory process. This process is based on the iterative and incremental lifecycle. Three main phases (planning, elaboration and execution) were defined as follows. 1. Planning phase aims at starting a project and performing the planning activities. The first activity “Initiate project” involves kick-off/initial meetings to understand and review (if applicable) the product requirements to be tested. In the “Plan Project”, the test factory manager elaborates the test plan with test requirements as agreed with the client. Also, the SQA (Software Quality Assurance) analyst must manage the adjustments, for instance, if nonconformities related to the testing process exist, such as a non-written confirmation that both parties agreed with the test plan, they should be solved in an established period. - The main artifacts produced in this phase are minutes of the kickoff meeting, test plan with schedule, process and product checklists for phase 1, and project status report. 2. Elaboration phase aims at preparing the test execution. This phase starts with an initial meeting involving the test team to align the test plan. Then, test scenarios and the test cases are specified by the test analysts in the “Design Tests” activity. This specification is based on product and test requirements provided by the client. To be approved, the test specification must be examined by another test analyst as a peer review task. Other tasks carried out in this phase are the establishment of traceability matrix, the environment configuration, and the creation of automated test scripts (if applicable). - The main artifacts produced in this phase are traceability matrix, test specification with test scenarios/cases, test environment with load test mass (if applicable), checklists for phase 2 (change control, audit) and test artifacts evaluation reports, such as test cases evaluation report. 3. Execution phase aims at carrying out the execution (manual or automated) of the tests artifacts specified previously (e.g., test scenarios/cases). Similarly, to the elaboration phase, the test team attends an initial meeting. In the next activity, the tests are executed, and their results are reported to be evaluated. It is worth noting that, the tests can be executed by a tester (e.g., a testing intern) but the test leader must determine in the “Analyze test incidents” activity whether the reported incidents are actual bugs. Once the incident is confirmed as a bug, it is registered in a bug/issue tracking tool. The Execution phase ends with a meeting with those involved in the project to record lessons learned. - The main artifacts produced in this phase are test incident reports, bugs/failures report, checklists for phase 3 (audit, adherence to process), lessons learned, and project closing statement. Our test factory process is adherent to the MR-MPS-SW (Rocha et al., 2005) and includes the quality assurance process and activities related to configuration management and verification. As depicted in Figure 3, two management activities are presented in all phases. The first one is “Manage Phase” that is executed throughout the phase. The second one, “Monitor project on milestones”, is the activity for monitoring the project in the final milestone of the phase. For example, this activity registers the project status, stores the phase artifacts (e.g., test plan, project status report) and audits the adherence of the process at a phase following a specific checklist. The organizational chart of our test factory is shown in Figure 4. The factory test team is composed of a high quality team with academic and professional experience on software such as PhDs with expertise in Software Testing, certified professional testers (International Software Testing Qualifications Board - ISTQB certification), usability experts, software quality experts, postgraduate and graduate students of Computer Science/Software Engineering courses. The roles and the main activities within the factory test process are described in Table 1. Also, the artifacts that should be produced by each role are presented in this table. We have applied the second improvement cycle on two projects (P4 and P5) that performed several sprints. Both were developed under the Scrum methodology and, therefore, we have considered a release with one or more sprints as a whole testing project. Indeed, the development process adopted by the client is transparent and thus independent of our test factory process. The main difference is the kinds of artifacts that we have to produce. In a Scrum project, we start by attending the planning meetings to understand the functional requirements and to have an overview of the test scenarios must be covered. Once the test scope is defined, the project manager elaborates the test plan with the test requirements, schedule, human resources, and risks. Table 1: Roles, main activities and artifacts. <table> <thead> <tr> <th>Role</th> <th>Main Activities</th> <th>Artifacts</th> </tr> </thead> <tbody> <tr> <td>Coordinator</td> <td>Coordinate the test factory project (decision making, fundraising, conflict resolution); develop and/or review artifacts; organize, participate and conduct meetings</td> <td>Test project work plans, budgets</td> </tr> <tr> <td>Test Manager</td> <td>Apply the test factory process and define measures appropriate to collect the test project status; elaborate process artifacts; plan and control the team activities</td> <td>Test plans, meeting minutes, project status reports</td> </tr> <tr> <td>Consultants</td> <td>Conduct the research activities in test project; organize and conduct training of advanced testing techniques; audit the adherence to the process and the product quality; provide new testing techniques (quality measures or fault models) to be applied to advanced application domains (ubiquitous/IoT domain)</td> <td>Usability test report, checklists, technical/researcher reports</td> </tr> <tr> <td>Test Leader</td> <td>Ensure compliance with planning execution; disseminate the technical information to the test team; evaluate test artifacts/deliverables</td> <td>Test artifacts evaluation reports</td> </tr> <tr> <td>Test Analyst</td> <td>Elaborate test artifacts; support the test leader to verify technical problems raised by the client; report the impediments to the test leader; validate the incidents reported by testers</td> <td>Test specification, test scripts, failures report</td> </tr> <tr> <td>Tester</td> <td>Execute the tests; report the test results (incidents) and submit to the test analyst to be validated</td> <td>Incidents report</td> </tr> </tbody> </table> We have faced several challenges in the implementation of the second cycle. Firstly, we have worked on several maintenance projects, whose the maintenance requirements are organized as a backlog of users stories. In these projects, most of the functional requirements are not specified or there is no previous test specification. To minimize the risks, we have to define the test scenarios according to some test criteria provided by the client and thus ensure minimal test coverage. Secondly, the phases defined in the second cycle require several test artifacts. Then, we have implemented this cycle incrementally. We have started by defining the test templates that must be followed in the elaboration/execution phases. Then, we have provided training sessions to explain the process and the artifacts that must be produced. This task was crucial since the test team of the previous cycles has a limited experience in test case specification. As previously mentioned, we applied (Do phase) the test process defined and the practices aforementioned in the testing of two development projects, named here P4 and P5. We conducted their test projects in four months (March 2016 to June 2016). The project P4 involved the development of three software systems (A, B and C) and was organized in ten sprints, while the project P5 concerns three other systems (D, E, and F) developed in the total of six sprints. The application domains of projects P4 and P5 are mostly mobile and web, respectively. Thus, the number of tests depends on systems requirements and also their domains. For example, we have tested for Software A and Software C, both the client (mobile) and the server (web). However, they are simpler than Software D, which is a game mobile that requires the testers’ skills to play it, and also the tests must cover the game rules. In some sprints, the tests only focus on bug fixed and their impact. We highlight that these results do not cover the unit and integration tests performed by the developers team and the acceptance testing executed by the client test team (if applicable). We have experienced in the second cycle a better control of our test activities since we have more tests documented and, therefore, we could leverage them for the next sprints, for instance, to perform regression tests. With the execution (Do phase of PDCA) in 16 software releases in projects P4 and P5, the main lessons learned were: - **LL06**: Process templates adjustment could be needed to some specific client. Although we standardized the test documents used in our testing process, in some cases new fields (e.g., indicating if the test is for basic, alternative or exceptional flow of use cases) are added to meet the needs of specific clients; - **LL07**: The application of the test process should be supported by the test team, which needs to be trained firstly. We have adopted an implementation of our test process in a bottom-up way starting by the test documents used daily (e.g., test scenario/case specification) to minimize the impacts. Also, we have provided intensive training to balance the test team that had never done documentation and regular evaluations of both test documentation and test scripts quality; • LL08: The hierarchical structure and roles/activities were essentials to centralize and manage the demands for the test factory. Besides, the inclusion of roles helps the team focuses on its objectives (e.g., test manager monitors all the activities, testers run tests specified by test analysts); • LL09: At the first moment, the test process increased the time spent and costs in the testing activity. For instance, the test analyst took a longer time to produce the test artifacts (e.g., test scenarios and their test cases) when we implemented the Elaboration/Execution phases. We have observed that the evaluation report took a meaningful time (between 1 hour and 3 hours). Moreover, this activity works as a round trip process: check-correct-check until the test specification is satisfactory. One improvement here is to provide checklists to support this activity; • LL10: In spite of the testing process that we follow rigorously, we observed that the experience-based testing (IEEE, 2015) is interesting for a first interaction with the application by using, for instance, the exploratory testing. In our process, we have started with this kind of testing when the requirement specifications or user stories (in Scrum projects) are not provided by the client. In such a case, the client must provide at least the test acceptance criteria. • LL11: Sharing the same database between tester team and development team could lead to rework, especially in the test documentation because the test data defined before could not be more available (e.g., if a developer deletes a database while implementing some new feature). Such problem also impacts on several test scripts that have to be updated. Furthermore, the previous versions of the application could be used as test oracle in the regression testing and also to verify intermittent bugs; and • LL12: An emergency release called “Hot fix” requires a fast test feedback. We call “Hot fix” the time box for fixing and testing critical bugs that often have to be deployed to a client in less than 24h. In such releases, the test team usually does not have time to run all the process as defined, so the team just creates the main test artifacts, for instance, the test scenarios/cases specification. Currently, we have worked on the specific checklists defined by the activities “Manage the phase”, and “Monitor the project in the final milestone of the phase”. 2.4 Results To evaluate the effectiveness of our test factory process, we used a well-known metric called Defect Removal Efficiency (DRE) (Jones, 1996), which is given as follows: \[ \text{DRE} \% = \frac{\text{TestFailures}}{\text{TestFailures} + \text{ProductionFailures}} \times 100 \] TestFailures are the number of total failures found by the test team before the software delivery. ProductionFailures are the number of failures found by clients and/or users after the software delivery. Figure 5 shows the DRE results collected for three software projects: software A, B, and C. We have measured the DRE in the first cycle (without the standard test process) and the second cycle (with the standard test process), with a total of 28 software releases: 13 without and 15 with the process. We did not distinguish the different software phases (e.g., requirements, design) to collect the DRE. Table 2 gives an overview of the software size, total of failures, DREs, and standard deviations results per software. The average DREs for the software A is 30,50% (first cycle) and 30,72% (second cycle). The average DREs for the software B is 15,58% (first cycle) and 35,08% (second cycle). The average DREs for the software C is 11,67% (first cycle) and 37,78% (second cycle). We can observe that the highest value of DRE was 37,78% (Software C) against the great value 95% suggested by Jones (Jones, 1996). However, the DRE values had increased for the three software when our test factory process was implemented in the second cycle. Also, the standard deviation value is low for the Software A (8,62%) in the second cycle. By contrast, the deviation values have increased for the Software B - from 18,31% (first cycle) to 38,14% (second cycle) and Software C - from 14,53% (first cycle) to 43,32% (second cycle). We believe that this result was affected by the small sample size (e.g., the number of failures and releases) and also by the team experience in applying the process as we discussed in the next section. Although the standard deviation was a little high for Software B and C, we conclude that our testing process had improved their quality since their DREs had increased more than 100% in the second cycle. 3 DISCUSSION The implantation of the test factory process has several lessons learned as we presented in the previous Table 2: Total of Failures, DREs, and Standard Deviations per Software. <table> <thead> <tr> <th>Software ID</th> <th>Size (KLoC)</th> <th>Total of Failures (#) without proc</th> <th>DRE (%) without proc</th> <th>Std. Deviation (%) without proc</th> <th>DRE (%) with proc</th> <th>Std. Deviation (%) with proc</th> </tr> </thead> <tbody> <tr> <td>A</td> <td>384</td> <td>152</td> <td>30.50</td> <td>21.59</td> <td>30.72</td> <td>8.62</td> </tr> <tr> <td>B</td> <td>101</td> <td>94</td> <td>15.58</td> <td>18.31</td> <td>35.08</td> <td>38.14</td> </tr> <tr> <td>C</td> <td>117</td> <td>58</td> <td>11.67</td> <td>14.53</td> <td>37.78</td> <td>43.32</td> </tr> </tbody> </table> Figure 5: DRE results in the first cycle (without process) and the second cycle (with process). sections. Such lessons help us to evolve from ad hoc testing activities to a standard testing process. We discuss some lessons below. As we identified early (LL01), the test documentation is crucial. When we introduced the standard testing process and their artifacts, we have identified several problems related to the test specification such as uncovered test scenarios, duplicated test cases, etc. Furthermore, we have observed that the elaboration of the test artifacts has impacted on the team productivity (see LL09), mainly when the new test artifacts are introduced. To overcome this problem, we analysed the artifacts elaborated by the test team and also monitored the time spent to produce them. So, we provided some adjusts in the documentation (see LL06) to meet the needs of both the clients and the test team. Also, we provided several training sessions (see LL07) to ensure that some misunderstanding does not impact on the team productivity. Currently, we have used a simple spreadsheet to specify the test scenarios/cases. Such specification contains: (i) test scenario (what is being tested); (ii) test steps; (iii) expected output; and (iv) actual result. However, we have observed that a spreadsheet is not a good choice when we have several test cases (e.g., more than 50 longer test cases). Also, we cannot use version control efficiently with spreadsheets. As a future improvement, we intend to adopt a tool that allows the test analysts specify the tests directly on it and stores them on a server (e.g., TestRail6). With regard to the failures, they are reported in both JIRA7 software, which is shared with the development team, and spreadsheets. Note that, only the bug repository is shared with both teams. Our experience shows that we have to clearly separate the development and test environments (see LL11). In such a case, the configuration manager is responsible to handle the changes in both environments. Moreover, the repository’s permissions are strictly managed, i.e., none of the team have permission to delete bugs. For example, once a bug is registered, it is analysed by the test analyst, if the bug is invalid, only its state changes in that repository. Another important point to be discussed is the team qualification (LL02). In the first cycle, the test team works together with the development team as a “Pair Testing” approach (LL04). This kind of work helped developers to create good unit and integration tests. In the second cycle, we applied the “Pair Testing” between the experienced test analysts and the novices, and the results were also positive. Furthermore, the hierarchical structure of the team (LL08) by including the consultants is important to improve the test factory process. For example, the researchers are responsible for investigating new testing techniques (e.g., test automation - LL03) or mea- 6http://www.gurock.com/testrail/ 7https://www.atlassian.com/software/jira sures while the test analysts are responsible for applying them. The other important role is the SQA analyst who must ensure that the process is followed by the test team. In some cases, the nonconformities pointed out by the SQA analyst in early stages of the testing process (e.g., a non-written confirmation that the client agreed with the test plan - see LL05) help us to identify several problems that may compromise the test quality. We also would like to highlight that we could not apply the standard testing process in Emergency Releases (LL12). The most difficulty is to elaborate all test artifacts and execute, for example, the functional and regression tests within one working day. In such a case, we only execute the tests already specified and perform the exploratory testing. Indeed, this kind of test plays a vital role in our testing process when the requirement specification is not provided (LL10). We rely on such test to explore the application and thus elaborate the test scenarios and their test cases. The lesson learned presented above are not quantitatively measure. However, we leverage DRE measure to show the benefits of the standard testing process. We observed that the DRE results have increased in the second cycle, but they do not achieve the great value (e.g., 95%). We identified several reasons as follows: - The test team does not have any experience in applying testing process. Also, most of the team are novices in the projects; - The software (i.e., A, B, and C) that we applied the standard testing process are maintenance projects, and most of them had no documentation. In this case, we elaborated the test artifacts incrementally according to the release plan. We performed this cycle until the test documentation was complete; and - The whole test process have been not implemented. We have adopted this process on March 2016, and incrementally the test artifacts are introduced in the projects. So, we believe that when all test artifacts can be produced, the DRE results will be better. However, we have obtained good results until the present moment. 4 RELATED WORK We have found several test factories (CWI, 2017)(Cyber:con, 2017) but none of them describe their testing process in a literature. Thus, we also investigate papers related to testing processes. In this section, we discuss the related work into two categories: Test Factory and Software Testing Process. 4.1 Test Factory We have found several test factories that offer test services for software development companies. For instance, there are the CWI’s test factory (CWI, 2017), Cyber:con’s test factory (Cyber:con, 2017) and FH’s test factory (FH, 2017). The main characteristic of these enterprises is to have a dedicated test team able to provide specialized testing services (e.g., test case specification, test case execution). Those test factories, however, do not present their testing process in scientific or white papers since they want to protect their business from the competitors. Therefore, we cannot do any relation between our testing process and their test factory processes. By contrast, we have found two papers (Sanz et al., 2009; Cooper-Brown, 2015) that focus only on the implantation of test factories. For example, Sanz et al. (Sanz et al., 2009) define a process model to create a test factory, determining the roles, capacities, and responsibilities for each specified process. In their paper, Sanz et al. present succinctly 11 processes (e.g., Testing Planning) that are classified into three categories: Management, Technical and Support. Thus, this model provides the key elements of the process of a test factory. In our work, we focus on describing the experience for defining a standard testing process in an test factory from ad hoc testing activities performed in-house. Cooper-Brown et al. (Cooper-Brown, 2015) present a process to setup a test factory. This process is organized into three major phases: (i) Solution Definition, in which the existing organizational test processes are evaluated; (ii) Solution Design which involves designing processes (e.g., related to test strategy, organizational structure, etc.); and (iii) Solution Implementation, which could be executed by steps or by using a big bang approach. In our work, we focus on the definition, use and improvement of a testing process to implement a test factory based on the lessons learned. Additionally, Xia et al. (Xia et al., 2015) investigate the challenges in test outsourcing. To do so, the authors perform a empirical study through a survey with testers and interviews with SQA managers and team leaders. In our paper, we report the experience by applying the test factory process in real-world daily use involving several stakeholders (e.g., tester, client, research, SQA analyst). Furthermore, the benefits of our test factory are evidenced by the positive results of DRE collected from industry soft- 4.2 Software Testing Process Regarding the software testing practices, we have identified several research studies in the literature, we discuss them below. Engström and Runeson (Engström and Runeson, 2010), for instance, present the results of a qualitative survey conducted by using focus group meeting with 15 industry participants and an online questionnaire with 32 respondents. Based on this survey, the authors identified weaknesses and strengths in regression testing practices and also their good practices such as “run automated daily tests on module level”. Collins e Lucena Jr. (Collins and de Lucena, 2012) describe the experience with the use of open source testing tools in automation testing into two development projects using Scrum. Santos et al. (Santos et al., 2011) also describe the use of testing practices in agile environments. In contrast to our work, they focus on specific issues within the software testing process (e.g., the use of testing tools) whereas we present an overview of our testing process and how we evolve this process over two years. Ramler and Felderer (Ramler and Felderer, 2015) propose a process for risk-based test strategy development that consists of seven steps: (1) definition of risk items, (2) probability estimation, (3) impact estimation, (4) computation of risk values, (5) determination of risk levels, (6) definition of test strategy, and (7) refinement of test strategy. Our testing process is not a risk-based test strategy. Instead, our process is adherent to the MR-MPS-SW(SOFTEX, 2006) and thus the risks are described in the test plan and managed during all the process. Afzal et al. (Afzal et al., 2016) present the results of a systematic literature review (SLR) which identified 18 software test process improvement approaches. Furthermore, they perform an evaluation with two of that approaches using an industrial case study. In contrast to this work, our goal is to apply PDCA (Plan-Do-Check-Act)(Johnson, 2002), which is an process improvement approach, to establish a standard testing process into a test factory. 5 CONCLUSIONS Several development enterprises have hired services of test factories to reduce the costs related to the software testing activities. These test factories are then an opportunity to reduce the costs and improve the quality of the tests. We presented in this paper our experience over two years by leveraging the PDCA cycle to define a standard testing process into a test factory. First, we identified the current ad hoc testing activities in Scrum projects and pointed out the main weakness of our testing approach. Next, the improvements were proposed based on the lessons learned to define a standard testing process. This process is adherent to the Brazilian Software Process Reference Model (MR-MPS-SW) and it is independent of the software development process. Last, we applied our standard testing process on 15 industry software releases and obtained good results for DRE. We have also presented 12 lessons learned that can help practitioners to improve their test process. As future work, we aim to continuous improvement process to perform an official CMMI appraisal for the test factory organization unit. Also, we aim at expanding the services of our test factory to advanced domains (e.g., Ubiquitous and Internet of Things) focusing on the human-computer interaction quality of such domains (Carvalho et al., 2016)(Andrade et al., 2017)(Rocha et al., 2017) and their advanced graphical user interfaces (Lelli et al., 2015b)(Lelli et al., 2015a). ACKNOWLEDGEMENTS We would like to thank the GREat’s test factory team for the technical support on this work. The authors thank the research groups involved in the CActUS - Context-Awareness Testing for Ubiquitous Systems project supported by CNPq (MCT/CNPq 14/2013 - Universal) under grant number 484380/2013-3. REFERENCES Carvalho, R. M., Andrade, R. M. C., Oliveira, K. M., Santos, I. S., and Bezerra, C. I. M. (2016). Quality char-
{"Source-Url": "http://www.scitepress.org/Papers/2017/63333/63333.pdf", "len_cl100k_base": 9339, "olmocr-version": "0.1.50", "pdf-total-pages": 12, "total-fallback-pages": 0, "total-input-tokens": 36647, "total-output-tokens": 11720, "length": "2e13", "weborganizer": {"__label__adult": 0.000377655029296875, "__label__art_design": 0.0003273487091064453, "__label__crime_law": 0.00031256675720214844, "__label__education_jobs": 0.0025615692138671875, "__label__entertainment": 4.905462265014648e-05, "__label__fashion_beauty": 0.00018727779388427737, "__label__finance_business": 0.00031948089599609375, "__label__food_dining": 0.000362396240234375, "__label__games": 0.0006718635559082031, "__label__hardware": 0.0004992485046386719, "__label__health": 0.0004131793975830078, "__label__history": 0.00018167495727539065, "__label__home_hobbies": 6.908178329467773e-05, "__label__industrial": 0.0003027915954589844, "__label__literature": 0.00026869773864746094, "__label__politics": 0.00018596649169921875, "__label__religion": 0.0003995895385742187, "__label__science_tech": 0.004383087158203125, "__label__social_life": 8.767843246459961e-05, "__label__software": 0.00496673583984375, "__label__software_dev": 0.982421875, "__label__sports_fitness": 0.0002703666687011719, "__label__transportation": 0.0003273487091064453, "__label__travel": 0.00019419193267822263}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 50497, 0.02425]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 50497, 0.21752]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 50497, 0.92368]], "google_gemma-3-12b-it_contains_pii": [[0, 3870, false], [3870, 8152, null], [8152, 13366, null], [13366, 14927, null], [14927, 19444, null], [19444, 22077, null], [22077, 27137, null], [27137, 31911, null], [31911, 35891, null], [35891, 40834, null], [40834, 45726, null], [45726, 50497, null]], "google_gemma-3-12b-it_is_public_document": [[0, 3870, true], [3870, 8152, null], [8152, 13366, null], [13366, 14927, null], [14927, 19444, null], [19444, 22077, null], [22077, 27137, null], [27137, 31911, null], [31911, 35891, null], [35891, 40834, null], [40834, 45726, null], [45726, 50497, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 50497, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 50497, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 50497, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 50497, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 50497, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 50497, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 50497, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 50497, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 50497, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 50497, null]], "pdf_page_numbers": [[0, 3870, 1], [3870, 8152, 2], [8152, 13366, 3], [13366, 14927, 4], [14927, 19444, 5], [19444, 22077, 6], [22077, 27137, 7], [27137, 31911, 8], [31911, 35891, 9], [35891, 40834, 10], [40834, 45726, 11], [45726, 50497, 12]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 50497, 0.07345]]}
olmocr_science_pdfs
2024-11-29
2024-11-29
e50114b450f50779ac6b5f4f72dfaae0e1fe3fec
Semantic Parsing to Probabilistic Programs for Situated Question Answering Jayant Krishnamurthy and Oyvind Tafjord and Aniruddha Kembhavi Allen Institute for Artificial Intelligence jayantk,oyvindt,anik@allenai.org Abstract Situated question answering is the problem of answering questions about an environment such as an image or diagram. This problem requires jointly interpreting a question and an environment using background knowledge to select the correct answer. We present Parsing to Probabilistic Programs ($P^3$), a novel situated question answering model that can use background knowledge and global features of the question/environment interpretation while retaining efficient approximate inference. Our key insight is to treat semantic parses as probabilistic programs that execute nondeterministically and whose possible executions represent environmental uncertainty. We evaluate our approach on a new, publicly-released data set of 5000 science diagram questions, outperforming several competitive classical and neural baselines. 1 Introduction Situated question answering is a challenging problem that requires reasoning about uncertain interpretations of both a question and an environment together with background knowledge to determine the answer. To illustrate these challenges, consider the 8th grade science diagram questions in Figure 1, which are motivated by the Aristo project (Clark and Etzioni, 2016). These questions require both computer vision to interpret the diagram and compositional question understanding. These components, being imperfect, introduce uncertainty that must be jointly reasoned about to avoid implausible interpretations. These uncertain interpretations must further be combined with background knowledge, such as the definition of a “predator,” to determine the correct answer. The challenges of situated question answering have not been completely addressed by prior work. Early “possible worlds” models (Matuszek et al., 2012; Krishnamurthy and Kollar, 2013; Malinowski and Fritz, 2014) were capable of compositional question understanding and using background knowledge, but did not jointly reason about environ- ment/question uncertainty. These models also used unscalable inference algorithms for reasoning about the environment, despite the lack of joint reasoning. More recent neural models (Antol et al., 2015; Malinowski et al., 2015; Yang et al., 2015) are incapable of using background knowledge and it remains unclear to what extent these models can represent compositionality in language. We present Parsing to Probabilistic Programs (\(P^3\)), a novel approach to situated question answering that addresses these challenges. It is motivated by two observations: (1) situated question answering can be formulated as semantic parsing with an execution model that is a learned function of the environment, and (2) probabilistic programming is a natural and powerful method for specifying the space of permissible execution models and learning over it. In \(P^3\), we define a domain theory for the task as a probabilistic program, then train a joint loglinear model to semantically parse questions to logical forms in this theory and execute them in an environment. Importantly, the model includes global features over parsing and execution that enable it to avoid unlikely joint configurations. \(P^3\) leverages semantic parsing to represent compositionality in language and probabilistic programming to specify background knowledge and perform linear-time approximate inference over the environment. We present an experimental evaluation of \(P^3\) on a new data set of 5000 food web diagram questions (Figure 1). We compare our approach to several baselines, including possible worlds and neural network approaches, finding that \(P^3\) outperforms both. An ablation study demonstrates that global features help the model achieve high accuracy. We also demonstrate that \(P^3\) improves accuracy on a previously published data set. Finally, we have released our data and code to facilitate further research. 2 Prior Work Situated question answering is often formulated in terms of parsing both the question and environment into a common meaning representation where they can be combined to select the answer. This general approach has been implemented using different meaning representations: Possible world models use a logical meaning representation defined by a knowledge base schema. These models train a semantic parser to map questions to queries and an environment model to map environments to knowledge bases in this schema. Executing the queries against the knowledge bases produces answers. These models assume that the parser and environment model are independent and furthermore that the knowledge base consists of independent predicate instances (Matuszek et al., 2012; Krishnamurthy and Kollár, 2013; Malinowski and Fritz, 2014). Despite these strong independence assumptions, these models have intractable inference. An exception is Seo et al., (2015) who incorporate hard constraints on the joint question/environment interpretation; however, this approach does not generalize to soft constraints or arbitrary logical forms. In some work only the environment model is learned (Kollár et al., 2010; Tellex et al., 2011; Howard et al., 2014b; Howard et al., 2014a; Berant et al., 2014; Krishnamurthy and Mitchell, 2015). Neural networks use a vector meaning representation that encodes both the question and environment as vectors. These networks have mostly been applied to visual question answering (Antol et al., 2015), where many architectures have been proposed (Malinowski et al., 2015; Yang et al., 2015; Fukui et al., 2016). It is unclear to what extent these networks can represent compositionality in language using their vector encodings. Dynamic Neural Module Networks (Andreas et al., 2016a; Andreas et al., 2016b) are the exception to the above generalization. This approach constructs a neural network to represent the meaning of the question via semantic parsing, then executes this network against the image to produce an answer. Our approach is similar except that we construct and execute a probabilistic program. Advantages of our approach are that it naturally represents the discrete structure of food webs and can use background knowledge. Preliminaries for our work are semantic parsing and probabilistic programming. Semantic parsing translates natural language questions into executable logical forms and has been used in applications such as question answering against a knowledge base (Zelle and Mooney, 1993; Zettlemoyer and Collins, 2005; Liang et al., 2011; Kwiatkowski et al., 2013; Berant et al., 2013; Reddy et al., 2014; Yih et al., 2015; Xu et al., 2016), direction following (Chen and Mooney, 2011; Artzi and Zettlemoyer, 2013), and information extraction (Krishnamurthy and Mitchell, 2012; Choi et al., 2015). Semantic parsing alone is insufficient for situated question answering because it does not interpret the environment; many of the above approaches use semantic parsing as a component in a larger model. Probabilistic programming languages extend programming languages with primitives for nondeterministic choice (McCarthy, 1963; Goodman and Stuhlmüller, 2014). We express logical forms in a probabilistic variant of Scheme similar to Church (Goodman et al., 2008); however, this paper uses Python-like pseudocode for clarity. The language has a single choice primitive called choose that nondeterministically returns one of its arguments. For example, choose(1, 2, 3) can execute three ways, returning either 1, 2, or 3. Multiple calls to choose can be combined. For example, choose(1, 2) + choose(1, 2) adds two nondeterministically chosen values, and therefore has four executions that return 2, 3, 3 and 4. Each execution also has a probability; in our case, these probabilities are assigned by a trained model given the environment and not explicitly specified in the program. 3 Parsing to Probabilistic Programs ($P^3$) The $P^3$ model is motivated by two observations. The first is that situated question answering can be formulated as semantic parsing with an execution model that is a learned function of the environment. Consider the first question in Figure 1. The meaning of this question could be represented by a logical form such as \( \text{COUNT}(\lambda x. \text{EATS}(x, \text{DEER})) \), which we could train a semantic parser to predict given a suitable domain theory of functions such as \( \text{COUNT} \) and \( \text{EATS} \). However, the information required to execute this logical form and answer the question must be extracted from the diagram. Specifically, \( \text{EATS}(x, y) \) depends on whether an arrow is present between \( x \) and \( y \), which we must train a vision model to determine. Thus, \( \text{EATS} \) should be a learned function of the environment. This first observation suggests a need for a formalism for representing uncertainty and performing learning over the domain theory’s functions. Our second observation is that probabilistic programming is a natural fit for this task. In this paradigm, the domain theory is a probabilistic program that defines the information to be extracted from the environment by using choose. To a first approximation, the diagram question theory includes: ```python def eats(x, y): choose(true, false) ``` Logical forms are then probabilistic programs, each of whose possible executions represents a different interpretation of the environment. For example, executing \( \text{EATS}(\text{LION}, \text{DEER}) \) hits the \text{choose} in the above definition, resulting in two executions where the lion either eats or does not eat the deer. In the \( \text{COUNT} \) example above, each execution represents a different set of animals that eat the deer. To learn the correct environment interpretation, we train an execution model to assign a probability to each execution given features of the environment. Using probabilistic programming enables us to combine learned functions, such as \( \text{EATS} \), with background knowledge functions, such as \( \text{COUNT} \), and also facilitates inference. According to these observations, applying $P^3$ has two steps. The first step is to define an appropriate domain theory. This theory is the main design decision in instantiating $P^3$ and provides a powerful way to encode domain knowledge. The second step is to train a loglinear model consisting of a semantic parser and an execution model. This model learns to semantically parse questions into logical forms in the theory and execute them in the environment to answer questions correctly. We defer discussion of the diagram question domain theory to Section 4 and focus on the loglinear model in this section. 3.1 Model Overview The input to the $P^3$ model is a question and an environment and its output is a denotation, which is a formal answer to the question. $P^3$ is a loglinear model with two factors: a semantic parser and an execution model. The semantic parser scores syntactic parses and logical forms for the question. These logical forms are probabilistic programs with multiple possible executions (specified by the domain theory), each of which may return a different denotation. The execution model assigns a score to each of these executions given the environment. Formally, the model predicts a denotation $\gamma$ for a question $q$ in an environment $v$ using three latent variables: $$P(\gamma|v, q; \theta) = \sum_{e,\ell,t} P(e, \ell, t|v, q; \theta) \mathbf{1}(\text{ret}(e) = \gamma)$$ $$P(e, \ell, t|v, q; \theta) = \frac{1}{Z_{q,v}} f_{\text{ex}}(e, \ell, t, v; \theta_{\text{ex}}) f_p(\ell, t, q; \theta_p)$$ The model is composed of two factors. $f_p$ represents the semantic parser that scores logical forms $\ell$ and syntactic parse trees $t$ given question $q$ and parameters $\theta_p$. $f_{\text{ex}}$ represents the execution model. Given parameters $\theta_{\text{ex}}$, this factor assigns a score to a logical form $\ell$ and its execution $e$ in environment $v$. The denotation $\gamma$, i.e., the formal answer to the question, is simply the value returned by $e$. $Z_{q,v}$ represents the model’s partition function. The following sections describe these factors in more detail. ### 3.2 Semantic Parser The factor $f_p$ represents a Combinatory Categorial Grammar (CCG) semantic parser (Zettlemoyer and Collins, 2005) that scores logical forms for a question. Given a lexicon\(^1\) mapping words to syntactic categories and logical forms, CCG defines a set of possible syntactic parses $t$ and logical forms $\ell$ for a question $q$. Figure 3.2 shows an example CCG parse. $f_p$ is a loglinear model over parses $(\ell, t)$: $$f_p(\ell, t, q; \theta_p) = \exp\{\theta_p^T \phi(\ell, t, q)\}$$ The function $\phi$ maps parses to feature vectors. We use a rich set of features similar to those for syntactic CCG parsing (Clark and Curran, 2007); a full description is provided in an online appendix. ### 3.3 Execution Model The factor $f_{\text{ex}}$ is a loglinear model over the executions of a logical form given an environment. Logical forms in $P^3$ are probabilistic programs with a set of possible executions, where each execution $e$ is a sequence, $e = [e_0, e_1, e_2, ... , e_n]$. $e_0$ is the program’s starting state, $e_i$ represents the state immediately after the $i$th call to choose, and $e_n$ is the state at termination. The score of an execution is: $$f_{\text{ex}}(e, \ell, v; \theta_{\text{ex}}) = \prod_{i=1}^n \exp\{\theta_{\text{ex}}^T \phi(e_{i-1}, e_i, \ell, v)\}$$ In the above equation, $\theta_{\text{ex}}$ represents the model’s parameters and $\phi$ represents a feature function that produces a feature vector for the difference between sequential program states $e_{i-1}$ and $e_i$ given environment $v$ and logical form $\ell$. $\phi$ can include arbitrary features of the execution, logical form and environment, which is important, for example, to detect cycles in a food web (Section 4.3). ### 3.4 Inference $P^3$ is designed to rely on approximate inference: our goal is to use rich features to accurately make local decisions, as in linear-time parsers (Nivre et al., 2006). We perform approximate inference using a two-stage beam search. Given a question $q$, the first stage performs a beam search over CCG parses to produce a list of logical forms scored by $f_p$. This step is performed by using a CKY-style chart parsing algorithm then marginalizing out the syntactic parses. The second stage performs a beam search over executions of each logical form. The space of possible executions of a logical form is a tree (Figure 4.2) where each internal node represents a partial execution up to a choose call. The search maintains a beam of partial executions at the same depth, and each iteration advances the beam to the next depth, discarding the lowest-scoring executions according to $f_{\text{ex}}$ to maintain a fixed size beam. This procedure runs in time linear to the number of choose calls. We implement the search by rewriting the probabilistic program into continuation-passing style, which allows choose to be implemented as a function that adds multiple continuations to the search queue; we refer the reader to Goodman and Stuhlmüller (2014) for details. Our experiments use a beam size of 100 in the semantic parser, executing each of the 10 highest-scoring logical forms with a beam of 100 executions. --- \(^1\)In our experiments, we automatically learn the lexicon in a preprocessing step. See Section 5.2 for details. 3.5 Training \( P^3 \) is trained by maximizing loglikelihood with stochastic gradient ascent. The training data \( \{(q^i, v^i, c^i)\}_{i=1}^n \) is a collection of questions \( q^i \) and environments \( v^i \) paired with supervision oracles \( c^i \). \( c^i(e) = 1 \) for a correct execution \( e \) and \( c^i(e) = 0 \) otherwise. The oracle \( c^i \) can implement various kinds of supervision, including: (1) labeled denotations, by verifying the value returned by \( e \) and (2) labeled environments, by verifying each choice made by \( e \). The oracle for diagram question answering combines both forms of supervision (Section 4.5). The objective function \( O \) is the loglikelihood of predicting a correct execution: \[ O(\theta) = \sum_{i=1}^n \log \sum_{e,\ell,t} c^i(e) P(e, \ell, t|q^i, v^i; \theta) \] We optimize this objective function using stochastic gradient ascent, using the approximate inference algorithm from Section 3.4 to estimate the necessary marginals. When computing the marginal distribution over correct executions, we filter each step of the beam search using the supervision oracle \( c^i \) to improve the approximation. 4 Diagram Question Answering with \( P^3 \) As a case study, we apply \( P^3 \) to the task of answering food web diagram questions from an 8th grade science domain. A few steps are required to apply \( P^3 \). First, we create a domain theory of food webs that represents extracted information from the diagram and background knowledge for the domain. Second, we define the features of the execution model that are used to learn how programs in the domain theory execute given a diagram. Third, we define a component to select a multiple-choice answer given a denotation. Finally, we define the supervision oracle used for training. 4.1 Food Web Diagram Questions We consider the task of answering food web diagram questions. The input consists of a diagram depicting a food web, a natural language question and a list of natural language answer options (Figure 1). The goal is to select the correct answer option. This task has many regularities that require global features: for example, food webs are usually acyclic and certain animals usually have certain roles (e.g., mice are herbivores). We have collected and released a data set for this task (Section 5.1). We preprocess the diagrams in the data set using a computer vision system that identifies candidate diagram elements (Kembhavi et al., 2016). This system extracts a collection of text labels (via OCR), arrows, arrowheads and objects, each with corresponding scores. It also extracts a collection of scored linkages between these elements. These extractions are noisy and contain many discrepancies such as overlapping text labels and spurious linkages. We use these extractions to define a set of candidate organisms (using the text labels), and also to define features of the execution model. 4.2 Domain Theory The domain theory is a probabilistic program encoding the information to extract from the environment as well as background knowledge about food webs. It represents the structure of a food web using two functions. These functions are predicates that invoke \texttt{choose} to return either true or false. The execution model learns to predict which of these values is correct for each set of arguments given the diagram. It furthermore has a collection of deterministic functions that encode domain knowledge, including definitions of animal roles such as \texttt{HERBIVORE} and a model of population change causation. Figure 4.2 shows pseudocode for a portion of the domain theory. Food webs are represented using two functions over the extracted text labels: \texttt{ORGANISM}(x) indicates whether the label \( x \) is an organism (as opposed to, e.g., the diagram title); and \texttt{EATS}(x,y). The definitions of these functions invoke \texttt{choose} while remembering previously chosen values to avoid double counting probabilities when executing logical forms such as \texttt{ORGANISM(DEER) \land ORGANISM(DEER)}. The remembered values are stored in a global variable that is also used to implement the supervision oracle. Deterministic functions such as \texttt{CAUSE} are defined in terms of these learned functions. The uses of \texttt{choose} in the domain theory create a tree of possible executions for every logical form. Figure 4.2 illustrates this tree for the logical form \( \lambda f.\texttt{CAUSE}(<\texttt{DECREASE}(<\texttt{MICE}), \ f(<\texttt{SNAKES})) \), which # initialize predicate instance variables # from text labels in environment world = {"mice": undef, ("mice", "snakes"): undef, ...} def organism(name) if world[name] == undef world[name] = choose(true, false) return world[name] def eats(x, y) # same as organism but with pairs. # entities referenced in the logical form # must be organisms. choose() represents # failure; it returns no values. def getOrganism(x) if organism(x) return x else choose() # change events are direction/ # text label tuples def decrease(x) return ("decrease", x) def cause(e1, e2) e12 = eats(e1[1], e2[1]) e21 = eats(e2[1], e1[1]) # deterministic model with cases. e.g. # if eats(y, x) then (cause (decrease x) # (decrease y)) -> true return doCause(e1[0], e2[0], e12, e21) Figure 3: Domain theory pseudocode for diagram question answering. corresponds to the question “what happens to the snakes when the mice decrease?” This logical form is shorthand for the following program: \[ \text{filter}(\lambda f. \text{cause} \begin{array}{l} \text{decrease(getOrganism("mice")),} \text{f(getOrganism("snakes"))}, \text{set\{decrease, increase, unchanged\}} \end{array} )\] Specifically, entities such as MICE are created by calling getOrganism and logical forms with functional types implicitly represent filters over the appropriate argument type. Executing this program first applies the filter predicate to decrease. Next, it evaluates getOrganism("mice"), which calls organism and encounters the first call to choose. This call is shown as the first branch of the tree in Figure 4.2. The successful branch proceeds to evaluate getOrganism("snakes"), shown as the second branch. Finally, the successful branch evaluates cause, which calls eats twice, resulting in the final two branches. The value returned by each branch is determined by the causation model which performs some deterministic logic on the truth values of the two eats relations. 4.3 Execution Features The execution model uses three sets of features: instance features, predicate features, and denotation features. Instance features treat each predicate instance independently, while the remainder are global features of multiple predicate instances and the logical form. We provide a complete listing of features in an online appendix. **Instance features** fire whenever an execution chooses a truth value for a predicate instance. These features are similar to the per-predicate-instance features used in prior work to produce a distribution over possible worlds. For ORGANISM(x), our features are the vision model’s extraction score for x and indicator features for the number of tokens in x. For EATS(x, y), our features are various combinations of the vision model’s scores for arrows that may connect the text labels x and y. **Predicate features** fire based on the global assignment of truth values to all instances of a single predicate. The features for ORGANISM count occurrences of overlapping text labels among true instances. The features for EATS include cycle count features for various cycle lengths and arrow reuse features. The cycle count features help the model learn that food webs are typically, but not always, acyclic and the arrow reuse features aim to prevent the model from predicting two different EATS instances on the basis of a single arrow. Denotation features fire on the return value of an execution. There are two kinds of denotation features: size features that count the number of entities in denotations of various types and denotation element features for specific logical forms. The second kind of feature can be used to learn that the denotation of $\lambda x.\textsc{Herbivore}(x)$ is likely to contain \textsc{Mouse}, but unlikely to contain \textsc{Wolf}. 4.4 Answer Selection $P^3$ predicts a distribution over denotations for each question, which for our problem must be mapped to a distribution over multiple choice answers. Answer selection performs this task using string match heuristics and an LSTM (Hochreiter and Schmidhuber, 1997). The string match heuristics score each answer option given a denotation then select the highest scoring answer, abstaining in the case of a tie. The score computation depends on the denotation’s type. If the denotation is a set of entities, the score is an approximate count of the number of entities in the denotation mentioned in the answer using a fuzzy string match. If the denotation is a set of change events, the score is a fuzzy match of both the change direction and the animal name. If the denotation is a number, string matching is straightforward. Applying these heuristics and marginalizing out denotations yields a distribution over answer options. A limitation of the above approach is that it does not directly incorporate linguistic prior knowledge about likely answers. For example, “snake” is usually a good answer to “what eats mice?” regardless of the diagram. Such knowledge is known to be essential for visual question answering (Antol et al., 2015; Andreas et al., 2016b) and important in our task as well. We incorporate this knowledge in a standard way, by training a neural network on question/answer pairs (without the diagram) and combining its predictions with the string match heuristics above. The network is a sequence LSTM that is applied to the question concatenated with each answer option $a$ to produce a 50-dimensional vector $v_a$ for each answer. The distribution over answers is the softmax of the inner product of these vectors with a learned parameter vector $w$. For simplicity, we combine these two components using a 50/50 mix of their answer distributions. 4.5 Supervision Oracle The supervision oracle for diagram question answering combines supervision of both answers and environment interpretations. We assume that each diagram has been labeled with a food web. An execution is correct if and only if (1) all of the chosen values in the global variable encoding the food web are consistent with the labeled food web, and (2) string match answer selection applied to its denotation chooses the correct answer. The first constraint guarantees that every logical form has at most one correct execution for any given diagram. 5 Evaluation Our evaluation compares $P^3$ to both possible worlds and neural network approaches on our data set of food web diagram questions. An ablation study demonstrates that both sets of global features improve accuracy. Finally, we demonstrate $P^3$’s generality by applying it to a previously-published data set, obtaining state-of-the-art results. Code, data and supplementary material for this paper are available at: http://www.allenai.org/paper-appendix/emnlp2016-p3 5.1 FOODWEBS Data Set FOODWEBS consists of $\sim$500 food web diagrams and $\sim$5000 questions designed to imitate actual questions encountered on 8th grade science exams. The train/validation/test sets contain $\sim$300/100/100 diagrams and their corresponding questions. The data set has three kinds of annotations in addition to the correct answer for each question. First, each diagram is annotated with the food web that it depicts using \textsc{Organism} and \textsc{Eats}. Second, each diagram has predictions from a vision system for various diagram elements such as arrows and text labels (Kembhavi et al., 2016). These are noisy predictions, not ground truth. Finally, each question is annotated by the authors with a logical form (or null if its meaning is not representable in the domain theory). These logical forms are not used to train $P^3$ but are useful to measure per-component error. We collected FOODWEBS by using a crowdsourcing process to expand a collection of real exam questions. First, we collected 89 questions from 4th and 8th grade exams and 500 food web diagrams us- ing an image search engine. Second, we generated questions for these diagrams using Mechanical Turk. Workers were shown a diagram and a real question for inspiration and asked to write a new question and its answer options. We validated each generated question by asking 3 workers to answer it, discarding questions where at least 2 did not choose the correct answer. We also manually corrected any ambiguous (e.g., two answer options are correct) and poorly-formatted (e.g., two answer options have the same letter) questions. The final data set has high quality: a human domain expert correctly answered 95 out of 100 randomly-sampled questions. 5.2 Baseline Comparison Our first experiment compares \( P^3 \) with several baselines for situated question answering. The first baseline, WORLDS, is a possible worlds model based on Malinowski and Fritz (2014). This baseline learns a semantic parser \( P(\ell, t|q) \) and a distribution over food webs \( P(w|v) \), then evaluates \( \ell \) on \( w \) to produce a distribution over denotations. This model is implemented by independently training \( P^3 \)’s CCG parser (on question/answer pairs and labeled food webs) and a possible-worlds execution model (on labeled food webs). The CCG lexicon for both \( P^3 \) and WORLDS was generated by applying PAL (Krishnamurthy, 2016) to the same data. Both models select answers as described in Section 4.4. We also compared \( P^3 \) to several neural network baselines. The first baseline, LSTM, is the text-only answer selection model described in Section 4.4. The second baseline, VQA, is a neural network for visual question answering. This model represents each image as a vector by using the final layer of a pre-trained VGG19 model (Simonyan and Zisserman, 2014) and applying a single fully-connected layer. It scores answer options by using the answer selection LSTM to encode question/answer pairs and diagram parses, which is roughly comparable to the supervision used to train \( P^3 \). Table 5.2 compares the accuracy of \( P^3 \) to these baselines. Accuracy is the fraction of questions answered correctly. LSTM performs well on this data set, suggesting that many questions can be answered without using the image. This result is consistent with results on visual question answering (Antol et al., 2015). The other neural network models have similar performance to LSTM, whereas both WORLDS and \( P^3 \) outperform it. We also find that \( P^3 \) outperforms WORLDS likely due to its global features, which we investigate in the next section. Given these results, we hypothesized that the neural models were largely memorizing common patterns in the text and were not able to interpret the diagram. We tested this hypothesis by running each model on a test set with unseen organisms created by reversing the organism names in every question and diagram (Table 5.2, right column). As expected, the accuracy of LSTM is considerably reduced on this data set. VQA and DQA again perform similarly to LSTM, which is consistent with our hypothesis. In contrast, we find that the accuracies of WORLDS and \( P^3 \) are only slightly reduced, which is consistent with superior diagram interpretation abilities but ineffective LSTM answer selection. <table> <thead> <tr> <th>Model</th> <th>Accuracy (Unseen Organisms)</th> </tr> </thead> <tbody> <tr> <td>( P^3 )</td> <td>69.1</td> </tr> <tr> <td>WORLDS</td> <td>63.6</td> </tr> <tr> <td>LSTM</td> <td>60.3</td> </tr> <tr> <td>VQA</td> <td>56.5</td> </tr> <tr> <td>DQA</td> <td>59.3</td> </tr> <tr> <td>Random</td> <td>25.2</td> </tr> </tbody> </table> Table 1: Accuracy of \( P^3 \) and several baselines on the FOOD-WEBS test set and a modified test set with unseen organisms. <table> <thead> <tr> <th>Model</th> <th>Accuracy</th> <th>( \Delta )</th> </tr> </thead> <tbody> <tr> <td>( P^3 )</td> <td>69.1</td> <td></td> </tr> <tr> <td>-LSTM</td> <td>59.8</td> <td>-9.3</td> </tr> <tr> <td>-LSTM -denotation</td> <td>55.8</td> <td>-13.3</td> </tr> <tr> <td>-LSTM -denotation -predicate</td> <td>52.4</td> <td>-16.7</td> </tr> </tbody> </table> Table 2: Test set accuracy of \( P^3 \) removing LSTM answer selection (Section 4.4), denotation features and predicate features (Section 4.3). 5.3 Ablation Study We performed an ablation study to further understand the impact of LSTM answer selection and global features. Table 5.2 shows the accuracy of \( P^3 \) trained without these components. We find that LSTM answer selection improves accuracy by 9 points, as expected due to the importance of linguistic prior knowledge. Global features improve accuracy by 7 points, which is roughly comparable to the delta between \( P^3 \) and WORLDS in Table 5.2. 5.4 Component Error Analysis Our third experiment analyses sources of error by training and evaluating \( P^3 \) while providing the gold logical form, food web, or both as input. Table 5.5 shows the accuracy of these three models. The final entry shows the maximum accuracy possible given our domain theory and answer selection. The larger accuracy improvement with gold food webs suggests that the execution model is responsible for more error than semantic parsing, though both components contribute. 5.5 SCENE Experiments Our final experiment applies \( P^3 \) to the SCENE data set of Krishnamurthy and Kollar (2013). In this data set, the input is a natural language expression, such as “blue mug to the left of the monitor,” and the output is the set of objects in an image that the expression denotes. The images are annotated with a bounding box for each candidate object. The data set includes a domain theory that was automatically generated by creating a category and/or relation per word based on its part of speech. It also includes a CCG lexicon and image features. We use these resources, adding predicate and denotation features. Table 5.5 compares \( P^3 \) to prior work on SCENE. The evaluation metric is exact match accuracy between the predicted and labeled sets of objects. We consider three supervision conditions: QA trains with question/answer pairs, QA+E further includes labeled environments, and QA+E+LF further includes labeled logical forms. We trained \( P^3 \) in the first two conditions, while prior work trained in the first and third conditions. KK2013 is a possible worlds model with a max-margin training objective. \( P^3 \) slightly outperforms in the QA condition and \( P^3 \) trained with labeled environments outperforms prior work trained with additional logical form labels. 6 Conclusion Parsing to Probabilistic Programs (\( P^3 \)) is a novel model for situated question answering that jointly reasons about question and environment interpretations using background knowledge to produce answers. \( P^3 \) uses a domain theory – a probabilistic program – to define the information to be extracted from the environment and background knowledge. A semantic parser maps questions to logical forms in this theory, which are probabilistic programs whose possible executions represent possible interpretations of the environment. An execution model scores these executions given features of the environment. Both the semantic parser and execution model are jointly trained in a loglinear model, which thereby learns to both parse questions and interpret environments. Importantly, the model includes global features of the logical form and executions, which help the model avoid implausible interpretations. We demonstrate \( P^3 \) on a challenging new data set of 5000 science diagram questions, where it outperforms several competitive baselines. Acknowledgments We gratefully acknowledge Minjoon Seo, Mike Salvato and Eric Kolve for their implementation help, Isaac Cowhey and Carissa Schoenick for their help with the data, and Oren Etzioni, Peter Clark, Matt Gardner, Hannaneh Hajishirzi, Mike Lewis, and Jonghyun Choi for their comments. References Mateusz Malinowski, Marcus Rohrbach, and Mario Fritz. 2015. Ask your neurons: A neural-based approach to answering questions about images. In International Conference on Computer Vision.
{"Source-Url": "http://ai2-website.s3.amazonaws.com/publications/emnlp2016-semantic-parsing.pdf", "len_cl100k_base": 8204, "olmocr-version": "0.1.50", "pdf-total-pages": 11, "total-fallback-pages": 0, "total-input-tokens": 38432, "total-output-tokens": 10171, "length": "2e13", "weborganizer": {"__label__adult": 0.0005545616149902344, "__label__art_design": 0.0010747909545898438, "__label__crime_law": 0.0006089210510253906, "__label__education_jobs": 0.00421142578125, "__label__entertainment": 0.0003888607025146485, "__label__fashion_beauty": 0.0004072189331054687, "__label__finance_business": 0.0003218650817871094, "__label__food_dining": 0.0006527900695800781, "__label__games": 0.0016050338745117188, "__label__hardware": 0.0010700225830078125, "__label__health": 0.0010137557983398438, "__label__history": 0.0006427764892578125, "__label__home_hobbies": 0.0002027750015258789, "__label__industrial": 0.0006818771362304688, "__label__literature": 0.00301361083984375, "__label__politics": 0.0004963874816894531, "__label__religion": 0.0009179115295410156, "__label__science_tech": 0.327392578125, "__label__social_life": 0.0002918243408203125, "__label__software": 0.01947021484375, "__label__software_dev": 0.63330078125, "__label__sports_fitness": 0.00045371055603027344, "__label__transportation": 0.0009064674377441406, "__label__travel": 0.0002751350402832031}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 41332, 0.02861]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 41332, 0.62065]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 41332, 0.88565]], "google_gemma-3-12b-it_contains_pii": [[0, 2175, false], [2175, 6807, null], [6807, 11445, null], [11445, 15688, null], [15688, 20231, null], [20231, 23644, null], [23644, 28120, null], [28120, 32293, null], [32293, 35957, null], [35957, 38869, null], [38869, 41332, null]], "google_gemma-3-12b-it_is_public_document": [[0, 2175, true], [2175, 6807, null], [6807, 11445, null], [11445, 15688, null], [15688, 20231, null], [20231, 23644, null], [23644, 28120, null], [28120, 32293, null], [32293, 35957, null], [35957, 38869, null], [38869, 41332, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 41332, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 41332, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 41332, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 41332, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 41332, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 41332, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 41332, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 41332, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 41332, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 41332, null]], "pdf_page_numbers": [[0, 2175, 1], [2175, 6807, 2], [6807, 11445, 3], [11445, 15688, 4], [15688, 20231, 5], [20231, 23644, 6], [23644, 28120, 7], [28120, 32293, 8], [32293, 35957, 9], [35957, 38869, 10], [38869, 41332, 11]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 41332, 0.07368]]}
olmocr_science_pdfs
2024-11-30
2024-11-30
95d40d007e9b82eaa171ff6c730ddb30d5ab413b
How do Scratch Programmers Name Variables and Procedures? Alaaeddin Swidan Delft University of Technology The Netherlands Email: alaaeddin.swidan@tudelft.nl Alexander Serebrenik Eindhoven University of Technology The Netherlands Email: a.serebrenik@tue.nl Felienne Hermans Delft University of Technology The Netherlands Email: f.f.j.hermans@tudelft.nl Abstract—Research shows the importance of selecting good names to identifiers in software code: more meaningful names improve readability. In particular, several guidelines encourage long and descriptive variable names. A recent study analyzed the use of variable names in five programming languages, focusing on single-letter variable names, because of the apparent contradiction between their frequent use and the fact that these variables violate the aforementioned guidelines. In this paper, we analyze variables in Scratch, a popular block-based language aimed at children. We start by replicating the above single-letter study for Scratch. We augment this study by analyzing single-letter procedure names, and by investigating the use of Scratch specific naming patterns: spaces in variable names, numerics as variables and textual labels in procedure names. The results of our analysis show that Scratch programmers often prefer longer identifier names than developers in other languages, while Scratch procedure names have even longer names than Scratch variables. For the single-letter variables, the most frequent names are $x$, $y$, $i$, and $j$. Single-letter procedures are less popular, but show more tendency to be in upper case. When compared to the other programming languages, the usage of single uppercase letters in Scratch variables seems to be similar to the pattern found in Perl, while for the lowercase letters—to the pattern found in Java. Concerning Scratch specific features, 44% of the unique variable names and 34% of the projects in the dataset include at least one space. The usage of textual labels between parameters in procedure names appears as not common, however textual patterns used imply an influence from textual languages, for example by using brackets. Previous research indicate the identifier names as one significant issue in transitioning from visual block-based to textual programming languages. The naming patterns we found support this claim for Scratch programmers who may incur difficulties when transitioning to the use of mainstream textual programming languages. Those languages restrict the use of spaces in identifiers and more often divert into short and single-letter names—tendencies opposite to the naming preferences in Scratch. I. INTRODUCTION The naming of identifiers in the source code has been extensively studied (see, e.g., recent studies of this subject [1], [2], [3], [4], [5], [6], [7], [8]). Still, the impact of the variable name choice on code readability and maintainability is controversial, as witnessed, e.g., by recent studies of Beniamini et al. [3] and Hofmeister et al. [5] reaching contradictory conclusions. Furthermore, many computer science and programming curricula focus on the programming concepts and the syntax of the languages as opposed to practices in naming variables and identifiers. Indeed, while "meaningful variable names" are advocated by some teachers [9], [10] and practitioners [11] neither the ACM Curriculum Guidelines for Undergraduate Programs in Computer Science nor the Curriculum Guidelines for Undergraduate Degree Programs in Software Engineering discuss this topic. In fact, as discussed by Raymond [12] standard metasyntactic variables used in syntax examples are "foo" and "bar". The names of these identifiers are meaningless, and to some extent, they represent a refusal to name, suggesting to the learner that naming is less important to the programming task. The goal of this paper is to contribute towards understanding the patterns in variable and procedure naming in Scratch. Scratch is a block-based visual language developed by MIT with the aim of helping young people learn the basic concepts of programming and collaboration. Scratch has recently become very popular among school-age children and in several countries has been introduced as part of the school curriculum as a means to teach programming [13], [14]. Moreover, the overall popularity of Scratch is witnessed by Scratch being currently rated 19 in the TIOBE index, topping such languages as Lua, Scala and Groovy and since early 2014 exhibiting an increasing trend shown in Fig. 1. Scratch programming materials too do not focus on naming. For example, the Creative Computing Learner Workbook created by the ScratchEd group at Harvard does not explain... how to select good names for procedures and variables\textsuperscript{4}. It is therefore interesting to explore the naming habits of Scratch programmers. And there are other reasons why understanding the naming practices in the Scratch community is important. First, it is important for the Scratch community itself as bad naming practices can easily propagate from one program to another through ‘remixing’ [15], [16], a code sharing practice similar to GitHub forking [17]. Second, it is important for researchers. Software engineering researchers can learn how to support novice programmers, taking their first steps in programming. As shown in Fig. 2, 51% of Scratch programmers are aged between 10 and 15 at the time of registration according to the statistics provided by Scratch\textsuperscript{5}. Therefore, researchers of software engineering education can obtain insights in how to define naming guidelines for educational materials, and analyzing the differences between Scratch and textual languages can help in supporting the transition from visual languages to textual ones [18], [19]. We start by a \textbf{general discussion of naming practices} in Scratch and analyze the previously published collection of 250,000 Scratch projects [20]. We replicate two studies from a recent paper by Beniamini et al. [3]. Similarly to Beniamini et al. we investigate the distribution of the lengths of variable names and study popularity of single-letter variable names such as \texttt{i} and \texttt{x}. As opposed to Beniamini et al. who focused on variable naming in five mainstream programming languages we focus on Scratch. Furthermore, while Beniamini et al. solely focused on the names of the variables, we repeat their study for procedure names as well. Variable names in Scratch range mostly between 4 and 10 characters, procedure names tend to be longer. For the single-letter variables, the most commonly used names are \texttt{x}, \texttt{y} and \texttt{i}, procedures—a, \texttt{y} and \texttt{r}. Compared to the other programming languages, single-letter variable names are less common in Scratch and overall Scratch variables have longer names. The usage of single uppercase letters is similar to Perl, for the lowercase—to Java. Next we focus on \textbf{Scratch-specific features in naming identifiers}. Scratch supports a number of less commonly used naming features, for example spaces may be used in names e.g., a variable \texttt{max i} and integers and even floating point numbers can be used as variable names e.g., a variable named \texttt{6 or 3.14159}. Finally, Scratch allows for textual labels in between parameters. For example a method for printing the first \texttt{n} letters from a string \texttt{s} could be called “\texttt{printlnn}(\texttt{i}, \texttt{s})” in a textual language. Scratch allows for this too, however, one can also define a procedure called “\texttt{say n characters from text s}”, as shown in Fig. 5. This feature does exist in textual languages too—most notable in SmallTalk—but is not commonly found in most mainstream languages. \textsuperscript{4}http://scratched.gse.harvard.edu/guide/files/CreativeComputing20140820_LearnerWorkbook.pdf \textsuperscript{5}https://Scratch.mit.edu/statistics/ \textbf{Fig. 2: Age distribution of Scratch users at the time of registration according to Scratch statistics web-page} Investigating the use of these Scratch-specific naming patterns is interesting to understand their role in novice programming. If they are popular among Scratch programmers, this might be because they ease novice programming, and that means one could even advocate that these features should be integrated in the textual programming languages, if only to ease the transition for the block-based languages programmers. Spaces in variable names are common: 34\% of projects use this feature. Numeric values as identifiers are rarely used, and mostly represent constants or parts of the data structure. The usage of textual string between parameters is not as common; however, textual patterns used imply an inference from textual languages, e.g., by using brackets. \section{Related work} Naming identifiers in software code has been studied extensively in the past decades [1], [2], [3], [4], [5], [6], [7], [8], [21], [22], [23], [24], [25], [26], [27]. In practice, identifiers constitute a major part of the source code: e.g., in Eclipse 3.0M7 which is tantamount to 2 MLoC, 33\% of the tokens and 72\% of characters correspond to identifiers [28]. For a human reading code, it is crucial to the understanding of code to also understand what the identifiers mean. As such, several studies have investigated the link between identifier naming and code readability and comprehension [2], [5], [24], [26], [27] or identifier naming and externally observable aspects of the software development process that are expected to be affected by comprehension such as change-proneness [1], quality [4], [6] and presence of faults [7], [8]. Caprile and Tonella [29] have observed that names of C functions consist of on average of 2.04–3.36 words, often verbs expressing action, while Caracciolo et al. observed that most method names in Java and Smalltalk also tend to consist of several words but rarely more than five words [30]. Going beyond the discussion of whether variable names should be shorter or longer, Armacostova et al. [31], [32] have studied linguistic anti-patterns, “recurring poor practices in the naming, documentation, and choice of identifiers in the implementation of an entity” such as discrepancies between the behavior implied by the identifier and the corresponding comment, while Høst has studied whether the Java method names relate to the behaviour of those methods [33]. In the educational setting Glassman et al. propose Foobaz, a tool giving semi-automatic feedback on student variable names based on the values the variable can take during the execution and limited input from the teacher [34]. While visual languages such as Scratch have recently become a favorable choice for schools as an introduction to programming [19], the lion’s share of the previous work on identifier naming has focused on textual languages. Notable exception is the recent work of Moreno and Robles [35]: they observed that Scratch programmers often do not change the sprite names that were automatically generated by the environment. van Zyl et al. have observed that one of the interviewed school teachers working with Scratch has taught the students to integrate variable types in their names, e.g., ‘S’ for Strings [13]. Finally, Hermans and Aivaloglou encouraged the students in Scratch MOOC to choose meaningful names and to avoid keeping default ones [10]. Understanding the naming patterns and preferences of students learning how to program with visual languages is essential to act upon the difficulties faced by students when transitioning to textual programming languages. According to Kölling et. al. [36], for these learners, dealing with user-defined identifiers is one of the “fundamental challenges”. It involves an extra cognitive load to remember identifiers, with case sensitivity in some cases, instead of selecting a variable from a drop-down list in Scratch. It also relates to the broader challenges of spelling and writing for these students. ### III. RELEVANT SCRATCH CONCEPTS We introduce several core features of Scratch required for understanding the reminder of the paper. Readers are referred to “Creative Computing” [37] for an extensive overview. Scratch is a block-based programming language aimed at children, developed by MIT. Scratch can be used to create games and interactive animations, and is available both as a stand-alone application and as a web application. Figure 3 shows the Scratch user interface in the Chrome browser. 1) **Sprites**: Scratch code is organized into ‘sprites’: two-dimensional pictures that each have their own source code. Scratch allows users to bring their sprites to life in various ways, for example by moving them in the plane, having them say or think words or sentences via text balloons, but also by having them make sounds, grow, shrink and switch costumes. The Scratch program in Fig. 3 consists of one sprite, the cat, which is Scratch’s default sprite and logo. The code in the sprite will cause the cat to jump up, say “hello”, and come back down, when the green flag is clicked, and to make the ‘meow’ sound when the space bar is pressed. ![Fig. 3: The Scratch UI consisting of the ‘cat’ sprite on the left, the toolbox with available blocks in the category ‘motion’ in the middle and the code associated with the sprite on the right.](https://Scratch.mit.edu/projects/97086781/) 2) **Scripts**: Source code within sprites is organized in scripts: a script always starts with an event, followed by a number of blocks. The Scratch code in Fig. 3 has two distinct scripts, one started by clicking on the green flag and one by pressing the space bar. It is possible for a single sprite to have multiple scripts initiated by the same event. In that case, all scripts will be executed simultaneously. 3) **Variables**: Like most textual languages, Scratch programmers can use variables. Variables are untyped, but have to be ‘declared’ through the Scratch user interface, shown in Fig. 4. This figure also shows that, contrary to most programming languages, variable names in Scratch may contain spaces. 4) **Procedures**: Scratch allows programmers to create their own blocks, called procedures. They can have input parameters, and labels in between. Procedures are created with an interface similar to the one to create variables. Figure 5 shows the definition and the invocation of a procedure in Scratch. ![Fig. 4: The Scratch user interface to create a variable](https://Scratch.mit.edu/projects/97086781/) ### IV. RESEARCH DESIGN AND DATASET **A. Overall design** The goal of this paper is to compare naming practices of the Scratch programmers to those of the developers in mainstream programming languages. To that end, we start by partially replicating the recent work of Beniamini et al. on single-letter variables in Java, C, PHP, Perl, and JavaScript [3]. In terms of the classification of Shull et al. [38], we perform a dependent replication of the studies summarized in Fig. 1 and 2 of the original work. Inherently, the programming language is the only factor we vary when compared to the original study. However, as opposed to the data in the original study, Scratch programs are not available on GitHub. Hence, we use the dataset previously scraped and processed by Aivaloglou and Hermans [20]. We report on the results of these replications in Sections V-A1 and V-A2. Furthermore, we perform another dependent replication of the same studies by considering Scratch procedures rather than variables (Section V-A3). Next, in Section V-A4 we perform a conceptual replication of the study of the single-letter variable types of Beniamini et al. [3]. The original study conducted a survey to understand the type-related user perceptions, with questions such as “what type would you consider for a variable called ...?”. We however focus on the types as used in the program. We investigate types “as-being-used”, as opposed to “as-being-perceived” in the original study due to the limited programming experience of the intended Scratch programmers. Scratch is meant for people taking their first steps in programming, such as school-age students, and we do not expect them to have established perceptions on data types of single-letters variables. As opposed to our work, in the original study, however, 30% of survey respondents claim 10-years experience in programming, while 23% have programming knowledge in six different languages or more [3]. Furthermore, we study types as used as opposed to types as defined, since Scratch does not have a concept of an explicit variable type. However, we can deduce the variable types from assignments involving those variables. For example, variable $i$ in Fig. 5 represents an integer since it is assigned 1. Finally, in Section V-B we report on the ways Scratch developers employ Scratch-specific naming practices such as spaces in variable names, numeric values as variables, and the use of textual labels in between parameters. C. Identifier Extraction To follow the steps of the replicated study, we collect the unique variable names used in the projects’ scripts. Within the scripts we identify Scratch blocks that are used to assign a value to the variables, e.g., “Change variable by value” or “Set variable to value”. Variable names in Scratch are unique: once a variable is declared in a project, its name cannot be used to create another variable in the same project, even in a different scope, e.g., in a different sprite. We note that we focus solely on artifacts created specifically through “Make a Variable” button in Scratch UI, rather than other named entities, such as sprites. However, we believe sprites should be excluded from consideration, since we perform a dependent replication study to variable names in textual languages. Therefore, what we consider as a Scratch variable must hold a major property similar to variables in the textual languages: its name must be entered by the user. In Scratch, however, sprites are assigned default names automatically, and they often remain unchanged by the users [35]. To determine the type of single-letter variables, we perform type inference on the parameter value assigned to each variable. The inference is performed via standard data type conversion of the value. If the variable is accessed multiple times in a project with different data types, for example first as a string and then as an integer, both data types are counted. For the procedure names, we identify the blocks used to call a procedure, extract the name of the procedure, and count the number of projects in which it occurs. We note here that Scratch allows the user to create multiple procedures with the same exact name in the same sprite. It is not clear to us why the language would support such a feature. We argue, however, that counting the procedure names once per project is an indication of the naming patterns used and fits the needs of this study. For the presence of spaces in and numbers as variables we simply analyze the previously extracted variable names, while textual patterns in procedure names are detected from the extracted procedures’ names. We provide the analysis code, input and output files for verification and replication purposes on a GitHub repository. D. Data Analysis Understanding differences in variable name lengths occurring between different programming languages requires comparison of multiple distributions. Such a comparison is traditionally performed as a two-step process consisting of (1) testing a global null hypothesis, that can be intuitively formulated as “all distributions are the same”, using ANOVA or its non-parametric counterpart, the Kruskal-Wallis test, and (2) performing multiple pairwise comparisons of different distributions, testing specific subhypotheses such as “distributions 2 and 4 are the same”. However, it has been observed that such a two-step approach can result in inconsistencies when either the global null hypothesis is rejected but none of the pairwise subhypotheses is rejected or vice versa [39]. https://github.com/Felienne/ScratchVars Moreover, it has been suggested that the Wilcoxon-Mann-Whitney test, commonly used for subhypothesis testing, is not robust to unequal population variances, especially in the unequal sample size case [40]. Therefore, one-step approaches have been sought. We opt for one such approach, the T-procedure of Konietschke et al. [41], [42]. This procedure is robust against unequal population variances, respects transitivity, and has been successfully applied in empirical software engineering [43], [44], [45], [46], [47], [48]. We use the Tukey (all-pairs) contrasts to compare all distributions pairwise. To understand differences between the distributions of single-letter variable names in different languages, we represent each programming language as a 26-dimensional vector with the dimensions corresponding to ‘a’, ..., ‘z’. For each language we consider two distributions: the distribution of the lower case letters (‘a’, ..., ‘z’) and the distribution of the lower case letters (‘A’, ..., ‘Z’). We compute the mean Euclidean distances between pairs of distributions and then perform hierarchical clustering based on the Euclidean distance. When comparing distributions of variable name lengths with the procedure name lengths, the T-procedure is not applicable. Hence, we perform the Mann-Whitney-Wilcoxon test together with the two-sample test for the nonparametric Behrens-Fisher problem, i.e., test for $H_0 : p = 1/2$, where $p$ denotes the relative effect of the two independent samples [42], [49]. For space usage in variables’ names we do two things: (i) To understand how much popular spaces are among all the names, we extract the space count per unique variable name. (ii) To understand the trend of using spaces across the dataset (multiple projects and multiple users), we extract per project the maximum space count found in the project’s variables. For the textual patterns in procedure names, we count the occurrence of each of the extracted token. V. RESULTS This section presents an overview of our analysis of variable and procedure name used in the previously published Scratch dataset [20]. We start by replicating studies of Beniamini et al. [3] and proceed with investigating Scratch-specific features. A. Replication Studies Our first analyses are the replication studies regarding one letter variables. 1) Variable Name Length: The original study of Beniamini et al. [3] concluded that the single-letter variable names “are approximately as common as other short lengths except in PHP” and that “in C, Java, and Perl they make up 9–20% of the names”. Figure 6 shows the distribution of lengths in the Scratch dataset. A closer look at the data reveals that the single-letter variables constitute ca. 4% of all the variable names, i.e., less than the 9–20% observed by Beniamini et al. Compared to the five programming languages in the study of Beniamini et. al., single-letter variables seem to be less common in Scratch, while the maximum length of a variable’s name ~250 characters– is significantly larger. These Observations lead us to wonder whether overall the variable names in Scratch are longer than in other programming languages. To this end, we apply the T-procedure (Section IV-D) that reveals that variable names in Scratch indeed are longer than in the textual languages studied in Beniamini et. al. Moreover, variable names in Java tend to be longer than those in PHP, those in PHP than those in C, those in C than those in JavaScript, and finally, those in JavaScript than those in Perl. In all cases p-values have been too small to be computed precisely ($p < 2.2 \times 10^{-16}$). 2) Single-letter Variable Names: Further we investigate the case of single-letter variable names. For the previously studied programming languages, Beniamini et. al. [3] highlight the following Observations about the single-letter usage: a) The most commonly occurring single-letter variable name is $i$. The authors attribute this to $i$ being commonly used as a loop counter. As opposed to the studied mainstream languages, loops are performed in Scratch using predefined blocks. As illustrated on Fig. 7, the two left-most blocks –forever and repeat 10– do not require a variable to control the loop iterations. However, inside the loop the user will have no access to the built-in loop’s iterator. When that is needed by the user, then the third block in Fig. 7 –repeat until– can be used. To understand its use see Fig. 5. In summary, because of the built-in language support to variable-free loops, we expect the usage of the variable name $i$ to be less common in Scratch. b) Apart from the popularity of $i$ the distribution is language-dependent. Since Scratch is quite different from the programming languages considered by Beniamini et al., we expect the distribution of the single-letter variable names in Scratch to be different to the distributions in those languages. Hence, we expect the similarity between Scratch and the languages considered by Beniamini et al. to be lower than the similarity between those five languages in Beniamini et. al. study. c) Finally, the authors observe that the lower case letters are used more frequently than the upper case letters. Since this is also the case for regular text in most natural languages as well, we expect the Scratch programs to follow the same pattern. Figure 8 shows the distribution of variables of one letter, Fig. 7: Scratch blocks that are used to repeat specific actions Fig. 8: A histogram of single-letter variables occurrences in Scratch projects Fig. 9: Examples of blocks using built-in variables x and y Fig. 10: A cluster dendrogram of Scratch compared to other programming languages for the single-letter pattern in upper and lower case, in the Scratch dataset. Note that one Scratch project may contain both the upper and lowercase version of one variable, and they will refer to a different variable. Inspecting the data we observe that similarly to the previous study i is the most commonly occurring variable. Hence, we conclude that contradicting our expectations Observation a) above also holds for Scratch. Furthermore, we observe that x and y are extremely popular in Scratch. This can be explained by the fact that x and y represent the coordinates of the sprites on the stage, and when reading the position of a sprite, Scratch developers access the built-in x and y properties. As such, they form the basis of moving sprites in the 2-D stage. There seems to be an agreement on this use among the developers of textual languages studied in Beniamini et. al. When they were surveyed about variable name interpretations, x and y were commonly interpreted as “coordinates”. In addition, built-in Scratch blocks often use x and y as shown in Fig. 9. We conclude that Scratch programmers seem to be inspired by the Scratch language in naming variables. Next we study the similarity of Scratch to the five programming languages in terms of frequency distribution of single-letter variable names. Hence, we compare the mean Euclidean distance between the pairs of the twelve distributions (the five programming languages plus Scratch, considered for the uppercase and the lowercase letters). The mean distance shows that the Scratch usage of the uppercase letters in the single-letter variable names is close to the ways the upper case letters are used in Perl, C and Java (mean distances between 36712.85 and 37076.95), while the way lowercase letters are used in Scratch quite similarly to the way letters are used in Java (Scratch—44572.57 and Java—46706.21). Hence, we claim that our expectation based on Observation b) has been confirmed for the uppercase letters and rejected for the lowercase letters. Closer look at Fig. 10 shows that the usage of single uppercase letters is similar to the pattern found in Perl, for the lowercase—to the pattern found in Java. Finally, Fig. 8 clearly shows that the lowercase letters are much more frequently used as variable names than the uppercase letters, providing support for Observation c). Single-letter variable names are less common in Scratch than in other programming languages (ca. 4% vs. 9–20%), and Scratch variables have longer names than variables in other programming languages. 3) Procedure Names: Going beyond the study of Beniamini, we additionally consider the naming of procedures in Scratch. For a detailed explanation of procedures in Scratch see Section III-4 and Fig. 5. Figure 11 shows the distribution of the procedure names length in the Scratch dataset. By inspecting this figure, we observe that the procedure names tend to be longer compared to Scratch variable names. Indeed, the two-sample test for the nonparametric Behrens-Fisher problem estimates the relative effect of the two samples (procedure name lengths vs. variable name lengths) as 0.149 (with the $p$-value being too small to be computed precisely ($p < 2.2 \times 10^{-16}$), i.e., it indicates that the procedure names’ lengths tends to be larger than the lengths of the variable names. This Observation is additionally confirmed by the Mann-Whitney-Wilcoxon test (the $p$-value is too small to be computed precisely). Short procedure names are not common, they are even less common than variable names: single-letter procedure names compose less than 1% of the extracted names, less than 4.9% observed for Scratch variables and 9–20% in C, Java and Perl variables [3]. The maximum length for a procedure name is 250 characters, which is the same as the maximum length for the variable names. We suspect this exact match is caused by a language constraint that was imposed in previous versions of Scratch. The current version of Scratch, however, allows for names longer than 250 characters. Next, we consider single-letter names for the procedures and revisit Observations a) and c). We could not revisit Observation b) with respect to procedures since data on single-letter procedure names was not collected for the five programming languages in the study of Beniamini et. al. Figure 12 shows the number of occurrences for each alphabetic letter. We see that $i$ is no longer among the most commonly used letters rejecting Observation a). The top used single-letter name is $a$, the first letter in the alphabet, which might explain its popularity. The uppercase letters are used more often than the lowercase letters (in 267 vs. 218 projects), rejecting Observation c). 4) Types: In the paper of Beniamini et al. [3] the authors observe that some letters are highly associated with the data type starting with the same letter: e.g., char for c and string for s. They also highlight that the integer data type is a common association for many other letters. Furthermore, a survey for developers showed that variable names $x$, $y$ and $z$ are commonly interpreted as coordinates, and for these letter it seems a balance exists between integer and float associations. As explained in Section IV-A we conduct a conceptual replication by considering the types of variables as they are used, as opposed to types as guesses by programmers. Figure 13 shows the distribution of single-letter variables with the types inferred. The majority of single-letter variables are encountered as integers in the Scratch dataset. This partially agrees with their Observation of integers being common for many letters, however, the data types are less diverse in Scratch compared to the five programming languages considered. One Observation that contradicts Observations in the original study is related to the string data type. While string data type in the five programming languages studied is commonly associated with $s$ and less frequently with many other letters, the strings are almost completely absent in the Scratch dataset apart from $i$. This is also observed for the other data types where no noticeable usage could be observed for floats, lists or strings. The only exception to some extent is the variable $c$ where we observe some usage linked with the $char$ data type. Floats as types for $x$, $y$ and to lesser extent $z$ seem to support the Observation that these single-letters variables are perceived as coordinates as suggested by Beniamini et al. [3]. B. Scratch-specific Constructs In this section we analyze the occurrence of naming practices that are allowed in Scratch, but are missing from or are not common in most mainstream textual languages. 1) Spaces in Variable Names: Most textual programming languages do not allow spaces in variable names. FORTRAN ignores spaces, this spaces could be used in variable names. However it does mean that ‘apples’ and ‘app les’ refer to the same variable. Other languages supporting spaces in variable names are SQL and some Scheme implementations. Even languages targeting data analysts rather than software developers recommend spaces be avoided [50]. To understand the usage of spaces in variable names, we measure their presence across the unique variable names, and across projects. Out of 67,286 unique variable names in the dataset, we find that 44.05% have at least one space: 30.95% have one space, 9.91% have two and 2.15% have three space characters. For the usage of space character per project, we count the maximum count of a space character in the project’s variable names. Out of 69,045 projects which include variables, we find 34% include variables names with at least one space character. As Fig. 14 shows, variable names with one space character are the most prevalent. We conclude that Scratch programmers prefer natural language naming of a variable: the use of a space character in variable names is common to some extent for many users, indicated by the project count, and for many used variable names. 2) Use of Numeric Variable Names: In addition to spaces in variable names, Scratch supports the use of numbers and even floating point numbers as variables. We found 718 projects using integer variable names and 19 with floating point names. While their use is rare, we manually examined some projects and numbers are used in interesting and clever ways. The most popular numeric values used as variable names include small natural numbers and 360 likely to represent 360° (cf. Fig. 16). There seem to be two main uses of numeric variable names. First, some variables with numeric names represent constants (cf. Fig. 15). This seems to indicate the Scratch programmers prefer to drag in a constant rather than repeatedly type it. A second use is the use of integer variables as simple list structures. For example, one of the projects we analyzed is a tic-tac-toe game. In that project, the programmer defined nine variables named 1 to 9. Each variable represents one of the nine boxes. Scratch supports lists, so the user here could have also used a list of 9 items, however, they did not. Maybe because they were not familiar with the concept of lists, or maybe they thought this would be easier for the user to memorize the game logic. 3) Use of Textual Labels between Parameters: Scratch is influenced by the SmallTalk family of languages which is visible from the fact that Scratch allows users to insert textual labels in between parameters in order to make procedures more readable, as shown in Fig. 5. This practice seems particularly idiomatic to Scratch, since built-in Scratch blocks use a similar syntax, e.g., in the “say ... for ... seconds” block. In total 4,414 projects use textual labels accounting for 25% of projects with procedures, and 1.77% of all projects in the dataset. Their use is relatively uncommon, however, we do find some interesting patterns. Fig. 17 shows the most commonly used labels. Here we see some patterns common in textual languages, like the use of labels for the names of the parameters ‘x:’ and ‘y:’, and the use of a closing bracket. We suspect the lack of the opening bracket ( to be caused by the fact that it would be included in the procedure name. We also see the use of ‘:’ at the end of many patterns, which could come from the users being inspired by Scratch default blocks, which use the colon at the end of many patterns, which could come from the users being inspired by Scratch default blocks, which use the colon as shown in Fig. 9. Finally, the use of the space (char-space in Fig. 17) is interesting, since Scratch already leaves some room between the parameters, also when a space is not used. VI. Threats to Validity As any empirical study our work is subject to series of threats to validity. Construct validity of our study might be threatened by the operationalization of the notion of a type. Due to the lack of explicit type declaration in Scratch our approach inferred the type by inspecting the value assigned to the variable. To be representative for a project, our method counted the different types encountered for the same variable within a project. For example if the variable “score” was set to “empty” at first, and then set to 0 in a different script, we count two types for the variable: one string and one integer. The same can be applied in textual languages with less strict type systems such as PHP. While the method is simple, it assures that data types used by Scratch programmers are represented in the data, and forms a good proxy to compare the results to the perceptions of professional developers. It is possible that these data types do not reflect the perception of users precisely. This is why this threat will be addressed in future work by surveying students in our running Scratch MOOC. Another threat to the construct validity is our decision of what is a variable name in Scratch. As explained above for the sake of replication we choose to include the names of variables created specifically through “Make a Variable” button in Scratch UI. One threat to the internal validity of our study comes from the use of non-Latin characters in identifiers. These characters are encoded as series of question marks, a limitation we inherit from the original dataset. Since one non-Latin character can be encoded as several question marks, the variable/procedure names length reported would overestimate the actual length. However, the impact of these identifiers is limited as the majority of Scratch programmers are from countries that use Latin alphabet. To validate this, we manually analyzed the variable names extracted and found that merely 450 variables have non-Latin alphabetic characters, less than 0.67% of the total 67,287 unique variable names. Therefore, we did not exclude names with non-Latin characters from the analysis. Finally, a threat to the external validity concerns the generalization of the study results. We argue that we use a large dataset which comprises around 1% of 23 million currently shared Scratch projects. It could be that the dataset does not reflect the users trend for identifier naming. However, the Scratch community represents novice programmers with younger age. For these users, it is difficult to imaging they have an established trend in naming without prior education. VII. Conclusion In this paper, we study naming patterns for variables and procedures in the Scratch programming language, a block-based programming language aimed at novice programmers. We use a previously released dataset consisting of 250,000 Scratch programs. Our analysis shows that Scratch programmers most often use variable names between 4 and 10 characters in length, while procedure names in Scratch tend to have longer names than the variables. For the single-letter variables, the most commonly used names are x, y and i. When compared to the other programming languages, Scratch variable length distribution, and the usage of single uppercase letters seems to be similar to the pattern found in Perl, while for the lowercase letters—to the pattern found in Java. Spaces in variable names, a feature relatively unique to Scratch, are used in 34% of projects in which variables can be found. The usage of textual string between parameters appears as not so common, however textual patterns used imply an inference from textual languages by using brackets for example. The paper makes the following contributions: - An analysis of procedure names in Scratch. - An analysis of naming patterns unique to Scratch, including spaces in variable names, numeric variable names and textual labels in procedures. Studies concerning the difficulties novice programmers have when transitioning to textual programming languages highlight that handling identifier naming is one of the fundamental challenges faced by these learners, as part of a broader spelling challenge [36]. We believe the naming patterns found in our study support the claim that challenges will be faced by Scratch programmers when transitioning to mainstream textual programming languages. Those languages restrict the use of spaces in identifiers and more often divert into short and single-letter names—tendencies opposite to the naming preferences in Scratch. This paper gives rise to a number of directions for future work. Firstly, Beniamini et al. [3] included a survey in which they ask developers to predict the type of a (one letter) variable. It could be interesting to ask a similar question to Scratch programmers for common variable names. Furthermore, a detailed study into the readability of variable names with and without spaces, and procedures with and without labels would help us to create naming guidelines for Scratch. Finally, one additional area to explore is the relation between name length of variables with the level of computational thinking [51], [52]. 8=https://scratch.mit.edu/statistics/ of the Scratch programmer in addition to other demographic factors like gender, age and language. References
{"Source-Url": "https://pure.tudelft.nl/portal/files/47579908/SCAM_camera_ready.pdf", "len_cl100k_base": 8576, "olmocr-version": "0.1.53", "pdf-total-pages": 11, "total-fallback-pages": 0, "total-input-tokens": 33536, "total-output-tokens": 10829, "length": "2e13", "weborganizer": {"__label__adult": 0.0004711151123046875, "__label__art_design": 0.0004737377166748047, "__label__crime_law": 0.0003077983856201172, "__label__education_jobs": 0.00814056396484375, "__label__entertainment": 8.779764175415039e-05, "__label__fashion_beauty": 0.00019693374633789065, "__label__finance_business": 0.0002713203430175781, "__label__food_dining": 0.0004076957702636719, "__label__games": 0.0006990432739257812, "__label__hardware": 0.0005688667297363281, "__label__health": 0.0003647804260253906, "__label__history": 0.0002720355987548828, "__label__home_hobbies": 0.00012767314910888672, "__label__industrial": 0.00032591819763183594, "__label__literature": 0.0004725456237792969, "__label__politics": 0.00028252601623535156, "__label__religion": 0.0005326271057128906, "__label__science_tech": 0.0052032470703125, "__label__social_life": 0.00021183490753173828, "__label__software": 0.005275726318359375, "__label__software_dev": 0.97412109375, "__label__sports_fitness": 0.0002741813659667969, "__label__transportation": 0.0005402565002441406, "__label__travel": 0.00021731853485107425}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 46434, 0.02149]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 46434, 0.75381]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 46434, 0.91091]], "google_gemma-3-12b-it_contains_pii": [[0, 0, null], [0, 4728, false], [4728, 10220, null], [10220, 15115, null], [15115, 20236, null], [20236, 25662, null], [25662, 29101, null], [29101, 32854, null], [32854, 35747, null], [35747, 42060, null], [42060, 46434, null]], "google_gemma-3-12b-it_is_public_document": [[0, 0, null], [0, 4728, true], [4728, 10220, null], [10220, 15115, null], [15115, 20236, null], [20236, 25662, null], [25662, 29101, null], [29101, 32854, null], [32854, 35747, null], [35747, 42060, null], [42060, 46434, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 46434, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 46434, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 46434, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 46434, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 46434, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 46434, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 46434, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 46434, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 46434, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 46434, null]], "pdf_page_numbers": [[0, 0, 1], [0, 4728, 2], [4728, 10220, 3], [10220, 15115, 4], [15115, 20236, 5], [20236, 25662, 6], [25662, 29101, 7], [29101, 32854, 8], [32854, 35747, 9], [35747, 42060, 10], [42060, 46434, 11]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 46434, 0.0]]}
olmocr_science_pdfs
2024-12-10
2024-12-10
723659ab441b43b1de41a9ff9e24ac2197252b1c
[REMOVED]
{"Source-Url": "https://es-static.fbk.eu/people/griggio/papers/tacas21.pdf", "len_cl100k_base": 14025, "olmocr-version": "0.1.53", "pdf-total-pages": 20, "total-fallback-pages": 0, "total-input-tokens": 71390, "total-output-tokens": 19494, "length": "2e13", "weborganizer": {"__label__adult": 0.0004858970642089844, "__label__art_design": 0.0005941390991210938, "__label__crime_law": 0.0005636215209960938, "__label__education_jobs": 0.0016841888427734375, "__label__entertainment": 0.00014078617095947266, "__label__fashion_beauty": 0.00025963783264160156, "__label__finance_business": 0.0004954338073730469, "__label__food_dining": 0.0005693435668945312, "__label__games": 0.0013666152954101562, "__label__hardware": 0.0016679763793945312, "__label__health": 0.0009889602661132812, "__label__history": 0.0005497932434082031, "__label__home_hobbies": 0.00020623207092285156, "__label__industrial": 0.0008563995361328125, "__label__literature": 0.0005521774291992188, "__label__politics": 0.0005488395690917969, "__label__religion": 0.0007829666137695312, "__label__science_tech": 0.243896484375, "__label__social_life": 0.0001533031463623047, "__label__software": 0.0081024169921875, "__label__software_dev": 0.73388671875, "__label__sports_fitness": 0.0004045963287353515, "__label__transportation": 0.0011510848999023438, "__label__travel": 0.000278472900390625}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 67240, 0.04096]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 67240, 0.37081]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 67240, 0.81504]], "google_gemma-3-12b-it_contains_pii": [[0, 2843, false], [2843, 6208, null], [6208, 10356, null], [10356, 13599, null], [13599, 16420, null], [16420, 18996, null], [18996, 22442, null], [22442, 27331, null], [27331, 31004, null], [31004, 34078, null], [34078, 37746, null], [37746, 40866, null], [40866, 44730, null], [44730, 48132, null], [48132, 51400, null], [51400, 54752, null], [54752, 58150, null], [58150, 61414, null], [61414, 64665, null], [64665, 67240, null]], "google_gemma-3-12b-it_is_public_document": [[0, 2843, true], [2843, 6208, null], [6208, 10356, null], [10356, 13599, null], [13599, 16420, null], [16420, 18996, null], [18996, 22442, null], [22442, 27331, null], [27331, 31004, null], [31004, 34078, null], [34078, 37746, null], [37746, 40866, null], [40866, 44730, null], [44730, 48132, null], [48132, 51400, null], [51400, 54752, null], [54752, 58150, null], [58150, 61414, null], [61414, 64665, null], [64665, 67240, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 67240, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 67240, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 67240, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 67240, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 67240, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 67240, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 67240, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 67240, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 67240, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 67240, null]], "pdf_page_numbers": [[0, 2843, 1], [2843, 6208, 2], [6208, 10356, 3], [10356, 13599, 4], [13599, 16420, 5], [16420, 18996, 6], [18996, 22442, 7], [22442, 27331, 8], [27331, 31004, 9], [31004, 34078, 10], [34078, 37746, 11], [37746, 40866, 12], [40866, 44730, 13], [44730, 48132, 14], [48132, 51400, 15], [51400, 54752, 16], [54752, 58150, 17], [58150, 61414, 18], [61414, 64665, 19], [64665, 67240, 20]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 67240, 0.0375]]}
olmocr_science_pdfs
2024-12-09
2024-12-09
a1c449860faa9f1a42830678f343a8cea88f9559
PolyBench/Python: benchmarking Python environments with polyhedral optimizations Miguel Á. Abella-González, Pedro Carollo-Fernández, Louis-Noël Pouchet, Fabrice Rastello, Gabriel Rodríguez To cite this version: HAL Id: hal-03153351 https://inria.hal.science/hal-03153351 Submitted on 26 Feb 2021 HAL is a multi-disciplinary open access archive for the deposit and dissemination of scientific research documents, whether they are published or not. The documents may come from teaching and research institutions in France or abroad, or from public or private research centers. L’archive ouverte pluridisciplinaire HAL, est destinée au dépôt et à la diffusion de documents scientifiques de niveau recherche, publiés ou non, émanant des établissements d’enseignement et de recherche français ou étrangers, des laboratoires publics ou privés. Abstract Python has become one of the most used and taught languages nowadays. Its expressiveness, cross-compatibility and ease of use have made it popular in areas as diverse as finance, bioinformatics or machine learning. However, Python programs are often significantly slower to execute than an equivalent native C implementation, especially for computation-intensive numerical kernels. This work presents PolyBench/Python, implementing the 30 kernels in PolyBench/C, one of the standard benchmark suites for polyhedral optimization, in Python. In addition to the benchmark kernels, a functional wrapper including mechanisms for performance measurement, testing, and execution configuration has been developed. The framework includes support for different ways to translate C-array codes into Python, offering insight into the tradeoffs of Python lists and NumPy arrays. The benchmark performance is thoroughly evaluated on different Python interpreters, and compared against its PolyBench/C counterpart to highlight the profitability (or lack thereof) of using Python for regular numerical codes. Keywords: Python, Benchmarking, JIT Optimization, Polyhedral Compilation 1 Introduction Python has become one of the most used and taught languages nowadays, popularized well beyond its first uses as a scripting language in e.g., bioinformatics [5] into a go-to language to implement full object-oriented complex applications such as for deep learning approaches, e.g. [10, 22]. Its benefits in terms of flexibility and ease-of-programming come in large part from dynamic typing and runtime interpretation. However, this typically comes with a performance penalty when comparing to e.g. a native C implementation compiled and ran on the target platform. As Python has become ubiquitous, its ecosystem is rapidly growing, including compiler analyses and optimizations for Python programs being developed. There is a compelling need to provide benchmarks and tools to help characterize the performance profile of various approaches to implement Python programs, recognizing the software ecosystem ranges from classical runtime interpreters [7], just-in-time compilation for improved performance [29] or even optimizing compilers for Python programs [20]. In this work, we aim to enable the evaluation of current and upcoming Python ecosystems for scientific programming, focusing specifically on numerical kernels that are typically implemented using dense arrays (lists). The kernels we consider are all polyhedral programs by design [15], that is, they involve only static control-flow (Static Control Parts, or SCoP). In a SCoP, no operation may be conditionally executed depending on the input data: the execution is deterministic and reproducible irrespective of the actual input data values. This includes numerous dense linear algebra methods (e.g., matrix product, tensor contractions), dynamic programming, stencil computations for image processing or physics simulation, and equation solvers. Polyhedral programs can be represented at compile-time using affine functions and integer lattices, enabling exact array dataflow analysis to be computed [11]. Consequently, it is possible to design highly advanced automatic optimizing compilation algorithms for polyhedral programs, where aggressive restructuring including loop parallelization and tiling can be seamlessly implemented, e.g. [4, 12, 21, 23, 27]. Production compilers like GCC [26] and LLVM [17] integrate already polyhedral optimizers, as well as numerous research tools such as Pluto [4] or ISL [32]. We introduce PolyBench/Python, a self-contained benchmarking suite made of 30 numerical polyhedral kernels, for which polyhedral compilers can be designed and evaluated. PolyBench/Python is on purpose an exact mirror of the 30 kernels in PolyBench/C 4.2 [28] in terms of computation performed, problem sizes and data types. This feature is key to... enable fair side-by-side comparison of Python-based implementations with clean, native C implementations optimized with state-of-the-art optimizing compilers. PolyBench/C provides a single reference implementation for each kernel, and a variety of schemes to allocate data along with mechanisms to ensure reproducible evaluations. PolyBench/Python offers similar features, but it also includes three Python implementations for each benchmark: a simple, C-like implementation using multidimensional arrays; another simple C-like implementation using linearized arrays; and a NumPy [31] implementation. As we demonstrate in this paper, different types of implementation may deliver the best performance, depending on the benchmark and execution environment. We developed an automated polyhedral optimizer for PolyBench/Python, automatically extracting the polyhedral representation of the kernel, and optimizing it with off-the-shelf polyhedral compilers. We present extensive experimental studies of the impact of several classical polyhedral loop transformations when applied to PolyBench/Python, including complex loop fusion to improve data reuse (using the Pluto algorithm [4]), and loop permutations to further expose parallel inner loops. We make the following contributions: - We introduce PolyBench/Python, a suite of 30 numerical kernels, for the purpose of benchmarking Python runtime environments and (just-in-time) Python compilers. - We developed an automated polyhedral compilation flow for PolyBench/Python, and present extensive experiments on the profitability (or lack thereof) of implementing loop transformations for improved data reuse for these benchmarks. - We present extensive experimental results characterizing PolyBench kernels, contrasting their execution profile in native C with their Python equivalent, to characterize the profitability and overhead of using Python for such numerical computations. - We present several insights on Python programming styles and good practice to expose solid performance for Python-based implementations of numerical kernels. The rest of the paper is organized as follows. Section 2 motivates the work. Section 3 introduces PolyBench/Python. Section 4 presents extensive experimental results. Section 5 presents related work, before concluding in Sec. 6. 2 Implementing Numerical Kernels in Python The Python Ecosystem. Python is a high-level, object-oriented programming language that is well established with a very large community in both academia and industry. It is a general-purpose language which is extremely easy to learn due to its very clean syntax and great readability. One of the best characteristics of Python is its productivity. It is a dynamically (but strongly!) typed and interpreted language, with elegant syntax that makes it a very good option for scripting and rapid application development. NumPy [31] includes both a C array-like storage format, and high performance operations on arrays for Python. Nowadays, many Python codes are efficient enough for production use. However, due to Python’s interpreted nature and the lackluster performance of “pure Python” (i.e., not using NumPy or external libraries) codes in the reference CPython interpreter, part of the community dismisses Python as a low performance language in itself. Execution Profiles with Different Implementations. Figure 1 illustrates the wide ranging performance profiles that can be obtained with various types of dense numerical kernels. It presents the normalized performance, in CPU execution cycles, achieved by different C and Python versions of five selected PolyBench kernels with and without polyhedral optimizations using the Pluto algorithm [4]2 ![Figure 1. Performance (CPU cycles elapsed) of selected C/Python PolyBench benchmarks. The plot presents two C versions, with and without polyhedral fusion to reduce the data reuse distance (through pocc –pluto); and three Python versions, with and without polyhedral fusion, and an additional manually vectorized version using NumPy. The Y axis is normalized to the values of gcc -O3. The full experimental setup is described in Sec. 4.](image) We observe that Python implementations may end up competing with native C implementations (e.g., gramschmidt, seidel-2d and syr2k); but may also massively degrade performance, e.g., by nearly 10x for the Python versions of 2Additional and/or different polyhedral optimizations may provide higher performance gain than reported here, no tuning of these optimizations was implemented: we limit here to evaluating the benefit of loop fusion/distribution (possibly including loop skewing/shifting to make the fusion possible). We extensively analyze the reasons for this execution profile differences in Sec. 4, pointing to an extremely significant overhead that can be added by the Python JIT in terms of branching and memory movement instructions for certain codes. We also observe that the NumPy implementations, the typical method of choice to implement numerical kernels in Python, do not necessarily outperform the other Python versions, as shown for the two stencils, seidel-2d and to a lesser extent jacobi-2d. Finally, the impact of polyhedral loop transformations for data reuse appears limited here, as is confirmed by experiments presented later: there is a massive impact for the C and Python versions of syr2k, but mostly no benefit elsewhere, pointing to the fact that the performance bottleneck of these codes is not the memory traffic. All this is carefully analyzed and explained later in Sec. 4. Evaluating PolyBench/Python. This paper targets the Python benchmarking of small computational kernels. The 30 PolyBench/C kernels are translated to Python, supporting the exploration of the optimization space, including parameters such as how arrays are implemented or what is the comparative performance of different Python interpreters for different types of codes. It provides support for automatically measuring performance counters through the PAPI library, enabling seamless performance analysis. Furthermore, we have developed a tool to generate a ScopLib representation [8] of a polyhedral Python kernel, and conversely, to generate a Python code from a ScopLib representation. This allows to integrate Python with off-the-shelf polyhedral compilers such as PoCC [8] and PLUTO [1, 4]. 3 PolyBench/Python We now introduce PolyBench/Python, which is based on PolyBench/C, and present the approach for the various kernel implementations we provide for each benchmark. 3.1 PolyBench PolyBench is a benchmark suite of 30 numerical computations with static control flow, extracted from operations in various application domains (linear algebra computations, image processing, physics simulation, dynamic programming, statistics, etc.). Its original objective is to offer a set of representative numerical computations that are amenable to polyhedral optimizations, and to offer a platform to ease reproducibility of experiments, including numerous features for e.g. cache flushing, highly accurate timing, support for PAPI hardware counters, and non-random initialization data. PolyBench/C was developed by Pouchet, with significant contributions from Yuki starting from PolyBench/C 4.0 [28]. PolyBench/Python, based on PolyBench/C 4.2.1 by Pouchet and Yuki [28] implements, by design, exactly the same computation as in the equivalent PolyBench/C program: the same data types, exact same algorithm (including the same execution order for the operations, for loop-based Python implementations), and exact same dataset sizes. The objective is to provide implementations in different languages of the exact same computation to allow "apple-to-apple" comparisons between native C implementations and JIT/interpreted implementations in Python, thereby enabling to observe the overhead of the Python techniques compared to the execution of only-necessary instructions in the native C program. Table 1 presents the 30 kernels in PolyBench and their descriptions, for completeness. We report the order of data reuse, that is roughly the order of magnitude of times a data element is being reused by different computations in the kernel. Programs with $O(N)$ reuse, where $N$ represents the problem size (e.g., the number of rows or columns of an input square matrix $N \times N$) are typically viewed as “compute-bound”, while those with $O(1)$ reuse as “memory-bound”. Stencil computations time-iterated $T$ times have their data reused $O(T)$ times. <table> <thead> <tr> <th>Benchmark</th> <th>Reuse</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td>2mm</td> <td>$O(N)$</td> <td>2 Matrix Mul. ($\alpha ABC + \beta D$)</td> </tr> <tr> <td>3mm</td> <td>$O(N)$</td> <td>3 Matrix Mul. ($(AB)(CD)$)</td> </tr> <tr> <td>adi</td> <td>$O(T)$</td> <td>Alternating Direction Implicit solver</td> </tr> <tr> <td>atax</td> <td>$O(1)$</td> <td>Matrix transpose and vector mult.</td> </tr> <tr> <td>bicg</td> <td>$O(1)$</td> <td>BiCG sub-kernel of BiCGstab solver</td> </tr> <tr> <td>cholesky</td> <td>$O(N)$</td> <td>Cholesky decomposition</td> </tr> <tr> <td>correlation</td> <td>$O(N)$</td> <td>Correlation computation</td> </tr> <tr> <td>covariance</td> <td>$O(N)$</td> <td>Covariance computation</td> </tr> <tr> <td>deriche</td> <td>$O(1)$</td> <td>Edge detection filter</td> </tr> <tr> <td>doitgen</td> <td>$O(N)$</td> <td>Multi-res. analysis kernel (MADNESS)</td> </tr> <tr> <td>durbin</td> <td>$O(N)$</td> <td>Toeplitz system solver</td> </tr> <tr> <td>ffdtd-2d</td> <td>$O(T)$</td> <td>2-D Finite Diff. Time Domain kernel</td> </tr> <tr> <td>floyd-warshall</td> <td>$O(N)$</td> <td>Graph shortest path length</td> </tr> <tr> <td>gemm</td> <td>$O(N)$</td> <td>Matrix-multiply ($C = \alpha AB + \beta C$)</td> </tr> <tr> <td>gemver</td> <td>$O(1)$</td> <td>Vector mul. and matrix add.</td> </tr> <tr> <td>gesummv</td> <td>$O(1)$</td> <td>Scalar, vector and matrix mult.</td> </tr> <tr> <td>gramschmidt</td> <td>$O(N)$</td> <td>Gram-Schmidt decomposition</td> </tr> <tr> <td>head-3d</td> <td>$O(T)$</td> <td>Heat equation over 3D data domain</td> </tr> <tr> <td>jacobi-1D</td> <td>$O(T)$</td> <td>1-D Jacobi stencil computation</td> </tr> <tr> <td>jacobi-2D</td> <td>$O(T)$</td> <td>2-D Jacobi stencil computation</td> </tr> <tr> <td>lu</td> <td>$O(N)$</td> <td>LU decomposition</td> </tr> <tr> <td>ludcmp</td> <td>$O(N)$</td> <td>LU decomposition + Forward Subst.</td> </tr> <tr> <td>mvt</td> <td>$O(1)$</td> <td>Matrix Vector product and Transpose</td> </tr> <tr> <td>nussinov</td> <td>$O(N)$</td> <td>Dyn. programming for seq. alignment</td> </tr> <tr> <td>seidel</td> <td>$O(T)$</td> <td>2-D seidel stencil computation</td> </tr> <tr> <td>symm</td> <td>$O(N)$</td> <td>Symmetric matrix-mult.</td> </tr> <tr> <td>syr2k</td> <td>$O(N)$</td> <td>Symmetric rank-2k update</td> </tr> <tr> <td>syrk</td> <td>$O(N)$</td> <td>Symmetric rank-k update</td> </tr> <tr> <td>trisolv</td> <td>$O(1)$</td> <td>Triangular solver</td> </tr> <tr> <td>trmm</td> <td>$O(N)$</td> <td>Triangular matrix-mult.</td> </tr> </tbody> </table> 3.2 PolyBench/Python: General design The PolyBench/Python benchmarks have been implemented following the Python 3 standard. Note no support was considered for Python 2 as it was discontinued in early 2020 [14]. The actual benchmark implementation is built around the PolyBench abstract class. It includes routines that support benchmarking and array allocation, and defines abstract handles that must be filled by implementing subclasses. In particular, a benchmark will extend the PolyBench class and define the abstract methods in Fig. 2. These implement the actual benchmark functionality, including array initialization, the kernel code itself, and printing the results in a standardized format which is readily compatible with the outputs produced by PolyBench/C, allowing for cross-language validation. The run_benchmark() method is similar to main() in C codes. It is in charge of defining the input and output structures of the benchmark, and initializing them and running the kernel via calls to the appropriate abstract methods. ```python def initialize_array(self, *args, **kwargs): ... def print_array_custom(self, array: list, dump_message: str = ''): ... def kernel(self, *args, **kwargs): ... def run_benchmark(self) -> list[tuple]: ... ``` Figure 2. Abstract functions to be implemented by a PolyBench/Python benchmark. PolyBench/Python provides two different ways to measure performance. The first is to measure the execution time of the kernel using the Timestamp Counter (TSC register). Its contents are directly accessed using assembly code executed through the inlineasm library. The second way is to measure performance counters using the PAPI library [24, 25] through the python_papi module. 3.2.1 Available Implementations. The process of translating PolyBench/C to Python requires a number of design decisions to deal with the intrinsic differences between both languages. One of the critical differences is related to data representation. Polyhedral codes in general, and the PolyBench benchmarks in particular, manipulate arrays and scalar variables of basic types. In C, these are stored sequentially in memory in row-major order. There is no equivalent representation in pure Python, where everything is an object and there are no basic data types, in contrast to other interpreted languages, such as Java, where both concepts coexist. Since everything is an object, lists of int values are not a collection of continguously stored 32- or 64-bit basic values, but rather a collection of continguously stored 64-bit pointers to int objects. This creates an additional level of indirection which degrades performance when traversing the array. Furthermore, when considering multidimensional structures, there is a choice between implementing them as a sequence of nested lists, similar to how a cascade of pointers to pointers would work in C, or flattening the structure and linearizing the accesses, as automatically done by C compilers with multidimensional array allocations. One can envision how the flattening should be more efficient, in the same way that in C using cascaded pointers introduces an additional level of indirection for each dimension in the data structure, degrading memory performance. One additional alternative for array implementation is to directly use NumPy arrays [31]. This looks like a good design alternative, since NumPy arrays are, by design, C-like objects, with homogeneously-typed data, and contiguous in memory. This has the potential to greatly improve the memory behavior, and therefore performance, but it comes with its own performance pitfalls that need to be carefully studied. In PolyBench/Python, the abstract PolyBench class that all benchmarks must extend implements all these different strategies for array allocation, exemplified in Fig. 3. The user must select the desired implementation using runtime knobs. These alternatives will be studied and compared in the experimental analysis in Sec. 4. 3.2.2 Control Structures. The PolyBench/C benchmarks prominently feature two control structures: if statements and for loops. The conditionals have a direct translation to Python, with no semantic and minimal syntactic variations. However, for loops in Python are foreach style loops that traverse a collection of objects. In order to implement them efficiently, a C for loop is translated to a Python for traversing a range expression. This is a special type of collection spawned by a Python generator object. This kind of collections are populated on demand, one object at a time, avoiding the memory overhead of instantiating the full collection. 3.3 Support for Polyhedral Optimizations We have implemented an analysis and translation layer capable of reading Python kernels and generating their ScopLib [8] representation, as well as back-generating Python codes and linearizing the accesses, as automatically done by C compilers with multidimensional array allocations. One can envision how the flattening should be more efficient, in the same way that in C using cascaded pointers introduces an additional level of indirection for each dimension in the data structure, degrading memory performance. One additional alternative for array implementation is to directly use NumPy arrays [31]. This looks like a good design alternative, since NumPy arrays are, by design, C-like objects, with homogeneously-typed data, and contiguous in memory. This has the potential to greatly improve the memory behavior, and therefore performance, but it comes with its own performance pitfalls that need to be carefully studied. Figure 3. List, flattened list, and NumPy alternative array implementations for the gemm kernel. ```python for i in range(0, self.NI): for j in range(0, self.NJ): C[i][j] += alpha * A[i][k] C[i][j] *= beta for k in range(0, self.NK): C[i][j] = alpha * np.dot(A[i][k], B[k][j]) C[i][j] = alpha * A[i][k] * B[k][j] # (a) List for i in range(0, self.NI): for j in range(0, self.NJ): C[i][j] += alpha * A[i][k] C[i][j] *= beta for k in range(0, self.NK): C[i][j] += alpha * A[i][k] * B[k][j] # (b) NumPy for i in range(0, self.NI): for j in range(0, self.NJ): C[i][j] += alpha * np.dot(A[i][k], B[k][j]) C[i][j] *= beta # (c) Flattened List ``` from the ScopLib. The input to this tool is not the Python source code, but the bytecode generated by CPython. This allows the optimizations to be performed in a just-in-time fashion, upon execution of the code, although this approach has not been used in the current work. However, no search or isolation of the static control part (SCoP) is performed at this time. The tool receives a Python function and assumes its entire body to be a valid SCoP. 3.4 Python Interpreters Similar to using different compilers for C codes, a collection of different interpreters exist for Python. CPython [13] is developed by the Python Software Foundation. Its goal is not to achieve high performance, but to provide a multi-platform environment that serves as the reference interpreter for other projects. PyPy [29] is a performance-oriented interpreter developed using the RPython [2] tool-chain. The Python code is translated to RPython, which is then translated to flow graphs, and then to C. The RPython layer includes a tracing just-in-time layer including an optimizer and a back-end that generates machine code. Intel Distribution for Python [7] is designed to make Intel libraries such as the Math Kernel Library [33] and the Data Analytics Acceleration Library [6] usable from Python. It does not intend to provide fast pure Python code, but to bridge the technological gap between Python libraries such as NumPy and Intel products. The performance of these interpreters will be compared in the next section. 4 Experimental Results Experiments with the 30 PolyBench kernels were executed on an Intel Core i7 8700K with 64 GB of RAM memory. The CPU frequency was fixed at the base frequency of 3.7 GHz to prevent thermal constraints affecting experimental variability. We first analyze the performance of the Python version of the benchmarks, comparing different interpreters and using both nested lists and flattened lists to implement arrays. Afterwards, we focus on PyPy and flattened lists to assess the relative performance of Python and C codes. Then, we study the performance impact of basic polyhedral optimization on both C and Python codes. Finally, we study the potential performance improvements to be gained from using NumPy on CPython. Our experimental study analyzes the performance of PolyBench/C 4.2.1-beta and PolyBench/Python. The tool-chain includes GCC 10.2.0, PoCC 1.5.0-beta, CPython 3.9.1, PyPy 7.3.2, and NumPy 1.19.4. All benchmarks are configured to use the default data types and dataset sizes, that is, the LARGE dataset size in PolyBench [28], where problem sizes typically far exceed L2 cache size. For each benchmark-configuration pair, selected PAPI hardware performance counters are collected during execution of the kernel, including those measuring hits and misses to each level of the memory hierarchy, execution cycles, total instructions executed, and stalled cycles. Instruction count is further broken down into several different instruction types, including memory instructions, branches, and floating point operations. For all experiments, we report the average of 5 runs. In all figures, performance counters are plotted relative to a baseline for simplicity and space. Complete experimental data, including absolute values for all measurements in the plots, are available as auxiliary material. 4.1 Relative Performance of Scalar Pure Python Implementations We first focus on pure Python codes, and more specifically on evaluating the performance of the different Python interpreters considered in our experimental setup. We found that for pure Python (i.e., not NumPy codes, which will be covered later), the performance metrics for PyPy are an order of magnitude better than those of CPython and the Intel Distribution for Python. This includes memory performance, CPU stalls, and branches and branch mispredictions. The average speedup over the full PolyBench/Python suite is 20x. For the sake of space saving, we do not report these results, and in the following we default to PyPy unless otherwise noted. Next, we study the tradeoffs of using nested lists versus flattened lists. Figure 4 summarizes key performance counters of the nested list-based implementation as compared to the flattened list-based one. Figure 4. Selected performance counters of the implementation with nested lists, executed using PyPy, normalized to the values of the implementation with flattened lists. Using flattened lists (i.e., linearized arrays) always offers the best performance, with an average speedup of 2x. Codes using flattened lists execute, on average, 1.9x fewer instructions, distributed as 1.7x fewer branches (20% of the total instruction count reduction), and 4.4x fewer load instructions (80% of the total instruction count reduction). This large reduction in the number of L1 accesses is caused by the removal of the intermediate levels of indirection when employing nested lists, but it does not have a large fundamental impact on the number of off-chip accesses, as the cache hierarchy is capable of absorbing the excess loads. L2 misses decrease by 2.2x. Misses to L3, where the actual data reside, and consequently main memory accesses, are decreased by only 1.1x, an indication that the actual benefit from the memory point of view is the elimination of repeated accesses to intermediate indirection levels in nested lists. If we categorize the benchmarks into compute-bound, memory-bound, and stencils following their data reuse profiles as shown in Table 1, we see a stark difference between memory-bound and compute-bound benchmarks. While for memory-bound benchmarks the average speedup is 1.4x, it goes up to 2.0x for the compute-bound and stencil kernels. The reason is that many compute-bound and stencil benchmarks become memory-bound as the number of memory accesses is multiplied by a factor of up to five when using nested lists. By flattening the lists the reduction in memory accesses directly translates into a halving of the pipeline stalls. PyPy provides an additional performance advantage when using flattened lists. Since PyPy 1.8, lists containing a collection of homogeneous objects, i.e., objects of the same Python type which corresponds to a C native type, will be internally stored as lists of native types, without a wrapping object [30]. Although this optimization is not identical to a native C array, as it still requires additional helper objects to implement operations on the list, a level of indirection is saved on the access to the data, improving overall performance. In the remainder of this section, all Python codes will be implemented through flattened lists, except where otherwise noted. 4.2 C vs Python This subsection focuses on the relative performance of C codes with different optimization levels and pure Python codes executed using PyPy and flattened lists. Since there is wide variability in the performance characteristics of different benchmarks in the PolyBench set, we break the 30 kernels down into smaller, more easily analyzable subsets that present common traits. We find that, for this comparison, the classical categorization into compute-bound, memory-bound and stencil benchmarks is not appropriate. In this case a categorization which follows the relative success of the C benchmarks depending on the optimization levels applied is more useful to determine the reasons for performance differences between Python and C, and it gives insight into how the Python-to-machine translation process can be further improved to speed up executions. For the remainder of this subsection, we will use the term “baseline” to refer to C codes compiled with gcc -O3 -fno-tree-vectorize. Indeed, we aim to isolate the effect of SIMD vectorization in our experiments for fair comparison, as PyPy does not appear to fully exploit SIMD vectorization in the generated programs. ![Figure 5](image-url) Figure 5. Performance, in execution cycles, of the benchmarks which benefit from -O3 but not from SIMD instructions. Results are normalized to those of the baseline, and the rightmost column is its IPC. Figure 5 shows the performance obtained by the subset of codes that benefit from -O3 optimizations, but not from vectorization. As for the Python performance, we can see that it is closely related to the performance of gcc -O1, except for nussinov, which will be isolated and studied later. The average speedup of -O3 with respect to -O1 in this subset is 1.4. This improvement comes from a reduction in the number of load instructions performed by the kernel. Applying differential analysis of performance optimizations, the culprit turns out to be load elimination on the innermost reductions, as exemplified in Fig. 6. The only exceptions are adi, where load elimination accounts for 30% of the improvement while -fexpensive-optimizations, a relatively opaque set of program analyses is responsible for the remaining 70%; and seidel-2d, where all the performance improvement comes from -fpredictive-commoning, which tries to reuse computations from previous iterations of a loop. ``` for c1 in range (N): for c2 in range ((c1-1)+1): x[c1] -= L[c1][c2] * x[c2] x[c1] = x[c1] / L[c1][c1] ``` (a) ``` for c1 in range (N): for c2 in range ((c1-1)+1): tmp = x[c1] x[c1] = tmp / L[c1][c1] ``` (b) Figure 6. Example of load elimination for a fragment of trisolv. We manually applied load elimination to this set of Python benchmarks, finding an average reduction in the number of both load and store instructions of approximately 25%, and in the number of total instructions executed of 11%, for a total average speedup of 1.1. Regarding performance, the Python version is, on average, 1.6x slower than the baseline, and only 1.2x slower than -O1. With the exception of nussinov, the execution cycles of all benchmarks present a correlation of 0.99 with the number of executed instructions. This is not at all the case for C codes, where this correlation is approximately 0.60. This signals that, for an interpreted language such as Python, where executing each instruction includes expensive operations such as types and dimensionality checks, the number of executed instructions determines, to a very large extent, the attainable performance. In fact, the relative performance of Python codes is closely related to the IPC (Instructions Per Cycle) of the C codes, as shown in the IPC column of Fig. 5. When the IPC is low, the slack available to the Python VM to execute each instruction is larger, and the effect on total execution time of the interpreting overhead is hidden. As the number of instructions per cycle increases, this overhead starts to become the bottleneck of the system. In the nussinov case, the number of L3 misses for this benchmark increases by 13x, an anomaly compared to the average 1.3x of this set of benchmarks. This signals that this benchmark, which has a very low L3 miss rate of 1.6% in the C version, becomes memory bound due to conflict caused by the extra memory pressure due to the interpreting process. The L3 miss rate in the Python version scales up to 8.3%. The second subset of analyzed codes benefits from both -O3 optimizations and the use of SIMD instructions, as detailed in Fig. 7. With the exception of deriche, gemver, amd atax, the kernels in this group are either stencils or compute-bound. The Python VM overhead manifests more clearly for these codes. The average slowdown with respect to the baseline goes up to 5.2, and to 4.3 with respect to -O1. The total executed instructions increase by 7.1x. When compared to the -O3 versions generating SIMD operations, the number of executed instructions scales up to 25.3x, and the slowdown to 8.5. The evolution of the overhead introduced by PyPy still has a high correlation to the number of instructions per cycle (IPC) of the baseline. Some exceptions appear, related to particular compiler optimizations being introduced by GCC which are not done by PyPy. For instance, in the worst performance case, syrk, GCC is performing a loop interchange, followed by loop fusion, and load elimination, as shown in Fig. 8. When manually applied to the Python code, these optimizations achieve a reduction in the amount of executed instructions of 5.2x, and a combined speedup of 7.4. The slowdown with respect to the baseline is limited to 2x, showing that, when similarly optimized, the performance of PyPy usually comes within the same order of magnitude as the performance of equivalent C codes. ![Figure 7](image-url) **Figure 7.** Performance, in execution cycles, of the benchmarks which benefit from -O3 and the generation of SIMD instructions. Results are normalized to those of the baseline, and the rightmost column is its IPC. Note that the Y axis is logarithmic. ![Figure 8](image-url) **Figure 8.** syrk code: (a) original, (b) after loop interchange and fusion, and load elimination. 4.3 Polyhedral Optimizations Figure 10 presents the relative performances, per benchmark, of 4 different PyPy implementations. The base implementation in PolyBench/Python (PyPy) is contrasted with three optimization approaches in the PoCC compiler: maxfuse implements the original Pluto algorithm [4] with maximal loop fusion for the kernel, resulting in possibly complex loop nest expressions when e.g. loop skewing is required to enable fusion. fusion is fusing statements surrounded by the same number of loops only, that is the legacy “smartfuse” heuristic of Pluto [4]. vectorizer implements also smart fusion, but adds additional loop permutations to expose when possible parallel inner loops with the most stride-1 accesses, i.e., favors spatial locality. While we observe numerous instances where the base PyPy version is outperformed by one or more versions using polyhedral transformations, such as for gemver, in most cases these optimizations do not provide additional performance improvement. For numerous benchmarks, this is to be expected: we did not implement any tiling in these experiments, and datasets typically exceed the L3 cache size, preventing to fully implement data reuse in the cache, e.g. as is observed for the various stencil computations. However attempting to derive a simple explanation based on the computational and data reuse patterns of the benchmarks would fail: we must instead take into account the overhead of PyPy that is added to the benchmarks, as discussed previously. Figure 11 displays aggregated hardware counter metrics over all 30 benchmarks, illustrating the PyPy overhead in terms of number of instructions executed often makes the code “worse” than GCC -O0, which implements a spill-everywhere approach. While instruction count is on average increased by 6x when using PyPy flattened lists (that is exactly the PyPy bar in Fig. 10), there is a wide ranging increase over the benchmarking suite. For example for gemver, the number of executed instructions grows by 7x and the number of branches grows by 9x. The instruction type distribution is altered for the PyPy version: loads represent 32% of instructions executed in the baseline C implementation, but only 20% in the PyPy version. But looking at jacobi-2d, instruction count increases by 26x, branches by 75x, loads by 20x and stores by 24x. Such overhead cannot be compensated by traditional loop transformations, irrespective of which loop order/fusion is implemented. Across all benchmarks, instruction count increases always by 4x or more (gesummv being the outlier, at 3.3x). Surprising differences occur, e.g., for gemm instructions increase by 20x, but for 2mm by 4x only. This increase alone explains the difficulty to reach performance comparable to the native C implementation in many cases, and the differences across benchmarks with similar compute and reuse patterns (e.g., gemm vs. 2mm) prevent from finding easily a performance model to predict the PyPy overhead. In general, of the various instances where polyhedral transformations have improved performance, we observed mostly a reduction in instruction count and overall PyPy overhead added in these variants compared to the base PyPy version. 4.4 NumPy: Loop-based vs. Vectorized Operation The core of the NumPy routines is directly implemented in C, both for performance reasons and to allow to easily pass data between applications. While the interfacing of CPython and C subroutines is seamless and provides native performance, interfacing PyPy with C codes requires ad-hoc extensions to bridge the gap between the C representation and the internal RPython representation used by PyPy. In particular, this requires a module, called cpyext, to make RPython’s garbage collector aware of the objects managed by the C layer [3]. Due to this, PyPy is on average 3x slower than CPython on NumPy codes and, for this reason, we will use CPython as the default interpreter in this section. The performance of NumPy codes is heavily conditioned by the coding style, and more specifically, on what type of operations are performed on the NumPy data. Although simply writing C-like code using the ndarray class provided by NumPy could seem like an easy way to improve execution performance, exactly the opposite is true. When NumPy arrays are traversed using regular loops accessing individual scalar elements, the basic data types stored in the ndarray object need to be promoted to first-class Python objects, which is the only kind of data that can actually be manipulated by the Python VM. In order to improve NumPy performance, it is necessary to write code in a “vectorized” fashion. In the context of NumPy, the term vectorization does not refer to issuing SIMD instructions, but rather to transferring control of a particular operation (e.g., matrix-matrix addition or multiplication) to a native C, highly efficient implementation. Given that NumPy arrays are homogeneous, there is no need to call the VM interpreter while inside the C implementations, and consequently fewer instructions are executed, efficiently issuing SIMD operations and even allowing for multi-threaded implementations (although NumPy developers have opted not to do so for design reasons). Figure 12 presents the NumPy performance compared to PyPy using flattened lists, and with the -O3 versions. As can be observed, for many benchmarks the performance offered by the NumPy codes is largely superior to that of the C codes. Such is the case with gramschmidt, where the speedup for the NumPy version with respect to the best C version is 3.3. However, for some other benchmarks the performance of NumPy lags far behind, such as with heat-3d, in which it delivers a 17.3x slowdown with respect to the -O3 execution. Figure 12. Performance, in execution cycles, of NumPy benchmarks compared to C and pure Python versions. Note that the Y axis is logarithmic. The reasons for these performance differences are varied. In the case of heat-3d, jacobi-2d and other similar stencil codes, the problem lies within the memory management performed by NumPy. Upon vectorizing a stencil operation, NumPy will replicate the data in the original buffer to achieve efficient operation. For large matrices, this might cause a significant degradation of their memory performance. For example, for jacobi-1d, a 3-point stencil, the number of L1 misses is increased by 20.4x. However, since its footprint comfortably fits L3, this increase does not scale to lower levels of the hierarchy and the large reduction in total number of instructions (1.64x), driven by the use of 256-bit packed floating point operations, achieves a net 1.2 speedup. When working with larger stencils this behavior degrades. For jacobi-2d, a 5-point stencil illustrated in Fig. 13, the number of L3 misses increases by 4.6x, and for heat-3d, a 9-point stencil, it increases by 10x. This seems to indicate that NumPy is replicating the original buffer for each of the shifted matrices in the stencil computation, causing slowdowns of 1.1 and 1.6, respectively. However, the total number of instructions executed decreases by a factor of 4.2x for jacobi-1d, and 1.8x for heat-3d. In both cases, all floating-point operations are executed using 256-bit packed SIMD instructions. Other benchmarks require special code transformations to be vectorized, as they present loop-carried dependences. For instance, it is necessary to perform loop interchanges in order to vectorize the innermost loop of adi and deriche. For other benchmarks with more complex dependences, such as... for t in range( self.TSTEPS ): Figure 13. NumPy version of jacobi-2d. seidel-2d or nussinov, index-set splitting [16] may be employed to expose parallelism. These transformations modify the original sequential memory access of the kernels, consequently damaging both temporal and spatial locality, and may even cause performance to degrade with respect to the non-vectorized PyPy version. They are, however, fundamental to achieving performance with NumPy. For example, if non-vectorized, adi will execute 135x more instructions, 50% of them loads and stores. The memory behavior is improved at the L2 level, as array traversals are in row-major order. However, the final performance is degraded by a factor of 80 with respect to the vectorized version. For benchmarks which can be vectorized without hindering locality, and that do not operate on a large number of array views at the same time, the performance of NumPy matches, or even beats, the performance of the best C version. 5 Related Work There is an immense body of work relating to Python performance measurement and optimizations, we limit below to highlighting several key software and publications, and their differences with the present work. Python Benchmarking Suites. There is a plethora of benchmarking suites written for Python, including specifically to evaluate the quality and performance of interpreters. The Python Performance Benchmarking Suite [34] integrates numerous applications and kernels, including (some synthetic) kernels to measure float and integer-heavy operations. However, nearly none of the algorithms implemented in PolyBench kernels are available. The PyPy benchmarking suite [9] similarly includes a high number of applications and some numerical computation programs, but does not provide the type of implementations we offer in PolyBench/Python. The Pythran project released Numpy-style implementations of numerous scientific kernels [19], several also available in Polybench. While these benchmark suites tend to focus on full applications, PolyBench/Python has been designed to specifically cover a spectrum of regular numerical kernels that are amenable to polyhedral optimizations and systematically provide 3 implementation flavors for each benchmark, including Numpy-style. Python Environments and Compilers. Similar as to using different compilers for C codes, a collection of different interpreters exist for Python. CPython [13] is developed by the Python Software Foundation. The Intel Distribution for Python [7] is designed to make Intel libraries such as the Math Kernel Library [33] and the Data Analytics Acceleration Library [6] usable from Python. Its aim is to bridge the technological gap between Python libraries such as NumPy and Intel products. PyPy [29] is a performance-oriented interpreter developed using the RPython [2] tool-chain. The Python code is translated to RPython, which is then translated to flow graphs, and then to C. The RPython layer includes a tracing just-in-time layer including an optimizer and a back-end that generates machine code. The Pythran compiler [18, 20] is a powerful optimizing compilation flow for (a subset of) Python that compiles programs into a C++ implementation for subsequent native execution. Pythran is an ahead-of-time compilation approach, which supports a variety of Python and Numpy concepts. It supports multi-threading. 6 Concluding Remarks This paper introduced PolyBench/Python, a polyhedral benchmarking suite for Python environments, and presented extensive experimental analysis. Our experiments show that the performance of PyPy is usually an order of magnitude better than that of CPython. In fact, PyPy provides performance of the same order of magnitude than C for most kernels, when disabling static compiler optimizations (i.e., using -O0). We observed high correlation between the relative performance of Python codes and the IPC of the C baselines. When the IPC is low, the slack available to the Python VM to execute each instruction is larger, and the effect on total execution time of the interpreting overhead is hidden, bringing Python performance closer to C. Besides the overhead introduced by the interpreting process itself, another important factor to explain the relative performance of Python and C codes is the absence of static or dynamic optimizations in the Python execution stack. Even though scientific-oriented interpreters, such as PyPy, perform high amounts of JIT optimizations, these usually target type inference and reducing the number of calls to the Python interpreter. Very few high-level code optimization is performed, specially given that most Python interpreters, including CPython and PyPy, are stack-based. While this reduces the complexity of the interpreter, which can just execute isolated pieces of code, it complicates the introduction of even very simple optimizations such as loop-invariant code motion or load elimination. Our results have shown how these very simple optimizations have potential to significantly improve the performance of Python codes, and suggest that these could be implemented in modern interpreters in a just-in-time fashion. For instance, load elimination could be implemented by detecting that the same array position is being repeatedly loaded from memory inside a loop, and dynamically enabling its lowering to a scalar during runtime. SIMDization is another optimization that could be dynamically enabled in a speculative fashion, by detecting floating point operations to consecutive positions of an array at runtime and fusing them together after a given number of iterations. By adding advanced SIMDization capabilities to performance-oriented Python interpreters such as PyPy, we can expect a substantial performance increase. The vectorization itself compounds with the reduction in the number of issued instructions to be interpreted, fundamentally in the number of memory accesses and branches. We have also shown how NumPy can achieve performance superior to that of native C codes, provided that no locality tradeoffs are required in order to vectorize the code. These tradeoffs manifest when loop-carried dependences prevent row-order vectorization, requiring column or even wavefront traversals of the data. Acknowledgments This research was supported in part by the Ministry of Science and Innovation of Spain (PID2019-104184RB-I00 / AEI / 10.13039/501100011033), and by the U.S. National Science Foundation (award CCF-1750399). CITIC is funded by Xunta de Galicia and FEDER funds of the EU (Centro de Investigación de Galicia accreditation, grant ED431G 2019/01). References
{"Source-Url": "https://inria.hal.science/hal-03153351/file/cc21.pdf", "len_cl100k_base": 10709, "olmocr-version": "0.1.50", "pdf-total-pages": 12, "total-fallback-pages": 0, "total-input-tokens": 40127, "total-output-tokens": 13154, "length": "2e13", "weborganizer": {"__label__adult": 0.0004279613494873047, "__label__art_design": 0.00037288665771484375, "__label__crime_law": 0.00035381317138671875, "__label__education_jobs": 0.000804901123046875, "__label__entertainment": 9.751319885253906e-05, "__label__fashion_beauty": 0.00020170211791992188, "__label__finance_business": 0.00025153160095214844, "__label__food_dining": 0.0004611015319824219, "__label__games": 0.0007376670837402344, "__label__hardware": 0.0014066696166992188, "__label__health": 0.0007419586181640625, "__label__history": 0.0003905296325683594, "__label__home_hobbies": 0.00012445449829101562, "__label__industrial": 0.0007772445678710938, "__label__literature": 0.0002923011779785156, "__label__politics": 0.000377655029296875, "__label__religion": 0.00072479248046875, "__label__science_tech": 0.0897216796875, "__label__social_life": 0.0001252889633178711, "__label__software": 0.008056640625, "__label__software_dev": 0.89208984375, "__label__sports_fitness": 0.0004131793975830078, "__label__transportation": 0.0007476806640625, "__label__travel": 0.00025463104248046875}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 55364, 0.03029]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 55364, 0.51398]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 55364, 0.87422]], "google_gemma-3-12b-it_contains_pii": [[0, 1189, false], [1189, 5191, null], [5191, 9888, null], [9888, 15955, null], [15955, 22322, null], [22322, 27000, null], [27000, 31915, null], [31915, 35273, null], [35273, 37838, null], [37838, 42868, null], [42868, 48569, null], [48569, 55364, null]], "google_gemma-3-12b-it_is_public_document": [[0, 1189, true], [1189, 5191, null], [5191, 9888, null], [9888, 15955, null], [15955, 22322, null], [22322, 27000, null], [27000, 31915, null], [31915, 35273, null], [35273, 37838, null], [37838, 42868, null], [42868, 48569, null], [48569, 55364, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 55364, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 55364, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 55364, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 55364, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 55364, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 55364, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 55364, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 55364, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 55364, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 55364, null]], "pdf_page_numbers": [[0, 1189, 1], [1189, 5191, 2], [5191, 9888, 3], [9888, 15955, 4], [15955, 22322, 5], [22322, 27000, 6], [27000, 31915, 7], [31915, 35273, 8], [35273, 37838, 9], [37838, 42868, 10], [42868, 48569, 11], [48569, 55364, 12]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 55364, 0.14222]]}
olmocr_science_pdfs
2024-12-01
2024-12-01
c01a59eb2d35ccbf74b636e1eb925d0345c296a5
Experiences Using Lightweight Formal Methods for Requirements Modeling Steve Easterbrook, Robyn Lutz, Rick Covington, John Kelly, Yoko Ampo and David Hamilton October 16, 1997 This technical report is a product of the National Aeronautics and Space Administration (NASA) Software Program, an agency wide program to promote continual improvement of software engineering within NASA. The goals and strategies of this program are documented in the NASA software strategic plan, July 13, 1995. Additional information is available from the NASA Software IV&V Facility on the World Wide Web site http://www.ivv.nasa.gov/ This research was funded under cooperative Agreement #NCC 2-979 at the NASA/WVU Software Research Laboratory. Experiences Using Lightweight Formal Methods for Requirements Modeling Steve Easterbrook NASA IV&E Facility, 100 University Drive, Fairmont, West Virginia 26505, steve@atlantis.iv.e.nasa.gov Robyn Lutz, Rick Covington, John Kelly NASA Jet Propulsion Lab, Pasadena, California Yoko Ampo NEC Corp, Tokyo, Japan and David Hamilton Hewlett Packard Corp, San Diego, California Abstract This paper describes three case studies in the lightweight application of formal methods to requirements modeling for spacecraft fault protection systems. The case studies differ from previously reported applications of formal methods in that formal methods were applied very early in the requirements engineering process, to validate the evolving requirements. The results were fed back into the projects, to improve the informal specifications. For each case study, we describe what methods were applied, how they were applied, how much effort was involved, and what the findings were. In all three cases, formal methods enhanced the existing verification and validation processes, by testing key properties of the evolving requirements, and helping to identify weaknesses. We conclude that the benefits gained from early modeling of unstable requirements more than outweigh the effort needed to maintain multiple representations. 1 The research described in this paper was carried out in part by the Jet Propulsion Laboratory, California Institute of Technology, under a contract with the National Aeronautics and Space Administration, and in part by West Virginia University under NASA cooperative agreement #NCC 2-979. Reference herein to any specific commercial product, process, or service by trade, name, trademark, manufacturer, or otherwise, does not constitute or imply its endorsement by the United States Government, the Jet Propulsion Laboratory, California Institute of Technology or West Virginia University. Experiences Using Lightweight Formal Methods for Requirements Modeling Steve Easterbrook (NASA IV&V Facility, 100 University Drive, Fairmont West Virginia), Robyn Lutz, Rick Covington, John Kelly (NASA Jet Propulsion Lab, Pasadena, California), Yoko Ampo (NEC Corp, Tokyo, Japan) and David Hamilton (Hewlett Packard Corp, San Diego, California) I. Introduction In the development of embedded, mission-critical software there is a serious, unmet need for early feedback on the viability of a system in the requirements and early design stages [1]. The impact of early feedback on cost and safety has been demonstrated empirically. Boehm showed that errors are cheaper to fix the earlier they are detected in the development lifecycle [2]. In a study of 387 software errors found during integration and system testing, Lutz found that safety-related software errors arose most often from inadequate or misunderstood requirements. [3]. It is also clear that conventional techniques fail to catch many requirements errors [4]. However, studies have suggested that formal methods have tremendous potential for improving the clarity and precision of requirements specifications, and in finding important and subtle errors [5-7]. This paper presents three case studies of successful application of formal methods for requirements modeling. The studies demonstrate that a pragmatic, lightweight application of formal methods can offer a cost-effective way of improving the quality of software specifications. The studies concern the Verification and Validation (V&V) of fault protection software on the International Space Station and the Cassini deep space mission. The three studies share a number of features: • Formal methods were applied in response to an existing development problem. In each case the problem was to provide an assurance that the fault protection requirements were correct. The informal techniques used on these projects had not been able to provide the desired level of assurance. Whilst the formal methods did not assure correctness, they improved the level of assurance by revealing errors that the informal techniques had missed. • Formal methods were applied selectively. Only the most critical portions of the requirements were modeled, and only a selection of properties of these requirements were analyzed. The formal methods were applied by a research team working in parallel with the requirements analysts, rather than by the analysts themselves. • In each case, formal methods offered a partial solution to the original problem. In particular, they provided a consistent requirements model, and revealed a number of errors, some of which had not been detected using inspection and traceability analysis. The studies increased the confidence in the requirements, but did not guarantee the completeness and correctness of the specifications. We argue that this is appropriate for early modeling of requirements. - In each case, the results of the study fed back into development process to improve the product. We summarize observations on the utility of formal methods in these studies, and describe problems we encountered in applying them. Finally, we describe our current work exploring applications of formal methods in evolutionary design of new architectures for autonomous spacecraft control systems, and the special challenges of formally modeling evolutionary designs. II. Background 1. Fault Protection For NASA spacecraft, the term fault protection is used to describe system elements that detect and respond to perceived spacecraft faults. There are two main requirements when a fault occurs: the system needs to guarantee the completion of any time critical activities, and that the spacecraft is still safe, observable and commandable. Each spacecraft function has a pre-defined set of operating parameters, where each parameter has a normal operating range. Values beyond this range are out-of-tolerance. An out-of-tolerance condition may have many possible causes, so information from multiple sources must be combined to locate the fault. The normal operating range for each parameter is derived from the results of various system analyses, including failure modes and effects analysis (FMEA), hazard analysis, and safety analysis. These analyses also provide rules of inference for fault recovery. Fault protection software initiates appropriate responses when out-of-tolerance conditions are detected in hardware and software components. Responses to loss of function include recovery (e.g. switch to a redundant backup), or retry (e.g. re-start a device in an attempt to restore functionality where no backup is available). Hazardous conditions generally require a safing response, to isolate the problem and minimize damage. For unmanned spacecraft, a typical safing response is to shut down all non-critical functions, ensure the antenna is pointing towards Earth, and await further commands. On Cassini, there is a requirement to be able to maintain such a safe state for up to two weeks. For manned spacecraft there is a possibility of crew intervention, so a further requirement is to isolate the fault to the smallest possible replaceable unit. Because of the need to maintain a safe, habitable environment for the crew, fault protection on the space station has additional requirements over those for unmanned craft, and is referred to as Fault Detection, Isolation and Recovery (FDIR). Responsibility for FDIR is divided up into five layers, or domains. The lowest domain is the individual device. The next layer is the function that uses the device, followed by the subsystem and system control layers. The highest layer is manual FDIR. If a domain cannot provide FDIR for some conditions, a higher layer must provide it. For example, the subsystem layer, rather than the device layer, might handle an error condition involving the interaction of two separate devices. Validation of the space station FDIR is particularly problematic, as FDIR functionality is distributed across many flight computers. The development and construction schedule for the space station does not permit full integration testing of the entire architecture prior to on-orbit assembly. Hence, FDIR functionality must be validated through a combination of inspection, simulation and analysis. Fault protection operates asynchronously, and may be invoked at any time. Hence, the addition of fault protection software to a spacecraft system significantly increases the complexity of the software. An error in the fault protection software may compound an existing failure. This occurred during the launch of Ariane 5, when the fault protection software erroneously shut down two healthy processors, in response to an unhandled floating point overflow exception in a non-critical software function [8]. If the spacecraft is executing a critical function (e.g. an orbital maneuver) when the failure occurs, the fault protection must respond quickly to allow the critical function to proceed. 2 The Need for Formal Methods Current requirements engineering processes within NASA rely extensively on informal processes, largely based on inspection. Inspection helps to remove a large number of specification errors, but cannot provide the desired level of assurance for the new generation of software-intensive spacecraft [4]. Remaining errors are detected throughout the lifecycle as the developers attempt to implement and test the system. There is a significant lack of effective methods and tool support for the requirements phase in comparison to those available for detailed design and coding. The lack of rigorous requirements engineering techniques is well illustrated in the fault protection area. Fault protection requirements are more volatile than most other requirements, as they are sensitive to any change during the development of the primary system. Interactions between requirements can be hard to identify, let alone validate. Formal methods can help provide this validation in a number of ways. The process of formalizing a specification provides a simple validation check, as it forces a level of explicitness far beyond that needed for informal representations. Once a formal specification is available, it can be formally challenged [9], by defining properties that should hold, and proving that they do indeed hold. Formal challenges may be achieved both through theorem proving, and through state exploration or 'model checking'. Rushby [9] points out that there is considerable scope for selective application of formal methods. Formal methods can be applied just to selected components of a system, and can be used just to check selected properties of that system. Most importantly, a great deal of benefit can be derived from formal methods without committing a project to the use of formal notations for baseline specifications. In the studies described in this paper, we used formal modeling to find errors in critical parts of existing informal specifications, but did not replace the informal specifications with their formal counterparts. We use the term 'lightweight' to indicate that the methods can be used to perform partial analysis on partial specifications, without a commitment to developing and baselining complete, consistent formal specifications. This approach is also consistent with the advocacy of multiple representations as a way of overcoming analysis bias [10]. 3 Methodology The authors are (or were) members of a multi-center team within NASA, funded primarily by the NASA Office of Safety and Mission Assurance, to explore the potential of formal methods for increasing safety and reducing cost of mission-critical software [11, 12]. The team combines personnel with experience in formal methods, in the domains where formal methods are being applied, in software assurance and V&V, and in technology transfer. We have explored formal methods on a number of NASA programs, including Space Shuttle [6], Space Station [13, 14], and Cassini [15]. Throughout these studies, the emphasis has been on pragmatic application of formal methods in areas where there appears to be the greatest need. Experiences gained from these studies have been used to develop two NASA guidebooks [16, 17]. Although some development of the methods themselves has been necessary in order to fit them to our purpose, this has not been the main focus of the studies. Rather, we have concentrated on addressing issues such as: • Can formal methods provide a cost-effective addition to existing techniques to improve the quality of requirements specifications? • Can formal methods increase confidence in the validity of the requirements? • Can early application of formal methods be beneficial even while requirements are volatile? • How much effort is needed to apply formal methods, and what is the most appropriate process for applying them? • Within any particular formal methods process, which activities require more effort, and which activities yield the greatest benefits? • Which formal methods and tools are useful for which tasks? In this paper we describe three studies that were implemented in the early requirements phase for new systems. These studies were responses to real needs on the projects. The requirements were often still volatile, and hence some effort was needed to ensure the formal analysis was kept up to date. Our goal was to demonstrate that formal methods could be applied and could add value in this context. Although the three studies described here used different tools and notations, the basic approach was the same: 1) Re-state the requirements in a clear, precise and unambiguous format. 2) Identify & correct internal inconsistencies. 3) Test the requirements by proving statements about expected behavior. 4) Discuss the results with the requirements' authors. The formal methods used in the studies were chosen according to need. PVS [18] was chosen for two of the studies, because it offers automated support for proof construction, and because the specification language appeared to be readily understandable to engineers and programmers. SCR [19] was chosen for the remaining study as it offered a tabular notation that corresponded well to the structure of the requirements, and provided tool support for consistency checking. In each study, an intermediate notation was used as a prelude to translating the requirements into the formal specification language. The first study used an annotated flowchart notation, the second used AND/OR tables [20], whilst the third used OMT (Object Modeling Technique) diagrams [21]. The intermediate notations helped to clarify ambiguities, and gain a better understanding of the structure of the requirements. This in turn helped to determine how the formal notation would be used. **Study 1: High level FDIR requirements for Space Station** This study was commissioned by the space station independent assessment\(^1\) panel, who were seeking some assurance that the high level FDIR concept was clearly defined and validated, before detailed requirements were derived from it. Subsequent changes to the FDIR concept would have significant impacts throughout the requirements and design of the entire system. The study analyzed 18 pages of FDIR requirements, and was conducted over a period of two months, by two people working part-time. The total effort was approximately 2 person-months. 1 **Approach** Three views of the FDIR had been documented: the functional concept diagram (FCD) which is a flowchart-like representation of the generic FDIR algorithm; baseline FDIR requirements; and capabilities, in which the requirements are grouped into related functional areas. This study concentrated on the first two of these views, developing a formal model of each, and testing traceability between them. The four-step approach described above was used as follows: 1) The FCD was restated by abstracting out common features. The 53 processing steps of the original FCD were partitioned, in order to reduce the detail. For example, the first 12 steps check parameters for out-of-tolerance conditions, the next 7 deal with safing, the next 8 check for functional failure, and so on. Each step was labeled as one of three procedural categories: performing automated procedures, checking for anomalous conditions, and --- \(^1\) Independent assessment is an oversight activity, covering all aspects of the system, including hardware, software and operational procedures. message: type = { parameter_OK, parameter_verified, safing_not_allowed, safing_executed, ... } % parameter is ok when its tolerance % check has just ran and the parameter % is OK (i.e. within tolerance) \texttt{rr\_parameter\_ok: axiom} for all (t: tolerance\_check): ( on(just\_ran(t, time) and OK?(t(time))) iff record\_check(time)(parameter\_OK, t) } \begin{figure} \centering \includegraphics[width=\textwidth]{example.png} \caption{Fragments of PVS specification, showing type definitions and axioms used to express FDIR concepts} \end{figure} recording/reporting results. Finally, six classes of condition under which control is passed to higher level FDIR domains were identified. The result of this initial analysis was a more structured (informal) model of the FDIR processes. This model was informally checked for reasonableness and for traceability to the original FCD. All the objects and attributes referenced in the FCD were then translated to PVS. Figure 1 shows two fragments of PVS generated at this stage. The baseline requirements were then translated directly into PVS, using the definitions and types from the formalized FCD. This translation concentrated only on the FDIR system itself; we did not model the primary system that the FDIR monitors. Translation of these requirements into PVS proved to be relatively straightforward. Figure 2 gives an example. 2) The resulting definitions were typechecked using the PVS tool. Typechecking helped to eliminate several types of errors in the specification, including typos, syntax errors and type consistency errors. 3) The PVS specification was validated by using the PVS proof assistant to prove claims based on the specification. An example of such a claim is “at any domain level, if a failure occurs then it will always be recovered at some domain level”. Although this claim was not very profound, several missing assumptions were detected in the \texttt{Requirement: automatic hazard and hazardous condition detection: ISSA shall automatically detect any out-of-tolerance condition or functional performance parameter that exhibits a time to catastrophic or critical effect of less than 24 hours.} \texttt{automatic\_hazard\_condition\_detection: axiom} for all (p: parameter) param\_out\_of\_tol?(p) AND time\_to\_effect(p)<24 => exists(d: fdir\_domain): detection(p, d) = automatic \begin{figure} \centering \includegraphics[width=\textwidth]{example2.png} \caption{An example FDIR requirement, and its PVS translation} \end{figure} process of proving it. For example, several sequencing constraints needed to be defined explicitly, even though the FDIR documentation states that no such constraints should be inferred from the requirements. A total of 14 claims were defined and proved. 4) A total of fifteen issues were documented and discussed with the requirements' authors. We had planned to explore traceability between the FDIR concept diagram and the baseline requirements. However, an initial analysis indicated that there was little traceability. The requirements' authors confirmed that the two documents expressed different kinds of requirements. The FCD describes the processing that is performed within an FDIR domain, while the baseline requirements describe a higher level view of the kinds of FDIR that must be provided. 2 Findings In general, the FDIR requirements were well thought out. However, there was some question over whether the documentation was sufficient so that system developers and other stakeholders would understand them. Most of the fifteen issues were minor ambiguities, inconsistent use of terms, and missing assumptions, discovered during the process of formalization. These reduce the ability of developers to understand the requirements. For example, the distinction between the primary system and the FDIR system was not clear in the original requirements. Other ambiguities surrounded the use of terms such as “anomaly”, “out-of-tolerance” and “functional failure”. Three of the issues were classed as “high-major”: a) There were inconsistencies in the FCD over reporting the status of safing, recovery and retry procedures. The intention was that the FDIR processes should report their status before, during and after execution of each procedure. However, some of the procedures were missing requirements for some of the reporting activities, so that most of them did not have requirements to report status at all three points. This problem was detected during the initial reformulation of the FCD diagram. b) The proper sequencing of FDIR processing is not clear from the FCD. Although the FCD looks like a flowchart, the accompanying text stipulates that it should not be interpreted as a sequential process. However, some important requirements can only be inferred by treating the flowchart as a sequential process. For example, it is not clear whether safing should be performed before isolation, although the diagram seems to imply it should be. This problem was detected during the proof process: some of the sequencing requirements had to be stated explicitly in order to prove necessary properties of the FDIR model. c) No requirements are given for checking inconsistencies between parameters. The requirements only mention limit checking of individual parameters. The requirements team clearly intended that inconsistency checking should be included. This problem was discovered during the process of formalizing the baseline requirements. (2.16.3.f) While acting as the bus controller, the C&C MDM CSCI shall set the e,c,w, indicator identified in Table 3.2.16-II for the corresponding RT to "failed" and set the failure status to "failed" for all RT's on the bus upon detection of transaction errors of selected messages to RTs whose 1553 FDIR is not inhibited in two consecutive processing frames within 100 millisec of detection of the second transaction error if; a backup BC is available, the BC has been switched in the last 20 sec, the SPD card reset capability is inhibited, or the SPD card has been reset in the last 10 major (10-second) frames, and either: 1. the transaction errors are from multiple RT's, the current channel has been reset within the last major frame, or 2. the transaction errors are from multiple RT's, the bus channel's reset capability is inhibited, and the current channel has not been reset within the last major frame. Figure 3: An example of a level 3 requirement for Bus FDIR. This requirement specifies the circumstances under which all remote terminals (RTs) on the bus should be switched to their backups. Study 2: Detailed Bus FDIR requirements for Space Station The purpose of this study was to analyze the detailed FDIR requirements associated with the bus controller for the main communications bus on the space station. These requirements represent a concrete implementation of the high level FDIR concepts addressed in the first study. The study was initiated by an Independent Verification and Validation (IV&V) team. The IV&V team was having difficulty validating the bus FDIR requirements, as some of the properties that the IV&V team wished to test could not be established using existing informal methods. The requirements for Bus FDIR are expressed in natural language, with a supporting flowchart showing the processing steps involved. The flowchart does not have the status of a requirement, but was merely provided for guidance; the intention was that the prose completely expressed the requirements (E.g. figure 3). The IV&V team had recommended that to improve clarity, the requirements should be re-written in a tabular form (E.g. table 1). This recommendation had been rejected because of the cost involved in re-writing them all. Hence, the IV&V team generated their own tabular versions, in order to facilitate the kinds of analysis they wished to perform. The study analyzed 15 pages of level 3 requirements, and was conducted over a period of four months, by one person working part time. The total effort was approximately 1.5 person months. 1 Approach The four-step approach was used as follows: 1) Each individual requirement was restated as an AND/OR table, to clarify the logic (see table 1). The generation of a tabular interpretation of each individual requirement proved to be hard, as there are a number of ambiguities --- IV&V is a practice in which a separate contractor is hired to analyze the products and process of the software development contractor [22]. The IV&V team reports to the Independent Assessment panel. C&C MDM acting as the bus controller & OR Detection of transaction errors in two consecutive processing frames & T & T & T & T errors are on selected messages & T & T & T & T the RT's 1553 FDIR is not inhibited & T & T & T & T A backup BC is available & T & T & T & T The BC has been switched in the last 20 seconds & T & T & T & T The SPD card reset capability is inhibited & T & T & • & • The SPD card has been reset in the last 10 major (10 second) frames & • & • & T & T The transaction errors are from multiple RTs & T & T & T & T The current channel has been reset within the last major frame & T & F & T & F The bus channel's reset capability is inhibited & • & T & • & T Table 1: The tabular version of the requirement shown in figure 3, showing the four conditions (the four columns) under which the action should be carried out. A dot indicates "don't care". correcting the associativity of 'and' and 'or' in English, and the correct binding of subclauses of long sentences. For example, in figure 3, it is not clear what the phrase "in two consecutive processing frames" refers to. When the requirement shown in figure 3 was given to four different people to translate, we obtained four semantically different tables. By comparing these different interpretations, an extensive list of ambiguities was compiled. The ambiguities were resolved through detailed reading of the documentation, and questioning the original authors. This process also revealed some inconsistencies in the way in which terminology was used. The individual tables were then combined into a single SCR state-machine model (see table 2). 2) The SCR model was type-checked using the SCR toolset. 3) Properties of the SCR model were tested in two ways. Static properties of the state model, such as disjointness and coverage, were tested using the built-in checker in the SCR tool. Example properties are "for each combination of failure conditions, there is an FDIR response specified" and "for each combination of failure conditions there is at most one FDIR response specified". Dynamic properties of the model were tested by translating the SCR state machine model into PROMELA [23], and applying the SPIN model checker to explore its behavior. For example, some of the requirements express conditions to test whether various recovery actions have already been tried. These conditions were validated by exploring the dynamic behavior of the model in the face of multiple failures, and recurring failures. An example property is "if an error persists after all recovery actions have been tried, the bus FDIR will eventually report failure of itself to a higher level FDIR domain". 4) The findings were discussed with the IV&V team, and fed back to the development team through the normal IV&V reporting process. In addition to a number of minor problems with inconsistent use of terminology, the following major problems were reported: a) There were significant ambiguities in the prose requirements, as a result of the complex sentence structure. Some of these ambiguities could be resolved by studying the higher level FDIR requirements, and the specifications for the bus architecture. Some of the ambiguities that arose from the sentence structure could not be resolved in this way, and could lead to mistakes in the design. These ambiguities were detected in the initial reformulation of the requirements as AND/OR tables. b) There was one missing requirement to test the value of the Bus Switch Inhibit Flag before attempting to switch to the backup bus. This was detected during the test for disjointness in the SCR specification. c) The requirements were missing a number of preconditions that enforce the ordering of the inference rules. The accompanying flowchart for these requirements implied a sequence for these rules. An attempt had been made in the prose requirements to express this sequence as a set of preconditions for each rule, to ensure that all the earlier rules have been tested and have failed. The preconditions did not completely capture the precedences implied by flowchart. This problem was found during the test for disjointness in the SCR specification. d) The timing constraints expressed in the requirements were incorrect. Several of the failure isolation tests referred to testing whether certain FDIR actions had already been tried “in the previous processing frame”. <table> <thead> <tr> <th>Current Mode</th> <th>errors in two cons. frames</th> <th>bus swch'd last frame</th> <th>bus switch inhibit</th> <th>bus swch'd this frame</th> <th>backup BC avail.</th> <th>BC swch'd in last 20 sec</th> <th>card reset inhibit</th> <th>card reset last 10 frames</th> <th>errors from multi. RTs</th> <th>channel reset last frame</th> <th>channel reset inhibit</th> <th>Next Mode</th> </tr> </thead> <tbody> <tr> <td>Normal</td> <td>@T</td> <td>-</td> <td>T</td> <td>-</td> <td>-</td> <td>-</td> <td>-</td> <td>-</td> <td>-</td> <td>-</td> <td>-</td> <td>switch buses</td> </tr> <tr> <td>@T</td> <td>-</td> <td>T</td> <td>F</td> <td>-</td> <td>-</td> <td>-</td> <td>-</td> <td>-</td> <td>-</td> <td>-</td> <td>-</td> <td>reset the channel</td> </tr> <tr> <td>@T</td> <td>-</td> <td>T</td> <td>F</td> <td>-</td> <td>-</td> <td>-</td> <td>F</td> <td>T</td> <td>-</td> <td>-</td> <td>-</td> <td>reset the card</td> </tr> <tr> <td>@T</td> <td>-</td> <td>T</td> <td>-</td> <td>-</td> <td>-</td> <td>F</td> <td>F</td> <td>T</td> <td>T</td> <td>-</td> <td>-</td> <td>switch the card</td> </tr> <tr> <td>@T</td> <td>F</td> <td>T</td> <td>-</td> <td>-</td> <td>-</td> <td>-</td> <td>F</td> <td>F</td> <td>F</td> <td>T</td> <td>-</td> <td>switch BC to backup</td> </tr> <tr> <td>@T</td> <td>T</td> <td>F</td> <td>-</td> <td>-</td> <td>-</td> <td>-</td> <td>F</td> <td>T</td> <td>F</td> <td>T</td> <td>-</td> <td>switch BC to backup</td> </tr> <tr> <td>@T</td> <td>-</td> <td>T</td> <td>T</td> <td>T</td> <td>-</td> <td>T</td> <td>T</td> <td>T</td> <td>-</td> <td>-</td> <td>-</td> <td>switch BC to backup</td> </tr> <tr> <td>@T</td> <td>-</td> <td>T</td> <td>T</td> <td>T</td> <td>-</td> <td>T</td> <td>T</td> <td>T</td> <td>-</td> <td>-</td> <td>-</td> <td>switch BC to backup</td> </tr> <tr> <td>@T</td> <td>-</td> <td>T</td> <td>T</td> <td>T</td> <td>-</td> <td>T</td> <td>T</td> <td>T</td> <td>-</td> <td>-</td> <td>-</td> <td>switch all RTs</td> </tr> </tbody> </table> Table 2: An SCR Mode transition table. Each of the central columns represents a condition, showing whether it should be true or false; '_' means "don't care"; '@T' indicates a trigger condition for the mode transition. The four columns of table 1 correspond to the last four rows of this table. The semantics of SCR require this table to represent a function, so that the disjunction of all the rows covers all possible conditions (coverage), and the conjunction of any two rows is false (disjointness). However, as each FDIR recovery action is followed by a time-out while the action takes effect, and as further FDIR intervention is only initiated on occurrence of errors in two consecutive processing frames, these conditions can never be true. This was discovered during model checking of the PROMELA model. **Study 3: Fault Protection on Cassini** The third study concerns the system level fault protection software for the Cassini deep space probe. System reliability is a major concern for Cassini, due to the duration of its mission to Saturn. Fault protection is a major factor in providing the required levels of reliability. The study examined the requirements for the software executive that manages fault protection and requirements for putting the spacecraft into a safe state. The Cassini project was interested in the potential of formal methods to provide an assurance that the fault protection requirements were correct. This study analyzed eighty-five pages of documented requirements. Fifteen pages of OMT diagrams [21] were produced, followed by twenty-five pages of PVS specifications. Twenty-four lemmas were proven. The study was conducted over the period of a year by two people working part-time, with a total effort of approximately twelve person-months. 1 **Approach** The four-step model was applied as follows: 1) The first step was the production of OMT diagrams representing the prose requirements (see figure 5). The production of object diagrams, state diagrams and dataflow diagrams, according to the OMT method, helped to define the boundaries and interfaces of the fault protection requirements, and helped to crystallize some of the issues that arose in the initial close reading of the requirements. A PVS model was then produced directly from the OMT models – the elements of the OMT model often mapped onto elements of the formal model in a relatively straightforward way. For example, object classes mapped onto type definitions in PVS, while state **Cassini Requirement:** If Spacecraft Safing is requested via a CDS (Command and Data Subsystem) internal request while the spacecraft is in a critical attitude, then no change is commanded to the AACS (Attitude and Articulation Control Subsystem) attitude. Otherwise, the AACS is commanded to the homebase attitude. ```plaintext saf: THEORY % Example is excerpted from saf theory. % Spacecraft safing commands the AACS to homebase mode, thereby % stopping delta-v's and desat's. BEGIN aacs_mode: TYPE = {homebase, detumble} atitude: TYPE cds_internal_request: VAR bool critical_attitude: VAR bool prev_aacs_mode: VAR aacs_mode aacs_stop_fnc (critical_attitude, cds_internal_request, prev_aacs_mode): aacs_mode = IF critical_attitude THEN IF cds_internal_request THEN prev_aacs_mode ELSE homebase ENDIF ELSE homebase ENDIF aacs_safing_req_met_l: LEMMA (critical_attitude AND cds_internal_request) OR (aacs_stop_fnc (critical_attitude, cds_internal_request, prev_aacs_mode) = homebase) END saf ``` **Figure 6:** An example Cassini fault protection requirement, a fragment of PVS representing this requirement, and an associated 'requirements-met' lemma. transitions mapped onto functions and axioms. 2) The PVS model was checked for internal consistency and traceability to the original requirements. Lemmas were defined to ensure that the model accurately captured the documented requirements. Figure 6 shows an example. The function expressed in this requirement is represented as part of the PVS theory for safing procedures. The requirement is also defined declaratively as a lemma, as a consistency check. Seven such lemmas were proved, and three disproved. 3) The PVS model was then checked for safety and liveness conditions. Safety lemmas represent conditions that should not arise. For example, “A fault protection response shall not change the instrument’s status during a critical sequence of commands”. Seven such lemmas were proved. Liveness lemmas ensure that required functions will eventually be performed. An example is “If a response has the highest priority among the candidates and does not finish in the current cycle, it will be active in the next cycle”. Seven such lemmas were proved. 4) The results were discussed with Cassini project personnel. In some cases where requirements issues were still being worked by the project, the formal methods effort was able to assist by formalizing undocumented concerns (e.g., whether starvation of tasks would be possible) clearly and unambiguously. This facilitated rapid response to proposed changes or alternatives by the Cassini Project. 2 Findings A total of 37 issues were identified during the study. These were classified as follows: 11 undocumented assumptions: None resulted in errors, but some significant ones needed documentation, to prevent future errors, especially at interfaces. These assumptions were identified during the process of formalizing the requirements. 10 cases of inadequate requirements for off-nominal or boundary cases: Such cases usually involved unlikely scenarios, and the spacecraft engineers had to help decide which were credible. An example case is when several monitors with the same priority level detect faults in the same cycle. Documentation of such cases is useful, as it helps to verify the robustness of the system. 9 traceability/inconsistency problems: The study uncovered a number of traceability problems between different levels of requirements, and inconsistencies between requirements and subsystem designs. Many of the latter were significant, as the correct functioning of the system depends on choosing the correct interpretation. For example, in the high-level requirements, the assumption is made that if multiple faults are detected within the response time of the first fault, they are all symptoms of the original fault. In the low-level requirements, a fault response will be cancelled if a fault of higher priority is detected, in order to handle the higher-priority fault. 6 cases of imprecise terminology: These were largely documentation problems, including synonyms and related terms. They were revealed during the process of defining the PVS model. 1 logical error: This was a problem of starvation when a request for service is pre-empted by a higher priority request. The issue was first spotted during initial close reading, and confirmed by disproving a lemma. V. Discussion The majority of published case studies of the use of formal methods are post hoc applications to on-going or finished projects. Such studies demonstrate what formal methods can do, and help to refine the methods, but they do not help to answer questions of how such methods can be integrated with existing practices on large projects. A few notable exceptions have used formal methods 'live' during the development of real systems [20, 24-26]. However, in all these cases, the emphasis was on the adoption of formal notations as baseline specifications, from which varying degrees of formal verification of the resulting design and implementation are possible. In contrast, we applied formal methods only in the early stages of requirements engineering, during which the requirements were still volatile. Rather than treating formal specification as an end product of the requirements phase, we used it to answer questions and improve the quality of the existing specifications. Our approach does not fit with any of the three process models suggested by Kemmerer [26] as ways of applying formal methods. Kemmerer offers three alternatives: after-the-fact, in which a formal specification is produced at the end of the development process to assist with testing and certification; parallel, in which formal specifications are developed alongside a conventional development process, and used to perform verification of code, design and requirements; and integrated, in which formal specification is used in place of conventional approaches. Our studies suggest a fourth model, in which formal modeling is used to increase quality during the requirements and high level design phases, without necessarily producing a baseline formal specification, or verifying low level design and code. Our studies also demonstrate that questions of tool support need not be a barrier to the adoption of formal methods. We conducted sophisticated validation of our models, via theorem proving and model checking, using tools that are essentially still research prototypes. In the 12 case studies surveyed by Gerhart et. al. [25], tool support was generally only used for syntax checking of specifications, and Gerhart suggests tool impoverishment is a barrier to wider use of formal methods. This may be true for the more complete process models used in case studies of the kinds described by Kemmerer [26], Hall [24] and Gerhart [25], but is not true of the ‘lightweight’ application of the kind we adopted. Although we have not attempted any detailed quantitative analysis of the costs and benefits of the application of formal methods in these studies, in each case the study added value to the project by clarifying the requirements and identifying important errors very early in the lifecycle. The costs, in terms of time and effort, were consistent with existing V&V tasks on these projects. Formalization of the requirements was the most time consuming part of the process, and in each case it revealed a large number of minor problems. Formalization also helps to focus attention on areas that are more susceptible to errors [27]. Consistency checking of the models was inexpensive, as it is largely done through automated typechecking. Formally challenging the models required a great deal of expertise, and it was often difficult to find suitable properties to test. This step uncovered a smaller number of more subtle errors, of the kind that are very hard to detect informally. A number of observations arising from these studies are worth further discussion: **Who should apply the methods?** In each of the studies, the formal analysis was conducted by experts in formal methods, who were external to the development project. There was a simple reason for this: it is easier to bring in a small team of formal methods experts than it is to train members of the development team. There are some interesting consequences of our use of external experts. Developing formal models of informal specifications involves a great deal of effort in understanding the domain, and figuring out how to interpret the documentation. As our external experts were unfamiliar with the projects prior to the studies, they did not share the assumptions that the requirements’ authors had made. Our experts questioned everything, spurred on by the explicitness needed to build the formal models. They also needed to present parts of their models back to the developers, in order to check the accuracy of their interpretations. The result was a healthy dialogue between the developers and our formal methods experts. This dialogue exposed many minor problems, especially unstated assumptions and inconsistent use of terminology. This dialogue was clearly an important benefit. Another aspect of this dialogue was that some of the issues that were raised were the result of misunderstandings by our experts, rather than genuine errors. The requirements’ authors therefore had to filter the issues, to pick out those for which the benefits of changing the requirements out-weighed the cost. This was especially true when the analysis revealed “interesting” off-nominal cases. A great deal of domain knowledge was needed to judge whether such cases were reasonable. The need for such filtering would be greatly reduced if the analysis were conducted by domain experts; however, the risk of analysis bias would then increase. *Is formal modeling of volatile requirements worthwhile?* During early stages of the requirements process, there may be a great deal of volatility. In each case study, some effort was needed to keep the formal model up to date with evolving requirements. For example, in the second study new drafts of the requirements document were being released approximately every two months. In at least one case (study 2, finding c), the error had already been fixed by the time we discovered it. We mitigated the problem of fluctuating requirements by only doing the minimum amount of modeling necessary to test the properties that were of interest. Our results indicate that there is no need to wait for the requirements to stabilize before applying formal methods. Early formalization allowed us to crystallize some of the outstanding issues, and explore different options. Most importantly, during this early phase the development team is more receptive to the issues raised from the formal modeling. This again emphasizes the importance of lightweight formal methods: the formal model itself can be discarded if the requirements change significantly, while the experience and lessons learned from it are retained. *Were Intermediate representations useful?* Like Hall [24], we found that the use of intermediate, structured representations facilitated the process of formalizing the requirements. The type of intermediate representation varied across the studies: the first study used an annotated version of the original FCD flowchart, the second study made use of AND/OR tables to clarify complex predicates, while the final study made extensive use of OMT diagrams. A large part of the effort in the formalization process lies in understanding the existing requirements. These intermediate representations helped to refine this understanding, and therefore reduced the effort needed to generate and debug the formal models. The intermediate representations also helped to create some initial structure for the formal models. Since the elements of the intermediate representations often mapped directly onto elements of the formal specifications, the subsequent effort of formalization was reduced. This also facilitated traceability between the formal and informal specifications, making it simpler to keep the formal model current. For example, in the third study, the OMT diagrams offered multiple perspectives on the requirements, and were easy for project personnel to review for accuracy. In effect the OMT model provided a higher level structural view of the requirements, while the PVS models filled in the processing details, and allowed detailed behavioral analysis. From our experience, it seems that this benefit more than outweighs the extra cost of maintaining several representations, at least for high levels of abstraction, even when requirements are still unstable. VI. Conclusions The three studies described here were conducted as pilot studies to demonstrate the utility of formal methods and to help us understand how to promote their use across NASA. An important characteristic of these studies is that in each case the formal modeling was carried out by a small team of experts who were not part of the development team. Results from the formal modeling were fed back into the requirements analysis phase, but formal specification languages were not adopted for baseline specifications. We have shown that lightweight formal methods complemented existing development and assurance practices in these projects. If formal methods is seen as an additional tool in the V&V toolbox, then selected application to existing large projects becomes feasible. As a follow-up to the studies described here, we have begun to investigate the role of formal methods in the development of new spacecraft technology. As part of NASA's New Millennium program, new architectures are being developed using knowledge-based systems to reduce the reliance of the spacecraft on ground support. Rather than produce a detailed statement of requirements, the project is using a rapid prototyping approach to explore the capabilities of the technology. The prototypes are tested against high level objectives, using a set of scenarios for guidance. We are exploring how to use lightweight formal analysis on rapidly changing information, in such a way as to provide useful and timely feedback. In particular, we are exploring the use of model checking to verify the fidelity between a formal model and the prototype. The model checker tests whether the formal model behaves in the same way as the prototype for a given scenario, while the formal model can be used to find interesting new scenarios on which to exercise the prototype. Acknowledgements The authors would like to thank Chris Jones, Sarah Gavit, Jan Berkeley, John Day, Jack Callahan, Chuck Neppach, Dan McCaugherty, John Hinkle, Larry Roberts, Alice Lee, Ernie Fridge, Kathryn Kemp, George Sabolish, Rick Butler and Alice Robinson for assistance in setting up these case studies and for helpful discussions as the work proceeded. We are also grateful to Ben Di Vito, Martin Feather, Frank Schneider, Judith Crow, Laurie Dillon, and the anonymous reviewers for their comments on earlier drafts of this paper. This research is partially a product of NASA’s Software Program, an agency-wide program that promotes continual improvement in software engineering and assurance within NASA. The funding for this program is provided by NASA’s Office of Safety and Mission Assurance. Bibliography Techniques (WIFT 95), Boca Raton, FL, April 1995.
{"Source-Url": "https://ntrs.nasa.gov/archive/nasa/casi.ntrs.nasa.gov/19980016986.pdf", "len_cl100k_base": 10149, "olmocr-version": "0.1.53", "pdf-total-pages": 21, "total-fallback-pages": 0, "total-input-tokens": 44549, "total-output-tokens": 12324, "length": "2e13", "weborganizer": {"__label__adult": 0.00035881996154785156, "__label__art_design": 0.00044918060302734375, "__label__crime_law": 0.000377655029296875, "__label__education_jobs": 0.0013875961303710938, "__label__entertainment": 0.00010544061660766602, "__label__fashion_beauty": 0.00020766258239746096, "__label__finance_business": 0.00043129920959472656, "__label__food_dining": 0.0003767013549804687, "__label__games": 0.00077056884765625, "__label__hardware": 0.00122833251953125, "__label__health": 0.0005803108215332031, "__label__history": 0.0004329681396484375, "__label__home_hobbies": 0.0001189112663269043, "__label__industrial": 0.0006299018859863281, "__label__literature": 0.0004508495330810547, "__label__politics": 0.0002880096435546875, "__label__religion": 0.0004825592041015625, "__label__science_tech": 0.113525390625, "__label__social_life": 0.00012540817260742188, "__label__software": 0.01091766357421875, "__label__software_dev": 0.865234375, "__label__sports_fitness": 0.0002837181091308594, "__label__transportation": 0.0008115768432617188, "__label__travel": 0.00023305416107177737}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 56272, 0.01401]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 56272, 0.39801]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 56272, 0.93765]], "google_gemma-3-12b-it_contains_pii": [[0, 730, false], [730, 2644, null], [2644, 5562, null], [5562, 8545, null], [8545, 11829, null], [11829, 14400, null], [14400, 17187, null], [17187, 19740, null], [19740, 22708, null], [22708, 25775, null], [25775, 28576, null], [28576, 33996, null], [33996, 35989, null], [35989, 38291, null], [38291, 41165, null], [41165, 44386, null], [44386, 47631, null], [47631, 50645, null], [50645, 53259, null], [53259, 55842, null], [55842, 56272, null]], "google_gemma-3-12b-it_is_public_document": [[0, 730, true], [730, 2644, null], [2644, 5562, null], [5562, 8545, null], [8545, 11829, null], [11829, 14400, null], [14400, 17187, null], [17187, 19740, null], [19740, 22708, null], [22708, 25775, null], [25775, 28576, null], [28576, 33996, null], [33996, 35989, null], [35989, 38291, null], [38291, 41165, null], [41165, 44386, null], [44386, 47631, null], [47631, 50645, null], [50645, 53259, null], [53259, 55842, null], [55842, 56272, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 56272, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 56272, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 56272, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 56272, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 56272, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 56272, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 56272, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 56272, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 56272, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 56272, null]], "pdf_page_numbers": [[0, 730, 1], [730, 2644, 2], [2644, 5562, 3], [5562, 8545, 4], [8545, 11829, 5], [11829, 14400, 6], [14400, 17187, 7], [17187, 19740, 8], [19740, 22708, 9], [22708, 25775, 10], [25775, 28576, 11], [28576, 33996, 12], [33996, 35989, 13], [35989, 38291, 14], [38291, 41165, 15], [41165, 44386, 16], [44386, 47631, 17], [47631, 50645, 18], [50645, 53259, 19], [53259, 55842, 20], [55842, 56272, 21]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 56272, 0.0428]]}
olmocr_science_pdfs
2024-12-07
2024-12-07
0c703e7c87c10f8053df03fefed802c574825bc9
In computer science and mathematics, a **sorting algorithm** is an algorithm that puts elements of a list in a certain order. The most used orders are numerical order and lexicographical order. Efficient sorting is important to optimizing the use of other algorithms (such as search and merge algorithms) that require sorted lists to work correctly; it is also often useful for canonicalizing data and for producing human-readable output. More formally, the output must satisfy two conditions: 1. The output is in nondecreasing order (each element is no smaller than the previous element according to the desired total order); 2. The output is a permutation, or reordering, of the input. Since the dawn of computing, the sorting problem has attracted a great deal of research, perhaps due to the complexity of solving it efficiently despite its simple, familiar statement. For example, bubble sort was analyzed as early as 1956. Although many consider it a solved problem, useful new sorting algorithms are still being invented to this day (for example, library sort was first published in 2004). Sorting algorithms are prevalent in introductory computer science classes, where the abundance of algorithms for the problem provides a gentle introduction to a variety of core algorithm concepts, such as big O notation, divide-and-conquer algorithms, data structures, randomized algorithms, worst-case, average-case, and best-case analysis, time-space tradeoffs, and lower bounds. **Classification** Sorting algorithms used in computer science are often classified by: - **Computational complexity** (worst, average and best behaviour) in terms of the size of the list \(n\). For typical sorting algorithms good behaviour is \(O(n \log n)\) and bad behaviour is \(O(n^2)\). Ideal behaviour for a sort is \(O(n)\). Sort algorithms which only use an abstract key comparison operation always need at least \(O(n \log n)\) comparisons on average; - **Memory usage** (and use of other computer resources). In particular, some sorting algorithms are "in place", such that little memory is needed beyond the items being sorted, while others need to create auxiliary locations for data to be temporarily stored. - **Stability**: stable sorting algorithms maintain the relative order of records with equal keys (*i.e.* values). That is, a sorting algorithm is *stable* if whenever there are two records \(R\) and \(S\) with the same key and with \(R\) appearing before \(S\) in the original list, \(R\) will appear before \(S\) in the sorted list. • Whether or not they are a comparison sort. A comparison sort examines the data only by comparing two elements with a comparison operator. • General method: insertion, exchange, selection, merging, etc. Exchange sorts include bubble sort and quicksort. Selection sorts include shaker sort and heapsort. When equal elements are indistinguishable, such as with integers, stability is not an issue. However, assume that the following pairs of numbers are to be sorted by their first coordinate: \[ (4, 1) \quad (3, 1) \quad (3, 7) \quad (5, 6) \] In this case, two different results are possible, one which maintains the relative order of records with equal keys, and one which does not: \[ (3, 1) \quad (3, 7) \quad (4, 1) \quad (5, 6) \quad (\text{order maintained}) (3, 7) \quad (3, 1) \quad (4, 1) \quad (5, 6) \quad (\text{order changed}) \] Unstable sorting algorithms may change the relative order of records with equal keys, but stable sorting algorithms never do so. Unstable sorting algorithms can be specially implemented to be stable. One way of doing this is to artificially extend the key comparison, so that comparisons between two objects with otherwise equal keys are decided using the order of the entries in the original data order as a tie-breaker. Remembering this order, however, often involves an additional space cost. In this table, \( n \) is the number of records to be sorted and \( k \) is the number of distinct keys. The columns "Best", "Average", and "Worst" give the time complexity in each case; estimates that do not use \( k \) assume \( k \) to be constant. "Memory" denotes the amount of auxiliary storage needed beyond that used by the list itself. "Cmp" indicates whether the sort is a **comparison sort**. <table> <thead> <tr> <th>Name</th> <th>Best</th> <th>Average</th> <th>Worst</th> <th>Memory</th> <th>Stable</th> <th>Cmp</th> <th>Method</th> </tr> </thead> <tbody> <tr> <td><strong>Bubble sort</strong></td> <td>( O(n) )</td> <td>—</td> <td>( O(n^2) )</td> <td>( O(1) )</td> <td>Yes</td> <td>Yes</td> <td>Exchanging</td> </tr> <tr> <td><strong>Selection sort</strong></td> <td>( O(n^2) )</td> <td>( O(n^2) )</td> <td>( O(n^2) )</td> <td>( O(1) )</td> <td>No</td> <td>Yes</td> <td>Selection</td> </tr> <tr> <td><strong>Insertion sort</strong></td> <td>( O(n) )</td> <td>—</td> <td>( O(n^2) )</td> <td>( O(1) )</td> <td>Yes</td> <td>Yes</td> <td>Insertion</td> </tr> <tr> <td><strong>Binary tree sort</strong></td> <td>( O(n \log(n)) )</td> <td>—</td> <td>( O(n \log(n)) )</td> <td>( O(1) )</td> <td>Yes</td> <td>Yes</td> <td>Insertion</td> </tr> <tr> <td><strong>Merge sort</strong></td> <td>( O(n \log(n)) )</td> <td>—</td> <td>( O(n \log(n)) )</td> <td>( O(n) )</td> <td>Yes</td> <td>Yes</td> <td>Merging</td> </tr> <tr> <td><strong>In-place merge sort</strong></td> <td>( O(n \log(n)) )</td> <td>—</td> <td>( O(n \log(n)) )</td> <td>( O(1) )</td> <td>Yes</td> <td>Yes</td> <td>Merging</td> </tr> <tr> <td><strong>Heapsort</strong></td> <td>( O(n \log(n)) )</td> <td>—</td> <td>( O(n \log(n)) )</td> <td>( O(1) )</td> <td>No</td> <td>Yes</td> <td>Selection</td> </tr> <tr> <td><strong>Quicksort</strong></td> <td>( O(n \log(n)) )</td> <td>( O(n \log(n)) )</td> <td>( O(n^2) )</td> <td>( O(\log n) )</td> <td>No</td> <td>Yes</td> <td>Partitioning</td> </tr> </tbody> </table> **Insertion sort** is a simple sort algorithm, a comparison sort in which the sorted array (or list) is built one entry at a time. It is much less efficient on large lists than the more advanced algorithms such as quicksort, heapsort, or merge sort, but it has various advantages: - Simple to implement - Efficient on (quite) small data sets - Efficient on data sets which are already substantially sorted - More efficient in practice than most other simple $O(n^2)$ algorithms such as selection sort or bubble sort: the average time is $n^2/4$ and it is linear in the best case - **Stable** (does not change the relative order of elements with equal keys) - **In-place** (only requires a constant amount $O(1)$ of extra memory space) - It is an online algorithm, in that it can sort a list as it receives it. In abstract terms, each iteration of an insertion sort removes an element from the input data, inserting it at the correct position in the already sorted list, until no elements are left in the input. The choice of which element to remove from the input is arbitrary and can be made using almost any choice algorithm. Sorting is typically done in-place. The result array after $k$ iterations contains the first $k$ entries of the input array and is sorted. In each step, the first remaining entry of the input is removed, inserted into the result at the right position, thus extending the result: <table> <thead> <tr> <th>Sorted partial result</th> <th>Unsorted data</th> </tr> </thead> <tbody> <tr> <td>$\leq x$</td> <td>$&gt; x$</td> </tr> </tbody> </table> becomes: <table> <thead> <tr> <th>Sorted partial result</th> <th>Unsorted data</th> </tr> </thead> <tbody> <tr> <td>$\leq x$</td> <td>$x$</td> </tr> </tbody> </table> with each element $> x$ copied to the right as it is compared against $x$. The most common variant, which operates on arrays, can be described as: 1. Suppose we have a method called *insert* designed to insert a value into a sorted sequence at the beginning of an array. It operates by starting at the end of the sequence and shifting each element one place to the right until a suitable position is found for the new element. It has the side effect of overwriting the value stored immediately after the sorted sequence in the array. 2. To perform insertion sort, start at the left end of the array and invoke \textit{insert} to insert each element encountered into its correct position. The ordered sequence into which we insert it is stored at the beginning of the array in the set of indexes already examined. Each insertion overwrites a single value, but this is okay because it's the value we're inserting. A simple pseudocode version of the complete algorithm follows, where the arrays are zero-based: ```c insert(array a, int length, value) { int i := length - 1; while (i ≥ 0 and a[i] > value) { a[i + 1] := a[i]; i := i - 1; } a[i + 1] := value; } insertionSort(array a, int length) { int i := 1; while (i < length) { insert(a, i, a[i]); i := i + 1; } } ``` **Java Implementation**: ```java static void insertionSort (int[] A) { int j; for (int i = 1; i < A.length; i++) { int a = A[i]; for (j = i - 1; j >=0 && A[j] > a; j--) A[j + 1] = a; } } ``` **Good and bad input cases** In the best case of an already sorted array, this implementation of insertion sort takes $O(n)$ time: in each iteration, the first remaining element of the input is only compared with the last element of the result. It takes $O(n^2)$ time in the average and worst cases, which makes it impractical for sorting large numbers of elements. However, insertion sort’s inner loop is very fast, which often makes it one of the fastest algorithms for sorting small numbers of elements, typically less than 10 or so. **Comparisons to other sorts** Insertion sort is very similar to bubble sort. In bubble sort, after \( k \) passes through the array, the \( k \) largest elements have bubbled to the top. (Or the \( k \) smallest elements have bubbled to the bottom, depending on which way you do it.) In insertion sort, after \( k \) passes through the array, you have a run of \( k \) sorted elements at the bottom of the array. Each pass inserts another element into the sorted run. So with bubble sort, each pass takes less time than the previous one, but with insertion sort, each pass may take more time than the previous one. Some divide-and-conquer algorithms such as quicksort and mergesort sort by recursively dividing the list into smaller sublists which are then sorted. A useful optimization in practice for these algorithms is to switch to insertion sort for "small enough" sublists on which insertion sort outperforms the more complex algorithms. The size of list for which insertion sort has the advantage varies by environment and implementation, but is typically around 8 to 20 elements. **Merge sort** In computer science, merge sort or mergesort is a sorting algorithm for rearranging lists (or any other data structure that can only be accessed sequentially, e.g. file streams) into a specified order. It is a particularly good example of the divide and conquer algorithmic paradigm. It is a comparison sort. Conceptually, merge sort works as follows: 1. Divide the unsorted list into two sublists of about half the size 2. Sort each of the two sublists 3. Merge the two sorted sublists back into one sorted list. The algorithm was invented by John von Neumann in 1945. In simple pseudocode, the algorithm could look something like this: ```plaintext function mergesort(m) var list left, right if length(m) ≤ 1 return m else middle = length(m) / 2 for each x in m up to middle add x to left for each x in m after middle add x to right left = mergesort(left) ``` ```plaintext ``` ```plaintext ``` ```plaintext ``` right = mergesort(right) result = merge(left, right) return result There are several variants for the merge() function, the simplest variant could look like this: ```plaintext function merge(left, right) var list result while length(left) > 0 or length(right) > 0 if length(left) > 0 and first(left) ≥ first(right) append first(left) to result left = rest(left) else append first(right) to result right = rest(right) return result ``` ### Analysis In sorting \( n \) items, merge sort has an **average** and **worst-case performance** of \( O(n \log n) \). If the running time of merge sort for a list of length \( n \) is \( T(n) \), then the recurrence \( T(n) = 2T(n/2) + n \) follows from the definition of the algorithm (apply the algorithm to two lists of half the size of the original list, and add the \( n \) steps taken to merge the resulting two lists). The closed form follows from the **master theorem**. In the worst case, merge sort does exactly \( (n \lceil \log n \rceil - 2\lceil \log n \rceil + 1) \) comparisons, which is between \( (n \log n - 0.9139n + 1) \) [logs are base 2]. Note, the worst case number given here does not agree with that given in the "bible", Knuth's Art of Computer Programming, Vol 3; the discrepancy is due to Knuth analyzing a variant implementation of merge sort that is slightly sub-optimal. For large \( n \) and a randomly ordered input list, merge sort's expected (average) number of comparisons approaches \( \alpha \cdot n \) fewer than the worst case, where \( \alpha = -1 + \sum 1/(2^k +1), k = 0 \rightarrow \infty, \alpha \approx 0.2645. \) In the **worst case**, merge sort does about 39% fewer comparisons than quicksort does in the **average** case; merge sort always makes fewer comparisons than quicksort, except in extremely rare cases, when they tie, where merge sort's **worst case** is found simultaneously with quicksort's **best** case. In terms of moves, merge sort's worst case complexity is \( O(n \log n) \)--the same complexity as quicksort's best case, and merge sort's best case takes about half as many iterations as the worst case. Recursive implementations of merge sort make \( 2n - 1 \) method calls in the worst case, compared to quicksort's \( n \), thus has roughly twice as much recursive overhead as quicksort. However, iterative, non-recursive, implementations of merge sort, avoiding method call overhead, are not difficult to code. Merge sort's most common implementation does not sort in place, meaning memory the size of the input must be allocated for the sorted output to be stored in. Sorting in-place is possible but requires an extremely complicated implementation. Merge sort is much more efficient than quicksort if the data to be sorted can only be efficiently accessed sequentially, and is thus popular in languages such as Lisp, where sequentially accessed data structures are very common. Unlike some optimized implementations of quicksort, merge sort is a stable sort as long as the merge operation is implemented properly. Merge sorting tape drives Merge sort is so inherently sequential that it's practical to run it using slow tape drives as input and output devices. It requires very little memory, and the memory required does not change with the number of data elements. If you have four tape drives, it works as follows: 1. divide the data to be sorted in half and put half on each of two tapes 2. merge individual pairs of records from the two tapes; write two-record chunks alternately to each of the two output tapes 3. merge the two-record chunks from the two output tapes into four-record chunks; write these alternately to the original two input tapes 4. merge the four-record chunks into eight-record chunks; write these alternately to the original two output tapes 5. repeat until you have one chunk containing all the data, sorted --- that is, for log \( n \) passes, where \( n \) is the number of records. On tape drives that can run both backwards and forwards, you can run merge passes in both directions, avoiding rewind time. For the same reason it is also very useful for sorting data on disk that is too large to fit entirely into primary memory. Online sorting Mergesort's merge operation is useful in online sorting, where the list to be sorted is received a piece at a time, instead of all at the beginning (see online algorithm). In this application, we sort each new piece that is received using any sorting algorithm, and then merge it into our sorted list so far using the merge operation. However, this approach can be expensive in time and space if the received pieces are small compared to the sorted list — a better approach in this case is to store the list in a self-balancing binary search tree and add elements to it as they are received. Comparison with other sort algorithms Although heap sort has the same time bounds as merge sort, it requires only $\Omega(1)$ auxiliary space instead of merge sort's $\Omega(n)$, and is consequently often faster in practical implementations. Quicksort, however, is considered by many to be the fastest general-purpose sort algorithm in practice. Its average-case complexity is $O(n \log n)$, with a much smaller coefficient, in good implementations, than merge sort's, even though it is quadratic in the worst case. On the plus side, merge sort is a stable sort, parallelizes better, and is more efficient at handling slow-to-access sequential media. Merge sort is often the best choice for sorting a linked list: in this situation it is relatively easy to implement a merge sort in such a way that it does not require $\Omega(n)$ auxiliary space (instead only $\Omega(1)$), and the slow random-access performance of a linked list makes some other algorithms (such as quick sort) perform poorly, and others (such as heapsort) completely impossible. As of Perl 5.8, merge sort is its default sorting algorithm (it was quicksort in previous versions of Perl). In Java, the Arrays.sort() methods use mergesort and a tuned quicksort depending on the datatypes. external sort **Definition:** Any sort algorithm that uses external memory, such as tape or disk, during the sort. Since most common sort algorithms assume high-speed random access to all intermediate memory, they are unsuitable if the values to be sorted don't fit in main memory. **Java Implementation:** ```java public int[] mergeSort(int array[]) // pre: array is full, all elements are valid integers (not null) // post: array is sorted in ascending order (lowest to highest) { // if the array has more than 1 element, we need to split it and merge the sorted halves if(array.length > 1) { // number of elements in sub-array 1 // if odd, sub-array 1 has the smaller half of the elements // e.g. if 7 elements total, sub-array 1 will have 3, and sub-array 2 will have 4 int elementsInA1 = array.length/2; // since we want an even split, we initialize the length of sub-array 2 to // equal the length of sub-array 1 int elementsInA2 = elementsInA1; // if the array has an odd number of elements, let the second half take the extra one // see note (1) if((array.length % 2) == 1) elementsInA2 += 1; // declare and initialize the two arrays once we've determined their sizes int arr1[] = new int[elementsInA1]; int arr2[] = new int[elementsInA2]; } ``` // copy the first part of 'array' into 'arr1', causing arr1 to become full for(int i = 0; i < elementsInA1; i++) arr1[i] = array[i]; // copy the remaining elements of 'array' into 'arr2', causing arr2 to become full for(int i = elementsInA1; i < elementsInA1 + elementsInA2; i++) arr2[i - elementsInA1] = array[i]; // recursively call mergeSort on each of the two sub-arrays that we've just created // note: when mergeSort returns, arr1 and arr2 will both be sorted! // it's not magic, the merging is done below, that's how mergesort works :) arr1 = mergeSort(arr1); arr2 = mergeSort(arr2); // the three variables below are indexes that we'll need for merging // [i] stores the index of the main array. it will be used to let us // know where to place the smallest element from the two sub-arrays. // [j] stores the index of which element from arr1 is currently being compared // [k] stores the index of which element from arr2 is currently being compared int i = 0, j = 0, k = 0; // the below loop will run until one of the sub-arrays becomes empty // in my implementation, it means until the index equals the length of the sub-array while(arr1.length != j && arr2.length != k) { // if the current element of arr1 is less than current element of arr2 if(arr1[j] < arr2[k]) { // copy the current element of arr1 into the final array array[i] = arr1[j]; // increase the index of the final array to avoid replacing the element // which we've just added i++; // increase the index of arr1 to avoid comparing the element // which we've just added j++; } // if the current element of arr2 is less than current element of arr1 else { // copy the current element of arr1 into the final array array[i] = arr2[k]; // increase the index of the final array to avoid replacing the element // which we've just added i++; // increase the index of arr2 to avoid comparing the element // which we've just added k++; } } // at this point, one of the sub-arrays has been exhausted and there are no more // elements in it to compare. this means that all the elements in the remaining // array are the highest (and sorted), so it's safe to copy them all into the // final array. while(arr1.length != j) { array[i] = arr1[j]; i++; j++; } while(arr2.length != k) { array[i] = arr2[k]; i++; k++; } // return the sorted array to the caller of the function return array; Quicksort Quicksort is a well-known sorting algorithm developed by C. A. R. Hoare that, on average, makes $\Theta(n \log n)$ comparisons to sort $n$ items. However, in the worst case, it makes $\Theta(n^2)$ comparisons. Typically, quicksort is significantly faster in practice than other $\Theta(n \log n)$ algorithms, because its inner loop can be efficiently implemented on most architectures, and in most real-world data it is possible to make design choices which minimize the possibility of requiring quadratic time. Quicksort is a comparison sort and, in efficient implementations, is not a stable sort. Quicksort sorts by employing a divide and conquer strategy to divide a list into two sub-lists. The steps are: 1. Pick an element, called a pivot, from the list. 2. Reorder the list so that all elements which are less than the pivot come before the pivot and so that all elements greater than the pivot come after it (equal values can go either way). After this partitioning, the pivot is in its final position. This is called the partition operation. 3. Recursively sort the sub-list of lesser elements and the sub-list of greater elements. The base case of the recursion are lists of size zero or one, which are always sorted. The algorithm always terminates because it puts at least one element in its final place on each iteration. In simple pseudocode, the algorithm might be expressed as: ```plaintext function quicksort(q) var list less, pivotList, greater if length(q) ≤ 1 return q select a pivot value pivot from q foreach x in q except the pivot element if x < pivot then add x to less if x ≥ pivot then add x to greater add pivot to pivotList return concatenate(quicksort(less), pivotList, quicksort(greater)) ``` Notice that we only examine elements by comparing them to other elements. This makes quicksort a comparison sort. Version with in-place partition In-place partition in action on a small list. The boxed element is the pivot element, blue elements are less or equal, and red elements are larger. The disadvantage of the simple version above is that it requires $\Omega(n)$ extra storage space, which is as bad as mergesort (see big-O notation for the meaning of $\Omega$). The additional memory allocations required can also drastically impact speed and cache performance in practical implementations. There is a more complicated version which uses an in-place partition algorithm and can achieve $O(\log n)$ space use on average for good pivot choices: ``` function partition(a, left, right, pivotIndex) pivotValue := a[pivotIndex] swap(a[pivotIndex], a[right]) // Move pivot to end storeIndex := left for i from left to right-1 if a[i] <= pivotValue swap(a[storeIndex], a[i]) storeIndex := storeIndex + 1 swap(a[right], a[storeIndex]) // Move pivot to its final place return storeIndex ``` This is the in-place partition algorithm. It partitions the portion of the array between indexes `left` and `right`, inclusively, by moving all elements less than or equal to `a[pivotIndex]` to the beginning of the subarray, leaving all the greater elements following them. In the process it also finds the final position for the pivot element, which it returns. It temporarily moves the pivot element to the end of the subarray, so that it doesn't get in the way. Because it only uses exchanges, the final list has the same elements as the original list. Notice that an element may be exchanged multiple times before reaching its final place. Once we have this, writing quicksort itself is easy: ``` function quicksort(a, left, right) if right > left ``` select a pivot value a[pivotIndex] pivotNewIndex := partition(a, left, right, pivotIndex) quicksort(a, left, pivotNewIndex-1) quicksort(a, pivotNewIndex+1, right) This version is the one more typically used in imperative languages such as C. **Performance details** Quicksort's inner loop, which performs the partition, is amenable to optimization on typical modern machines for two main reasons: - All comparisons are being done with a single pivot value, which can be stored in a register. - The list is being traversed sequentially, which produces very good locality of reference and cache behavior for arrays. This close fit with modern architectures makes quicksort one of the fastest sorting algorithms on average. Because of this excellent average performance and simple implementation, quicksort has become one of the most popular sorting algorithms in practical use. Although it is often believed to work in-place, quicksort uses $O(\log n)$ additional stack space on average in recursive implementations and $O(n)$ stack space in the worst case. The most crucial concern of a quicksort implementation is the choosing of a good pivot element. A naïve pivot choice, such as always choosing the first element, will be terribly inefficient for certain inputs. For example, if the input is already sorted, a common practical case, always choosing the first element as the pivot causes quicksort to degenerate into a selection sort with $O(n^2)$ running time. When using the simplest variant, the recursion depth also becomes linear, requiring $O(n)$ extra stack space. This worst-case performance is much worse than comparable sorting algorithms such as heapsort or merge sort. However, if pivots are chosen randomly, most poor choices of pivots are unlikely; the worst-case, for example, has only probability $1/n!$ of occurring. This variation, called randomized quicksort, can be shown to use $O(n \log n)$ comparisons on any input with very high probability. Note that the partition procedure only requires the ability to traverse the list sequentially; therefore, quicksort is not confined to operating on arrays (it can be used, for example, on linked lists). Choosing a good pivot, however, benefits from random access, as we will see. Choosing a better pivot The worst-case behavior of quicksort is not merely a theoretical problem. When quicksort is used in web services, for example, it is possible for an attacker to deliberately exploit the worst case performance and choose data which will cause a slow running time or maximize the chance of running out of stack space. See competitive analysis for more discussion of this issue. Sorted or partially sorted data is quite common in practice and a naïve implementation which selects the first element as the pivot does poorly with such data. To avoid this problem the middle element may be chosen. This works well in practice, but attacks can still cause worst-case performance. Another common choice is to randomly choose a pivot index, typically using a pseudorandom number generator. If the numbers are truly random, it can be proven that the resulting algorithm, called randomized quicksort, runs in an expected time of $\Theta(n \log n)$. Unfortunately, although simple pseudorandom number generators usually suffice for choosing good pivots, they are little defense against an attacker who can run the same generator to predict the values. One defense against this is to use highly unpredictable random seeds, such as numbers generated from hardware random number generators or entropy pools, and to avoid exposing partial information that might reveal information about the random seed or sequence. Another choice is to select the median of the first, middle and last elements as the pivot. Adding two randomly selected elements resists chosen data attacks. The use of the fixed elements reduces the chance of bad luck causing a poor pivot selection for partially sorted data when not under attack. These steps increase overhead, so it may be worth skipping them once the partitions grow small and the penalty for poor pivot selection drops. Interestingly, since finding the true median value to use as the pivot can be done in $O(n)$ time (see selection algorithm), the worst-case time can be reduced to $O(n \log n)$. Because the median algorithm is relatively slow in practice, however, this algorithm is rarely useful; if worst-case time is a concern, other sort algorithms are generally preferable. The way that partitioning is done determines whether or not a quicksort implementation is a stable sort. Typically, in-place partitions are unstable, while not-in-place partitions are stable. Other optimizations Using different algorithms for small lists Another optimization is to switch to a different sorting algorithm once the list becomes small, perhaps ten or less elements. Insertion sort or selection sort might be inefficient for large data sets, but they are often faster than quicksort on small lists, requiring less setup time and less stack manipulation. One widely used implementation of quicksort, found in the 1997 Microsoft C library, used a cutoff of 8 elements before switching to insertion sort, asserting that testing had shown that to be a good choice. It used the middle element for the partition value, asserting that testing had shown that the median of three algorithm did not, in general, increase performance. Sedgewick (1978) suggested an enhancement to the use of simple sorts for small numbers of elements, which reduced the number of instructions required by postponing the simple sorts until the quicksort had finished, then running an insertion sort over the whole array. This is effective because insertion sort requires only \(O(n)\) time to sort an array where every element is less than \(k\) places from its final position. LaMarca and Ladner (1997) consider "The Influence of Caches on the Performance of Sorting", a significant issue in microprocessor systems with multi-level caches and high cache miss times. They conclude that while the Sedgewick optimization decreases the number of instructions, it also decreases locality of cache references and worsens performance compared to doing the simple sort when the need for it is first encountered. However, the effect was not dramatic and they suggested that it was starting to become more significant with more than 4 million 64 bit float elements. Greater improvement was shown for other sorting types. Another variation on this theme which is becoming widely used is introspective sort, often called introsort. This starts with quicksort and switches to heapsort when the recursion depth exceeds a preset value. This overcomes the overhead of increasingly complex pivot selection techniques while ensuring \(O(n \log n)\) worst-case performance. Musser reported that on a median-of-3 killer sequence of 100,000 elements running time was 1/200th that of median-of-3 quicksort. Musser also considered the effect of Sedgewick's delayed small sorting on caches, reporting that it could double the number of cache misses when used on arrays, but its performance with double-ended queues was significantly better. Because recursion requires additional memory, quicksort has been implemented in a non- recursive, iterative form. This in-place variant has the advantage of predictable memory use regardless of input, and the disadvantage of considerably greater code complexity. A simpler in-place sort of competitive speed is heapsort. A simple alternative for reducing quicksort's memory consumption is to use true recursion only on the smaller of the two sublists and tail recursion on the larger. This limits the additional storage of quicksort to \(\Theta(\log n)\); even for huge lists, this variant typically requires no more than roughly 100 words of memory. The procedure quicksort in the pseudocode with the in-place partition would be rewritten as ```plaintext function quicksort(a, left, right) while right > left ``` select a pivot value \(a[pivotIndex]\) \[pivotNewIndex := partition(a, left, right, pivotIndex)\] \[\begin{align*} \textbf{if} & \quad (pivotNewIndex-1) - left < right - (pivotNewIndex+1) \\ & \quad \text{quicksort}(a, left, pivotNewIndex-1) \\ & \quad \text{left} := pivotNewIndex+1 \end{align*}\] \[\begin{align*} \textbf{else} & \quad \text{quicksort}(a, pivotNewIndex+1, right) \\ & \quad \text{right} := pivotNewIndex-1 \end{align*}\] **Competitive sorting algorithms** Quicksort is a space-optimized version of the binary tree sort. Instead of inserting items sequentially into an explicit tree, quicksort organizes them concurrently into a tree that is implied by the recursive calls. The algorithms make exactly the same comparisons, but in a different order. The most direct competitor of quicksort is heapsort. Heapsort is typically somewhat slower than quicksort, but the worst-case running time is always \(O(n \log n)\). Quicksort is usually faster, though there remains the chance of worst case performance except in the introsort variant. If it's known in advance that heapsort is going to be necessary, using it directly will be faster than waiting for introsort to switch to it. Heapsort also has the important advantage of using only constant additional space (heapsort is in-place), whereas even the best variant of quicksort uses \(\Theta(\log n)\) space. However, heapsort requires efficient random access to be practical. Quicksort also competes with mergesort, another recursive sort algorithm but with the benefit of worst-case \(O(n \log n)\) running time. Mergesort is a stable sort, unlike quicksort and heapsort, and can be easily adapted to operate on linked lists and very large lists stored on slow-to-access media such as disk storage or network attached storage. Although quicksort can be written to operate on linked lists, it will often suffer from poor pivot choices without random access. The main disadvantage of mergesort is that it requires \(\Omega(n)\) auxiliary space in the best case, whereas the variant of quicksort with in-place partitioning and tail recursion uses only \(O(\log n)\) space. **Formal analysis** From the initial description it's not obvious that quicksort takes \(O(n \log n)\) time on average. It's not hard to see that the partition operation, which simply loops over the elements of the array once, uses \(\Theta(n)\) time. In versions that perform concatenation, this operation is also \(\Theta(n)\). In the best case, each time we perform a partition we divide the list into two nearly equal pieces. This means each recursive call processes a list of half the size. Consequently, we can make only \(\log n\) nested calls before we reach a list of size 1. This means that the depth of the call tree is \(O(\log n)\). But no two calls at the same level of the call tree... process the same part of the original list; thus, each level of calls needs only $O(n)$ time all together (each call has some constant overhead, but since there are only $O(n)$ calls at each level, this is subsumed in the $O(n)$ factor). The result is that the algorithm uses only $O(n \log n)$ time. An alternate approach is to set up a recurrence relation for $T(n)$, the time needed to sort a list of size $n$. Because a single quicksort call involves $O(n)$ work plus two recursive calls on lists of size $n/2$ in the best case, the relation would be: $$T(n) = O(n) + 2T(n/2)$$ Standard mathematical induction techniques for solving this type of relation tell us that $T(n) = \Theta(n \log n)$. In fact, it's not necessary to divide the list this precisely; even if each pivot splits the elements with 99% on one side and 1% on the other, the call depth is still limited to $100 \log n$, so the total running time is still $O(n \log n)$. In the worst case, however, the two sublists have size 1 and $n-1$, and the call tree becomes a linear chain of $n$ nested calls. The $i$th call does $O(n-i)$ work, and $$\sum_{i=0}^{n} (n - i) = O(n^2)$$ The recurrence relation is: $$T(n) = O(n) + T(1) + T(n - 1) = O(n) + T(n - 1)$$ This is the same relation as for insertion sort and selection sort, and it solves to $T(n) = \Theta(n^2)$. **Randomized quicksort expected complexity** Randomized quicksort has the desirable property that it requires only $O(n \log n)$ expected time, regardless of the input. But what makes random pivots a good choice? Suppose we sort the list and then divide it into four parts. The two parts in the middle will contain the best pivots; each of them is larger than at least 25% of the elements and smaller than at least 25% of the elements. If we could consistently choose an element from these two middle parts, we would only have to split the list at most $2 \log_2 n$ times before reaching lists of size 1, yielding an $O(n \log n)$ algorithm. Unfortunately, a random choice will only choose from these middle parts half the time. The surprising fact is that this is good enough. Imagine that you are flipping a coin over and over until you get $k$ heads. Although this could take a long time, on average only $2k$ flips are required, and the chance that you won't get $k$ heads after 100$k$ flips is astronomically small. By the same argument, quicksort's recursion will terminate on average at a call depth of only $2(2 \log_2 n)$. But if its average call depth is $O(\log n)$, and each level of the call tree processes at most \( n \) elements, the total amount of work done on average is the product, \( O(n \log n) \). **Average complexity** Even if we aren't able to choose pivots randomly, quicksort still requires only \( O(n \log n) \) time over all possible permutations of its input. Because this average is simply the sum of the times over all permutations of the input divided by \( n \) factorial, it's equivalent to choosing a random permutation of the input. When we do this, the pivot choices are essentially random, leading to an algorithm with the same running time as randomized quicksort. More precisely, the average number of comparisons over all permutations of the input sequence can be estimated accurately by solving the recurrence relation: \[ C(n) = n - 1 + \frac{1}{n} \sum_{i=0}^{n-1} (C(i) + C(n - i - 1)) = 2n \ln n = 1.39n \log_2 n. \] Here, \( n - 1 \) is the number of comparisons the partition uses. Since the pivot is equally likely to fall anywhere in the sorted list order, the sum is averaging over all possible splits. This means that, on average, quicksort performs only about 39% worse than the ideal number of comparisons, which is its best case. In this sense it is closer to the best case than the worst case. This fast average runtime is another reason for quicksort's practical dominance over other sorting algorithms. **Space complexity** The space used by quicksort depends on the version used. The version of quicksort with in-place partitioning uses only constant additional space before making any recursive call. However, if it has made \( O(\log n) \) nested recursive calls, it needs to store a constant amount of information from each of them. Since the best case makes at most \( O(\log n) \) nested recursive calls, it uses \( O(\log n) \) space. The worst case makes \( O(n) \) nested recursive calls, and so needs \( O(n) \) space. We are eliding a small detail here, however. If we consider sorting arbitrarily large lists, we have to keep in mind that our variables like \( left \) and \( right \) can no longer be considered to occupy constant space; it takes \( O(\log n) \) bits to index into a list of \( n \) items. Because we have variables like this in every stack frame, in reality quicksort requires \( O(\log^2 n) \) bits of space in the best and average case and \( O(n \log n) \) space in the worst case. This isn't too terrible, though, since if the list contains mostly distinct elements, the list itself will also occupy \( O(n \log n) \) bits of space. The not-in-place version of quicksort uses $O(n)$ space before it even makes any recursive calls. In the best case its space is still limited to $O(n)$, because each level of the recursion uses half as much space as the last, and $$\sum_{i=0}^{\infty} \frac{n}{2^i} = 2n.$$ Its worst case is dismal, requiring $$\sum_{i=0}^{n} (n - i + 1) = \Theta(n^2)$$ space, far more than the list itself. If the list elements are not themselves constant size, the problem grows even larger; for example, if most of the list elements are distinct, each would require about $O(\log n)$ bits, leading to a best-case $O(n \log n)$ and worst-case $O(n^2 \log n)$ space requirement. **Relationship to selection** A [selection algorithm](#) chooses the $k$th smallest of a list of numbers; this is an easier problem in general than sorting. One simple but effective selection algorithm works nearly in the same manner as quicksort, except that instead of making recursive calls on both sublists, it only makes a single tail-recursive call on the sublist which contains the desired element. This small change lowers the average complexity to linear or $\Theta(n)$ time, and makes it an in-place algorithm. A variation on this algorithm brings the worst-case time down to $O(n)$ (see selection algorithm for more information). Conversely, once we know a worst-case $O(n)$ selection algorithm is available, we can use it to find the ideal pivot (the median) at every step of quicksort, producing a variant with worst-case $O(n \log n)$ running time. In practical implementations, however, this variant is considerably slower on average. **The QuickSort Algorithm** As one of the more advanced sorting algorithms, you might think that the QuickSort Algorithm is steeped in complicated theoretical background, but this is not so. Like Insertion Sort, this algorithm has a fairly simple concept at the core, but is made complicated by the constraints of the array structure. The basic concept is to pick one of the elements in the array as a pivot value around which the other elements will be rearranged. Everything less than the pivot is moved left of the pivot (into the left partition). Similarly, everything greater than the pivot goes into the right partition. At this point each partition is recursively quicksorted. The Quicksort algorithm is fastest when the median of the array is chosen as the pivot value. That is because the resulting partitions are of very similar size. Each partition splits itself in two and thus the base case is reached very quickly. In practice, the Quicksort algorithm becomes very slow when the array passed to it is already close to being sorted. Because there is no efficient way for the computer to find the median element to use as the pivot, the first element of the array is used as the pivot. So when the array is almost sorted, Quicksort doesn't partition it equally. Instead, the partitions are lopsided like in Figure 2. This means that one of the recursion branches is much deeper than the other, and causes execution time to go up. Thus, it is said that the more random the arrangement of the array, the faster the Quicksort Algorithm finishes. **Figure 1:** The ideal Quicksort on a random array. Figure 2: Quicksort on an already sorted array. These are the steps taken to sort an array using QuickSort: public void quickSort(int array[]) // pre: array is full, all elements are non-null integers // post: the array is sorted in ascending order { quickSort(array, 0, array.length - 1); // quicksort all the elements in the array } public void quickSort(int array[], int start, int end) { int i = start; // index of left-to-right scan int k = end; // index of right-to-left scan if (end - start >= 1) // check that there are at least two elements to sort { int pivot = array[start]; // set the pivot as the first element in the partition while (k > i) // while the scan indices from left and right have not met, { while (array[i] <= pivot && i <= end && k > i) // from the left, look for the first i++; // element greater than the pivot while (array[k] > pivot && k >= start && k >= i) // from the right, look for the first k--; // element not greater than the pivot if (k > i) // if the left seekindex is still smaller than swap(array, i, k); // the right index, swap the corresponding elements } swap(array, start, k); // after the indices have crossed // swap the last element in // the left partition with the pivot quickSort(array, start, k - 1); // quicksort the left partition quickSort(array, k + 1, end); // quicksort the right partition } else // if there is only one element in the partition, do not do any sorting { return; // the array is sorted, so exit } } public void swap(int array[], int index1, int index2) // pre: array is full and index1, index2 < array.length // post: the values at indices 1 and 2 have been swapped { int temp = array[index1]; // store the first value in a temp array[index1] = array[index2]; // copy the value of the second into the first array[index2] = temp; // copy the value of the temp into the second
{"Source-Url": "http://condor.depaul.edu/ichu/csc383/notes/notes2/sorting.pdf", "len_cl100k_base": 11154, "olmocr-version": "0.1.50", "pdf-total-pages": 22, "total-fallback-pages": 0, "total-input-tokens": 54464, "total-output-tokens": 12130, "length": "2e13", "weborganizer": {"__label__adult": 0.0003027915954589844, "__label__art_design": 0.0003070831298828125, "__label__crime_law": 0.0003993511199951172, "__label__education_jobs": 0.0007176399230957031, "__label__entertainment": 8.428096771240234e-05, "__label__fashion_beauty": 0.00015056133270263672, "__label__finance_business": 0.00016641616821289062, "__label__food_dining": 0.0004208087921142578, "__label__games": 0.001220703125, "__label__hardware": 0.0014200210571289062, "__label__health": 0.00039887428283691406, "__label__history": 0.0002777576446533203, "__label__home_hobbies": 0.0001189112663269043, "__label__industrial": 0.0003921985626220703, "__label__literature": 0.0002636909484863281, "__label__politics": 0.00025153160095214844, "__label__religion": 0.0003826618194580078, "__label__science_tech": 0.048675537109375, "__label__social_life": 7.420778274536133e-05, "__label__software": 0.010223388671875, "__label__software_dev": 0.9326171875, "__label__sports_fitness": 0.00033783912658691406, "__label__transportation": 0.0003719329833984375, "__label__travel": 0.00018930435180664065}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 46341, 0.0102]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 46341, 0.65967]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 46341, 0.88667]], "google_gemma-3-12b-it_contains_pii": [[0, 2542, false], [2542, 3888, null], [3888, 5403, null], [5403, 7596, null], [7596, 9221, null], [9221, 11294, null], [11294, 13664, null], [13664, 16166, null], [16166, 18815, null], [18815, 21361, null], [21361, 23266, null], [23266, 25064, null], [25064, 27321, null], [27321, 29998, null], [29998, 33087, null], [33087, 35948, null], [35948, 38477, null], [38477, 41034, null], [41034, 43241, null], [43241, 44271, null], [44271, 44380, null], [44380, 46341, null]], "google_gemma-3-12b-it_is_public_document": [[0, 2542, true], [2542, 3888, null], [3888, 5403, null], [5403, 7596, null], [7596, 9221, null], [9221, 11294, null], [11294, 13664, null], [13664, 16166, null], [16166, 18815, null], [18815, 21361, null], [21361, 23266, null], [23266, 25064, null], [25064, 27321, null], [27321, 29998, null], [29998, 33087, null], [33087, 35948, null], [35948, 38477, null], [38477, 41034, null], [41034, 43241, null], [43241, 44271, null], [44271, 44380, null], [44380, 46341, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 46341, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 46341, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 46341, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 46341, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 46341, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 46341, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 46341, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 46341, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 46341, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, true], [5000, 46341, null]], "pdf_page_numbers": [[0, 2542, 1], [2542, 3888, 2], [3888, 5403, 3], [5403, 7596, 4], [7596, 9221, 5], [9221, 11294, 6], [11294, 13664, 7], [13664, 16166, 8], [16166, 18815, 9], [18815, 21361, 10], [21361, 23266, 11], [23266, 25064, 12], [25064, 27321, 13], [27321, 29998, 14], [29998, 33087, 15], [33087, 35948, 16], [35948, 38477, 17], [38477, 41034, 18], [41034, 43241, 19], [43241, 44271, 20], [44271, 44380, 21], [44380, 46341, 22]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 46341, 0.03524]]}
olmocr_science_pdfs
2024-12-03
2024-12-03
973e4a592ec9e0863084d4c7598a33c3e4654775
Automated Code Generation for Lattice QCD Simulation Denis Barthou, Gilbert Grosdidier, Konstantin Petrov, Michael Kruse, Christine Eisenbeis, Olivier Pène, Olivier Brand-Foissac, Claude Tadonki, Romain Dolbeau To cite this version: Denis Barthou, Gilbert Grosdidier, Konstantin Petrov, Michael Kruse, Christine Eisenbeis, et al.. Automated Code Generation for Lattice QCD Simulation. [Research Report] University of Bordeaux, University of Paris Sud, INRIA, University of Paris Sud, Mines ParisTech, CAPS Entreprise. 2016. hal-01433302 HAL Id: hal-01433302 https://hal-mines-paristech.archives-ouvertes.fr/hal-01433302 Submitted on 12 Jan 2017 HAL is a multi-disciplinary open access archive for the deposit and dissemination of scientific research documents, whether they are published or not. The documents may come from teaching and research institutions in France or abroad, or from public or private research centers. L’archive ouverte pluridisciplinaire HAL, est destinée au dépôt et à la diffusion de documents scientifiques de niveau recherche, publiés ou non, émanant des établissements d’enseignement et de recherche français ou étrangers, des laboratoires publics ou privés. Automated Code Generation for Lattice QCD Simulation Denis Barthou*, Gilbert Grosdidier†, Konstantin Petrov‡, Michael Kruse‡ Christine Eisenbeis§, Olivier Pène§, Olivier Brand- Foissac§, Claude Tadonki§, Romain Dolbeau∥ °University of Bordeaux LaBRI / INRIA Bordeaux Sud-Ouest firstname.name@inria.fr ‡University of Paris Sud Laboratoire de l’Accelerateur Lineaire firstname.name@lal.fr §University of Paris Sud Laboratory of Theoretical Physics firstname.name@lpt.fr ∥University of Bordeaux Laboratoire de l’Accelerateur Lineaire firstname.name@lal.fr University of Paris Sud Laboratory of Theoretical Physics firstname.name@lpt.fr In a context of fast moving parallel architectures, the design of an optimized LQCD simulation, and in particular of an efficient inversion function is complex. This requires to design, select and combine iterative methods and preconditioners adapted to the problem and the target architecture, to optimize data layout and organize parallelism between nodes, cores, accelerators and SIMD units. In order to harness all resources of the hardware, orchestrating the work on many cores and accelerators, using different levels of parallelism, complex memory hierarchies and interconnect networks takes a large part of the tuning time, often at the expense of the exploration of new algorithms/preconditioners. Indeed, testing new methods can only be achieved with large enough data sets, requiring efficient parallel codes. Several codes and libraries have been designed for Lattice QCD (tmLQCD [10] as part of the European Twisted Mass Collaboration or Chroma [9] as part of the USQCD effort to name a few) and many works have been proposed on code optimization for Lattice QCD, among them recent works on Blue Gene/Q [7], Intel Xeon Phi [12] or clusters of GPUs [11]. While taking architectural features into account is crucial for high performance simulations, the key to exascale simulations also lies in new algorithms, new data layouts and communication patterns. However, designing new iterative methods, combining existing ones, changing data layout within these frameworks and tools is difficult and requires a significant code rewriting effort. This clearly hinders the adaptation of code to new parallel machines, limiting performance and the expected scientific results. This paper proposes a domain-specific language (DSL), QIRAL, for the description of Lattice QCD simulations, and its compiler to generate parallel code. A domain-specific language can help to separate the high level aspects of the simulation from machine-dependent issues. The contribution of QIRAL is to address this twofold challenge: - Propose to physicists a domain-specific language expressive enough to enable the description of different models and algorithms, and more importantly, expressive enough to enable algorithmic exploration by composing different algorithms and preconditioners as well as the design of new algorithms. - Generate from this description efficient codes for parallel machines. Explicit parallelism and data layout are automatically generated and can be guided by the user. The code generated by QIRAL targets shared memory parallel machines, corresponding to one node of larger Lattice QCD simulations. This code uses OpenMP and a library for efficient SIMD operations. With a higher level description of the Lattice QCD formulation, it becomes easier to try new algorithmic ideas, the high level code is easier to maintain and develop, and therefore makes numerical simulation accessible to a large number of users, not necessarily high performance computing experts. We show Abstract—Quantum Chromodynamics (QCD) is the theory of strong nuclear force, responsible of the interactions between sub-nuclear particles. QCD simulations are typically performed through the lattice gauge theory approach, which provides a discrete analytical formalism called LQCD (Lattice Quantum Chromodynamics). LQCD simulations usually involve generating and then processing data on petabyte scale which demands multiple teraflop-years on supercomputers. Large parts of both, generation and analysis, can be reduced to the inversion of an extremely large matrix, the so-called Wilson-Dirac operator. For this purpose, and because this matrix is always sparse and structured, iterative methods are definitely considered. Therefore, the procedure of the application of this operator, resulting in a vector-matrix product, appears as a critical computation kernel that should be optimized as much as possible. Evaluating the Wilson-Dirac operator involves symmetric stencil calculations where each node has 8 neighbors. Such configuration is really hindering when it comes to memory accesses and data exchanges among processors. For current and future generation of supercomputers the hierarchical memory structure make it next to impossible for a physicist to write an efficient code. Addressing these issues in other to harvest an acceptable amount of computing cycles for the real need, which means reaching a good level of efficiency, is the main concern of this paper. We present here a Domain Specific Language and corresponding toolkit, called QIRAL, which is a complete solution from symbolic notation to simulation code. I. INTRODUCTION In a context of fast moving parallel architectures, the design of an optimized LQCD simulation, and in particular of an efficient inversion function is complex. This requires to design, select and combine iterative methods and preconditioners adapted to the problem and the target architecture, to optimize data layout and organize parallelism between nodes, cores, accelerators and SIMD units. In order to harness all resources of the hardware, orchestrating the work on many cores and accelerators, using different levels of parallelism, complex memory hierarchies and interconnect networks takes a large part of the tuning time, often at the expense of the exploration of new algorithms/preconditioners. Indeed, testing new methods can only be achieved with large enough data sets, requiring efficient parallel codes. Several codes and libraries have been designed for Lattice QCD (tmLQCD [10] as part of the European Twisted Mass Collaboration or Chroma [9] as part of the USQCD effort to name a few) and many works have been proposed on code optimization for Lattice QCD, among them recent works on Blue Gene/Q [7], Intel Xeon Phi [12] or clusters of GPUs [11]. While taking architectural features into account is crucial for high performance simulations, the key to exascale simulations also lies in new algorithms, new data layouts and communication patterns. However, designing new iterative methods, combining existing ones, changing data layout within these frameworks and tools is difficult and requires a significant code rewriting effort. This clearly hinders the adaptation of code to new parallel machines, limiting performance and the expected scientific results. This paper proposes a domain-specific language (DSL), QIRAL, for the description of Lattice QCD simulations, and its compiler to generate parallel code. A domain-specific language can help to separate the high level aspects of the simulation from machine-dependent issues. The contribution of QIRAL is to address this twofold challenge: - Propose to physicists a domain-specific language expressive enough to enable the description of different models and algorithms, and more importantly, expressive enough to enable algorithmic exploration by composing different algorithms and preconditioners as well as the design of new algorithms. - Generate from this description efficient codes for parallel machines. Explicit parallelism and data layout are automatically generated and can be guided by the user. The code generated by QIRAL targets shared memory parallel machines, corresponding to one node of larger Lattice QCD simulations. This code uses OpenMP and a library for efficient SIMD operations. With a higher level description of the Lattice QCD formulation, it becomes easier to try new algorithmic ideas, the high level code is easier to maintain and develop, and therefore makes numerical simulation accessible to a large number of users, not necessarily high performance computing experts. We show... on several architectures, from Nehalem-EX with 128 cores to the Xeon Phi accelerator that the code generated with QIRAL competes in terms of parallel efficiency and performance with tmLQCD, while QIRAL provides an easier framework for the writing of algorithms and the adaptation to new architectures. This paper is organized as follows: first we describe the DSL in Section II, describe the high-level compiler in Section III. Then the optimizations for locality, parallelism and SIMDization are presented in Section IV. Comparisons with related works are in Section V and experimental results, comparing with tmLQCD and describing strong scalability are shown in Section VI. The whole project, under the name PetaQCD [1], was partly funded by a grant from ANR, through the program COSINUS-2008, from 2009 up to 2011. II. THE QIRAL DOMAIN-SPECIFIC LANGUAGE As one of the purposes of the QIRAL DSL is to give scientists a familiar tool to describe the problem in scope, it makes sense to take an existing system of symbolic notation as the basic language. There are two such systems in most disciplines, LATEX and Mathematica. While we are not attached to a particular one, we chose to use LATEX-like syntax where certain additional macros have been defined. Therefore the QIRAL description can be processed either using the QIRAL compiler to produce program source code or alternatively, by the LATEXtypesetter to produce its documentation, as shown in Figure 1. This means we revive the principle of literate programming coined by Donald Knuth [13]. For instance, the algorithm in Figure 4 is a QIRAL program included into this document as processed by LATEX. The description of the language given in the following complements a description previously presented by the author’s [4]. QIRAL is an array language for linear algebra, dedicated to the manipulation of sparse matrices defined through tensor products and direct sums of dense matrices as they appear in Lattice QCD. The language relies on specificities of Lattice QCD: the inversion computation is a stencil computation, on a regular, 4D Cartesian mesh (the lattice). The Dirac operator, used for this inversion, is a sparse but regularly structured matrix that can be seen as a diagonal of dense matrices. This operator transforms values from the lattice into new values. These values are made of 12 complex values, indexed by their spin (4 indices) and color (3 indices). Hence for a $24^4 \times 48$ lattice, the Dirac operator is a matrix of $(24^4 \times 48 \times 12)^2$ complex values. As it is sparse, its structure carries the parallelism of the computation, hence the language and the compiler captures this structure through the operators building the matrix. Elements of the language are declarations, equations, algorithms and the goal. Declarations declare symbols and properties. Equations are used to define variables or functions. Figures 2 and 3 describe nearly all properties and definitions on the Dirac operator, and the definition of Dirac operator as a matrix. The two other matrices, $P_e$ and $P_o$ are projections, keeping only black or white elements of the lattice, like a 4D checkerboard. Constant: $$\begin{align*} \text{Dirac}, P_e, P_o, \gamma_5 & \in M, \\ L, S, C, \text{even} & \in \text{Index set}, \\ \gamma & \in \text{Index} - > M, \\ U & \in \text{Index} - > M, \\ \kappa, \mu & \in \mathbb{R}, \\ D & \in \text{Index set} \end{align*}$$ Variable: $s \in \text{Index}, d \in \text{Index}$ $$\begin{align*} \text{Dirac} &= I_{L \otimes C \otimes S} + 2 * i * \kappa * \mu * I_{L \otimes C} \otimes \gamma_5 \\ &+ - \kappa * \sum_{d \in D} ((J_L^d \otimes I_C) \otimes \bigoplus_{s \in L} U[s \otimes d]) \otimes (I_S - \gamma[d]) \\ &+ - \kappa * \sum_{s \in L} ((J_L^s \otimes I_C) \otimes \bigoplus_{d \in D} U[s \otimes -d]) \otimes (I_S + \gamma[d]) \end{align*}$$ $$\begin{align*} P_e &= P_{\text{even},L} \otimes I_{C \otimes S} \\ P_o &= P_{\text{even},L} \otimes I_{C \otimes S} \end{align*}$$ Fig. 2. Definitions of the Dirac matrix on a Lattice $L$ in QIRAL, and the two projections for even and odd elements ($P_e$ and $P_o$ respectively) of this lattice. Equations are used to define variables or functions. Figure 3 describes nearly all properties and definitions on the constant and functions used for the simulation. For instance, the function “invertible” is defined for only some expressions. Algorithms are given as possible definitions for statements or expressions. For instance, the conjugate gradient algorithm in Figure 4 provides the code that compute expressions of the form $x = A^{-1} * b$, when $A$ and $b$ are given. It outputs the value of $x$, i.e. solve the linear system $Ax = b$. ![Diagram of QIRAL compiler](image) compute for instance A literature. The QIRAL compiler finds automatically how to for Lattice QCD or any other algorithm found in common QCD. The user has the possibility to write new algorithms. **Constant:** \[ dx, dy, dz, dt \in \text{Index} \] \[ D = \{dx, dy, dz, dt\} \] isPeriodic(L) = true \[ U[s \otimes d] = U[(s + d) \otimes -d] \] \[ U[s \otimes -d] = U[(s + d) \otimes d] \] Preconditioner1(\text{Dirac}) = Po Preconditioner2(\text{Dirac}) = Pp \[ \gamma[d] = \gamma[d] \] \[ \gamma_5 \gamma_5 \gamma_5 = \text{true} \] \[ \text{invertible}(I_S + c \gamma_5) = \text{true} \] \[ \text{invertible}(I_S - c \gamma_5) = \text{true} \] \[ \text{invertible}(-c(I_S + i \gamma_5)) = \text{true} \] \[ \gamma_v^\dagger = \gamma_5 \] \[ \text{type}(\gamma[d]) = S \times S \] \[ \text{type}(U[s \otimes d]) = C \times C \] \[ \text{type}(\gamma_5) = S \times S \] \[ \text{vol}(S) = 4 \] \[ \text{vol}(C) = 3 \] The QIRAL compiler determines the type of local variables. This algorithm is written using the “algorithm2e” package in \LaTeX, and is not specific to Lattice QCD. The user has the possibility to write new algorithms for Lattice QCD or any other algorithm found in common literature. The QIRAL compiler finds automatically how to compute for instance \( A \ast p \) when \( A \) is instantiated with the Dirac operator. Most often the validity of an algorithm depends on prerequisites, special properties the inputs must have. These prerequisites are declared in a clause \textbf{Require} and is proved by the QIRAL compiler. The following example illustrates this prerequisite mechanism. Figure 5 describes the Schur complement method that is used as a preconditioner for the conjugate gradient. The condition invertible(\( P_e \ast A \ast P_o \)) is proved automatically by the compiler when \( A \) matches the matrix \textit{Dirac}. To prove this, the property defined previously for the function “invertible” is used. If the compiler is not able to prove the requirements attached to an algorithm, the algorithm is not applied and an error is generated. Notice that on this preconditioning, the statements involve computation of inverse matrices. For the expression \( D_{11}^{-1} \), the QIRAL compiler can prove automatically that \( D_{11} \) is diagonal (when \( A \) is the Dirac operator), and knows how to invert this matrix. For the computation of the expression \( (D_{22} - D_{21} \ast D_{11}^{-1} \ast D_{12})^{-1} \), an iterative method has to be applied. The goal defines the initial code and the list of algorithms to apply. The algorithms are composed from right to left. **Input:** \( A, P_e, P_o \in M, b \in V \) **Output:** \( x \in V \) **Constant:** \( D_{11}, D_{12}, D_{21}, D_{22} \in M \) **Var:** \( v_1, v_2, x_1, x_2 \in V \) **Require:** invertible(\( P_e \ast A \ast P_o \)) \[ D_{21} = P_o \ast A \ast P_o \] \[ D_{11} = P_e \ast A \ast P_e \] \[ D_{22} = P_e \ast A \ast P_o \] \[ D_{12} = P_e \ast A \ast P_o \] \[ v_1 = P_o \ast b \] \[ v_2 = P_o \ast b \] \[ x_2 = (D_{22} - D_{21} \ast D_{11}^{-1} \ast D_{12})^{-1} \ast (v_2 - D_{21} \ast D_{11}^{-1} \ast v_1) \] \[ v_1 = P_e \ast (2 \ast k \ast b) \] \[ x_1 = D_{11}^{-1} \ast (v_1 - D_{12} \ast x_2) \] \[ x = P_o \ast x_1 + P_o \ast x_2 \] **Fig. 5.** Definition of Schur complement method. The initial statement, in the \textbf{Match} clause, is then defined (and replaced) by the pseudo-code. The \textbf{Var} keyword declares the type of local variables. This algorithm is written using the “algorithm2e” package in \LaTeX, and is not specific to Lattice QCD. The user has the possibility to write new algorithms for Lattice QCD or any other algorithm found in common literature. The QIRAL compiler finds automatically how to compute for instance \( A \ast p \) when \( A \) is instantiated with the Dirac operator. The \textbf{Input} and \textbf{Output} are defined. The \textbf{Constant} and \textbf{Match} clauses define the data types and variables to be used. The \textbf{Var} clause declares variables, and the \textbf{Require} clause specifies the requirements for the algorithm to be applied. For this goal here the preconditioner \textbf{schur} is applied on the initial statement, and then the CGNR algorithm. It is possible to chain multiple algorithms, used to apply preconditions before the solvers. The index set \( L \otimes C \otimes S \) represents the Cartesian product of these sets and the domain for the vector \( bb \). At this level, there is no implicit data layout for vectors and matrices. The vector \( bb \) could be either a 4D array of structures, one dimension for each dimension of \( L \) and the structure representing elements indexed by \( C \) and \( S \), or a 1D array of structures, or just a large 1D array of complex values. This is orthogonal to the expression of the algorithm. The output of QIRAL compiler is a function in C and OpenMP pragmas representing the computation described in the goal, and taking as parameters \( bb \) and \( xx \). All other constant **Fig. 4.** Conjugate Gradient, normal residual method (CGNR). values (in particular constant matrices) are assumed to be global. III. IMPLEMENTATION DETAILS The QIRAL compiler is based on a rewriting system, Maude [6]. The different steps of this transformation are explained in this section. A. Algorithms composition and expression simplification Algorithms are translated into rules of the rewriting system, while equations define the equational theory for the rewriting system. The first step consists in transforming $\text{LiFiXinput}$ into a Maude program. Additional modules, defining usual algebraic simplifications are added to this code. The first step parses the $\text{LiFiXinput}$ and captures only what is described in predefined environments, for algorithms, definitions and the goal. Syntactic verification as well as type checking is performed. The output generated is a Maude module, with equations corresponding to definitions, rules corresponding to algorithms, and an unique Maude statement, corresponding to the goal. The algorithms declared in the goal are applied, in turn, to the statements provided. These statements are terms for Maude. The Match clause is the left-hand side (lhs) of the rule, while the pseudo-code corresponds to a term that is the right-hand side (rhs) of the rule. Any statement matching the lhs will then be rewritten in the rhs. In order to identify this match, Maude unifies the input variables of the lhs with the real values, corresponding to the binding of the formal parameters of the actual function parameters of a function call. If a Require clause exists, it constitutes the condition for the rewriting. The first statement is provided by the goal, then algorithms are applied successively. Definitions and properties are considered by Maude as defining the equational theory for the rewriting system. Actually, these equations are handled as automatic rewriting rules: Maude automatically applies all possible equations, rewriting their lhs into rhs, until the term is normalized. For instance, the property $x * (y + z) = x * y + x * z$, stating the distributivity of + over *, will only be used to distribute the operators, not to factorize terms. The main objective of this formal rewriting is to eliminate all terms that are equal to zero. In Lattice QCD, the Dirac matrix used in the problem is sparse, but built from dense matrices with a regular structure. To obtain such simplifications, an additional module defines properties for the linear algebra operators, on complex, vectors and matrices: Addition is commutative and associative, multiplication is associative and distributes over the addition, binary subtraction is converted to unary minus, transposition distributes over the addition and multiplication, etc. Moreover, some properties are also defined for permutation and projection matrices, in particular to handle Schur preconditioning. B. Generating Element-wise Computation The term obtained after the first application and simplification step still manipulates matrices and vectors representing the whole lattice. Parallel loops are generated to iterate over the lattice component of the index sets used by all vectors. The different phases of the QIRAL compilation are driven by meta-rewriting rules. The user here can change the parameters for the compiler and choose for instance 4D iterators of the domain (building one loop for each dimension of $L$), 1D iterator (linearized space) or any combination, performing tiling for instance. For this, the user has to indicate in the properties that the lattice is decomposed into sub-lattices: $$L = L_1 \otimes L_2$$ where $L_1$ and $L_2$ are two index sets. $L_2$ represents then sub-lattices and $L_1$ is the iteration domain, iterating through these different blocks. The generation of loops for Lattice QCD is straightforward, as all array statements are parallel. All such loops are therefore parallel, possibly nested. Parallelism is expressed through OpenMP. C. Open Issues A number of difficulties may arise during this high level compilation step, since the range of properties and algorithms that can be described is not limited. - Convergence: the properties the user define have to form a convergent rewriting system. For instance if the properties $x * (y + z) = x * y + x * z$ and $x * y + x * z = x * (y + z)$ are simultaneously present, the compiler is unable to know which one to apply (no priority). Maude is not able to detect such situation. For algorithms, preconditions, there is no such issue since the user defines the sequence of algorithms to apply. - Confluence: this only concerns properties and definitions. Confluence means that any order of application of the properties leads to the same resulting term. Some recent works [2], [8] have shown that this can be checked automatically. The impact is that depending on the order of the properties given by the user, there is a risk the code generated is not the same. This has not occurred in QIRAL so far. These two limitations are therefore more theoretical than practical. More work though has to be done in order to provide a high quality development environment to users, in particular for the identification of the reasons why an algorithm cannot be applied to a particular code (the requirements are not fulfilled). IV. CODE OPTIMIZATIONS Once parallel loops are generated, several code optimizations are applied. These transformations are also described in the rewriting system, with built-in modules of QIRAL, in a similar way to a compiler such as Stratego [20]. Current optimizations range from loop transformations, versioning and data layout. The output of this phase is a C-code with OpenMP. A. Improving Locality Loops fusion is a transformation to reduce reuse distances, hence improving locality. To check if fusion is valid, a simple dependence analysis, based on dependence distance, is computed. The fusion method is applied on consecutive independent loops that share the same iterators, and is applied on all code until no more fusion is possible. This simple strategy is sufficient for Lattice QCD generated codes. Following this fusion, the regions of arrays that are written/read by all loops, and the regions that are inputs/outputs of loops are computed. All arrays that are used only in one loop are scalar promoted. The resulting values are allocated on the stack, and aligned for further vectorization. This reduces memory consumption. Both transformations are applied automatically. B. Versioning Matrix Multiplication The computation involve many multiplications of vectors by constant matrices, accounting for transformations on spin and color (S and C index sets respectively). These matrices are small, of size $3 \times 3$ and $4 \times 4$ respectively, and the latest have only 2 non-null elements per line, these elements being among $\{1, -1, i, -i\}$. Therefore specialization of these product is necessary in order to obtained better performance. These matrix-vector multiplications appear in expressions of the form $(M_1 \otimes M_2) \cdot V$ with $M_1$ and $M_2$ the two matrices multiplied by a tensor product, and $V$ is a 12 element vector. In this case the QIRAL compiler uses the identity $$(M_1 \otimes M_2) \cdot V = M_1 \cdot V \cdot M_2^t$$ where on the lhs, $V$ is considered a matrix of size $3 \times 4$ and $\ast$ stands for the matrix product. Therefore, instead of using general matrix multiplication, QIRAL compiler finds these occurrences and calls versioned matrix multiplications. Specializing such multiplications for these particular sizes, in particular performing SIMDization, is essential for performance. These functions correspond to the hot-spot of the codes generated by QIRAL. The codes of these functions are hand-written in libqiral library as presented in Figure 1. Other expressions can be replaced by library calls, and QIRAL changes expressions on vectors and matrices into BLAS calls (or specialized BLAS). The fact that the QIRAL compiler automatically identifies these functions in the code generated from the different algorithms facilitates the optimization process and is an asset of QIRAL. The optimization of these functions in libqiral, specializations of BLAS, can indeed be achieved by an expert in high-performance computing, independent of any Lattice QCD context. C. Optimizing Data layout and Iterators The choice of data layout is essential for performance. The dimensionality of the data structures (how many dimensions to the array) and the temporal locality loosely depend on the way the index domains are iterated. In QIRAL, loop iterators and number of loops are selected according to the transformation on data layout to achieve. Three different transformations are explored by the QIRAL compiler. Tiling is a well established approach to reduce the overhead impact of memory accesses or inter-node communications. In our code generation framework, tiling can be specified by decomposing the lattice into sub-lattices and iterating in each sub-lattice in turn. As the Lattice QCD computation is an 8 point stencil (2 neighbors in each of the 4 dimensions), tiling leads to spacial reuse of each element read by the stencil, provided the tile fits into the cache. Note that as all loops are initially parallel, by tiling we create innermost sequential loops, and keep the outermost loops parallel. When using an accelerator, tiling is essential for effective and optimal data transfer [18]. An important point here is that for given a tile, we may need to pack the necessary data to proceed with. This is required for instance when we need to distribute the tiles among several processors or threads, or to offload tiled calculation into accelerator units. Another technical aspect, which sounds non-trivial, is the organization of the computation related to the border of the tiles. In most of the cases, data communications occur only between the borders. Consequently, the computation of a tile has to be split into two parts, one for the bulk and another for the border. We should be able to generate code accordingly in future work. Even-odd preconditioning (or Schur complement method) leads to computation on only one element out of 2 in the lattice. These elements are accessed as the white squares of a 4D checkerboard. The QIRAL compiler analyzes the set of elements accessed for each array, and arrays are allocated only for the elements accessed. The loop domains are also redefined accordingly, thus no conditionals are created. Half-lattice arrays are therefore created when even-odd preconditioning is applied. This avoids useless memory strides, improving spacial locality, and reduces the in-memory working-set. Finally, as the lattice is a 4D lattice, 2 options are possible: either vectors are indexed with a 4D index (meaning there are four loops), or their indices are linearized. As the 4D space is a torus, the computation of the index for all the neighbors requires a modulo arithmetic operation. This is simpler with a 4D index than with a 1D linearized index. Both versions can be generated, and combined with tiling or even-odd transformations. Figure 6 shows an example of the code automatically generated by the QIRAL compiler. Note that all statements are calls to functions. The QIRAL compiler has matched expressions with these functions, all corresponding to BLAS functions or specialized BLAS. These functions are implemented in the libqiral library. D. Hand-tuned Optimizations As presented in the previous section, the QIRAL compiler generates code for Lattice QCD that calls dedicated versions of BLAS functions. This versioning is due to constant and simple matrices, special sizes or coefficients. Different versions for these functions are implemented: one corresponds to a naïve C implementation, letting the compiler perform optimizations. This has the advantage of simplifying the port to new architectures. Other versions are obtained by SIMDization of these functions, either through the Intel SPMD Program Compiler (ISPC) [16], or through manually-written code using compiler intrinsics. The compiler ISPC requires adding a few extra keywords to standard C in order to help SIMDization. Back-ends for ISPC are Intel architectures with SSE, AVX, AVX-2 and in future versions, Xeon Phi SIMD. For complex value manipulation, ISPC tries to generate SIMD code with real and imaginary #pragma omp parallel for for(iL = 0 ; iL < L / 2 ; iL += 1) { double complex tmp[12] __attribute__((aligned(0x1000))) ; double complex IDschur9[12] __attribute__((aligned(0x1000))) ; double complex IDschur10[12] __attribute__((aligned(0x1000))) ; xgemmGAMMApdx(& ISchur5[12 * layouteven(sup(idxodd(iL), dx, L))],tmp); xgemmGAMMApdy(& ISchur5[12 * layouteven(sup(idxodd(iL), dy, L))],tmp); xgemmGAMMApdxz(& ISchur5[12 * layouteven(sup(idxodd(iL), dz, L))],tmp); xgemmGAMMApdxz(& ISchur5[12 * layouteven(sup(idxodd(iL), dz, L))],tmp); xcopy(12, IDschur9, IDschur10) ; xscal(12, kappa, IDschur9) ; } Fig. 6. Excerpt of the code generated by the QIRAL compiler for the CGNR algorithm with the Schur preconditioning. parts in different vectors. For complex values allocated contiguously, this requires the use of strided loads and stores (named GATHER and SCATTER in Intel ISA), not available on Sandybridge for instance. Alternatively, complex values can be loaded into the same vectors, storing imaginary and real parts contiguously. Depending on the instruction set, complex multiplication is then implemented either using a shuffle operation, or directly dedicated SIMD instructions. Use of shuffle operations or of these instructions requires on the architectures considered the use of intrinsics. Besides SIMDization, for shared-memory non-uniform (NUMA) architectures, memory allocation has to take into consideration the precise cores that are using this memory. The use of NUMA policy library is a way to distribute memory among the cores, according to their predefined affinity. This hand-optimization is conducted on all structures allocated before the execution of the function generated by QIRAL. V. RELATED WORKS Since it is a heavily CPU time consuming type of application, LQCD was the focus of many developments and papers in the last 15 years. To name a few, some recent works target mostly Intel processors like Chroma [9] on Xeon Phi [12], for a Wilson-Dirac Lagrangian type, or mostly the BlueGene family like tmLQCD [10] on the BlueGene/Q supercomputer [7] with the twisted-mass Lagrangian type. A whole bunch of works also appeared in the last years targeting the GPUs, [11], [5], and the latter are definitely part of our own road map: QIRAL will have a great impact on the GPU coding due to the flexibility it provides, specifically for data-layout. The Spiral language [17] was obviously the precursor of the QIRAL tool and the model for this work on a LQCD-dedicated DSL, specifically designed for sparse matrices with very small conditioning factor. Qiral initial work was described in [4]. It is a multi-disciplinary project [1] merging fruitfully Lattice QCD theory labs like LPT/CNRS, High Energy Physics people like LAL/IN2P3/CNRS and HPC Parallel Computing experts coming from several INRIA teams (Orsay, Bordeaux) and CAPS-Entreprise. Pochoir [19] is also a similar tool targeting at stencils. But while Spiral model was inspiring to QIRAL, the former is only targeting at Signal Line Processing, where the latter is fully managing the algorithm, together with the data layout issues, and this part is crucial to improve computing speed. This new tool will allow theory physicists to propose, validate and evaluate the efficiency of their new algorithms more easily and quickly. It will speedup as well the inversion coding for new types of Lagrangian [14] (Clover [3], Overlap [15], and so on). To summarize, even if the current version is this running on a single node with threads (no MPI), the very huge effort achieved for the data-layout will allow for an easier mixed implementation (MPI-like, OpenMP), and the performances in terms of CPU speed for the global algorithm is very attractive, even for rather large QCD lattices (up to $2^{32}$-node lattice already tested). This is very important, since there was always a huge gap between small and large lattices when comparing their behavior, because this application is both memory-size and memory-bandwidth bound. VI. PERFORMANCE RESULTS The following architectures are used for the experiments: <table> <thead> <tr> <th>Name</th> <th>Processor</th> <th># of cores (hyperthreading)</th> <th>Clock in Ghz</th> </tr> </thead> <tbody> <tr> <td>Nehalem-EX</td> <td>Intel X7560</td> <td>$4 \times 32$ (2)</td> <td>2.26</td> </tr> <tr> <td>SandyBridge1</td> <td>E5-2680</td> <td>16 (2)</td> <td>2.7</td> </tr> <tr> <td>SandyBridge2</td> <td>E5-2687W</td> <td>16 (2)</td> <td>3.1</td> </tr> <tr> <td>Haswell</td> <td>i5-4670T</td> <td>4 (1)</td> <td>2.3</td> </tr> <tr> <td>Xeon Phi</td> <td>SE10P</td> <td>60 (4)</td> <td>1.1</td> </tr> </tbody> </table> The Nehalem-EX and the Sandybridge1 correspond to Curie machines from the TGCC Supercomputer center, Curie Fat and Curie Thin respectively. The same compiler, ICC, is used for the compilation of tmLQCD and QIRAL generated codes. Several iterative methods are written with QIRAL. Figure 7 presents some of these methods, for two architectures: CGNR, CRNE, MCR1 and MCR2 with some preconditioners: Schur and preMCR. We observe that while MCR2 exhibits the best time per iteration, the method takes more time to converge than CGNR and Schur. This shows that the best method cannot be determined only by benchmarking a single iteration, but it is necessary to run all iterations. This justifies the need for an automatic approach to the generation of parallel codes, able to run for large data-sets, in order to compare different methods. Besides, the second plot of Figure 7 shows that the relative difference may vary according to the architecture. While the absolute best method is still the same (here CGNR combined with Schur), this stresses the fact that the algorithmic solution may be chosen depending on the target architecture. In order to compare tmLQCD with the code generated by QIRAL, the same algorithm is used for both (CGNR and Schur preconditioning). Performance is displayed for all architectures as the total execution time multiplied by the number of cores. Due to the fact that tmLQCD is using MPI, there is no version for Xeon Phi. Besides, the tmLQCD code uses in-line assembly code with SSE3 instructions. Adapting this code for newer SIMD extensions is more difficult than adapting intrinsics as used by QIRAL. Indeed for intrinsics, part of the optimization work still relies on the compiler: register allocation, generation of FMAs, scheduling. The code generated by QIRAL has been quickly ported to these architectures, and then code tuning has focused on the library used by QIRAL (with versioned BLAS), using intrinsics and aggressive in-lining. Figure 8 presents timing results on different architectures, comparing tmLQCD code with QIRAL generated code. For QIRAL, the “hand-optimized library” corresponds to the best version obtained, using intrinsics (AVX, AVX2, Xeon Phi) for Sandybridge, Haswell and Xeon Phi architectures. The Nehalem EX version does not use SSE SIMD intrinsics. This explains why QIRAL/Nehalem EX version is more than two times slower than tmLQCD. For Xeon Phi, the performance displayed corresponds to the use of all the 60 cores, and a linear speed-up can be observed by using an increasing number of cores. The ISPC compiler has been used to generate SIMD version of matrix multiplication of size $3 \times 4$ on complexes. The compiler is still in development, does not fully work for Xeon Phi. Figure 8 shows that the level of performance reached with ISPC is not competing with the level for hand-tuned intrinsics. The strong scalability of the code generated by QIRAL is evaluated on Xeon Phi and Nehalem-EX architectures. Figure 9 shows efficiency results for different number of cores. Note that the size of the lattice is different for both architectures, reflecting the need for different granularity. The efficiency for the Xeon Phi is compared to the run on 4 cores, with 4 threads each. This explains why for some number of threads, the efficiency goes beyond 1. The code scales well up to the 60 cores (240 threads). For the Nehalem-EX machine, the efficiency is higher than 95% up to 32 cores, and then drops quickly. The reason is that a 128-core node is structured with 4 groups of 4 octo-cores, connected through a switch. Going through the switch has a high penalty in terms of performance. could be improved. Besides, the fine tuning of the library functions used by QIRAL would enable to run Lattice QCD simulations on a larger scale. A hand-tuned Lattice QCD application, tmLQCD, it compares or outperforms the performance of the Nehalem-EX the efficiency is measured with and without NUMA-aware memory allocation. VII. CONCLUSION The contribution of this paper is a new domain-specific language, QIRAL, for the automatic code generation of OpenMP codes for Lattice QCD simulations. QIRAL language offers to physicists the possibility to implement iterative methods and preconditioners, literally “from the book” using L, or design new ones, and test them on large parallel shared memory machines or on accelerators such as the Xeon Phi. The language enables the composition of preconditioners and iterative methods, and the compiler checks automatically the validity of application for each method. This makes possible a more systematic exploration of the algorithmic space: indeed, it removes from the physicists the burden of long and stressful validations of their new code since it will be automatically generated, then safer, and the time-to-market for a viable product will be much shorter. The QIRAL compiler generates OpenMP parallel code using BLAS or specialized versions of BLAS functions. Further hand-tuning is possible on the code generated by QIRAL, and we have shown that the performance on various multi-core architectures and on Xeon Phi accelerator it compares or outperforms the performance of a hand-tuned Lattice QCD application, tmLQCD. Among the perspectives of this work, the automatic generation of a communication code for multi-node computation would enable to run Lattice QCD simulations on a larger scale. Besides, the fine tuning of the library functions used by QIRAL on different architectures, in particular their SIMDization, could be improved. REFERENCES
{"Source-Url": "https://hal-mines-paristech.archives-ouvertes.fr/hal-01433302/file/E-395.pdf", "len_cl100k_base": 9735, "olmocr-version": "0.1.50", "pdf-total-pages": 9, "total-fallback-pages": 0, "total-input-tokens": 33182, "total-output-tokens": 11786, "length": "2e13", "weborganizer": {"__label__adult": 0.0004475116729736328, "__label__art_design": 0.0005087852478027344, "__label__crime_law": 0.0005006790161132812, "__label__education_jobs": 0.0008487701416015625, "__label__entertainment": 0.000179290771484375, "__label__fashion_beauty": 0.0002589225769042969, "__label__finance_business": 0.0003249645233154297, "__label__food_dining": 0.0005464553833007812, "__label__games": 0.00103759765625, "__label__hardware": 0.0026607513427734375, "__label__health": 0.0008087158203125, "__label__history": 0.0004901885986328125, "__label__home_hobbies": 0.00016748905181884766, "__label__industrial": 0.0012598037719726562, "__label__literature": 0.00031256675720214844, "__label__politics": 0.0005483627319335938, "__label__religion": 0.0009598731994628906, "__label__science_tech": 0.403076171875, "__label__social_life": 0.00016260147094726562, "__label__software": 0.0123443603515625, "__label__software_dev": 0.57080078125, "__label__sports_fitness": 0.000568389892578125, "__label__transportation": 0.0009760856628417968, "__label__travel": 0.0002703666687011719}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 45971, 0.02783]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 45971, 0.51458]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 45971, 0.85256]], "google_gemma-3-12b-it_contains_pii": [[0, 1195, false], [1195, 9473, null], [9473, 14240, null], [14240, 19369, null], [19369, 25244, null], [25244, 31782, null], [31782, 36880, null], [36880, 40197, null], [40197, 45971, null]], "google_gemma-3-12b-it_is_public_document": [[0, 1195, true], [1195, 9473, null], [9473, 14240, null], [14240, 19369, null], [19369, 25244, null], [25244, 31782, null], [31782, 36880, null], [36880, 40197, null], [40197, 45971, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 45971, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 45971, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 45971, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 45971, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 45971, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 45971, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 45971, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 45971, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 45971, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 45971, null]], "pdf_page_numbers": [[0, 1195, 1], [1195, 9473, 2], [9473, 14240, 3], [14240, 19369, 4], [19369, 25244, 5], [25244, 31782, 6], [31782, 36880, 7], [36880, 40197, 8], [40197, 45971, 9]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 45971, 0.03256]]}
olmocr_science_pdfs
2024-11-28
2024-11-28
35c949d21083b08ee1665808bf5e90097a17086c
[REMOVED]
{"Source-Url": "https://www.cqse.eu/fileadmin/content/news/publications/2011-on-the-extent-and-nature-of-software-reuse-in-open-source-java-projects.pdf", "len_cl100k_base": 9041, "olmocr-version": "0.1.49", "pdf-total-pages": 16, "total-fallback-pages": 0, "total-input-tokens": 37946, "total-output-tokens": 10200, "length": "2e13", "weborganizer": {"__label__adult": 0.0003619194030761719, "__label__art_design": 0.00025463104248046875, "__label__crime_law": 0.0003151893615722656, "__label__education_jobs": 0.0007023811340332031, "__label__entertainment": 4.464387893676758e-05, "__label__fashion_beauty": 0.0001188516616821289, "__label__finance_business": 0.00017786026000976562, "__label__food_dining": 0.000263214111328125, "__label__games": 0.00045013427734375, "__label__hardware": 0.0004253387451171875, "__label__health": 0.0002911090850830078, "__label__history": 0.0001538991928100586, "__label__home_hobbies": 5.012750625610352e-05, "__label__industrial": 0.00018155574798583984, "__label__literature": 0.0002007484436035156, "__label__politics": 0.000194549560546875, "__label__religion": 0.00031828880310058594, "__label__science_tech": 0.0031585693359375, "__label__social_life": 7.94529914855957e-05, "__label__software": 0.0048828125, "__label__software_dev": 0.98681640625, "__label__sports_fitness": 0.00020635128021240232, "__label__transportation": 0.0002760887145996094, "__label__travel": 0.00013709068298339844}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 43981, 0.04144]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 43981, 0.65348]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 43981, 0.91682]], "google_gemma-3-12b-it_contains_pii": [[0, 2706, false], [2706, 5521, null], [5521, 7928, null], [7928, 9693, null], [9693, 13169, null], [13169, 16547, null], [16547, 19345, null], [19345, 22415, null], [22415, 25489, null], [25489, 26185, null], [26185, 29028, null], [29028, 31573, null], [31573, 34780, null], [34780, 38087, null], [38087, 41214, null], [41214, 43981, null]], "google_gemma-3-12b-it_is_public_document": [[0, 2706, true], [2706, 5521, null], [5521, 7928, null], [7928, 9693, null], [9693, 13169, null], [13169, 16547, null], [16547, 19345, null], [19345, 22415, null], [22415, 25489, null], [25489, 26185, null], [26185, 29028, null], [29028, 31573, null], [31573, 34780, null], [34780, 38087, null], [38087, 41214, null], [41214, 43981, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 43981, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 43981, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 43981, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 43981, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 43981, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 43981, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 43981, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 43981, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 43981, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 43981, null]], "pdf_page_numbers": [[0, 2706, 1], [2706, 5521, 2], [5521, 7928, 3], [7928, 9693, 4], [9693, 13169, 5], [13169, 16547, 6], [16547, 19345, 7], [19345, 22415, 8], [22415, 25489, 9], [25489, 26185, 10], [26185, 29028, 11], [29028, 31573, 12], [31573, 34780, 13], [34780, 38087, 14], [38087, 41214, 15], [41214, 43981, 16]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 43981, 0.26519]]}
olmocr_science_pdfs
2024-11-26
2024-11-26
aa857703b7dc8c5739c9fdee700c808837d1570d
When Testing Meets Code Review Why and How Developers Review Tests Spadini, Davide; Aniche, Mauricio; Storey, Margaret-Anne; Bruntink, Magiel; Bacchelli, Alberto DOI 10.1145/3180155.3180192 Publication date 2018 Document Version Accepted author manuscript Published in Proceedings of the 40th International Conference on Software Engineering, ICSE '18 Citation (APA) Important note To cite this publication, please use the final published version (if applicable). Please check the document version above. Copyright Other than for strictly personal use, it is not permitted to download, forward or distribute the text or part of it, without the consent of the author(s) and/or copyright holder(s), unless the work is under an open content license such as Creative Commons. Takedown policy Please contact us and provide details if you believe this document breaches copyrights. We will remove access to the work immediately and investigate your claim. Davide Spadini, Maurício Aniche, Margaret-Anne Storey, Magiel Bruntink, Alberto Bacchelli Report TUD-SERG-2018-004 Acknowledgments. This project has received funding from the European Unions’ Horizon 2020 research and innovation programme under the Marie Sklodowska-Curie grant agreement No. 642954 and the Swiss National Science Foundation through the SNF Project No. PP00P2 170529. Davide Spadini Delft University of Technology Software Improvement Group Delft, The Netherlands d.spadini@sig.eu Mauricio Aniche Delft University of Technology Delft, The Netherlands m.f.aniche@tudelft.nl Margaret-Anne Storey University of Victoria Victoria, BC, Canada mstorey@uvic.ca Magiel Brun tink Software Improvement Group Amsterdam, The Netherlands m.bruntink@sig.eu Alberto Bacchelli University of Zurich Zurich, Switzerland bacchelli@ifi.uzh.ch ABSTRACT Automated testing is considered an essential process for ensuring software quality. However, writing and maintaining high-quality test code is challenging and frequently considered of secondary importance. For production code, many open source and industrial software projects employ code review, a well-established software quality practice, but the question remains whether and how code review is also used for ensuring the quality of test code. The aim of this research is to answer this question and to increase our understanding of what developers think and do when it comes to reviewing test code. We conducted both quantitative and qualitative methods to analyze more than 300,000 code reviews, and interviewed 12 developers about how they review test files. This work resulted in an overview of current code reviewing practices, a set of identified obstacles limiting the review of test code, and a set of issues that developers would like to see improved in code review tools. The study reveals that reviewing test files is very different from reviewing production files, and that the navigation within the review itself is one of the main issues developers currently face. Based on our findings, we propose a series of recommendations and suggestions for the design of tools and future research. CCS CONCEPTS • Software and its engineering → Software testing and debugging; KEYWORDS software testing, automated testing, code review, Gerrit Permission to make digital or hard copies of all or part of this work for personal or classroom use is granted without fee provided that copies are not made or distributed for profit or commercial advantage and that copies bear this notice and the full citation on the first page. Copyrights for components of this work owned by others than the author(s) must be honored. Abstracting with credit is permitted. To copy otherwise, or republish, to post on servers or to redistribute to lists, requires prior specific permission and/or a fee. Request permissions from permissions@acm.org. ICSE ’18, May 27–June 3, 2018, Gothenburg, Sweden © 2018 Copyright held by the owner/author(s). Publication rights licensed to Association for Computing Machinery. ACM ISBN 978-1-4503-5638-1/18/05... https://doi.org/10.1145/3180155.3180192 1 INTRODUCTION Automated testing has become an essential process for improving the quality of software systems [15, 31]. Automated tests (hereafter referred to as just ‘tests’) can help ensure that production code is robust under many usage conditions and that code meets performance and security needs [15, 16]. Nevertheless, writing effective tests is as challenging as writing good production code. A tester has to ensure that test results are accurate, that all important execution paths are considered, and that the tests themselves do not introduce bottlenecks in the development pipeline [15]. Like production code, test code must also be maintained and evolved [49]. As testing has become more commonplace, some have considered that improving the quality of test code should help improve the quality of the associated production code [21, 47]. Unfortunately, there is evidence that test code is not always of high quality [11, 49]. Vazhabzadeh et al. showed that about half of the projects they studied had bugs in the test code [46]. Most of these bugs create false alarms that can waste developer time, while other bugs cause harmful defects in production code that can remain undetected. We also see that test code tends to grow over time, leading to bloat and technical debt [49]. As code review has been shown to improve the quality of source code in general [12, 38], one practice that is now common in many development projects is to use Modern Code Review (MCR) to improve the quality of test code. But how is test code reviewed? Is it reviewed as rigorously as production code, or is it reviewed at all? Are there specific issues that reviewers look for in test files? Does test code pose different reviewing challenges compared to the review of production code? Do some developers use techniques for reviewing test code that could be helpful to other developers? To address these questions and find insights about test code review, we conducted a two-phase study to understand how test code... code is reviewed, to identify current practices and reveal the challenges faced during reviews, and to uncover needs for tools and features that can support the review of test code. To motivate the importance of our work, we first investigated whether being a test changes the chances of a file to be affected by defects. Having found no relationship between type of file and defects, then in the first phase, we analyzed more than 300,000 code reviews related to three open source projects (Eclipse, OpenStack and Qt) that employ extensive code review and automated testing. In the second phase, we interviewed developers from these projects and from a variety of other projects (from both open source and industry) to understand how they review test files and the challenges they face. These investigations led to the following research contributions: (1) To motivate our study, we first explored whether the type of code (production or test) is associated with future defects. Our results show that there is no association, which suggests that test files are no less likely to have defects in the future and should benefit from code review. (2) We investigated how test code is reviewed and found empirical evidence that test files are not discussed as much as production files during code reviews, especially when test code and production code are bundled together in the same review. When test files are discussed, the main concerns include test coverage, mocking practices, code maintainability, and readability. (3) We discovered that developers face a variety of challenges when reviewing test files, including dealing with a lack of testing context, poor navigation support within the review, unrealistic time constraints imposed by management, and poor knowledge of good reviewing and testing practices by novice developers. We discuss recommendations for practitioners and educators, and implications for tool designers and researchers. (4) We created GerritMiner, an open source tool that extracts code reviews from projects that use Gerrit. When performing a review, GerritMiner provides information regarding files, comments, and reviewers. We designed this tool to help us collect a dataset of 654,570 code reviews from three popular open source, industry-supported software systems. GerritMiner and the dataset we studied are publicly available [7]. 2 BACKGROUND AND MOTIVATION Past research has shown that both test code and production code suffer from quality issues [11, 32, 49]. We were inspired by the study by Vahabzadeh et al. [46] who showed that around half of all the projects they studied had bugs in the test code, and even though the vast majority of these test bugs were false alarms, they negatively affected the reliability of the entire test suite. They also found that other types of test bugs (silent horrors) may cause tests to miss important bugs in production code, creating a false sense of security. This study also highlighted how current bug detection tools are not tailored to detect test bugs [46], thus making the role of effective test code review even more critical. Some researchers have examined MCR practices and outcomes and showed that code review can improve the quality of source code. For example, Bacchelli et al. [12] interviewed Microsoft developers and found that code reviews are important not only for finding defects or improving code, but also for transferring knowledge, and for creating a bigger and more transparent picture of the entire system. McIntosh et al. [30] found that both code review coverage and participation share a significant link with software quality, producing components with up to two and five additional post-release defects, respectively. Thongtanumam et al. [43] evaluated the impact that characteristics of MCR practices have on software quality, studying MCR practices in defective and clean source code files. Di Biase et al. [22] analyzed the Chromium system to understand the impact of MCR on finding security issues, showing that the majority of missed security flaws relate to language-specific issues. However, these studies, as well as most of the current literature on contemporary code review, either focus on production files only or do not explicitly differentiate production from test code. Nevertheless, past literature has shown that test code is substantially different from production code. For instance, van Deursen et al. [21] showed that when refactoring test code, there is a unique set of code smells—distinct from that of production code—because improving test code involves additional test-specific refactoring. Moreover, test files have their own libraries that lead to specific coding practices: for example, Spadini et al. [41] studied a test practice called mocking, revealing that the usage of mocks is highly dependent on the responsibility and the architectural concern of the production class. Furthermore, other literature shows that tests are constantly evolving together with production code. Zaidman et al. [49] investigated how test and production code co-evolve in both open source and industrial projects, and how test code needs to be adapted, cleaned and refactored together with production code. Due to the substantial differences between test code and production code, we hypothesize that how they should be reviewed may also differ. However, even though code review is now widely adopted in both open source and industrial projects, how it is conducted on test files is unclear. We aim to understand how developers review test files, what developers discuss during review sessions, what tools or features developers need when reviewing test files, and what challenges they face. 3 SHOULD TEST FILES BE REVIEWED? Even though previous literature has raised awareness on the prevalence of bugs in test files, such as the work by Vahabzadeh et al. [46], it may well be that these type of bugs constitute such a negligible number compared to defects found in production code that investing resources in reviewing them would not be advisable. If test code tends to be less affected by defects than production code, pragmatic developers should focus their limited time on reviewing production code, and research efforts should support this. To motivate our research and to understand whether test code should be reviewed at all, we conducted a preliminary investigation to see whether test and production code files are equally associated with defects. To study this, we used a research method proposed by McIntosh et al. [30] where they analyzed whether code review coverage and participation had an influence on software quality. They built a statistical model using the post-release defect count as a dependent variable and metrics highly correlated with defect-proneness as explanatory variables. They then evaluated the effects of each variable by analyzing their importance in the model [17]. We applied the same idea in our case study: however, as our aim was to understand whether test files are less likely to have bugs than production files, we added the type of file (i.e., either test or production) as an additional explanatory variable. If a difference existed, we would expect the variable to be significant for the model. If the variable was not relevant, a test file should neither increase or decrease increase the likelihood of defects, indicating that test files should be reviewed with the same care as production files (assuming one also cares about defects with tests). Similar to McIntosh et al. [30], we used the three most common families of metrics that are known to have a relationship with defect proneness as control variables, namely product metrics (size), process metrics (prior defects, churn, cumulative churn), and human factors (total number of authors, minor authors, major authors, author ownership). To determine whether a change fixed a defect (our dependent variable), we searched version-control commit messages for co-occurrences of defect identifiers with keywords like ‘bug’, ‘fix’, ‘defect’, or ‘patch’. This approach has been used extensively to determine defect-fixing and defect-inducing changes [27, 28]. We considered the same systems that we used for the main parts of our study (Qt, Eclipse, and Openstack) as they perform considerable software testing and their repositories are available online. Due to the size of their code repositories, we analyzed a sample of sub-projects from each one of them. For Qt and Openstack, we chose the five sub-projects that contained more code reviews: qt, qt3d, qtbase, qtdeclarative, qtwbengine (Qt), and cinder, heat, neutron, nova, and tempest (Openstack). Eclipse, on the other hand, does not use identifiers in commit messages. Therefore, we used the dataset provided by Lam et al. [29] for the Platform sub-project. This dataset includes all the bugs reported in the Eclipse bug tracker tool, together with the corresponding commit hash, files changed, and other useful information. We measured dependent and independent variables during the six-month period prior to a release date in a release branch. We chose the release that gave us at least 18 months of information to analyze. In contrast to McIntosh et al.’s [30] work, we calculated metrics at the file level (not package level) to measure whether the file being test code vs. production code had any effect. We observed that the number of buggy commits was much smaller compared to the number of non-buggy commits, i.e., classes were imbalanced, which would bias the statistical model. Therefore, we applied SMOTE (Synthetic Minority Over-sampling Technique) [18] to make both classes balanced. All R scripts are available in our online appendix [7]. To rank the attributes, we used Weka [6], a suite of machine learning software written in Java. Weka provides different algorithms for identifying the most predictive attributes in a dataset—we chose Information Gain Attribute Evaluation (InfoGainAttributeEval), which has been extensively used in previous literature [9, 26, 40]. InfoGainAttributeEval is a method that evaluates the worth of an attribute by measuring the information gain with respect to the class. It produces a value from 0 to 1, where a higher value indicates a stronger influence. The precision and recall of the resulting model were above 90%, indicating that it is able to correctly classify whether most of the files contain defects, strengthening the reliability of the results. <table> <thead> <tr> <th>Attribute</th> <th>Average merit</th> <th>Average Rank</th> </tr> </thead> <tbody> <tr> <td>Churn</td> <td>0.753 ± 0.010</td> <td>1 ± 0</td> </tr> <tr> <td>Author ownership</td> <td>0.599 ± 0.002</td> <td>2.2 ± 0.4</td> </tr> <tr> <td>Cumulative churn</td> <td>0.588 ± 0.013</td> <td>2.8 ± 0.4</td> </tr> <tr> <td>Total authors</td> <td>0.521 ± 0.001</td> <td>4 ± 0</td> </tr> <tr> <td>Major authors</td> <td>0.506 ± 0.001</td> <td>5 ± 0</td> </tr> <tr> <td>Size</td> <td>0.411 ± 0.027</td> <td>6 ± 0</td> </tr> <tr> <td>Prior defects</td> <td>0.293 ± 0.001</td> <td>7 ± 0</td> </tr> <tr> <td>Minor authors</td> <td>0.149 ± 0.001</td> <td>8 ± 0</td> </tr> <tr> <td>Is test</td> <td>0.085 ± 0.001</td> <td>9 ± 0</td> </tr> </tbody> </table> We ran the algorithm using 10-fold cross-validation. Table 1 shows the results of the importance of each variable in the model as evaluated by InfoGainAttributeEval. The variable is test was consistently ranked as the least important attribute in the model, while Churn, Author ownership, and Cumulative churn were the most important attributes (in that order) for predicting whether a file will likely contain a bug. This is in line with previous literature. From this preliminary analysis, we found that the decision to review a file should not be based on whether the file contains production or test code, as this has no association with defects. Motivated by this result, we conducted our investigation of practices, discussions, and challenges when reviewing tests. 4 RESEARCH METHODOLOGY The main goal of our study is to increase our understanding of how test code is reviewed. To that end, we conducted mixed methods research [19] to address the following research questions: RQ1: How rigorously is test code reviewed? Previous literature has shown that code changes reviewed by more developers are less prone to future defects [35, 38], and that longer discussions between reviewers help find more defects and lead to better solutions [30, 45]. Based on our preliminary study (Section 3) that showed how the type of file (test vs. production) does not change its chances of being prone to future defects, and to investigate the amount of effort developers expend reviewing test code, we measured how often developers comment on test files, the length of these discussions, and how many reviewers check a test file before merging it. RQ2: What do reviewers discuss in test code reviews? In line with Bacchelli & Bird [12], we aimed to understand the concerns that reviewers raise when inspecting test files. Bacchelli & Bird noted that developers discuss possible defects or code improvements, and share comments that help one understand the code or simply acknowledge what other reviewers have shared. We investigated if similar or new categories of outcomes emerge when reviewing test code compared with production code to gather evidence on the key aspects of test file reviews and on the reviewers’ needs when working with this type of artifact. RQ3: Which practices do reviewers follow for test files? Little is known about developer practices when reviewing test files. To identify them, we interviewed developers from the 3 open source projects analyzed in the first two RQs, as well as developers from other projects (including closed projects in industry). We asked them how they review test files and if their practices are different to those they use when reviewing production files. This helped discover review patterns that may guide other reviewers and triangulate reviewers’ needs. **RQ1:** What problems and challenges do developers face when reviewing tests? We elicited insights from our interviews to highlight important issues that both researchers and practitioners can focus on to improve how test code is reviewed. In the following subsections, we discuss the three data collection methods used in this research. Section 4.1 describes the three open source projects we studied and Section 4.2 explains how we extracted quantitative data related to the prevalence of code reviews in test files. Section 4.3 discusses the manual content analysis we conducted on a statistically significant sample of comments pertaining to reviews of test code. Section 4.4 describes the interview procedure used to collect data about practices, challenges, and needs of practitioners when reviewing test files. ### 4.1 Project Selection To investigate what the current practices in reviewing test files are, we aimed at choosing projects that (1) test their code, (2) intensively review their code, and (3) use Gerrit, a modern code review tool that facilitates a traceable code review process for git-based projects [30]. The three projects we studied in our preliminary analysis (discussed in Section 3), match these criteria: Eclipse, Openstack and Qt and we continue to study these projects to answer our research questions. Moreover, these projects are commonly studied in code review research [24, 30, 43]. Table 2 lists their descriptive statistics. #### Table 2: Subject systems’ details after data pre-processing <table> <thead> <tr> <th></th> <th>prod. files</th> <th># of test files</th> <th># of code reviews</th> <th># of reviewers</th> <th># of comments</th> </tr> </thead> <tbody> <tr> <td>Eclipse</td> <td>215,318</td> <td>19,977</td> <td>60,023</td> <td>1,530</td> <td>95,973</td> </tr> <tr> <td>Openstack</td> <td>75,459</td> <td>48,676</td> <td>199,251</td> <td>9,221</td> <td>894,762</td> </tr> <tr> <td>Qt</td> <td>159,894</td> <td>8,871</td> <td>114,797</td> <td>1,992</td> <td>19,675</td> </tr> <tr> <td><strong>Total</strong></td> <td><strong>450,671</strong></td> <td><strong>77,524</strong></td> <td><strong>374,071</strong></td> <td><strong>12,743</strong></td> <td><strong>1,010,410</strong></td> </tr> </tbody> </table> ### 4.2 Data Extraction and Analysis To investigate how developers review test files, we extracted code review data from the Gerrit review databases of the systems under study. Gerrit explicitly links commits in a Version Control System (VCS) to their respective code review. We used this link to connect commits to their relevant code review, obtaining information regarding which files have been modified, the modified lines, and the number of reviewers and comments in the review. Each review in Gerrit is uniquely identified by a hash code called Change-ID. After a patch is accepted by all the reviewers, it is automatically integrated into the VCS. For traceability purposes, the commit message of the integrated patch contains the Change-ID; we extracted this Change-ID from commit messages to link patches in the VCS with the associated code review in Gerrit. To obtain code review data, we created GERRITMINER, a tool that retrieves all the code reviews from Gerrit for each project using the Gerrit REST API [4]. The tool saves all review-related data (e.g., Change-ID, author, files, comments, and reviewers) in a MySQL database. Through GERRITMINER, we retrieved a total of 654,570 code reviews pertaining to the three systems. Since we were interested in just production and test files, we only stored code reviews that changed source code files (e.g., we did not consider ‘.txt’ file, ‘README’, JSON files, configuration files). After this process, we were left with 374,071 reviews. Table 2 presents the statistics. To answer RQ1, we selected only reviews that contained less than 50 files and had at least one reviewer involved who was different than the author [8, 34, 37]. In fact, as explained by Bigby et al. [36], a code review should ideally be performed on changes that are small, independent, and complete: a small change lets reviewers focus on the entire change and maintain an overall picture of how it fits into the system. As we were interested in code reviews where reviewers actually examined the code closely, we did not consider reviews where the author was the only reviewer. We also did not consider bots as reviewers (e.g., Jenkins and Sanity Bots). At the end, the distribution of the number of reviewers per review (excluding the author) is the following: 27% have 1 reviewer, 26% have 2, 16% have 3, 10% have 4, and 20% have more than 4. To understand how often and extensively discussions are held during reviews about test files, we considered the following metrics as proxies, which have been validated in previous literature [42]: number of comments in the file, number of files with comments, number of different reviewers, and the length of the comments. We only considered code reviews that contained at least one comment because we were interested in understanding whether there was any difference between review discussions of test and production files, and reviews that do not contain any discussion are not useful for this investigation. We used the production file metrics as a baseline and separately analyzed the three different review scenarios based on what needed to be reviewed: (1) both production and test files, (2) only production files, or (3) only test files. ### 4.3 Manual Content Analysis To answer RQ2, we focused on the previously extracted comments (Section 4.2) by practitioners reviewing test files. To analyze the content of these comments, we performed a manual analysis similar to Bacchelli & Bird [12]. Due to the size of the total number of comments (1,010,410), we analyzed a statistically significant random sample. Our sample of 600 comments was created with a confidence level of 99% and error (E) of 5% [44]. The manual analysis was conducted by the first two authors of this paper, using the following process: (1) Each researcher was responsible for coding 300 comments. (2) All the sampled comments were listed in a shared spreadsheet. (3) The researchers worked together to categorize and explain comments, using a negotiated agreement technique [39] to achieve agreement. As agreement is negotiated on-the-fly, there is no inter-rater agreement value. Agreement was found after 60 comments, at which point the work continued in parallel. (4) As a starting point, researchers used the same categories described by Bacchelli & Bird [12], including code improvement, understanding, social communication, defect, knowledge transfer, miscellaneous, testing, external impact, and review tool. Furthermore, researchers did a second pass to retrieve more fine-grained information for each category, obtaining more details on what developers discuss. (5) In case of doubt, i.e., the category of a specific comment was not clear to one of the researchers, the category was then analyzed by both researchers together. **4.4 Interviews** To answer RQs 3 and 4, guided by the results of the previous RQs, we designed an interview in which the goal was to understand which practices developers apply when reviewing test files. The interviews were conducted by the first author of this paper and were semi-structured, a form of interview often used in exploratory investigations to understand phenomena and seek new insights [48]. Each interview started with general questions about code reviews, with the aim of understanding why the interviewee performs code reviews, whether they consider it an important practice, and how they perform them. Our interview protocol also contained many questions derived from the results of previous research questions. Our full interview protocol is available in the appendix [7]. We asked interviewees the following main questions: 1. What is the importance of reviewing these files? 2. How do you conduct reviews? Do you have specific practices? 3. What are the differences between reviewing test files and production files? 4. What challenges do you face when reviewing test files? What are your needs related to this activity? During each interview, the researcher summarized the answers, and before finalizing the meeting, these summaries were presented to the interviewee to validate our interpretation of their opinions. We conducted all interviews via Skype. With the participants’ consent, the interviews were recorded and transcribed for analysis. We analyzed the interviews by initially assigning codes [25] to all relevant pieces of information, and then grouped these codes into higher-level categories. These categories formed the topics we discuss in our results (Section 5). We conducted 12 interviews (each lasting between 20 and 50 minutes) with developers that perform code reviews as part of their daily activities. Three of these developers worked on the projects we studied in the previous RQs. In addition, we had one participant from another open-source project and 8 participants from industry. Table 3 summarizes the interviewees’ demographics. **4.5 Threats to Validity and Limitations** We describe the threats to validity and limitations to the results of our work, as posed by the research methodology that we applied. *Construct validity.* When building our model we assume that each post-release defect has the same importance, when in reality this could not be the case. We mitigate this issue analyzing only the post-release defect having the same importance, when in reality this could not be the case. We mitigate this issue by considering diverse systems and by collecting opinions from a range of developers from different open-source and industry projects. In addition, their interviewees’ opinions may also be influenced by other factors, such as current literature on MCR, which could have led them to social desirability bias [23], or by practices in other projects that they participate in. To mitigate this issue, we constantly reminded interviewees that we were discussing the code review practices specifically of their project. At the end of the interview, we asked them to freely talk about their ideas on code reviews in general. *Internal validity – Credibility.* Threats to internal validity concern factors we did not consider that could affect the variables and the relations being investigated. In our study, we interview developers from the studied software to understand how they review test files. Every developer has a specific way of reviewing, which may differ from the practices of other practitioners. We try to mitigate this issue by interviewing a range of developers from different open-source and industry projects. In addition, their interviewees’ opinions may also be influenced by other factors, such as current literature on MCR, which could have led them to social desirability bias [23], or by practices in other projects that they participate in. To mitigate this issue, we constantly reminded interviewees that we were discussing the code review practices specifically of their project. At the end of the interview, we asked them to freely talk about their ideas on code reviews in general. *Generalizability – Transferability.* Our sample contains three open-source systems, which is small compared to the overall population of software systems that make use of code reviews. We reduce this issue by considering diverse systems and by collecting opinions from other open-source projects as well as from industry. **5 RESULTS** In this section, we present the results to our research questions that aimed to understand how rigorously developers review tests, what developers discuss with each other in their reviews of test code, and what practices and challenges developers use and experience while performing these code reviews. **RQ1. How rigorously is test code reviewed?** In Table 4, we show the distribution of comments in code reviews for both production and test files when they are in the same review, and for code reviews that only contain either type. **Discussion in code reviews of test files.** The number of test file reviews that contain at least one comment ranges from 29% (in reviews that combine test and production files) to 48% (in reviews that only look at test files). The number of production files that Table 4: The prevalence of reviews in test files vs production files (baseline) <table> <thead> <tr> <th>Code review</th> <th># of files w/ comments</th> <th># of files w/o comments</th> <th>odds ratio</th> <th># of comments</th> <th>Avg number of comments</th> <th>Avg # of reviewers</th> <th>Avg length of comments</th> </tr> </thead> <tbody> <tr> <td>Production</td> <td>157,507</td> <td>68,338 (43%)</td> <td>89,169 (57%)</td> <td>1.90</td> <td>472,020</td> <td>3.00</td> <td>5.49</td> </tr> <tr> <td>Test</td> <td>102,266</td> <td>29,327 (29%)</td> <td>72,939 (71%)</td> <td></td> <td>129,538</td> <td>1.27</td> <td>5.65</td> </tr> </tbody> </table> Only production 74,602 32,875 (44%) 41,725 (56%) 0.86 122,316 1.64 3.95 18.13 Only test 22,732 10,808 (48%) 11,924 (52%) 35% 52,370 2.30 5.15 17.01 contain at least a single comment ranges from 43% (when together with test files) to 44% (in reviews that only look at production files). In a code review that contains both types of files, the odds of a production file receiving a comment is 1.90 [1.87 – 1.93] higher than with test files. On the other hand, when a review only contains one type of file, the odds of a test file receiving a comment is higher than that of a production file: 1.15 [1.11 – 1.18]. We also observed a large number of files that did not receive any discussion. The number of code files that did not receive at least a single comment ranges from 52% (in reviews that only look at test files) to 71% (in reviews that combine test and production files). Discussion intensity in test files. In the code reviews that contain both types of files, production files received more individual comments than test files (3.00 comments per file for production, 1.27 comments for tests). The difference is statistically significant but small (Wilcoxon p-value < 2.2e-16, Cliff’s Delta=0.1643); this is due to the large number of files with no comments (median = 0 in both test and production, 3rd quantile = 1). The difference is larger when we analyze only files with at least a single comment (Wilcoxon p-value < 2.2e-16, Cliff’s Delta=0.1385). Again, numbers change when both files are not bundled in the same review. Code reviews on only production files contain fewer individual comments on average than reviews on only test files (1.64 comments for production, 2.30 comments for tests). The difference is statistically significant but small (Wilcoxon p-value < 2.2e-16, Cliff’s Delta=0.0585). Production files receive longer comments than test files on average, both when they are in the same review (an average of 19.08 characters per comment in a production file against 15.32 in a test) and when they are not (18.13 against 17.01). The difference is again statistically significant but small (Wilcoxon p-value < 2.2e-16, Cliff’s Delta=0.0888). Reviewers of test files. The number of reviewers involved in reviews containing both files and only tests is slightly higher compared to reviews containing production files. However, from the Wilcoxon rank sum test and the effect size, we observe that the overall difference is statistically significant but small (Wilcoxon p-value < 2.2e-16, Cliff’s Delta=0.1724). Finding 1. Test files are almost 2 times less likely to be discussed during code review when reviewed together with production files. Yet, the difference is small in terms of the number and length of the comments, and the number of reviewers involved. discussion comments are “Where is the assert for the non synchronized case?”, “Add a test for context path of /”, and “I wouldn’t do this test. That’s an implementation detail.” Another 6% of the comments concern wrong assertions. As we discuss in the following RQs, developers often complain about readability of the assertions, namely the assertion has to be as specific as possible to let the developer better understand why the test failed. As an example, a developer asked to change an assertTrue(equals()) to an assertEquals() in one comment. Finally, we observed that 12% of the comments concern unused or unnecessary code, and 17% of them mention code styling. These kinds of comments are in line with those found on reviews of production code [12, 14]. Understanding (32%). This category represents all the comments where reviewers ask questions to better understand the code, including posing questions asking for explanations, suggestions, and motivating examples. In this category, we included comments such as “why do you need this for?”, “what does this variable name mean?” and “why is this class static?”. Interestingly, as opposed to review comments related to code improvements, the comments in this category did not reveal any differences from what we found in the test and production files analyzed in our previous work, i.e., there were no comments that were specifically related to testing practices, such as assertion and mocking. This provides additional evidence on the importance of understanding when performing code reviews [12], regardless of the types of files under review. Defect finding (9%). Within this category, we see discussion concerning test defects such as wrong assert handling, missing tests, misuse of test conventions, and incorrect use of mocks. We observe three different categories of defects: severe, not severe, and wrong assertions. More specifically, 43% of the comments are about severe issues, i.e., tests that completely fail because of a wrong variable initialization, a wrong file path, or incorrect use of mocks. On the other hand, 41% of the comments are focused on less severe issues, such as missing test configurations. Finally, 14% of the comments concern wrong assertion handling, such as assertions of wrong scenarios. Interestingly, as opposed to the results reported by Bachelli & Bird who found that “review comments about defects … mostly address ‘micro’ level and superficial concerns” [12], a large portion of the defects discussed in test file code reviews concern rather high-level and severe issues. A hypothesis for this difference may be that a good part of the severe, high-level defects that affect test files are localized (i.e., visible just looking at the changed lines), while production files are affected by more delocalized defects that may be harder to detect by simply inspecting the changed lines. Knowledge transfer (4%). This category, which also emerged in previous work [12], represents all the comments where the reviewers direct the committer of the code change to an external resource (e.g., internal documentation or websites). We observe two different types of comments in this category: comments that link to external resources and that contain examples. More specifically, 55% of these comments contain links to external documentation (e.g., Mockito website, python documentation), to other classes of the project (e.g., other tests), and to other patches. The rest of the comments are examples where the reviewer showed how to tackle the issue with an example, within the review comment itself, of how s/he would do it. Social communication (11%). Finally, this category, in line with the work by Bachelli & Bird [12], includes all the comments that are social in nature and not about the code, examples such as “Great suggestion!” and “Thank you for your help”. **Finding 2.** Reviewers discuss better testing practices, tested and untested paths, and assertions. Regarding defects, half of the comments regard severe, high-level testing issues, as opposed to results reported in previous work, where most of the comments on production code regarded low level concerns. **RQ3.** Which practices do reviewers follow for test files? We analyze the answers obtained during our interviews with developers. We refer to individual interviewees using (P). **Test driven reviews.** Regardless of having test files in the patch, all participants agreed that before diving into the source code, they first get an idea of what the change is about, by reading the commit message or any documentation attached to the review request [P1,2,6–10,12]. P2 added: “I look at what it says and I think to myself ‘how would I implement that’?, just to give a sense of what are the files that I would be expecting to be changed, what are the areas of the system that I’m expecting that they touch.” If the files that are attached to the patch look much different from what they expected, they immediately reject the code change [P2,7,9,10]. Once they understood what the change is about, developers start to look at the code. In this case, we identified two different approaches: some developers prefer to read test files first followed by production files [P2,4,5], while other developers prefer to read production files first and then review tests [P1,3,6–10]. When starting from tests, developers say they can understand what the feature should do even before looking at its implementation [P2,4,5]. P5 says: “It is similar to read interfaces before implementations. I start from the test files because I want to understand the API first.” In this approach, developers first see what the code is tested for, then check whether the production code does only what is tested for or if it does more than what is necessary [P2,4,5]: “If I start to find something in production that is much different of what I am inferring from the tests, those are my first questions” [P5]. More developers instead start reviewing the change in its production files first [P1,3,6–10]. As P8 explained: “I start first from the production code, because I can have a sense of what should be tested.” The advantage of such an approach is that developers do not waste time validating whether the test covers every path for a change that is wrong in first place [P1,3,6–10]. P7 also said that he would prefer to start reviewing the tests, but the poor quality of the tests makes this not realistic: “I would prefer to starting with the tests, the problem is that tests are usually very bad. And the reason is because they usually tend to test what they implemented and not what they should have implemented. In TDD I would also start to review tests first but, as you know, this is not the case.” Finding 3. Similarly to when writing new code, when reviewing some developers prefer to start from tests, others from production. Reviewers who start inspecting tests use them to determine what the production code should do and whether it does only that. Reviewers who start inspecting production code prefer to understand the logic of production code before validating whether its tests cover every path. Reviewers look for different problems when reviewing tests. According to the interviewees, reviewing test files require different practices to those used for reviewing production files; this is in line with the differences we found in the content of the subcategories of comments left for test files vs. production files for RQ2. Interviewees explain that it is especially different in terms of what to look for. P10 said that when reviewing production code they discuss more about the design and cleanliness of the code, whereas for reviews of tests they discuss more on tested/untested paths, testing practices like mocking and the complexity of the testing code. A main concern for all the developers is understanding if all the possible paths of the production code are tested, especially corner cases [P9–12]. “If the method being tested receives two variables, and with these two variables it can have on average five to ten different returns, I’ll try to see whether they cover a sufficient number of cases so that I can prove that that method won’t fail.”[P11] Interviewees explained that they often complain about maintainability and readability of the test (i.e., complex or duplicated code, if the test can be simpler, or divided into two smaller tests), but especially the name of the tests and the assertions [P7–12]. “I often complain on the assertions, some assertions are really difficult to understand, we should try to be as specific as possible.”[P8] Finding 4. A main concern of reviewers is understanding whether the test covers all the paths of the production code and to ensure tests’ maintainability and readability. Having the contextual information about the test. As we will discuss in the next RQ, a main concern for developers is the small amount of information provided in the code review [P1, 6, 8–10, 12]. Indeed, within a code review, reviewers can only see files that are changed and only the lines that have been modified, while interviewees complain that they do not have the possibility to, for example, automatically switch between production code and its test code, or to check other related test cases that are not modified in the patch [P1, 8, 9]. For this reason, two developers explained that they check out the code under review and open it with another tool, for example a local IDE [P9, 12]. In this way, they can have the full picture of what is changed and get full support of other tools: “I particularly like opening the pull request to know what has come in again, which classes have been edited. I [open] GitHub, I access the PR and open it [in] my IDE. So I can look at the code as a whole, not just the files changed as it is in GitHub.”[P12] Another advantage of checking out the commit with the patch is that developers can see the tests running: “Most of the time I pull the pull request to see the feature and tests running, so I can have a sense of what have changed and how.”[P3] Nevertheless, this practice can only be accomplished when the code base is limited in size and the coding environment can be easily pulled to the local machine of the reviewers. Finding 5. Due to the lack on test-specific information within the code review tool, we observed that developers check out the code under review and open it in a local IDE: This allows them to navigate through the dependencies, have a full picture of the code, and run the test code. However this workaround is limited to small scale code bases. RQ4. What problems and challenges do developers face when reviewing tests? Test code is substantially different than production code. According to our interviewees, even if sometimes writing tests is simpler than writing production code [P1, 3, 4, 6–9, 11], this changes when reviewing tests [P3, 4, 6–9]: “Imagine you have to test a method that does an arithmetic sum. The production code only adds two numbers, while the test will have to do a positive test, a negative and have about fifteen different alternatives, for the same function.”[P11] According to our interviewees, reviewing test files becomes complicated due to lack of context [P1, 6, 8–10, 12]. When reviewing a test, code review tools do not allow developers to have production and test files side-by-side [P12]: “Having the complete context of the test is difficult, we often use variables that are not initialized in the reviewed method, so often I have to go around and understand where the variable is initialized.”[P8] Another developer said that “It’s hard to understand which test is actually testing this method, or this path in the function.”[P1] and that when the test involves a lot of other classes (it is highly coupled) s/he never knows whether and how the other classes are tested [P5]. Furthermore, one of the main challenges experienced by our interviewees is that often reviewing a test means reviewing code additions, which is more complicated than reviewing just code changes [P2, 11, 12]. “Code changes make me think, why is this line changing from the greater than side to a less than side? While code changes you have to think what’s going on in there, and tests are almost all the time new additions.”[P2] According to developers, test code is theoretically written once and if it is written correctly it will not change [P2]. The reason is that while the implementation of the feature may change (e.g., how it is implemented), both the result and the tests will stay the same [P11]. Finding 6. Reviewing test files requires developers to have context about not only the test, but also the production file under test. In addition, test files are often long and are often new additions, which makes the review harder to do. The average developer believes test code is less important. “I will get a call from my manager if there is a bug in production while I’m not going to get a call if there’s a bug in the test right?”[P2] According to our interviewees, developers choose saving time to the detriment of quality. This is due to the fact that there is no immediate value on having software well tested; as P7 explained “it is only According to our interviewees, the navigation between the production and the test files within the review is difficult [P2,9,10,12]. "We don’t have a tool to easily switch between your tests and your production code, we have to go back and forth, then you have to look for the same name and trying to match them."[P2] As mentioned before, the context of the review is limited to the files attached to the review itself, and this makes it difficult to have a big picture of the change. For example, test files are usually highly coupled to several production classes: however, developers can not navigate to the dependencies of the test, or other test in general, without opening a new window [P2,9]. “If we could click on the definition of a class and go to its implementation would be amazing. That’s why I pull the PR every-time and I lose a lot of time doing it.”[P9] P12’ said: “It’s very unproductive to review in GitHub, because you first visualize all the codes, and then at the end are all the tests, and it ends up being more difficult having to keep going in the browser several times.” In addition, adding fine-grained information about code coverage during the review is considered helpful [P1,7,11,12]. More specifically, which tests cover a specific line [P1,7,11,12], what paths are already covered by the test suite [P2,12], and whether tests exercise exceptional cases [P12]. Regarding the latter, P12 says: “I think it’s harder to automate, but it is to ensure that not only the “happy” paths are covered. It is to ensure that the cover is in the happy case, in case of errors and possible variations. A lot of people end up covering very little or too much.” Tool features that are not related to test also emerged during our interviewees. For example, enabling developers to identify the importance of each file within the code review [P7,8,11,12] and splitting the code review among different reviewers [P7]. 6 DISCUSSION We discuss how our results lead to recommendations for practitioners and educators, as well as implications for future research. 6.1 For Practitioners and Educators Underline the importance of reviewing test code. The results of both our quantitative and qualitative analysis indicate that most reviewers deem reviewing tests as less important than reviewing production code. Especially when inspecting production and test files that are bundled together, reviewers tend to focus more on production code with the risk of missing bugs in the tests. However, previous research has shown that bugs in test files can lower the quality of the corresponding production code, because a bug in the test can lead to serious issues such as ‘silent horrors’ or ‘false alarms’ [46]. Moreover, our analysis provided empirical evidence that being a test does not change the chances of a file to have future defects (Section 3). For this reason, practitioners should be instructed and keep in mind to put the same care when reviewing test or production code. Good for the long term.” For a product that is customer-driven, it is more important to release the feature without bugs, because that is the code that will run on the client’s machine [P2,4,7,9]. P7 said: “If I want to get a good bonus by the end of the year I will make sure that my features make it into production level code. If instead we would start to get punished for bugs or bad code practices, you will see a very different approach, you would see way more discussions about tests than production code.” Interviewees affirmed that the main problem is the developers mindset [P1,2,7,8]: “It is the same reason as why people write bad tests, testing is considered as secondary class task, it is considered not but it is not.”[P7] Developers see test files as less important, because a bug in a test is a developer’s problem while a bug in production code is a client’s problem. As explained by P7, developers are not rewarded for writing good code, but for delivering features the clients want. Furthermore, according to our interviewees, during a review sometimes they do not even look at the test files, their presence is enough [P1,3,6]. As P6 said “Sometimes you don’t look at the test because you see there is the file, you know that the code is doing what it has to do and you trust the developer who wrote it (maybe we trust too much sometimes).” Finding 7: Developers have a limited amount of time to spend on reviewing and are driven by management policies to review production code instead of test code which is considered less important. Better education on software testing and reviewing. Most interviewees agreed on the need to convince developers and managers that reviewing and testing are highly important for the software system overall quality [P1,2,4,6–8,10]. Educating developers on good and bad practices and the dangers of bad testing [P2,7,10]. “I would love to see in university people teaching good practice on testing. Furthermore, people coming from university they have no freaking clue on how a code review is done. Educating on testing and reviewing, how to write a good test and review it.”[P7] Furthermore, with the help of researchers, developers could solve part of the education problem: one interviewee said that research should focus more on developers’ needs, so that tool designers can take advantage of these needs and improve their tools [P6]. “I think it is important to give this feedback to the people who write [code review] tools so they can provide the features that the community wants. Having someone like you in the middle, collecting this feedback and sending them to tool developers, this could be very helpful.”[P6] Finding 8: Novice developers and managers are not aware of what is the impact of poor testing and reviewing on software quality, education systems should fix this. Moreover, research should focus more on developers’ needs and expose them to tool makers to have an impact. Tool improvements. Part of the interview was focused on what can be improved in the current code review tools. Set aside sufficient time for reviewing test files. Our interviewees agreed that reviewing test files is a non-trivial task, because changes involving tests are often coded as additions rather than code modifications and several test options must be analyzed. This indicates that correctly reviewing test files would hardly take less time than reviewing production code. A good team culture must be developed, in which the time spent on reviewing test code is considered as important as the time spent on reviewing production code and scheduled accordingly. In fact, as previous work already pointed out [12], good reviewing effectiveness is found mostly within teams that value the time spent on code review; tests should not be treated differently. Educate developers on how to review test code. Many books and articles have been written by practitioners on best practices for code review [1, 2, 5] and researchers continue to conduct studies to increase our empirical understanding of code review [30, 42]. Nevertheless, best practices for reviewing test code have not been discussed nor proposed yet. Our work, as a first step, collects current best practices for reviewing of tests. These practices show us that developers should learn how to look for possible false alarms, to check that the tests will be easily understandable and maintainable, and to check whether all the possible paths of the production code are tested. Novice reviewers may also consider the practice of reviewing test code before production to (1) make sure to give it enough time and (2) to better understand the goals of the production code under test, since novices may not know them beforehand. 6.2 For Tool Designers and Researchers Providing context to aid in reviewing of tests. The lack of context when reviewing test code is a concern for many developers. Specifically, developers argue that it is important to understand and inspect the classes that are under test as well as which dependencies are simulated by tests (i.e., mock objects). However, knowing which classes are executed by a test normally requires dynamically executing the code during review, which is not always feasible, especially when large code bases are involved [20]. This is an opportunity to adapt and extend existing research that determines the coverage of tests using static analysis [10]. Moreover, developers would like to be able to easily navigate through the test and tested classes; future research studies could investigate how to improve file navigation for code review in general (an existing open research problem [13]) but also to better support review of tests in particular. Providing detailed code coverage information for tests. As our results show, one of the most important tasks during the review of a test code is to make sure the test covers all the possible paths of the production code. Although external tools provide code coverage support for developers (e.g., Codecov [3]), this information is usually not “per test method”, i.e., coverage reports focus on the final coverage after the execution of the entire test suite, and not for a single test method. Therefore, new methods should be devised to not only provide general information on code coverage, but also provide information that is specific to each test method. An effort in this direction has been presented by Oosterwaal et al. [33]; our analysis points to the need for further research in this area. Understanding how to review test code and benefits of test reviews. Our research highlights some of the current practices used by developers when reviewing test files, such as test driven review (review tests before production code). Nevertheless, the real effect of these practices on code review effectiveness and on the eventual test code quality is not known: some practices may be beneficial, other may simply waste reviewers’ time. This calls for in-depth, empirical experiments to determine which practices should be suggested for adoption by practitioners. 7 CONCLUSIONS Automated testing is nowadays considered to be an essential process for improving the quality of software systems. Unfortunately, past literature showed that test code, similarly to production code, can often be of low quality and may be prone to contain defects [46]. To maintain a high code quality standard, many software projects employ code review, but is test code typically reviewed and if so, how rigorously? In this paper we investigated whether and how developers employ code review for test files. To that end, we studied three OSS projects, analyzing more than 300,000 reviews and interviewing three of their developers. In addition, we interviewed another 9 developers, both from OSS projects and industry, obtaining more insights on how code review is conducted on tests. Our results provide new insights on what developers look for when reviewing tests, what practices they follow, and the specific challenges they face. In particular, after having verified that a code file that is a test does not make it less likely to have defects—thus little justification for lower quality reviews—we show that developers tend to discuss test files significantly less than production files. The main reported cause is that reviewers see testing as a secondary task and they are not aware of the risk of poor testing or bad reviewing. We discovered that when inspecting test files, reviewers often discuss better testing practices, tested and untested paths, and assertions. Regarding defects, often reviewers discuss severe, high-level testing issues, as opposed to results reported in previous work [12], where most of the comments on production code regarded low level concerns. Among the various review practices on tests, we found two approaches when a review involves test and production code together: some developers prefer to start from tests, others from production. In the first case, developers use tests to determine what the production code should do and whether it does only that, on the other hand when starting from production they want to understand the logic before validating whether its tests cover every path. As for challenges, developers’ main problems are: understanding whether the test covers all the paths of the production code, ensuring maintainability and readability of the test code, gaining context for the test under review, and difficulty reviewing large code additions involving test code. We provide recommendations for practitioners and educators, as well as viable directions for impactful tools and future research. We hope that the insights we have discovered will lead to improved tools and validated practices which in turn may lead to higher code quality overall. ACKNOWLEDGMENTS The authors would like to thank all participants of the interviews. A. Bacchelli gratefully acknowledges the support of the Swiss National Science Foundation through the SNF Project No. PP00P2_170529.
{"Source-Url": "https://pure.tudelft.nl/portal/files/47765254/TUD_SERG_2018_004.pdf", "len_cl100k_base": 13261, "olmocr-version": "0.1.49", "pdf-total-pages": 17, "total-fallback-pages": 0, "total-input-tokens": 46031, "total-output-tokens": 14329, "length": "2e13", "weborganizer": {"__label__adult": 0.0004177093505859375, "__label__art_design": 0.0002796649932861328, "__label__crime_law": 0.0003681182861328125, "__label__education_jobs": 0.0024662017822265625, "__label__entertainment": 4.7147274017333984e-05, "__label__fashion_beauty": 0.00017058849334716797, "__label__finance_business": 0.0002493858337402344, "__label__food_dining": 0.0003421306610107422, "__label__games": 0.0005908012390136719, "__label__hardware": 0.0004930496215820312, "__label__health": 0.0004024505615234375, "__label__history": 0.00015747547149658203, "__label__home_hobbies": 8.255243301391602e-05, "__label__industrial": 0.00022923946380615232, "__label__literature": 0.00024259090423583984, "__label__politics": 0.00024580955505371094, "__label__religion": 0.00038242340087890625, "__label__science_tech": 0.002521514892578125, "__label__social_life": 0.00010877847671508788, "__label__software": 0.00420379638671875, "__label__software_dev": 0.9853515625, "__label__sports_fitness": 0.00031447410583496094, "__label__transportation": 0.0003879070281982422, "__label__travel": 0.00018668174743652344}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 62688, 0.04822]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 62688, 0.27784]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 62688, 0.94523]], "google_gemma-3-12b-it_contains_pii": [[0, 1302, false], [1302, 1487, null], [1487, 1756, null], [1756, 6590, null], [6590, 13530, null], [13530, 20187, null], [20187, 27057, null], [27057, 32711, null], [32711, 36314, null], [36314, 43078, null], [43078, 49585, null], [49585, 55714, null], [55714, 62688, null], [62688, 62688, null], [62688, 62688, null], [62688, 62688, null], [62688, 62688, null]], "google_gemma-3-12b-it_is_public_document": [[0, 1302, true], [1302, 1487, null], [1487, 1756, null], [1756, 6590, null], [6590, 13530, null], [13530, 20187, null], [20187, 27057, null], [27057, 32711, null], [32711, 36314, null], [36314, 43078, null], [43078, 49585, null], [49585, 55714, null], [55714, 62688, null], [62688, 62688, null], [62688, 62688, null], [62688, 62688, null], [62688, 62688, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 62688, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 62688, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 62688, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 62688, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 62688, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 62688, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 62688, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 62688, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 62688, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 62688, null]], "pdf_page_numbers": [[0, 1302, 1], [1302, 1487, 2], [1487, 1756, 3], [1756, 6590, 4], [6590, 13530, 5], [13530, 20187, 6], [20187, 27057, 7], [27057, 32711, 8], [32711, 36314, 9], [36314, 43078, 10], [43078, 49585, 11], [49585, 55714, 12], [55714, 62688, 13], [62688, 62688, 14], [62688, 62688, 15], [62688, 62688, 16], [62688, 62688, 17]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 62688, 0.09813]]}
olmocr_science_pdfs
2024-11-24
2024-11-24
07e043d63a58dd255b506fdfbc4fec42e2fcf877
Comparison of Proof Producing Systems in SMT Solvers Arjun Viswanathan Abstract Satisfiability Modulo Theories (SMT) solvers input typically large formulas that contain both Boolean logic and logic in different theories - such as arithmetic and strings - and decide whether the formulas are satisfiable or unsatisfiable. Verification tools use these solvers to prove system properties. As a result, solver output must be trustable. However, SMT solvers are really complicated tools that have tens of thousands of lines of code. One way to make SMT solver output more reliable is to have them produce proofs of their results. For satisfied formulas, this can be a model of satisfaction, that is, values for all the variables in the formula. For unsatisfied formulas, it is a transformation of the formula into a simple contradiction using a small set of inference rules, checkable by an external tool such as a proof checker. This report describes the proof producing mechanisms commonly used in SMT solvers and compares the proof systems of CVC4, VeriT, and Z3, three state-of-the-art SMT solvers. 1 Introduction Boolean satisfiability, often called the SAT problem, is the problem of satisfying a Boolean formula, that is, consistently assigning values of True or False to the variables of the formula so that the entire formula evaluates to True. For example, \((x \lor y) \land z\) can be satisfied by the assignment \(\{x = True, y = False, z = True\}\). On the other hand, \(x \land \neg x\) is unsatisfiable, no matter what value is assigned to \(x\). Satisfiability Modulo Theories [6] or SMT lifts SAT to a level that includes theories. For example, \((a = b) \land (b = c) \land \neg(a = c)\) is a formula that is unsatisfiable in the theory of equality over uninterpreted functions. This is because, by transitivity of \( a = b \) and \( b = c \), we have \( a = c \). SMT allows us to be more expressive with our formulas, but this comes at the cost of more complicated decision procedures. SMT solvers have plenty of applications in formal methods and software verification. For instance, SMT solvers are used in the back-end of model checkers [2], which input mathematical models of a software system, and verify whether they satisfy a particular property or not. Another area of application is symbolic execution [3], which is to analyze a program to figure out what set of inputs work for each part of the program. Other uses of SMT solvers include program synthesis [8], static analysis, and interpolant generation [13]. Given their rise in popularity and usage in the software verification world, it is really important that we are able to trust the outputs of SMT solvers. SMT solvers are typically very complex systems with tens of thousands of lines of code, likely to contain bugs. Verifying such a large codebase can be a cumbersome, if not impossible task. An alternative is to rely on tools called proof checkers [20], that have a much more trusted kernel containing a small set of axioms and inference rules. These proof checkers sacrifice in automatic capability what they gain in terms of trustability over SMT solvers. To exploit these proof checkers, SMT solvers produce proof certificates of their outputs, that can be checked by the proof checker. In this report, I introduce the workings of an SMT solver and their proof producing capabilities; I also compare the proof systems of CVC4, VeriT, and Z3 - three state-of-the-art SMT solvers - as respectively described in the research papers titled “Lazy Proofs for DPLL(T)-Based SMT Solvers” [16], “Expressiveness + Automation + Soundness : Towards Combining SMT Solvers and Interactive Proof Assistants” [12], and “Proofs and Refutations, and Z3” [9]. I begin by explaining the algorithm that is at the core of most SMT solvers. I then explain the logical basis for proof production in SMT solvers, and then get into comparing the research work as I explain the proof production systems of the SMT solvers. 2 Formal Preliminaries The following grammar specifies the syntax of the formulas we will use: \[ \begin{align*} \text{Variable} & \rightarrow x \mid y \mid ... \\ \text{Constant} & \rightarrow c_1 \mid c_2 \mid ... \\ \text{Term} & \rightarrow \text{Variable} \mid \text{Constant} \mid f(t_1,\ldots,t_n) \\ \text{Literal} & \rightarrow \text{Term} \mid \neg\text{Term} \\ \text{Formula} & \rightarrow \text{True} \mid \text{False} \mid p(t_1,\ldots,t_n) \mid \text{Literal} \mid \text{Literal} \lor \text{Literal} \\ & \quad \mid \text{Literal} \land \text{Literal} \mid \text{Literal} \Rightarrow \text{Literal} \mid \text{Literal} \iff \text{Literal} \end{align*} \] where $f$ is a function symbol and $p$ is a predicate symbol. Functions can be understood as they are in basic mathematics, and predicates are functions to the Boolean type. Negation ($\neg$), disjunction ($\lor$), conjunction ($\land$), implication ($\Rightarrow$), and double implication ($\iff$) have semantics as in classical logic [21]. Our setting consists of a background theory $T$ consisting of $m$ theories $T_1, \ldots, T_m$ with respective many-sorted signatures $\Sigma_1, \ldots, \Sigma_m$. All signatures share a set of sort (type) symbols, and equality is the only predicate. The theories also share a set of uninterpreted constants which are used for reasoning about terms that belong to multiple theories. The preceding part of this section formalizes the fact that the framework here is described for a single theory, but that theory can be considered a combination of multiple theories [18]. This means that formulas are composed of Boolean components, each of which will evaluate to True or False. However, since we have theories, these components could be just Boolean variables, or they could be (dis)equalities over our multiple theories, which gives us expressivity. For example, the following formula is over the theory of linear integer arithmetic (LIA) and the theory of equality over uninterpreted functions (EUF) [17]. $$(x \land y) \Rightarrow (a = 0 \land a + b = c \land \neg(f(b) = f(c)))$$ $x$ and $y$ are terms in the formula, and hence can only evaluate to True or False. $a$, $b$, and $c$, on the other hand, are integer variables that must evaluate to an integer constant. To generalize this, we assume our theory $T$ to be a combination of $m$ theories $T_1, \ldots, T_m$. Each theory $T_i$ is formally described by means of a signature $\Sigma_i$, but we will stick to intuitive theories such as the ones mentioned before, so we don’t have to deal with such formalisms. A formal definition of theories and SMT can be found at [6]. When it is used as a set, $\emptyset$ refers to the empty set. We also allow for representation of formulas that are conjunctions, as sets of the corresponding conjuncts. So we represent $c_1 \land \ldots \land c_n$ as \{ $c_1, \ldots, c_n$ \}. We need the notion of entailment on two levels. Propositional entailment $p \models_P q$ read as “formula $p$ propositionally entails formula $q$” says that $q$ is a logical consequence of $p$. For example, $a \land b \models_P a$, where $a$ and $b$ are Boolean variables. Entailment also occurs in a theory $x \models_i y$ read as “formula $x$ i-entails formula $y$”, where $i$ is the concerned theory. For example, $x > 3 \models_{LIA} x > 0$, where $x$ is an integer variable. If we abstracted these formulas to the propositional level, $m = (x > 3)$, and $n = (x > 0)$, the entailment $m \models_P n$ cannot be realized at the propositional level. We need reasoning at the level of the theory of arithmetic for this entailment to hold. A formula is satisfiable if we can consistently assign values to all its variables (Boolean and theory), so that the formula evaluates to True. A formula is unsatisfiable if there is no consistent assignment that we can give its variables so that the formula evaluates to True. $(x + y = 0) \land (m \lor n)$ is satisfiable, and a satisfying assignment is \{ $x = 0, y = 0, m = True, n = False$ \}. $p \land \neg p$ is unsatisfiable. Two formulas are equisatisfiable if they are both satisfiable, or if they are both unsatisfiable. Two formulas are equivalent if every model that satisfies one of them satisfies the other as well. Consider \( a \land b \) and \( a \land b \land n \). These are equisatisfiable since both of them are satisfiable - \( \{ a = True, b = True \} \) satisfies the first one and \( \{ a = True, b = True, n = True \} \) satisfies the second one. However, they are not equivalent since model \( \{ a = True, b = True, n = False \} \) satisfies the first one, but not the second one. A formula is valid, if no matter what values we assign its variables, it evaluates to True. In other words, it is entailed from nothing. For example, \( \models p \lor \neg p \), and \( \models LIA (x = 0) \lor (x < 0) \lor (x > 0) \). Finally, the universal quantifier (\( \forall \)) and the existential quantifier (\( \exists \)) help us quantify variables in formulas. For example, \( \forall x, x > 0 \Rightarrow \neg (x < 0) \) states the obvious fact that positive numbers aren’t negative, and \( \exists x, y = 2x \) is the predicate that is true if \( y \) is even. Our discussion in this report only involves quantifier-free logic of SMT solvers, but these are useful tools to have at the meta-level. 3 The DPLL(T) Algorithm Davis-Putnam-Logemann-Loveland or DPLL - named after its developers - is an algorithm developed in the 1960s for deciding the satisfiability of propositional formulas. About half a century later, most SAT solvers and SMT solvers are still based on some form of DPLL. All the solvers discussed in this work are DPLL(T) solvers, that is an extension of DPLL to accommodate theories. Section 3.1 introduces the normal form required by these solvers, and Section 3.2 explains the DPLL(T) algorithm as a transition system as presented in [16] and originally in [19]. 3.1 CNF Conversion SMT solvers require that the input formula is converted to a normal form called conjunctive normal form (CNF), before they start solving them. The CNF of a formula represents the formula as a conjunction of disjunctions. A clause is a disjunction (Boolean OR) of variables. So CNF is a conjunction (Boolean AND) of clauses. Using Tseitin clausification [1], any formula can be converted into an equisatisfiable CNF formula. The following is an example where a set of rewrite rules are applied to F to convert it into CNF. \[ F \quad a \Rightarrow (b \land c) \] **Step 1** \[ a \Rightarrow x_1 \land (x_1 \iff (b \land c)) \] **Step 2** \[ x_2 \land (x_2 \iff a \Rightarrow x_1) \land (x_1 \iff (b \land c)) \] **Step 3** \[ x_2 \land (x_2 \Rightarrow (a \Rightarrow x_1) \land (a \Rightarrow x_1) \Rightarrow x_2) \land \\ (x_1 \Rightarrow (b \land c) \land (b \land c) \Rightarrow x_1) \] **Step 4** \[ x_2 \land (¬x_2 \lor ¬a \lor x_1) \land (a \lor x_2) \land (¬x_1 \lor x_2) \land \\ (¬x_1 \lor b) \land (¬x_1 \lor c) \land (¬b \lor ¬c \lor x_1) \] Steps 1 and 2 involve introducing fresh variables \( x_1 \) and \( x_2 \) for all subterms of \( F \) by means of equivalence between the subterm and the fresh variable. Steps 3 and 4 reduce these subterms to CNF by common rewrite rules such as distribution and De Morgan’s law. This example is to illustrate that the conversion can be done. There are many optimizations that are applied in addition, that keep the normal form’s size in check. ### 3.2 Abstract DPLL(T) Framework At a high level, DPLL(T) takes a formula in CNF, and tries to satisfy every conjunct. There are two levels of reasoning - propositional and theory. The algorithm can be understood as always working in the propositional level (theory literals are abstracted to propositional ones), trying to satisfy the formula. If the formula is propositionally unsatisfiable, then the algorithm concludes, without any theory reasoning, that the formula is unsatisfiable. However, if the formula is propositionally satisfiable by a model, then the SAT solver sends the satisfying model to the theory solver(s) concerned to check whether it is satisfiable at the theory level as well. If it is satisfiable in the theory level, then the solver returns to the user that the formula is satisfiable. If the theory solver finds an inconsistency, it sends back information to the propositional solver, restricting the current model, and the solver tries again. If the propositional solver is unable to please all the theory solvers for any model that it finds at the propositional level, then we conclude by exhaustion that the formula is unsatisfiable. Checking whether the formula is unsatisfiable at the propositional level is nontrivial. It involves incrementally assigning literals by propagation, and when that isn’t an option, by guessing. When a guess takes us down a path that results in unsatisfiability, we must backtrack and check the whether the formula is indeed unsatisfiable if we flip the guess. Section 3.2.1 explains the preliminaries for the system, Sections 3.2.2 and 3.2.3 discuss solving at the SAT level, and Sections 3.2.4 and 3.2.5 discuss solving at the theory level. 3.2.1 Transition System DPLL(T) solvers can be formalized abstractly as state transition systems defined by a set of transition rules. The states of a system are either fail or \((M, F, C)\) where \(M\) is the current context, that is, it is the current assignment of literals in the formula; a literal in \(M\) is preceded by a • if the literal was a decision, that is, it was guessed. If \(M = M_0 • M_1 • ... • M_n\), each \(M_i\) is the decision level, and \(M^{[i]}\) denotes \(M_0 • ... • M_i\). \(F\) is a set of clauses representing some form of the input formula in CNF. \(C\) represents the conflict clause, the clause from \(F\) that is falsified by the assignment. Initial state: \(\langle \phi, F_0, \phi \rangle\), where \(F_0\) is the input formula converted to CNF. Final state: - • fail, when \(F_0\) is unsatisfiable in \(T\). - • \(\langle M, F, \Phi \rangle\) where \(M\) is satisfiable in \(T\), \(F\) is equisatisfiable with \(F_0\) in \(T\), and \(M \models F\). The transition system goes from the initial state from one of the final states by application of the rules in Sections 3.2.2 and 3.2.4 nondeterministically. In practice and for proof production, they are applied with a particular strategy but for completeness, a nondeterministic order works. A rule is applicable when all its premises hold, and it is applied to make the conclusion true. The following technicalities are necessary for solving of clauses that are a combination of multiple theories. They are only mentioned here for completeness. For a higher level understanding, consider the term \((f(a) = 1 + x)\) that combines the theory of equality over uninterpreted functions (EUF), and that of arithmetic. Since each theory has its own solver, this term that uses functions from both theories, must be purified for each theory solver, and this is done by means of a shared constant. If the term is replaced by the terms \(f(a) = s_1\) and \(s_1 = 1 + x\), we now have one term that is entirely over EUF, and one over arithmetic ones. \(\text{Int}_M\) is the set of all interface literals of \(M\): the (dis)equalities between shared constants. \(\text{Shared constants}\) are the set represented by \(\{c \mid \text{constant } c \text{ occurs in } \text{Lit}_{M[i]} \text{ and } \text{Lit}_{M[j]}, \text{ for some } 1 \leq i < j \leq m\}\). \(\text{Lit}_{M[i]}\) consists of the \(\Sigma_i\) literals of \(\text{Lit}_M\). The paper gives a guarantee of refutation soundness: if an execution starting with \(\langle \phi, F_i, \phi \rangle\) ends with \(\text{fail}\), then \(F_0\) is unsatisfiable in \(T\). 3.2.2 Propositional Rules Figure 1 enumerates the propositional rules. These rules constitute the DPLL(T) algorithm at the propositional level, or just DPLL. They model the behavior of the SAT engine, which treats atoms as Boolean variables. Propagations (Prop) allow us to assign literals that we are forced to assign by the logic. For example, if the input formula is \(\neg a \land (a \lor b)\), then \(a\) must be assigned to False, so that the \(\neg a\) conjunct evaluates to True. As a consequence, of this, \(b\) must be True Figure 1: Transition rules at Propositional level so that the next conjunct is True. Both of these assignments are propagations that the logic forces us to assign, given that we are trying to satisfy the formula. We might not always have this luxury; sometimes, we may have to make a guess on an assignment, and decisions (Dec) let us do this. If we are trying to satisfy \((\neg a \lor c) \land (\neg b \lor d) \land (a \lor b)\), each conjunct is a non-unit formula, so we need to guess the value of one of the literals. Propagations and/or decisions could lead us to a point where our current assignment conflicts with our goal of trying to satisfy the input formula. The conflict rule (Confl) recognizes this. In the previous example, assume we came up with the assignment \(\{a = False, b = False\}\) by guessing. This assignment satisfies the first two clauses, but falsifies the third, so the third clause \(a \lor b\) is recognized as a conflict clause. If we encounter a conflict, and there were no previous decisions made, then we were forced by the logic to arrive at that conflict, so we conclude that the input formula is unsatisfiable. The Fail rule ensures this. If, there are previous decisions at the time of conflict, then the explain rule (Expl) and the backjump rule (Backj) work together to rewind the state to a point where the decision is flipped. Decisions may cause propagations, and once we suspect that a decision was wrongly made, we want to undo the propagations that were caused by it. This is intuitively what the explain rule (Expl) does. Once this is done, the backjump rule (Backj) is able to flip the decision. A conflict clause always consists of a formula that is entailed by the input formula. Explanations could transform the conflict clause into a clause that we didn’t have to begin with, and this could be useful information for future propagations. The Learn rule allows us to add a non-empty conflict clause to the input clauses to be satisfied. 3.2.3 DPLL Example Consider the following example from [16]. The formula F expressed as a set in CNF is: \{ a \lor \neg b, \neg a \lor \neg b, b \lor c, \neg c \lor b \} Figure 2 shows how DPLL solves this formula. Notice that at Step 11, the Fail rule can be applied to conclude that the formula is unsatisfiable, and this is what the solver would typically do. However, for producing a proof of unsatisfiability, it is necessary for the conflict clause to be the empty clause \( \bot \), and hence the solver explains on the conflict instead (explained in section 4). A few steps later, the solver does conclude that the formula is unsatisfiable, while deriving the most basic conflict, the empty clause. 3.2.4 Theory Rules The rules in Figure 3 model the interaction between the SAT solver and the theory solvers. These rules maintain the invariant that every conflict clause and learned clause is entailed in T by the initial clause set. The rules are analogous \[ | \begin{array}{c} l \in \text{Lit}_F \cup \text{Int}_M \\ \vdash_i \bigvee l_1 \ldots \bigvee l_n \lor l \Longrightarrow \neg l_1, \ldots, \neg l_n \in M \land l \notin M \end{array} | \quad \text{Prop}_i \] \[ C = \phi \quad \vdash_i \bigvee l_1 \ldots \bigvee l_n \neg l_1, \ldots, \neg l_n \in M \] \[ C := \{l_1 \ldots \bigvee l_n\} \quad \text{Confl}_i \] \[ C = \{\neg l \lor D\} \quad \vdash_i \bigvee l_1 \ldots \bigvee l_n \lor l \neg l_1, \ldots, \neg l_n \prec_M l \] \[ C := \{l_1 \ldots \bigvee l_n \lor D\} \quad \text{Expl}_i \] \[ l_1, \ldots, l_n \in \text{Lit}_M | \quad \vdash_i \exists x(l_1[x] \lor \ldots \lor l_n[x]) \] \[ F := F \cup \{l_1[c] \lor \ldots \lor l_n[c]\} \quad \text{Learn}_i \] Figure 3: Transition rules at Theory level. \(x\) is a possibly empty tuple of variables, and \(c\) is a tuple of fresh constants from \(C\) - the set of shared constants between the sorts - of the same sort as \(x\); \(L_i\) is a finite set consisting of literals not present in the original formula \(F\). to their propositional rules, but have reasoning powers at the level of theories. For example, \(x \land y\) is true at the propositional level, if both \(x\) and \(y\) are true. However, if the variables store these arithmetic theory literals: \(x = (a > 3)\) and \(y = (a < 0)\), then \(x \land y\) is unsatisfiable in the theory of arithmetic. So even though the \textit{Conflict} rule won't recognize this inconsistency, the \textit{Conflict}_{LIA} rule can recognize this, as long as the arithmetic solver is able to generate this fact as a \textit{theory lemma}, which is a fact that is true in the theory, generated in CNF form by the theory solvers. This example as a lemma would look like this: \(\neg(a > 3) \lor \neg(a < 0)\) which would trigger the \textit{Conflict}_i clause given that \(x\) and \(y\) above are assigned to true, to satisfy \(x \land y\). Thus, the \textit{Propagate}_i, \textit{Conflict}_i, \textit{Explain}_i, and \textit{Learn}_i rule are similar to their propositional versions except that each rule is associated to a theory \(i\) and operates on lemmas provided by that theory. ### 3.2.5 DPLL(T) Example Consider the following example that consists of terms in the theory of EUF. Since this is the only theory we consider \(T\) the to be the combination of \(T_1 = EUF\). The input formula for the solver in CNF is: \[(a = b) \land (f(a) = f(b) \lor f(g(a) = h(b)) \land (f(a) = c) \land (c \neq d) \land (f(b) = d)\] Abstraction the terms and using the set notation, we have: \[\{1, 2 \lor 3, 4, -5, 6\}\] DPLL(T)’s execution on the example is shown in Figure 4. The interesting steps here are steps 2 to 4 that use theory lemmas. The clauses \(-1 \lor 2\) and \(-2 \lor 5\) are theory lemmas. Intuitively, they are saying “if 1 is true, then 2 is true” (by congruence), and ”if 2 is true, then 5 is true” (from the information gained from 2, 4, and 6), respectively. Essentially, these clauses are valid in the theory of EUF, and the solver conveniently gives us these lemmas to help us solve the problem at the propositional level. As in the propositional example, we could’ve used the Fail rule after the conflict to conclude that the formula is unsatisfiable (Step 4), but we want to reduce the conflict clause to the empty disjunction \(\bot\) since it will help us with our proof. 4 DPLL(T) Proofs This section describes the general framework used for a DPLL(T) solver to produce proofs for unsatisfiable formulas. A proof for a satisfiable formula is just a model that satisfies that formula, that is an assignment of values to the variables in the formula that make the formula evaluate to \(True\). For an unsatisfiable formula, the proof involves transforming formula into a simple contradiction by means of proof rules or inference rules. An important rule is that of resolution, which is introduced in Section 4.1. Proofs of unsatisfiability are then explained, at the propositional level in Section 4.2, and at the theory level in Section 4.3. Finally, Section 4.4 explains how theory solver produce proofs of theory lemmas. 4.1 Propositional Resolution Logical calculi operate by means of rules of inferences. A rule of inference consists of a number of premises and a conclusion. The rule of inference specifies a schema for a logical calculus where, if the premises are true, then the conclusions are true. For example, \[ \phi \Rightarrow \psi \quad \phi \quad \text{modus ponens} \] Modus ponens is a rule in classical logic that says that "if A implies B is true and if A is true, then B is true". The inference rule that is central to the construction of proofs for SMT solvers is propositional resolution. It is stated as follows. \[ \phi_1 \lor \ldots \lor \phi_n \lor \chi \lor \psi_1 \lor \ldots \lor \psi_m \quad \text{resolution} \] Assuming the usual interpretations of the conjunction (\(\land\)) and disjunction (\(\lor\)) in classical logic, the intuition behind the resolution rule is explained using the following instance of the resolution rule. \[ a \lor \neg b \quad b \lor c \] If the first premise is true, and \(b\) is true - that is, \(\neg b\) is false, then \(a\) must be true. If the second premise is true, and \(b\) is false, then \(c\) must be true. Now, both premises must be true for the conclusion to be true, and \(b\) must be either true or false in classical logic. So, either \(a\) must be true, or \(c\) must be true, and this is the logical representation of our conclusion. There exist logical calculi - that is sets of inference rules - that, given a set of clauses, can generate all clauses that are logically entailed by this set. In other words, these calculi are generatively complete. Resolution is a powerful rule since it alone constitutes a logical calculus. Even though the resolution calculus isn’t generatively complete, it has the useful property that if a set of clauses are unsatisfiable, then the calculus will derive the empty clause \(\bot\) from this set of clauses. ### 4.2 Proofs at the Propositional Level At the propositional level, the proof system works as follows. Given an execution of an DPLL(T) based SMT solver that ends in the fail state, we can prove that the input formula \(F_0\) is unsatisfiable as follows. We use the resolution calculus mentioned above to build a refutation tree - a tree with the input clauses and the learned clauses at the leaves, that lead - through the application of the resolution rule - to the empty clause \(\bot\). The learned clauses aren’t technically in the leaf position, since they need to be justified as well. A learned clause is obtained, when an input clause that is conflicted by the context \(M\) is modified by the application of the Explain rule. In fact, the Explain rule resolves the... current conflict clause with a clause belonging to \( F \) to obtain a new conflict clause. So proofs for learned clauses are also resolution proofs that are built by observing the conflict clauses and the explanations applied. Figure 5 shows the proof tree for the unsatisfiability of \( F \) from the example in Figure 2. The nodes of the tree contain the clause being used followed by the step number from algorithm in parentheses. The left subtree is a proof of \( \neg a \). The right subtree is the proof of \( a \) which is a learned clause. Steps 1 to 7 constitute the left subtree of the proof tree that adds \( \neg a \) as a learned clause to \( F \) (Although \( \neg a \) is actually used in Step 14, it is derived in Step 7). Steps 8 to 14 constitute the left subtree of the proof tree. Conflict clauses and explanations represent propositional resolution between clauses and the proof tree has a leaf for every application of the Conflict and the Explain rules - except the \( \neg a \) node since it is learned - and the node at the root represents the Fail rule. For the learned clause, the tree could be considered as a split of the current tree at the \( \neg a \) node. The left subtree of the new tree would then just consist of \( \neg a \) as a leaf, and the proof for \( \neg a \) would be a satellite proof tree representing the left sub-tree of the current tree. That is how it is depicted in [16]. 4.3 Proofs at the Theory Level At the propositional level, we saw proof trees as being refutation trees that derived \( \bot \) at the root using input clauses and learned clauses at the leaves, with learned clauses supported by satellite resolution proofs. At the theory level, we have clauses called theory lemmas that the theory solvers present to us to help us apply constraints from the theory level. Since the theory solvers come up with the lemmas, the proof is also expected to be at the theory level. And thus the theory solver also provides us with the proof for the lemma. In our refutation tree, when we arrive at a leaf with a theory clause, we ask the theory solver for its proof and plug it into the tree. Figure 6 shows the proof tree for the example from Figure 4. The part here that is different from the propositional case here is the theory lemmas in steps 3 and 4. Notice these aren’t leaves in the proof tree. A proof from the theory solver is plugged in to support these lemmas. The parenthesized numbers indicate the relevant step from the algorithm. 4.4 Theory Solver Proofs So far, section 4 has presented the proof-producing system of SMT solvers as building refutation trees up to the root containing ⊥, from leaves that are either inputs or learned clauses with supported proofs. In section 4.3 we added to this picture, the idea of proofs from theory solvers. This section talks about these proofs produced by theory solvers which aren’t the resolution proofs we have got used to seeing. Instead, these proofs are in natural deduction [23], which is a calculus that is more expressive than the resolution calculus, and can even be generatively complete. The main rule we are concerned with is the proof by contradiction rule, which works as follows. If you assume ψ and derive False, then ¬ψ is true. Theory solvers use theory specific rules along with the proof by contradiction rule, to prove their lemmas. Consider the following example from [16]. The EUF proof for the lemma $L = (x \neq y) \lor (z \neq f(y)) \lor (f(x) = z)$ is as follows. 1. Convert the lemma into its negation: \[ \neg L : \neg((x \neq y) \lor (z \neq f(y)) \lor (f(x) = z)) \] which is equivalent to \[ L_1 : (x = y) \land (z = f(y)) \land (f(x) \neq z). \] 2. Prove that $L_1$ is false using rules of EUF as necessary. \[ \frac{ x = y \quad \text{Cong.} \\ f(x) = f(y) \quad \text{Symm.} \\ z = f(y) \quad \text{Trans.} }{f(x) \neq z \quad \perp} \] The leaves of this contain input formulas, or the literals in $L_1$. The congruence rule (Cong.) gives $f(a) = f(b)$, given $a = b$. The other two rules refer to symmetry (Symm.) and transitivity (Trans.) of equality. 5 Comparison This section compares the proof systems of 3 state-of-the-art solvers CVC4, Z3, and VeriT as described in [16], [9], and [12] respectively. Although each paper introduces proof production in an SMT solver, they are from different times, and aimed at different goals. This section begins by summarizing each paper and then comparing the proof production systems by some particular metrics. 5.1 CVC4 The proof production system of the CVC4 SMT solver is described in [16]. The paper introduces the concept of lazy proof production for SMT solvers. In DPLL(T), the SAT solver reasons about the input formula using feedback from theory solvers in the form of theory lemmas. The proof of unsatisfiability is a refutation proofs that has input clauses, learned clauses, and theory lemmas at its leaves, and derives the empty clause at the root. The SAT solver is able to build the refutation proofs for the input formula; however, these proofs are completed using proofs for the theory lemmas from the theory solver. One way to produce these proofs would be to have the theory solver produce proofs eagerly every time a theory lemma is generated. However, in [16], the authors found that doing this lazily is efficient - that is, all proofs for theory lemmas are generated only after the final refutation tree has been found. Once the tree is generated, the solver asks the respective theory solver for the proofs for each theory lemma to complete the tree. This means that each theory lemma occurring in the proof gets processed twice: once when they are generated for solving, and again when they need to be proved for the tree. However, by producing proofs lazily, in most cases the solvers save a lot of computation since many lemmas produced during solving do not end up contributing to the final refutation. [16] discusses lazy proof production for three different theories - equality over uninterpreted functions (EUF), arrays with extensionality (AX), and bitvectors (BV). For EUF, they propose a completely lazy approach. For AX, they do lazy proof productions with some book-keeping. Briefly, arrays are representable as terms in the AX theory - \( a[i] \) is the result of reading the value at index \( i \) in array \( a \) and \( a[i] := b \) is the result of writing value \( b \) to array \( a \) at index \( i \). An axiom that the array solver uses to produce proofs is the extensionality axiom: for any two arrays \( a \) and \( b \), if \( a \neq b \) then there exists a \( k \) such that \( a[k] \neq b[k] \). Since this axiom requires that the disequality of two arrays is witnessed by an index \( k \), the value of \( k \) needs to be stored so that when the proof is being produced for this unsatisfiability lazily, the solver can use this information to produce the proof. Finally, proof production for BV, elaborated in [14], is done semi-lazily. Bit-vectors are arrays of binary bits, so they are solved by a technique called bit-blasting where bitvector formulas are converted into an equisatisfiable propositional formula which is solved by an internal SAT solver. Since redoing the bit-blasting technique can be expensive, the SAT solver eagerly records a trace of the bit-blasting refutations. In contrast, the proof for the bit-blasting process - converting a formula to a propositional one, is done lazily for lemmas that occur in the final proof. The paper concludes by showing comparisons between lazy and eager proofs for EUF and AX- they extend CVC4 with lazy and eager proof production systems, and check the proofs for a set of standard benchmarks. The evaluations show that for most of the benchmarks, CVC4 produces lazy proofs faster than eager ones. 5.2 Z3 Z3 is an SMT solver developed at Microsoft Research. [9] elaborates on the proof production system of Z3, highlighting their approach of implicit quotation and their natural deduction style proofs for theory lemmas, also explained in Section 4.4. Implicit quotation is an implementation detail that saves the Z3 solver computation when it comes to CNF conversion of input formulas of the SMT solvers. As explained in 3.1, a formula that needs to be checked for satisfiability by an SMT solver is first converted to CNF. This is done by recursively taking the subterms of the input formula, and creating equivalences between the subterms and fresh variables. Since an equivalence is logically the same as a conjunction of inferences, this method fits well into CNF conversion. For example, \( a \iff b \) is converted to CNF as follows. \[ \begin{align*} \text{Step 1} : & \quad a \iff b \\ \text{Step 2} : & \quad (a \Rightarrow b) \land (b \Rightarrow a) \\ \text{Step 3} : & \quad (\neg a \lor b) \land (\neg b \lor a) \end{align*} \] Introducing these fresh variables increases the number of literals in the formula. Z3 treats the subterm itself as a literal. To distinguish the literal representation from the sub-term, they quote it. If \( a \) above is a fresh literal, and \( b \) is a sub-term representing the formula \( x \land y \), instead of introducing the fresh literal \( a \), Z3 stores a quoted version of the formula - \( [x \land y] \). By doing this, they avoid all the extra clauses that are added to the formula to maintain this equivalence, as shown in the example above. Instead, the name of the literal gives enough information to tell us what formula it is abstracting. They provide an example of using implicit quotation for slack variables during linear integer arithmetic solving. This paper also briefly explains the proof producing calculus, which is similar to the calculus explained in sections 2 to 4, except that they choose a different representation. Their main rules can be summarized as follows. A rule called \textit{unit resolution} handles a general form of resolution. The \textit{hypothesis} rule states a statement that needs to be proved. This is done by the \textit{lemma} rule by a proof by contradiction. An important characteristic of proofs in Z3 are that the proof producer axiomatizes many theory rewrites. These can be considered holes in proofs that must be proven by the proof checker. As argued in [16], this gives the proof checker work that is more nontrivial than just checking proofs - they actually need to fill in parts of the proofs. [9] argues that this is a trade-off that saves the solver time in producing proofs and that proof checkers are fairly well-equipped to prove these axioms. 5.3 VeriT [12] describes the proof production system of the haRVey SMT solver, which was a precursor to the solver VeriT. This paper is more application-oriented than the other two. As mentioned in Section 1, verification tools can be evaluated using three different metrics - soundness or trustability, automation, and expressiveness. There are classes of tools that score highly on one or two of those qualities, but not all. [12] combines harVey, a highly automated tool with Isabelle/HOL a proof assistant, which is a tool that interactively allows a user to prove theorems in higher-order logic. The user benefits from the expressive higher-order logic and the high trustability of Isabelle/HOL while also benefitting from the automation of the SMT solver. The trade-off of course is the work done to have the SMT solver produce proofs of its work to the proof assistant, before its results are trusted, which has been the theme in all the papers that I chose to study. This work is an improvement on previous work that use the SMT solver as an oracle, without requiring it to produce proofs. HarVey provides proof hints to Isabelle that helps the proof assistant reconstruct the proofs of the theorems proven by the SMT solver. Proof assistants such as Isabelle offer users functions known as tactics that help the user in their proof aspirations. HarVey benefits from converting its proofs into expressions in sequent calculus, which is an alternate notation for formulas in natural deduction, since Isabelle is well-equipped to deal with sequents. Modulo this encoding as sequents, proof production is similar to the methods described in this report. They extended Isabelle with the sat and satx tactic that can be called in the proof assistant for proving subgoals of the current goal being proven. This work also suggests optimization techniques for SMT solving such as operating on partial models that are models of a formula where not all literals in the formula are assigned a value. This has the benefit that finding a partial model that is unsatisfiable eliminates multiple full models that the partial model can be extended to. For instance, if a formula contains literals $a = b$ and $f(a) \neq f(b)$ and 1000 other literals, all models in which $a = b$ and $f(a) \neq f(b)$ are unsatisfiable, regardless of the values of the 1000 other literals. Finally, the paper presents a congruence closure algorithm to solve formulas in the theory of equality over uninterpreted functions (EUF). In this theory, we only know the function symbols as they appear in terms, without knowing their full behavior. The algorithm propagates the equalities from the formula using the rules of reflexivity, transitivity, and symmetry along with the congruence rule that gives $f(a) = f(b)$ given that $a = b$. Once a disequality is found between terms found to be equal, the algorithm concludes that the formula is unsatisfiable. Section 4.4 shows a small example. The implementation interface between Isabelle and harVey takes proofs for lemmas in the theory of EUF and reconstructs them for the proof assistant. In short, this is how the interface works. When the user is trying to prove something in Isabelle, they may have the subgoal of proving a formula $F$, that is to show that $F$ is valid. This is the same as checking whether $\neg F$ is unsatisfiable. So the user invokes the sat or satx tactic from Isabelle which has harVey check $\neg F$ for unsatisfiability. If $\neg F$ is satisfiable, the model provided by harVey is given to the user as a counterexample for $F$. If it is unsatisfiable, then harVey constructs a proof trace of the unsatisfiability along with proofs of any theory lemmas used, encodes them as sequents, and sends it to the interface at Isabelle, where the proof is reconstructed. 5.4 Differences and Similarities All three papers discuss the proof production systems of DPLL(T)-based SMT-solvers. Sections 2 to 4 explain the concepts that these systems have in common - the DPLL(T) algorithm and resolution-based proofs. Each paper does take a different approach in explaining this concept. This report borrows the formalizations of these concepts from [16] which seemed to do the best job of elaboration with examples. The following discuss some particular points of comparison between the papers. Eager vs Lazy Proof Production. CVC4 introduces the idea of lazy proof production in the paper, and argues for their use by presenting evaluations on particular fragments of the solver. The authors also suggest that one approach might work better than the other, depending on the theory solver concerned. Z3 takes an eager approach, in which it skip logging the steps taken by the solver. Instead it produces proofs during conflict resolution. Fine-Grained vs Coarse-Grained Proofs. CVC4 produces fine-grained proofs in which the tinier details of the proofs are also accounted for. Input formulas are converted to CNF; the CNF clauses, the learned clauses, and the theory lemmas constitute the leaves of the proof tree. While the input clauses are axioms, the learned clauses are entailed by the input formula and this entailment is proven by a separate resolution tree for each clause. Theory clauses are produced by theory solvers which also provide the proofs for these clauses. The advantage of fine-grained proofs is that they are complete, and the proof checker only needs to check them. The disadvantage is that the proofs must be well specified by the solver. There may be more rules, and since none of the truths in the theories are assumed, they must be specified as well. Proofs in Z3 are more coarse-grained in that they have holes in them that the proof assistant must fill in during proof checking/reconstruction. These holes might be obvious to fill for certain theories and prove practical in such cases. VeriT, or haRVey in this case, suggests taking a slightly coarse-grained approach as well, since they produce proof hints to the proof assistant to help it reconstruct the proof. However, this was aimed at a particular application, and papers published by the VeriT group seem to have fine-grained proofs [4]. Rewriting. Formula rewriting is an aspect of SMT solving that wasn’t mentioned in this work so far. Apart from conversion to a normal form, theory solvers rewrite simple truths in the formula. For example, \(x + 0\) could be rewritten to \(x\). Because of how solvers work to combine multiple theory solvers, these rewrites might complicate things by changing what a formula appears like. In CVC4’s lazy solvers, it is even more dangerous because solving and proving are decoupled. So a formula may look one way while solving, and be reduced to a rewritten form before the proof is extracted. The solution for this is to store the information of the rewrite so that the proof producer can prove the formula before it was rewritten, and the formula is then rewritten with some justification provided for the rewrite itself. Note that in the experiments that they conducted, the rewrites were still unimplemented, and thus axiomatized. In Z3, the rewrites seem to be prime candidates for the holes in the proofs - they are axiomatized and the proof checker is expected to prove them. **Proof Format.** Although these papers don’t talk about the formats of the solvers’ proofs, these solvers have other publications that explain in detail their proof format. CVC4 outputs proofs in the LFSC (Logical Framework with Side Conditions) format [22] that was developed by many of the same authors as [16]. LFSC is based on a simply typed $\lambda$-calculus with dependent types. The main idea is that the type theory uses the Curry-Howard isomorphism or the proposition-as-types/ programs-as-proofs analogy to reduce proof checking to type checking. LFSC takes an input proof term and a signature which declares the constants and functions in the theories, along with the proof rules. In [7], the developers of VeriT proposed a proof format that motivated by SMTLib, a standard syntax for SMT solvers [5], which it currently uses. To the best of my knowledge, Z3 doesn’t have a paper describing its proof format, but it does have its own proof format. Even though SMT solvers have been able to converge on a common input format in SMTLib, the same can’t be said for a proof format, as explained in [11]. 6 Conclusion and Moving Forward In this report, I have tried to summarize my investigation of the proof production systems of three state-of-the-art SMT solvers - CVC4, Z3, and VeriT. In the process, I have learned how SMT solvers produce refutation proofs for the formulas that they solve as unsatisfiable, by combining the internal SAT solver with its theory solvers. The papers also explain how theory solvers produce their proofs by means of a natural deduction calculus. This report presents these findings after introducing the basic working of an SMT solver. It also compares the the papers of the respective solvers and discusses some points of difference such as granularity of proofs, lazy proof production, and handling of rewrites by the solvers. The report also mentions the motivation for SMT solvers to produce proofs - these highly automatic tools with thousands of lines of code are ubiquitous in the verification community, and thus would benefit from giving soundness guarantees. One of the papers briefly investigates the connection between an SMT solver and a proof assistant. My motivation is aligned with this kind of work. The Coq proof assistant [15] is a popular proof checker that falls in the category of trustable verification tools. SMTCoq [10] is a Coq plugin that is able to leverage the power of an SMT solver to prove goals in Coq. The support for CVC4 in SMTCoq has been implemented for a few theories by my advisor, Cesare Tinelli’s research group at the Computer Science Department at the University of Iowa. My goal is to extend this support to other theories and the literature survey of the proof producing systems of SMT solvers is an important step toward that goal. References
{"Source-Url": "http://homepage.divms.uiowa.edu/~viswanathn/qual.pdf", "len_cl100k_base": 11493, "olmocr-version": "0.1.50", "pdf-total-pages": 20, "total-fallback-pages": 0, "total-input-tokens": 63968, "total-output-tokens": 14246, "length": "2e13", "weborganizer": {"__label__adult": 0.0004475116729736328, "__label__art_design": 0.0006799697875976562, "__label__crime_law": 0.0006399154663085938, "__label__education_jobs": 0.0027217864990234375, "__label__entertainment": 0.00016677379608154297, "__label__fashion_beauty": 0.0002593994140625, "__label__finance_business": 0.0004701614379882813, "__label__food_dining": 0.00072479248046875, "__label__games": 0.001583099365234375, "__label__hardware": 0.00121307373046875, "__label__health": 0.0009145736694335938, "__label__history": 0.00047898292541503906, "__label__home_hobbies": 0.00018012523651123047, "__label__industrial": 0.0010023117065429688, "__label__literature": 0.0007405281066894531, "__label__politics": 0.0005602836608886719, "__label__religion": 0.0008091926574707031, "__label__science_tech": 0.28515625, "__label__social_life": 0.00016260147094726562, "__label__software": 0.01004791259765625, "__label__software_dev": 0.689453125, "__label__sports_fitness": 0.0004432201385498047, "__label__transportation": 0.0009675025939941406, "__label__travel": 0.00024700164794921875}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 51292, 0.02723]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 51292, 0.82102]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 51292, 0.9119]], "google_gemma-3-12b-it_contains_pii": [[0, 1711, false], [1711, 4695, null], [4695, 8241, null], [8241, 10496, null], [10496, 13216, null], [13216, 16364, null], [16364, 17910, null], [17910, 19327, null], [19327, 21912, null], [21912, 23813, null], [23813, 26141, null], [26141, 28646, null], [28646, 30864, null], [30864, 34171, null], [34171, 37179, null], [37179, 40592, null], [40592, 43959, null], [43959, 46855, null], [46855, 49154, null], [49154, 51292, null]], "google_gemma-3-12b-it_is_public_document": [[0, 1711, true], [1711, 4695, null], [4695, 8241, null], [8241, 10496, null], [10496, 13216, null], [13216, 16364, null], [16364, 17910, null], [17910, 19327, null], [19327, 21912, null], [21912, 23813, null], [23813, 26141, null], [26141, 28646, null], [28646, 30864, null], [30864, 34171, null], [34171, 37179, null], [37179, 40592, null], [40592, 43959, null], [43959, 46855, null], [46855, 49154, null], [49154, 51292, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 51292, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 51292, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 51292, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 51292, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 51292, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 51292, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 51292, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 51292, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 51292, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 51292, null]], "pdf_page_numbers": [[0, 1711, 1], [1711, 4695, 2], [4695, 8241, 3], [8241, 10496, 4], [10496, 13216, 5], [13216, 16364, 6], [16364, 17910, 7], [17910, 19327, 8], [19327, 21912, 9], [21912, 23813, 10], [23813, 26141, 11], [26141, 28646, 12], [28646, 30864, 13], [30864, 34171, 14], [34171, 37179, 15], [37179, 40592, 16], [40592, 43959, 17], [43959, 46855, 18], [46855, 49154, 19], [49154, 51292, 20]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 51292, 0.0]]}
olmocr_science_pdfs
2024-12-01
2024-12-01
d60ce46d227f343b5932992b2f4f8171212dd080
Full-System Critical Path Analysis Ali G. Saidi† Nathan L. Binkert‡ Steven K. Reinhardt†* Trevor Mudge† saidi@eecs.umich.edu binkert@hp.com stever@reservoir.com tnm@eecs.umich.edu †The University of Michigan ‡Hewlett-Packard Labs *Reservoir Labs Department of EECS Palo Alto, California Portland, Oregon Abstract Many interesting workloads today are limited not by CPU processing power but by the interactions between the CPU, memory system, I/O devices, and the complex software that ties all the components together. Optimizing these workloads requires identifying performance bottlenecks across concurrent hardware components and across multiple layers of software. Common software profiling techniques cannot account for hardware bottlenecks or situations where software overheads are hidden due to overlap with hardware operations. Critical-path analysis is a powerful approach for identifying bottlenecks in highly concurrent systems, but typically requires detailed domain knowledge to construct the required event dependence graphs. As a result, to date it has been applied only to isolated system layers (e.g., processor microarchitectures or message-passing applications). In this paper we present a novel technique for applying critical-path analysis to complex systems composed of numerous interacting state machines. We avoid tedious up-front modeling by using control-flow tracing to expose implicit software state machines automatically, and iterative refinement to add necessary manual annotations with minimal effort. By applying our technique within a full-system simulator, we achieve an integrated trace of hardware and software events with minimal perturbation. As a result, we can perform this analysis across the user/kernel and hardware/software boundaries and even across multiple systems. We apply this technique to analyzing network performance, and show that we are able to find performance bottlenecks in both hardware and software, including some surprising bottlenecks in the Linux 2.6.13 kernel. 1 Introduction A key challenge in evaluating the performance of a modern computer system is that end-to-end behavior is the result of often subtle interactions between many complex, concurrently operating hardware and software components. When results do not match expectations, locating the bottleneck component is difficult. As architects and developers look to improve system performance, the areas in which they should focus their effort are not necessarily clear [15]. They can be left with no choice but to rely on ad-hoc methods or intuition, which can be faulty, or to explore a huge state space, which is costly both in terms of time and resources. This situation is particularly acute in high-bandwidth network processing [7], where there is no single bottleneck that can be easily addressed. Instead, performance losses come from the combination of numerous overheads in interactions between the network protocol, software running on the CPU, the memory system, and the network interface controller [11, 18]. For example, consider the case where the end-to-end bandwidth between some sender and receiver is lower than expected. There are a number of reasons that this could be the case: - Transmit data is queued for the network interface controller (NIC) in its DMA descriptor ring, but the NIC DMA controller cannot process the descriptors quickly enough. Perhaps the NIC cannot fetch the descriptors fast enough or the I/O bandwidth is insufficient to fetch descriptors and packets at the rate the OS is making them available. - There is data ready to be transmitted in the kernel, but the device driver cannot fill the NIC’s DMA descriptors from the kernel I/O buffers quickly enough. Perhaps the number of allocated buffers is insufficient, or the overhead of reclaiming processed buffers is too high. - The application has requested a transmission, but the kernel’s TCP/IP protocol stack has not completed processing the data so the device driver has not received it. - There is data ready to be transmitted in the kernel, but the TCP protocol is delaying transmission because the receiver has not advertised sufficient buffer space to accept it. In this case, the receiving system is the bottleneck; a similar exercise must be repeated on that system to isolate the bottleneck to the NIC, device driver, kernel, application, or other source. - There is data ready to be transmitted in the kernel, but the TCP protocol is delaying transmission because the number of outstanding packets has reached the TCP congestion window size. The application has not requested a transmission via `write()` or `send()`. In this case, the application is the bottleneck. Note that these reasons span from hardware through kernel code up to the application on both the sending and receiving systems. Furthermore, because the transmission process is pipelined, simply observing snapshots of system state is insufficient: at any given point in time, the application, kernel stack, device driver, and NIC may all be actively operating on different data units without any obvious indication of which one is the bottleneck. Finally, each of the reasons listed is only an intermediate determination, not a final cause. For example, if the application or protocol processing is the bottleneck, further analysis is required to determine which part of the code is problematic, whether the lack of performance is due to limitations in instruction execution or memory bandwidth, etc. We have found that the complexity of this problem generally stymies attempts to tease out bottlenecks using traditional means such as ad-hoc analysis or iterative testing of hypotheses. In this paper we describe and apply a rigorous methodology to identify bottlenecks quantitatively using critical-path analysis. A prerequisite for critical-path analysis is an event dependence graph representing timing constraints (PERT chart). Unfortunately, since there are many interacting components, the task of developing a global dependence graph through ad-hoc familiarity with the subject matter rapidly becomes intractable. We make the following contributions in this paper: 1. We describe an automated technique for converting systems of multiple interacting state machines into a global dependence graph suitable for performance analysis, including bottleneck identification. 2. We show that the annotations necessary for this analysis can be developed with modest effort and without detailed knowledge of the particular implementation of the components involved; in particular: - (a) state machines implicit in complex software systems, such as the Linux kernel’s UDP and IP stacks, can be traced with limited manual effort by relying primarily on control-flow tracing and symbol table lookup - (b) the necessary inter-state-machine dependence annotations can be uncovered using iterative refinement 3. We demonstrate an implementation of our technique that uses a full-system multi-machine simulator to identify bottlenecks across hardware/software boundaries. Implementing our analysis using a simulator provides deterministic results and easy, low-overhead observability of both hardware and software components, along with the ability to find performance bottlenecks in hardware designs before they are built. We believe the techniques presented here could be applied to real systems using instrumentation toolkits such as DTrace [5] or the Linux Trace Toolkit [20], though the observability of hardware devices would likely be more limited. We discuss our techniques in Section 2 and our particular implementation in Section 3. In Section 4 we describe an experimental analysis we performed using our tools, presenting results in Section 5. We discuss related work in Section 6, and we conclude and present future work in Section 7. ### 2 Technique Critical-path analysis is a powerful technique for identifying the key bottlenecks in a complex system with multiple concurrent operations. It can also provide other useful metrics such as slack (the amount of additional time an operation could take without impacting the system) and speedup potential (the difference between the critical path and the next-most-critical path). The prerequisite for critical-path analysis is a graph representing the dependences and timing between events in a system. Building this graph for a simple system with a few events is relatively simple. However, as the scope of the analysis increases, the difficulty of building the graph increases at a faster rate: in the extreme, the number of possible event interactions increases as the square of the number of events. In the networking domain, the task of developing a global dependence graph between the application, kernel stack code, device driver, and NIC rapidly becomes intractable. The task requires substantial effort, and detailed knowledge of all the systems involved. We have identified a key technique that enables us to extend critical-path analysis to a much wider scope by algorithmically mapping the state machines that govern the behavior of individual components (software or hardware) to a global dependence graph representing the overall execution of this collection of machines. Our technique involves two steps. First, the execution of each individual state machine is converted into a dependence graph. Second, the dependencies between the individual state machines (or equivalently their dependence graphs) must be explicitly marked. We begin by describing the conversion of an explicit state machine to a dependence graph. While some systems, such as hardware devices, are designed as state machines, software normally is not. Thus for software systems we have the additional challenge of generating a meaningful implicit state machine from program execution. We automate this process substantially by using program flow control information to identify states. The final step of identifying dependences between state machines must be performed manually. We describe how this step can be done in an incremental, iterative fashion, eliminating the need for substantial up-front effort. #### 2.1 Explicit State Machines We convert a state machine into a dependence graph by a simple transformation. The fundamental insight is that events of interest, which are the nodes in the dependence graph, correspond to transitions (edges) in the executing state machine. Similarly the time spent waiting between events, which are edge weights in the dependence graph, correspond to the time spent in a state of the state machine. There is thus a correspondence between the states (nodes) of the state machine and the edges of the dependence graph. These two equivalences are sufficient to generate a dependence graph from the execution of a single state machine. We illustrate the conversion of one explicit state machine in Figure 1. An execution path through the state machine is transformed into a DAG by turning each edge traversal into a node and each node visit into an edge, with the edge weight corresponding to how long the state machine remained in the corresponding state. When multiple state machines interact, they do so because a transition in one state machine creates an output that induces a transition in a different state machine. In this case, an edge must be inserted in the dependence graph between the node representing the first state machine’s transition and the node representing the induced transition. The weight on these inter-state-machine edges corresponds to the communication latency between two interacting state machines and is normally assumed to be zero. Additionally, the weight on the other (intra-state-machine) edge coming into the induced transition node is set to zero. This edge corresponds to the waiting state in the consuming state machine, which ideally has no inherent latency of its own. Setting this weight to zero enables the correct calculation of the critical path through the node. This technique reduces the generation of a global dependence graph to the description of several local state machines and their interactions. These local state machines are often well understood—in fact, hardware devices are often specified in terms of these state machines—or can be derived by inspection. To further illustrate this process, consider the state machines presented in Figure 2. These state machines are simplified versions of three state machines in a NIC that interact to send packets out onto the network. The Descriptor Fetch state machine DMA’s buffer descriptors from main memory where the device driver has placed them. The Transmit state machine reads these descriptors, DMA’s any packets that are referenced in them, and places the packet in the outbound FIFO. Finally, the TX FIFO state machine takes packets from the TX FIFO and sends them out onto the wire. Figure 3 shows one set of possible paths through the state machines in Figure 2. Note that the nodes are the transitions between states and not the states themselves in this graph. In the scenario shown, the TX FIFO state machine waits on the Transmit State machine, and the Transmit state machine waits on the Descriptor Fetch state machine. Once the Descriptor Fetch state machine has fetched a descriptor, the Transmit state machine can DMA the associated packet and hand it off to the TX FIFO state machine to be sent down the wire. For our analysis, we must record two events: when the machine enters a new state (including the identity of the state being entered) and when the machine is blocked waiting on an external state machine (including the identity of the state machine and state being waited on). The mechanism for recording these events will vary, depending on both the nature of the state machine itself (e.g., software vs. hardware) and the instrumentation environment (e.g., run-time tracing on real hardware vs. simulation). In Section 3, we discuss how we annotate state machines to record these events in our simulator-based implementation. The resulting dependence graph (which is very similar to a PERT chart [16]) is a fully connected DAG. (Any unconnected component is not on the critical path and can be ignored.) Every node in the graph corresponds to some state machine making a state transition, and the edges between nodes are weighted with the amount of time spent in that state. Every interaction edge represents a causal interaction and thus must point forward in time. We call this graph a bottleneck graph (bgraph) for the remainder of this paper. The critical path between two nodes in the bgraph can be found using standard graph analysis techniques. Generally, the critical path of interest is one that starts where a request or data is produced and ends where the result is consumed. In our future discussion we use the term starting state machine to be any node in the producing state machine and destination state machine to mean any node in the consuming state machine. 2.2 Implicit state machines It is not always the case that a component design is based on an explicit state-machine model, particularly for software components. Even when a software design is based on a state machine, that structure may not be evident in the source code. Nevertheless, for the purposes of our analysis, each software component must be decomposed into states where the component is busy and states where it is waiting on an external component for input. Given this decomposition, along with the transitions in the software component on which other state machines wait (i.e., outgoing dependence edges), we can determine whether the component is a bottleneck. If the component is a bottleneck, it may be desirable to decompose its behavior further into finer-grained states to better understand the nature of that bottleneck. To enable non-experts to identify the state machines—even in such substantial pieces of unfamiliar software as the UDP and IP stacks in the Linux kernel—we can automatically generate an initial decomposition by using function entry and exit points (calls and returns) to delineate state boundaries. These events can be recorded at runtime with the aid of a binary recompiler, JIT, simulator, or VM. If the symbol table is available, the states can be labeled according to source function names. Given this automatic decomposition, the manual effort is reduced to three tasks, all of which can be performed incrementally as described in the following section. All of these tasks are handled by manual identification of points of interest using source-code annotations. We discuss our annotation implementation further in Section 3.2. The first task is identification of inter-state-machine dependences, which is largely unchanged from the explicit state machine case. Second, the automatic decomposition may require refining if there are places where the function-level decomposition is too coarse, e.g., if there is a waiting state in the middle of a function. The third task arises when a single executable binary Figure 1: Conversion of a state machine. a) The original state machine; b) the trellis of that state machine (a DAG of all possible state transitions in a state machine); c) the execution path through the trellis; d) the conversion of the execution path to a set of nodes in the global dependence graph. (e.g., an application or the Linux kernel) contains multiple state machines. In this situation, users must indicate when the CPU’s execution path leaves one state machine and enters another. This event typically corresponds to a call from one subsystem into another, e.g., from the protocol stack into the device driver, and is thus not too difficult to recognize. The CPU may also switch from one state machine to another when executing an interrupt handler or time-slicing between applications. For software state machines sharing a single CPU, the currently executing state machine stops running when a new state machine begins because of an interrupt or function call. In our experience so far, the difficulty in instrumenting software state machines has been minimal, requiring not more than a few hours of effort. For example, fewer than 100 lines of annotations were required to instrument the entire UDP code path—from application to driver—in a 2.6 series Linux kernel. We have gone through the process twice now, once manually instrumenting all states of interest and a second time relying on a tool to automatically generate software states as described above. 2.3 Iterative Model Construction and Verification A key feature of our approach is that a complete and detailed state-machine decomposition is not required to perform analysis. As a result, users can make some minimal initial effort towards labeling states and inter-state-machine dependences, or use automatic tools as described above; use this information to perform an initial analysis; then use the results of that analysis to identify where critical modeling information is missing. This technique allows users to construct the model through iterative refinement, focusing their effort on the interesting and relevant portions, and using some trial-and-error where necessary to tease out key model attributes. There are several tell-tale signs that a model is incomplete. States that are occupied for extremely long periods are typically waiting on another state machine, indicating a missing inter-machine dependence edge. Incorrect dependences can be detected by observing when a state machine that is labeled as waiting advances before the waited-on transition occurs. Our implementation prints a detailed warning message in this situation. Spurious edges connecting otherwise disjoint components often indicate that a transition between separate software state machines was not labeled. The function-based state names produced by our automatic decomposition do a reasonably good job of indicating the software state machine to which they belong, aiding in identifying these situations. If there is no path from the starting state machine to the destination state machine, there are two possibilities. One is that the graph has disjoint components, in which case the user can direct their attention to the state machines on either side of the disconnect, where a dependence has likely been overlooked. The other possibility is that a resource along the way is so under-provisioned that a producing state machine is always waiting on its consumer, e.g., a queue is always full causing the producer to stall. In this situation, only the dependence edge from the consumer to the producer is created; because the system never observes the consumer waiting on the producer, the corresponding forward dependence edge does not exist. As a result, the graph is not strongly connected. We have only seen this happen when we intentionally under-provisioned a resource. The situation is easily identified by starting at the destination state machine and traversing inter-state-machine edges in reverse until a state machine is found that has no incoming inter-state-machine edges. 3 Implementation In this section we describe our particular implementation of the analysis technique described above. First we discuss the simulator that we used, followed by the changes required to enable annotation of state machines. Next we discuss the tool that processes the recorded annotations, and finally we discuss the analysis and visualization techniques we have found useful. 3.1 M5 Simulator Though our approach is not restricted to simulation, a simulator provides benefits not easily obtainable otherwise, specifically deterministic results and complete visibility into all aspects of both hardware and software. For this work we use the M5 simulator [4], which models Compaq Alpha systems with enough fidelity to boot unmodified Linux 2.6 kernels and includes a range of hardware components including multithreaded out-of-order processors, multi-level memory hierarchies, and I/O devices. M5’s full-system simulation capability and detailed performance models of memory and I/O devices are particularly important, as they provide state-machine timing information from not only the application but also the kernel and hardware devices to enable meaningful end-to-end critical path analysis. 3.2 Supporting Annotations We perform an analysis experiment in two steps: first M5 simulates the system(s) of interest and outputs the annotations to a file, then an analysis program reads the file and processes it. Decoupling the data generation and data analysis allows interactive analysis of the data. This ability comes at the cost of storage space for the data; however, in practice, this requirement has been relatively modest. One million annotation records require approximately 15MB of storage space (4MB compressed). The amount of simulated time these annotations represent is dependent on the workload and the number of states in each state machine. Our automatic function-based approach to decomposing software leads to software state machines have hundreds of states. As a result, our current system generates a million annotations for every hundredth of a second of simulated time. Due to the cost of detailed performance simulation, a typical run may represent only a second of real time, producing about 1.5GB of uncompressed annotation data. Since M5 uses software models to simulate all hardware components, adding state-machine annotations to the hardware is as simple as calling a function when the hardware model changes states. We added two functions to M5, begin(state_machine, state) and wait(state_machine, state, wait_state_machine, wait_state), which record their parameters in a buffer. Periodically this buffer is flushed to disk. To annotate software state machines, we leverage the simulator’s ability to monitor execution with minimal system perturbation. Given some processor state (PC, privilege level, etc.) the simulator can find the nearest symbol (function name or label) and in that way we can automatically create states from symbol names in the kernel and applications as described in Section 2. When the simulator observes a branch-and-link instruction, it automatically finds the target symbol and records the beginning of a new state. However, using this technique, it is unclear what state machine that particular state belongs to. We solve this problem by annotating the entry and exit of state machines with pseudo-instructions. During simulation, we maintain a stack of active state machines, pushing the old machine each time a new state machine is entered and popping the old machine when the currently running machine is exited. Whenever a context switch occurs, we also change our state machine stack to the one that matches the newly running thread. Finally, we check that state machines are popped in the same order they are pushed, verifying that all entries and exits of the state machines are properly annotated. In this way every function in the kernel and application can become its own state with no overhead and the user need only annotate the beginning and end of state machines as well as where waiting occurs. Explicit annotations in source code are converted (using gcc asm directives) into “pseudo-instructions” in the application and kernel binaries. These pseudo-instructions are encoded as unused opcodes and instruct the simulator to take a specific action. We have four pseudo instructions: beginSM(state_machine), endSM(state_machine), begin(state), and wait(state, wait_state_machine, wait_state). These instructions mark the beginning of a state machine, the end a state machine, entry into a state (in case the user wants to split up a large function), and waiting for a state machine, respectively. In each case the simulator simply records the event type, time of occurrence, and parameters involved. 3.3 Analysis The bottleneck graph described above can be used for both data visualization and to find the critical path. While it’s useful to think about the graph as a whole, building the entire graph is impractical. The graph quickly consumes memory and becomes difficult to work with, let alone visualize. While the algorithm to find the longest path of a DAG is straightforward [6], the time to do these operations on millions of nodes is impractical. We solve this problem by avoiding the need to construct the full graph in memory. Instead we utilize the structure of the graph to find the critical path while reading in the data produced by our simulator. Because of the structure of the graph if the annotations are processed in the order that they occurred—which is trivial to do—the critical path from a given starting state machine to the current node is either from the previous node in that state machine or via an interaction with a different state machine. Thus to find the critical path we only need to store the current longest path from the start point to the newest state transition in each state machine. Any time one state machine interacts with another one, that state machine chooses the longer of its longest path or the longest path from state machine it’s interacting with. Hollingsworth et al. used a similar method for their online computation of critical paths in the MPI domain [14]. With this method our analysis program can process 1 million annotations in approximately 80 seconds. While the above technique can quickly find the critical path and can provide considerable data on the graph structure for analysis, it’s also useful to visualize the graph to see how and where various state machines interact. Unfortunately, as mentioned previously, the graph is far too large to visualize when the number of nodes exceeds a few thousand. To cope with this problem, we created a graphical model that is a hybrid between a canonical state machine graph and the previously described bgraph. We call this graph a combined graph (cgraph). Like the bgraph, cgraph nodes are state transitions; however, there is only one cgraph node for each transition regardless of the number of times that transition occurs at runtime. These transformations result in a graph that is much easier to visualize and work with. An example of this combined graph (based on the NIC model of Figures 2 and 3) is shown in Figure 4. Nodes are labeled with the system (computer) they belong to and the transition that is taking place. Edges are labeled with a state name and three numbers corresponding to the number of entrances into that state, the time spent in that state, and the time on the critical path spent in that state. We define the criticality of a particular state as the ratio of the time spent on the critical path in that state to the total time on the critical path. This metric gives a quick summary of the most important states on the critical path that is easy to compare with other experiments. This criticality is available by itself and is also coded on the graph by varying the edge color from black (non-critical) to red (most critical). There are several graph invariants: 1. For every node in the graph, the sum of the entrance count of the outgoing edges must be equal to the sum of the entrance count of the incoming edges.¹ 2. The time on the critical path in the node can not exceed the time spent in that node. ¹This count can be off by one due to the window in which data was recorded. 3. For every system and state machine, there exists only one node for any state transition $A \rightarrow B$. 4. For any edge, there can be more than one edge corresponding to the same state. Multiple state transitions can end up in state $B$, so an edge corresponding to state $B$ must be able to appear multiple times. 5. Inter-state-machine edges (dashed lines) do not represent any time spent executing in a state machine but instead describe interactions between state machines. When a state machine $A$ reaches a state $X$ in which it is waiting for another state machine $B$ to reach state $Z$ before it can continue, an inter-state-machine edge is placed between the successor of state $X$ in state machine $A$ and the node in state machine $B$ that begins state $Z$. In Figure 5, we show a complete cgraph based on the data presented in the results section. All the text normally on the graph has been removed as it would be too small to read. Though the graph’s details are illegible, we include it to illustrate its size and complexity. Even though the cgraph is quite large, it is many orders of magnitude smaller than the corresponding bgraph, and is not too difficult to navigate online using panning and zooming. We present and discuss the most interesting portions of this graph in the results section. 4 Methodology We have tested our methodology by running micro-benchmarks under Linux 2.6 on an appropriately modified copy of the M5 simulator. In the following sections we describe the benchmarks and simulator parameters in turn. 4.1 Benchmarks Netperf [13] is a network microbenchmark suite developed at Hewlett-Packard. We used the UDP stream benchmark with the system under test sending UDP packets to its peer as fast as possible. In general, the time spent executing the user-space code is minimal; most of the processing time is spent in the networking stack processing packets or in driver code managing the NIC. Netperf produces a bandwidth measurement indicating the maximum achievable communication rate between two systems. Though the critical-path analysis identifies the bottleneck in terms of latency, this latency bottleneck will also be the bandwidth bottleneck for the pipelined transmission of multiple packets. Put another way, if a state machine is still processing a block of data when the next block for it to process arrives it is both a source of additional latency and limits the rate at which the blocks of data can flow out of the system. For the results shown in the next section we used a selection of kernels, parameters and packet sizes, each illustrating a different bottleneck. We started with Linux 2.6.13. After doing some initial experiments we found some interesting and unexpected performance problems in the kernel’s “netfilter” code, which provides packet-filtering hooks used to implement firewalls and network address translation in Linux. To further investigate these we also used Linux 2.6.16 which fixed a number of issues with the netfilter code. In addition we ran each kernel with netfilter enabled and disabled. In our simulations we used a fixed 1500 byte maximum transmission unit (MTU) as is standard on the internet today. We ran Netperf with two different UDP packet sizes, 1480 bytes (equal to the MTU after a header is added) and 16KiB (greater than the MTU, thus requiring fragmentation), to see how the bottlenecks are affected when fragmentation is introduced. 4.2 Simulator Parameters As mentioned before, we modified a copy of the M5 simulator to support the annotating of states in hardware state machines and in software. We configured M5 to model an Alpha 21264 system based on the Compaq Tsunami chipset and used the default parameters for such a system with few exceptions. The I/O latencies were set to values similar to that of real hardware and the L2 cache size was set to 8MB. Additionally, the bandwidth of the I/O bus was set to that of a PCI-X bus (64bit, 133MHz) except when otherwise mentioned in the results section. The I/O bus is modeled as a generic bus, and does not model the particulars of ![Combined bottleneck graph](image) the PCI bus specification. As such the generic bus tends to have a slightly higher effective bandwidth than a real PCI bus. For the network interface we model an Intel 8254xGB chipset and scaled the link performance to not be the bottleneck. The model is accurate enough to support the standard Linux driver for this device. We use a 10 Gbps physical link to prevent the link itself from being the bottleneck. All our experiments used two systems. In all cases one of the two systems is of interest (the system under test), while the other serves to stress the system under test. The system under test is configured using detailed CPU and memory-system models, as described above. The stressor is modeled with a simple 1 CPI CPU and a perfect memory system to prevent it from being the bottleneck and to reduce simulation time relative to modeling detailed CPUs on both systems. 5 Results In this section, we begin by quantifying the perturbation that our annotations introduce. We then demonstrate the flexibility of our critical-path analysis by showing how our technique can detect bottlenecks at various levels of the system, including both hardware and software bottlenecks. 5.1 Annotation Overhead We analyze the perturbation that our annotations introduce into the system by measuring the change in bandwidth between an annotated system and an unannotated system. To verify that our annotations are not introducing a large overhead, we compared the performance of each configuration we present in this section using the original kernel and application with the same experiment using our annotated kernel and application. The perturbations we saw are a result of several things: 1. a larger binary due to the inserted pseudo-instructions; 2. different code emitted by the compiler (since functions are of a slightly different size the compiler could choose different optimizations for the function); and 3. interrupts and scheduling occurring at different times in the simulator due to the difference in the code size and instruction counts. We found the annotations had very little effect on the bandwidth, resulting in a 3.8% change on average. This variation included both slight increases and slight decreases relative to the unannotated system, depending on the specific configuration. 5.2 Hardware bottlenecks In our first experiment, we look at a Linux 2.6.13 kernel with netfilter disabled sending 1480-byte UDP packets. We configured the I/O bus to be a conventional 32-bit PCI bus running at 66MHz. This bus provides 2 Gbps of peak I/O bandwidth. However, a fraction of this bandwidth is lost to bus arbitration. An additional portion of the bandwidth is consumed by the NIC to manage DMA descriptors: for each DMA transfer of actual network data, the NIC must read the descriptor corresponding to that buffer, then update and write back the descriptor to mark it as processed. In the case of the Intel NIC we model, these descriptors are normally 16 bytes long. Finally, data may not always be ready to transfer when the bus is free, introducing idle cycles which further reduce the effective bus bandwidth. Simulating this configuration resulted in a bandwidth of 1813 Mbps on the link. Our critical-path analysis identified the NIC transmit state machine as the primary bottleneck, specifically spending 96% of the time in the “DMA packet” state. The transmit state machine portion of the combined graph (cgraph) for this experiment is shown in Figure 6. All other state machines have been removed from the graph, and rarely traversed paths of the transmit state machine have been omitted for legibility as well. As discussed in Section 3.3, each edge of the cgraph is labeled with the name of the corresponding state in the original state machine and the triple of values indicating the number of visits to that state, the total time spent in the state, and the time spent in that state on the critical path. The state machine presented here is similar to the simplified one we mention in Section 2. The state machine operates by reading a locally cached descriptor, executing the action specified (DMAing a packet), queuing the packet for transmission, updating the descriptor, and repeating. The only waiting observed in this state machine during its execution was waiting for descriptors (the dotted line at the top left of the graph). The other intra-state-machine edges present in this graph are because of some state machine waiting on transmit state machine. The graph shows that the edges consuming by far the most total time and most time on the critical path (the second and third numbers in the triple), marked in bold, both correspond to the “DMA packet” state. The next most critical path has a critical state in the Transmit Descriptor Fetch state machine (not shown). Both of these clearly indicate that the I/O bandwidth is insufficient to support the rate at which the application and kernel can generate data. We verify this by replacing the PCI-like I/O bus (66MHz, 32-bit) with a PCI-X-like bus (133MHz, 64bit) and rerunning the experiment. The new bus has four times the bandwidth of the original bus, so it should no longer be the bottleneck. Upon rerunning the experiment—only changing the I/O bus—we observed 2173Mbps of bandwidth on the link. The most critical state was no longer in the NIC’s transmit state machine (or in the NIC at all), but instead was the more typical bottleneck of the (software) user-to-kernel data copy. Our original I/O bus bottleneck would not be easily observed via software profiling, even given detailed visibility into the kernel code. The profiler would see various kernel components working steadily, since packets are still being sent at a fast rate. The only kernel indicator that the DMA is a bottleneck would be number of free DMA descriptors the driver has available and the size of the device queue. However, an execution-time profiler would not provide any insight to the size or occupancy of these structures. 5.3 Software and configuration bottlenecks We now shift from looking at bottlenecks in hardware to bottlenecks in software. Here again we use a Linux 2.6.13 kernel, now with netfilter enabled, and a PCI-X-like bus. We look at the difference in bottlenecks between sending a 1480-byte UDP payload, the maximum size that can be sent without fragmentation, and a 16 KiB payload, which must be fragmented. The smaller payload size requires the application to perform more system calls to send the same amount of data. On the other hand, the larger payload must be fragmented by the transmitter and checksummed without the help of the NIC. These differences result in different paths through the kernel and more importantly different critical paths. Upon running the two experiments, we noticed again that the bottlenecks were not in the expected location of the user-to-kernel copy, but instead being in the netfilter code. In Table 1 we show the states in which most of the time on the critical path is spent. The most critical state in the small UDP payload experiment was the netfilter function ipt_do_table which iterates through the table of netfilter rules—of which there were none in our experiment—checking the packet against each one. The experiment with larger payloads showed an even more surprising result: the most critical state was ip_defrag. By showing two different critical paths—and critical states—when only the payload size is changed, our technique demonstrates its sensitivity. to changes in workload parameters. Additionally, we reran the analysis program to find the next most critical path and the resulting critical states on that path. The next most critical states are shown in Table 2. The small payload critical path is 36% shorter than the original one and the big payload critical path is 9% shorter. In both cases the path returns to the user-to-kernel copy. The significantly smaller next critical paths suggest that a large performance gain could be achieved if the current critical path through the netfilter code could be eliminated. The critical paths we showed in Table 1 are a bit peculiar, especially for the larger payload. The most critical state, `ip_defrag`, defragments IP packets. However, the system under test is the transmit side, which is expected only to fragment packets. In fact, 5 rows below the `ip_defrag` state there is an state named `ip_fragment`, which (with the help of some of the states in between) fragments packets that are larger than the MTU. Looking at the combined graph or the critical path confirms that the kernel is fragmenting the packet to be sent down the wire and then almost immediately reassembling the fragments to pass them to netfilter. This order results in a large overhead, and is an error in the code; netfilter should be invoked before the packet is fragmented. This problem was fixed in Linux 2.6.16, something that we were unaware of when we began running experiments, but sought out after we found our surprising result. Turning our attention to the results for the small payload we again see an unexpected function call, `ip_csum_partial`. While we do expect the outgoing packet to be checksummed, we expect the checksumming to be done by the hardware since the NIC is capable of checksumming packets smaller than the MTU. In this case the netfilter code erroneously believes it must calculate the checksum manually. Again, once we investigated this issue, we found that it had been fixed in 2.6.16. An interesting observation from the most critical states tables above is that netfilter states appear quite often as critical even though no netfilter rules are present. Disabling netfilter and re-running our experiments results in a 44% and 75% increase in performance for the small and large payload workloads, further validating the bottlenecks we have identified. To verify the fixes mentioned above, we reran our experiments using the 2.6.16 kernel. The critical path in all the 2.6.16 experiments is the user-to-kernel copy, as might be expected. Enabling netfilter still affects performance, although not as significantly as it did in the 2.6.13 kernels. Netfilter is on the second most critical path which is only 5% shorter than the critical path including the user-to-kernel copy. Unlike the PCI bottleneck described above, these netfilter bottlenecks are theoretically visible to a kernel profiler. However, the user-to-kernel copy function is still by far the dominant item on a function-based profile, consuming roughly five times more cycles than `ip_defrag` in the 16 KiB payload experiment. To discover this bottleneck with a profiler, a user would have to realize that the UDP and IP stacks form a pipeline, then sum the time spent in UDP functions and in IP functions separately to determine that the aggregate IP processing dominates. This function categorization is not obvious, as it cannot be performed solely based on function names. In contrast, our implicit-state-machine approach automatically assigns functions to the appropriate state machine once the boundary between state machines is properly identified, and can even cope with a single static function being called from multiple state machines. Thus our technique provides a much more direct, reliable, and automatic identification of the bottleneck. While many of the problems highlighted above have been fixed in the 2.6.16 Linux kernel, our technique found these problems without any knowledge of the code or potential places that needed improvement. This technique can be useful to people in engaged in large or distributed development—where two programmers might not understand the interaction between their components—or to drive future hardware development giving engineers the ability locate and fix bottlenecks before building a product. ### Table 1: Most critical states Linux 2.6.13 w/netfilter <table> <thead> <tr> <th>1480 byte payload</th> <th>16KiB payload</th> </tr> </thead> <tbody> <tr> <td>Ip Send:ipt_do_table</td> <td>11.36%</td> </tr> <tr> <td>Ip Send:csum_partial</td> <td>10.23%</td> </tr> <tr> <td>Ip Send:nf_iterate</td> <td>7.38%</td> </tr> <tr> <td>Ip Send:read_unlock_bh</td> <td>3.61%</td> </tr> <tr> <td>Ip Send:read_lock_bh</td> <td>3.56%</td> </tr> <tr> <td>Ip Send:memcopy</td> <td>3.47%</td> </tr> <tr> <td>Ip Send:nhook_slow</td> <td>3.42%</td> </tr> <tr> <td>Ip Send:Call_Pal_Swipl</td> <td>3.26%</td> </tr> <tr> <td>Ip Send:ip_finish_output</td> <td>2.95%</td> </tr> <tr> <td>Ip Send:neighbor_resolve_output</td> <td>2.40%</td> </tr> <tr> <td>Ip Send:_remlu</td> <td>2.31%</td> </tr> <tr> <td>Ip Send:skb_checksum</td> <td>2.26%</td> </tr> <tr> <td>Ip Send:ip_defrag</td> <td>12.78%</td> </tr> <tr> <td>Ip Send:memcpy</td> <td>9.59%</td> </tr> <tr> <td>Ip Send:ipt_do_table</td> <td>6.94%</td> </tr> <tr> <td>Ip Send:ip_copy_metadata</td> <td>6.90%</td> </tr> <tr> <td>Ip Send:ip_fragment</td> <td>6.51%</td> </tr> <tr> <td>Ip Send:ip_fast_csum</td> <td>4.87%</td> </tr> <tr> <td>Ip Send:nf_iterate</td> <td>3.84%</td> </tr> <tr> <td>Ip Send:read_unlock_bh</td> <td>3.33%</td> </tr> <tr> <td>Ip Send:read_lock_bh</td> <td>3.12%</td> </tr> <tr> <td>Ip Send:sock_wfrees</td> <td>2.66%</td> </tr> <tr> <td>Ip Send:ip_finish_output2</td> <td>2.29%</td> </tr> <tr> <td>Ip Send:neighbor_resolve_output</td> <td>2.29%</td> </tr> </tbody> </table> 2See http://git.kernel.org/?p=linux/kernel/git/torvalds/linux-2.6.git;a=commit;h=1bd9be60f9e06dd04238ac877ce85b6b364ac062. 6 Related Work There is a large body of relevant work on performance analysis and critical-path analysis. A prerequisite for critical-path analysis is a dependence graph representing timing constraints. Fields et al. developed a relatively simple model from scratch for an out-of-order execution pipeline [9]. In this paper and follow-on work [8, 10] the principal concern was at the granularity of instructions; they seek to find critical instructions and minimize the delay that each cause through steering and scheduling. Nagarajan et al. extended this work to the TRIPS architecture modeling their block execution model and network links [17]. In that work, the focus shifts from instructions to micro-architectural events. Our work shifts the focus again upwards to system-level events. In the networking domain, Barford and Crovella developed a critical-path model for TCP [2]. They create a Packet Dependence Graph by observing traces collected at the endpoints of a given TCP connection, then analyze the traces using a simulation of the TCP stack to attribute delay to one of several coarse-grain causes (server, client, propagation delay, protocol timeout, etc.). Unlike our work, their technique does not provide visibility into the specific bottlenecks within the client or server systems. Work on critical-path analysis has also been done in the MPI domain. Yang and Miller developed a methodology to extract critical path information from message and synchronization calls and build a program activity graph based on these calls [21]. In this case the authors were interested in the network’s usage, but not its implementation. Their methodology is based on instrumenting well defined interfaces to record events, which is not feasible for our work because many of the components in the systems we are interested in interact via custom interfaces (e.g., the descriptor ring between the driver and the NIC). In all the work above, the models were developed essentially from scratch based on familiarity with the subject domain. One of our primary goals is to simplify model creation, allowing much larger systems to be analyzed. The Magpie [3] work at Microsoft Research gathered fine grained traces of a large number of software components across multiple systems, attributed the events in the trace to an initial request and used machine learning techniques to find execution anomalies for real-time performance debugging. The goal was not to improve baseline performance, but instead find problems in a real system relative to the expected baseline as they ran. In similar work, Tierney et. al [19] modify applications and use kernel logging to timestamp interesting events, which are then visualized to help diagnose performance issues in real-time in a large distributed system. Aguilera et. al [1] attempt to find causal paths between messages by passively recording the traffic between systems without any instrumentation in the machines themselves. They analyze the collected network traces to find patterns and attempt to infer request chains. They are able to identify the node in a distributed system (for example the database server for a website) that is the largest source of latency in responding to a request. However, their technique does not provide any information about performance bottlenecks within individual machines. Hauswirth et. al [12] explain performance phenomena in systems composed of multiple layers of software in their Vertical Profiling work. They use a combination of hardware performance counters and software performance monitors to understand system behavior. The information at various levels is gathered separately and must be correlated manually. Additionally, the user must know what particular software event(s) to monitor that will provide useful information but not significantly perturb the system. 7 Conclusion and Future Work In this paper we have shown how find bottlenecks in complex hardware and software systems through critical-path analysis. In doing so we have described a method for creating a dependence graph without complete familiarity of all the systems involved and proposed a method to visualize the interactions. We have then applied these techniques, with the aid of a simulator, to the Linux kernel, and shown that we can find both hardware and software bottlenecks. In the process, we identified two problems that existed in the Linux 2.6.13 kernel that we did not know about. We believe that the techniques described here can greatly assist architects by replacing ad-hoc methods based on intuition with a rigorous method. These methods not only can help find performance bottlenecks, but also quantify the possible performance gain achievable. Furthermore, using these techniques can minimize the number of experiments an architect would normally run by focusing attention to the bottlenecks at hand. We have a great deal of future work planned. In the near term we hope to analyze the performance bottlenecks inside the Linux TCP stack and extend this methodology to multi-processor systems. While it would be very difficult to analyze hardware on a real system, we would like to apply our technique to the analyze the software on a real system using a tracing toolkit. Finally, we hope apply these techniques to completely different systems, for example the cache hierarchy in a multiprocessor. Acknowledgments We would like to thank Kevin Lim and Lisa Hsu for their suggestions on early drafts of this paper and the anonymous reviewers for their helpful comments. This work was supported by a gift from Sun Microsystems. References
{"Source-Url": "http://web.eecs.umich.edu/~tnm/trev_test/papersPDF/2008.04.Full%20System%20Critical%20Path%20Ananlysis.pdf", "len_cl100k_base": 10498, "olmocr-version": "0.1.53", "pdf-total-pages": 12, "total-fallback-pages": 0, "total-input-tokens": 38715, "total-output-tokens": 12240, "length": "2e13", "weborganizer": {"__label__adult": 0.00040984153747558594, "__label__art_design": 0.00045943260192871094, "__label__crime_law": 0.0003209114074707031, "__label__education_jobs": 0.0009331703186035156, "__label__entertainment": 0.0001647472381591797, "__label__fashion_beauty": 0.00020599365234375, "__label__finance_business": 0.00039005279541015625, "__label__food_dining": 0.0003719329833984375, "__label__games": 0.000972747802734375, "__label__hardware": 0.006984710693359375, "__label__health": 0.000682830810546875, "__label__history": 0.0005021095275878906, "__label__home_hobbies": 0.0001436471939086914, "__label__industrial": 0.0007767677307128906, "__label__literature": 0.0003871917724609375, "__label__politics": 0.0002696514129638672, "__label__religion": 0.0005764961242675781, "__label__science_tech": 0.392578125, "__label__social_life": 9.447336196899414e-05, "__label__software": 0.0177001953125, "__label__software_dev": 0.5732421875, "__label__sports_fitness": 0.00033473968505859375, "__label__transportation": 0.00099945068359375, "__label__travel": 0.00026416778564453125}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 55854, 0.0348]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 55854, 0.38373]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 55854, 0.90913]], "google_gemma-3-12b-it_contains_pii": [[0, 4583, false], [4583, 10590, null], [10590, 17083, null], [17083, 20760, null], [20760, 23131, null], [23131, 29470, null], [29470, 33612, null], [33612, 37431, null], [37431, 41124, null], [41124, 46521, null], [46521, 50990, null], [50990, 55854, null]], "google_gemma-3-12b-it_is_public_document": [[0, 4583, true], [4583, 10590, null], [10590, 17083, null], [17083, 20760, null], [20760, 23131, null], [23131, 29470, null], [29470, 33612, null], [33612, 37431, null], [37431, 41124, null], [41124, 46521, null], [46521, 50990, null], [50990, 55854, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 55854, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 55854, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 55854, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 55854, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 55854, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 55854, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 55854, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 55854, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 55854, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 55854, null]], "pdf_page_numbers": [[0, 4583, 1], [4583, 10590, 2], [10590, 17083, 3], [17083, 20760, 4], [20760, 23131, 5], [23131, 29470, 6], [29470, 33612, 7], [33612, 37431, 8], [37431, 41124, 9], [41124, 46521, 10], [46521, 50990, 11], [50990, 55854, 12]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 55854, 0.14286]]}
olmocr_science_pdfs
2024-12-07
2024-12-07
c1d18059196d8bdf574017b7655db9343314268c
Software Process Improvement: Where Is the Evidence? Initial Findings from a Systematic Mapping Study Kuhrmann, Marco; Konopka, Claudia; Nellemann, Peter; Diebold, Philipp; Münch, Jürgen Published in: Proceedings of the 2015 International Conference on Software and System Process DOI: 10.1145/2785592.2785600 Publication date: 2015 Document version Peer reviewed version Citation for published version (APA): General rights Copyright and moral rights for the publications made accessible in the public portal are retained by the authors and/or other copyright owners and it is a condition of accessing publications that users recognise and abide by the legal requirements associated with these rights. • Users may download and print one copy of any publication from the public portal for the purpose of private study or research. • You may not further distribute the material or use it for any profit-making activity or commercial gain • You may freely distribute the URL identifying the publication in the public portal Take down policy If you believe that this document breaches copyright please contact us providing details, and we will remove access to the work immediately and investigate your claim. Download date: 18. feb., 2019 Software Process Improvement: Where Is the Evidence? Initial Findings from a Systematic Mapping Study Marco Kuhrmann University of Southern Denmark kuhrmann@mmm.sdu.dk Claudia Konopka 4Soft GmbH Munich, Germany claudia.konopka@4soft.de Peter Nelleman University of Southern Denmark Odense, Denmark peter@dineitkonsulenter.dk Philipp Diebold Fraunhofer IESE Kaiserslautern, Germany philipp.diebold@iese.fhg.de Jürgen Münch University of Helsinki Helsinki, Finland Juergen.Muench@cs.helsinki.fi ABSTRACT Software process improvement (SPI) is around for decades: frameworks are proposed, success factors are studied, and experiences have been reported. However, the sheer mass of concepts, approaches, and standards published over the years overwhelms practitioners as well as researchers. What is out there? Are there new emerging approaches? What are open issues? Still, we struggle to answer the question for what is the current state of SPI and related research? In this paper, we present initial results from a systematic mapping study to shed light on the field of SPI and to draw conclusions for future research directions. An analysis of 635 publications draws a big picture of SPI-related research of the past 25 years. Our study shows a high number of solution proposals, experience reports, and secondary studies, but only few theories. In particular, standard SPI models like CMMI and ISO/IEC 15504 are analyzed, enhanced, and evaluated for applicability, whereas these standards are critically discussed from the perspective of SPI in small-to-medium-sized companies, which leads to new specialized frameworks. Furthermore, we find a growing interest in success factors to aid companies in conducting SPI. Categories and Subject Descriptors D.2.9 [Software Engineering Management]: Software process models General Terms Experimentation, Measurement Keywords software process, software process improvement, systematic mapping study 1. INTRODUCTION Software process improvement (SPI; [12]) aims to improve software processes and comprises a variety of tasks, such as scoping, assessment, design and realization, and continuous improvement (e.g., [15, 17]). A number of SPI models competes for the companies’ favor, success factors to support SPI implementation at the large and the small scale are studied, and numerous publications report on experiences in academia and practice. SPI is considered an important topic (according to Horvat et al. [10] regardless of company size), as many companies put emphasis on the software process and its adaptation to the company context [6, 19, 40] to improve the quality of software products or to accelerate software development. However, SPI is a diverse field: On the one hand, a number of standards is available, e.g., ISO/IEC 15504 [13] or CMMI [4] but, on the other hand, these standards are criticized oftentimes, e.g., [3, 5, 34]. In response, tailored SPI models are proposed, inter alia, to better address needs of small and very small companies, e.g., [14, 27, 29, 30]. Moreover, since SPI is mainly a human endeavor, much research was spent to study human factors, e.g., [1, 35, 39]. Beyond, we find numerous experience reports, guidelines, and tools—all together providing a huge body of knowledge on SPI. However, despite this comprehensive body of knowledge, we still struggle to answer questions like: What is out there? What are open issues? Are there new emerging approaches? What is the current state of SPI and related research? Problem Statement. The field of SPI evolved for decades and provides a vast amount of publications addressing a huge variety of topics. Still, we see new method proposals, research on success factors, and experience reports. However, missing is a big picture that illustrates where SPI gained a certain level of saturation and where are still hot topics and unresolved issues calling for more investigation. Objectives. To better understand the state of the art in SPI, we aim to analyze the whole publication flora to draw a big picture on SPI. Our overall goal is not to judge particular SPI research directions, but to provide the focus points of the past and to illustrate emerging/unresolved areas. Contribution. In this paper, we present initial findings from a comprehensive systematic mapping study. We con- ducted a broadband search in six literature databases to harvest SPI-related publications, and we analyzed the resulting 635 publications for publication frequency, research type facet, contribution type facet, and focus type facet. We draw a big picture that shows that the majority of publications on SPI either proposes new approaches (i.e., models or frameworks) or is of philosophical nature (i.e., collecting, structuring, and analyzing knowledge). Our results show continuous publication of new approaches while evaluation research regarding these proposals is scarcely available. Furthermore, our data shows rare evidence and, notably, missing long-term and independently replicated studies. However, our data also reveals some (still) emerging topics, e.g., SPI for small and very small companies, and SPI in the context of lean and agile methods. Outline. The remainder of the paper is organized as follows. Section 2 summarizes the related work. In Section 3, we describe the research design, and discuss the results in Section 4. We conclude the paper in Section 5. 2. RELATED WORK Literature on software process improvement is rich and addresses a variety of topics. Yet, available secondary studies mainly focus on investigating success factors, e.g., Monteiro and Oliveira [21], Bayona-Oré [2], and Dybå [7]. Some studies provide insights into selected topics. For example, Helgesson et al. [9] review maturity models, and Hull et al. [11] and El-Emam and Goldenson [8] review different assessment models. Pino et al. [26] contribute a review on SPI in the context of small and very small companies, and Staples and Niazi [32] study motivating factors to adopt CMMI for improvement programs, while Müller et al. [22] study SPI in general from the perspective of organizational change. All these representatively selected studies address specific topics; yet, they do not contribute to a more general perspective on SPI. Such general studies are scarcely to find. For instance, Rainer and Hall [28] analyze some ‘core’ studies on SPI for the purpose to work out addressed topics and gaps in the domain. However, they select only few studies of which they assume to be good representatives thus providing a limited picture only. In terms of analyzing the entire domain and providing new (generalizable) knowledge, Unterkalmsteiner et al. [38] contribute a systematic review on the state of the art of evaluation and measurement in SPI. They conduct a systematic literature review for the purpose of synthesizing a list of evaluation and measurement approaches, which they also analyze for the practical application. The study at hand does not aim at generating generalizable knowledge for one or more SPI-related topics. The purpose of the present study is to draw a big picture of the current state of the art of SPI in general. That is, as there is no comparable study available, this paper closes a gap in literature by providing a comprehensive picture of the development of the field of SPI over time and by summarizing the current state of the art. Other than, e.g., [28] or [38], we use the mapping study instrument according to Petersen et al. [25] as research method and to present our results. Therefore, our study does not address selected details, but aims to draw a general picture from a “bird’s-eye perspective.” 3. RESEARCH DESIGN In this section, we present the study design. After describing the research questions, we describe the overall research design, and the case study instrument including case selection, data collection, and analysis procedures. 3.1 Research Method In this study, we followed the general approach as applied in [18] in which we applied different methods from systematic literature reviews (SLR; Kitchenham et al. [16]) and systematic mapping studies (SMS; Petersen et al. [25]). Figure 1 shows the overall research approach. ![Figure 1: Overall research approach.](image) The overall study was designed as a breadth-first search to capture the SPI domain as complete as possible. In February 2013, we performed the study preparation (definition of research questions and search queries, and the selection of data sources), conducted a series of test runs, and refined the search queries iteratively. End of April 2013, we conducted the main search, which results in about 85,000 hits. As we expected this large number of results and in order to support the data set cleaning, we defined filter questions, which we applied to the initial result set. When the initial result set was cleaned, we performed a voting procedure to select the relevant publications from the result set. Based on this selection, we developed the classification schemas (by manual sampling as well as tool-supported) and harmonized the data set (e.g., completion of keyword lists). In subsequent sections, we detail the single steps of the previously described procedures. Section 3.2 presents the research questions, before we describe the detailed data collection (Sect. 3.3) and analysis procedure (Sect. 3.4). 3.2 Research Questions Our objective is to capture the domain of Software Process Improvement (SPI), to provide a snapshot of the available publication flora, and to investigate research trends. Therefore, we define the following research questions: **RQ 1: What is the general publication population on SPI?** This research question aims to get an overview of the general publication flora in SPI. We are interested into getting information regarding publication count, frequency and, even- Table 1: Final search strings used for the automatic database search. <table> <thead> <tr> <th>Search string</th> <th>Addresses...</th> </tr> </thead> <tbody> <tr> <td>S₁ (life-cycle or lifecycle or life cycle) and (management or administration or development or authoring or deployment)</td> <td>process management: general life cycle phases of the software process's life cycle</td> </tr> <tr> <td>S₂ (life-cycle or lifecycle or life cycle) and (design or modeling or mod-elling or analysis or training)</td> <td>process modeling</td> </tr> <tr> <td>S₃ modeling or modelling or model-based or approach or variant</td> <td>process modeling and tailoring</td> </tr> <tr> <td>S₄ optimization or optimisation or customization or customisation or tailoring</td> <td>general measurement and improvement reference models and quality management</td> </tr> <tr> <td>S₅ (measurement or evaluation or approach or variant or improvement)</td> <td>reference models and assessment approaches</td> </tr> <tr> <td>S₆ reference model or quality management or evaluation or assessment or audit or CMMI or Capability Maturity Model Integration</td> <td>reported knowledge and empirical research</td> </tr> <tr> <td>S₇ SCAMPI or Standard CMMI Appraisal Method for Process Improvement or SPICE or ISO/IEC 15504 or PSP or Personal Software Process or TSP or Team Software Process</td> <td>context definition: software processes context definition: SPI</td> </tr> <tr> <td>S₈ (feasibility or experience) and (study or report)</td> <td>context definition: SPI evaluation research on SPI, e.g., studies, reports, etc.</td> </tr> </tbody> </table> RQ 2: What is the contribution population? Based on the found publications, we are interested into the addressed topics and major contributions (e.g., SPI models, theories, secondary studies, and lessons learned) to work out the fields in SPI to which research contributed so far. RQ 3: What trends in SPI and SPI-related research can be observed? The third research question aims at investigating the focus points addressed by SPI research so far, and to work out gaps as well as trends. This research question shall thus pave the way to direct future research on SPI. 3.3 Data Collection Procedures In the following, we describe the query construction process, data source selection, and data storage format. 3.3.1 Query Construction In a series of workshops, we defined the keywords that we are interested in and defined the general search strings (Table 1), which were then validated in several test runs before being used in an automated full-text search in several literature databases. The queries were built based on keyword lists given by the common terminology in the area of software processes and SPI. General Queries. The general search strings S₁—S₈ were defined according to the relevant topics in SPI, e.g., improvement, assessment, measurement, ISO/IEC 15504, CMMI, quality management, and so forth. Due to the expected large number of results, we decided to complement the general search strings with context selectors C₁ and C₂ to limit the search to the domain of interest. Finally, we concluded the search strings shown in Table 1. These search strings were used to conduct a full-text search in the selected literature databases (Sect. 3.3.2). Filter Queries. Because of the full-text search, we expected a variety of publications including some overhead. Hence, we defined two filter queries (Table 1) to be applied to the initial result set with the purpose of reducing the result set to the key publications. Query F₁ aims at finding all publications in the result set that explicitly present SPI approaches and practices, or that address the management of SPI. F₂ aims at finding all reports in the context of SPI in which feasibility is analyzed or experiences are reported. While the initial search was a full-text search, the filter queries were applied to the abstracts only. However, for technical reasons, ACM and Springer abstracts were partially not available in the initial result set and, thus, the filtering was done manually during the voting procedure (Sect. 3.4). Table 2: Data collection table (simplified). <table> <thead> <tr> <th>Info. Set</th> <th>Attributes</th> </tr> </thead> <tbody> <tr> <td>Meta data</td> <td>ID, Citation-key.</td> </tr> <tr> <td>Content</td> <td>Authors, Title, Abstract, Year</td> </tr> <tr> <td>Voting</td> <td>Relevance (defined during further analysis and voting by the different authors), Comments</td> </tr> <tr> <td>Analysis data</td> <td>Publication type, Research type classification, etc.</td> </tr> </tbody> </table> 3.3.2 Data Sources and Data Format The data collection was an automated full-text search in several literature databases. As main data sources, we relied on established literature databases, which we consider... 3.4 Analysis Procedures We describe the analysis preparation as well as the steps conducted to answer the research questions. 3.4.1 Analysis Preparation We performed an automated search that required us to filter and prepare the result set. The data analysis is prepared by harmonizing the data and performing a 2-staged voting process to prepare the result set analysis. Harmonization. Due to the query construction, we found a vast amount of multiple occurrences in the result set, and we also found a number of publications that are not in software engineering or computer science. To make the selection of the contributions more efficient, we first cleaned the initial result set (cf. Table 7 for the results per phase). In the first step, we removed the duplicates, which we identified by title, year, and author list. In the second step, we performed an automated search that required us to refine. The goal of this stage was to figure out those publications not devoted to software processes and SPI. In order to double-check the result set, we used word clouds generated from abstracts and keyword lists to validate if the result set meets our requirements. This procedure was performed individually per database and again on the integrated result set. Finally, we added the yet non-filtered ACM and Springer sets to prepare the voting procedure. Voting. Similar to [18], we performed a multi-staged voting process to classify the papers as relevant or irrelevant and to build a set of publications for further investigation. The integrated result table therefore contains several columns (attribute “relevance” in Table 2). In the voting, the inclusion and exclusion criteria listed in Table 3 guided the decision-making process. Two researchers performed individual votings (initially: publication title). If both agreed, the paper was initially decided. For those papers that were not immediately decided, a number of workshops were performed in which the decision was made based on the papers’ title and abstract. After the initial voting, the selection was reviewed by a third researcher and refined. The goal of this stage was to figure out those publications that are relevant for the analyses and classifications. 3.4.2 Analysis and Classification After the voting, the final set of publications was defined. On this set, the analysis and classification was performed using the abstracts and—where necessary—the complete publication title. We used the word clouds to visually inspect the result set for “intruders”, e.g., medicine, chemistry, and cancer therapy. Terms not matching our search criteria were collected and used to identify and remove the misselected papers from the result set. Table 3: Inclusion and exclusion criteria (summary). <table> <thead> <tr> <th>Crit.</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td>IC₁</td> <td>Title, keyword list, and abstract make explicit that the paper is related to SPI.</td> </tr> <tr> <td>IC₂</td> <td>Paper presents SPI-related topics, e.g., SPI models, assessments, experiences in adopting and deploying software processes, and reports on improving specific methods/practices.</td> </tr> <tr> <td>EC₁</td> <td>Paper is not in English.</td> </tr> <tr> <td>EC₂</td> <td>Paper is not in the field of software engineering or computer science in general.</td> </tr> <tr> <td>EC₃</td> <td>Paper is a tutorial or workshop summary only.</td> </tr> <tr> <td>EC₄</td> <td>Paper occurred multiple times.</td> </tr> <tr> <td>EC₅</td> <td>Paper full text is not available for download.</td> </tr> </tbody> </table> Table 4: Research type facets (summary). <table> <thead> <tr> <th>Crit.</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td>Evaluation research</td> <td>implemented in practice, evaluation of implementation conducted; requires more than just one demonstrating case study</td> </tr> <tr> <td>Solution proposal</td> <td>solution for a problem is proposed, benefits/application is demonstrated by example, experiments, or student labs; also includes proposals complemented by one demonstrator demonstrating study for which no long-term evaluation/dissemination plan is obvious</td> </tr> <tr> <td>Philosophical paper</td> <td>new way of thinking, structuring a field in form of a taxonomy or a framework, secondary studies like SLR or SMS</td> </tr> <tr> <td>Opinion paper</td> <td>personal opinion, not grounded in related work and research methodology</td> </tr> <tr> <td>Experience paper</td> <td>personal experience, how are things done in practice</td> </tr> </tbody> </table> Table 5: Contribution type facets (summary). <table> <thead> <tr> <th>Crit.</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td>Model</td> <td>representation of observed reality by concepts after conceptualization</td> </tr> <tr> <td>Theory</td> <td>construct of cause-effect relationships</td> </tr> <tr> <td>Framework</td> <td>frameworks/methods related to SPI</td> </tr> <tr> <td>Guideline</td> <td>list of advices</td> </tr> <tr> <td>Lessons learnt</td> <td>set of outcomes from obtained results</td> </tr> <tr> <td>Advice</td> <td>recommendation (from opinion)</td> </tr> <tr> <td>Tool</td> <td>a tool to support SPI</td> </tr> </tbody> </table> Table 6: Focus type facets from key wording. <table> <thead> <tr> <th>Crit.</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td>Standard SPI models</td> <td>Application, adaptation, and evaluation of standard SPI models, e.g., CMMI or ISO/IEC 15504</td> </tr> <tr> <td>SPI models in SME</td> <td>SPI models (new models and adaptations of standards) for SME and VSE</td> </tr> <tr> <td>Assessment</td> <td>General assessment and/or measurement approaches and models</td> </tr> <tr> <td>General SPI</td> <td>Work on general SPI initiatives (e.g., company level)</td> </tr> <tr> <td>Method</td> <td>Improvement of specific methods and/or procedures, e.g., testing</td> </tr> <tr> <td>Success factors</td> <td>Investigation of success factors, e.g., survey-based research</td> </tr> </tbody> </table> Contribution Type Facets. In order to analyze what search type facets applied to the result set. During a test classification on a small sample, we found the need to adjust the facet definitions. Table 4 lists the re- during a test classification on a small sample, we found the need to adjust the facet definitions. Table 4 lists the re- da too specific set of search criteria, we performed a breadth- during a test classification on a small sample, we found the need to adjust the facet definitions. Table 4 lists the re- 3.5 Validity Procedures To increase the validity of our study, we implemented the following procedures: First, to avoid limitations caused by a too specific set of search criteria, we performed a breadth- Table 7: Data collection and filtering results (tentative result sets during selection and final result set). <table> <thead> <tr> <th>Step</th> <th>IEEE</th> <th>ACM</th> <th>Springer</th> <th>Elsevier</th> <th>Wiley</th> <th>IET</th> <th>Total</th> </tr> </thead> <tbody> <tr> <td><strong>Step 1: Search (Sect. 3.3.1)</strong></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> </tr> <tr> <td>$S_1$ and ($C_1$ or $C_2$)</td> <td>71</td> <td>543</td> <td>306</td> <td>991</td> <td>1,185</td> <td>89</td> <td>3,185</td> </tr> <tr> <td>$S_2$ and ($C_1$ or $C_2$)</td> <td>68</td> <td>539</td> <td>306</td> <td>989</td> <td>1,133</td> <td>89</td> <td>3,124</td> </tr> <tr> <td>$S_3$ and ($C_1$ or $C_2$)</td> <td>1,310</td> <td>2,341</td> <td>1,032</td> <td>2,675</td> <td>16,113</td> <td>726</td> <td>24,197</td> </tr> <tr> <td>$S_4$ and ($C_1$ or $C_2$)</td> <td>130</td> <td>925</td> <td>438</td> <td>945</td> <td>2,480</td> <td>479</td> <td>5,397</td> </tr> <tr> <td>$S_5$ and ($C_1$ or $C_2$)</td> <td>1,585</td> <td>2,459</td> <td>1,038</td> <td>2,731</td> <td>17,184</td> <td>822</td> <td>25,819</td> </tr> <tr> <td>$S_6$ and ($C_1$ or $C_2$)</td> <td>535</td> <td>1,746</td> <td>762</td> <td>1,863</td> <td>9,182</td> <td>484</td> <td>14,572</td> </tr> <tr> <td>$S_7$ and ($C_1$ or $C_2$)</td> <td>168</td> <td>324</td> <td>143</td> <td>242</td> <td>765</td> <td>41</td> <td>1,683</td> </tr> <tr> <td>$S_8$ and $C_2$</td> <td>114</td> <td>105</td> <td>433</td> <td>1,015</td> <td>6,341</td> <td>366</td> <td>8,374</td> </tr> <tr> <td><strong>Step 2: Removing Duplicates (Sect. 3.4.1)</strong></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> </tr> <tr> <td>Duplicates per database</td> <td>1,486</td> <td>566</td> <td>4,388</td> <td>7,161</td> <td>1,328</td> <td>1,714</td> <td>16,643</td> </tr> <tr> <td>Duplicates across all databases</td> <td>916</td> <td>551</td> <td>1,059</td> <td>2,043</td> <td>370</td> <td>376</td> <td>5,315</td> </tr> <tr> <td><strong>Step 3: In-depth Filtering (Sect. 3.3.1)</strong></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> </tr> <tr> <td>Applying filters $F_1$ and $F_2$</td> <td>578</td> <td>–</td> <td>–</td> <td>710</td> <td>221</td> <td>53</td> <td>1,562</td> </tr> <tr> <td>Unfiltered</td> <td>–</td> <td>551</td> <td>1,059</td> <td>–</td> <td>–</td> <td>–</td> <td>1,610</td> </tr> <tr> <td>Result set (search process)</td> <td>578</td> <td>551</td> <td>1,059</td> <td>710</td> <td>221</td> <td>53</td> <td>3,172</td> </tr> <tr> <td><strong>Step 4: Voting (Sect. 3.4.1)</strong></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> </tr> <tr> <td>Final result set</td> <td>283</td> <td>65</td> <td>114</td> <td>103</td> <td>67</td> <td>3</td> <td>635</td> </tr> </tbody> </table> Figure 2: Number of published papers per year (incl. trend) and distribution over the research type facets. 4.1 RQ1: General Publication Flora Figure 2 illustrates the distribution of the 635 selected publications over time beginning in 1989 and ending in 2013\(^5\). The figure provides two perspectives: The upper part shows the number of publications over time including a trend line (trend calculation basis: mean, 3-year period). In 1996, the numbers show a growing interest in SPI. From this point on, SPI became an inherent part of software engineering research. Figure 2 shows periodical waves over the years starting three to five years. Within these waves the largest gap/decrease is between 2002 and 2003. In the lower part, Figure 2 shows the detailed numbers of the publications and their relative distribution regarding the research type facets (cf. Table 4): The chart shows that the majority (approx. 2/3 of the result set) of the contributions was categorized as solution proposal (\(n = 244\)) or philosophical paper (\(n = 214\)). However, the result set also contains a number of evaluation research papers (\(n = 102\)) and experience papers (\(n = 70\)), which shows that the field of SPI is still moving, but accumulates evidence (solutions are proposed that are followed by evaluation papers or papers reporting experiences). The least published papers are opinion papers (\(n = 5\)). Among all publications, one trend can be observed over time: solution proposals and philosophical papers continually represent the majority of the publications. Furthermore, the different paper types follow cycles. For instance, in the categories solution proposals and philosophical papers, the papers dip sometimes to one type and then again to the other. Papers in the category of evaluation papers also roughly follow a 3-year cycle. The category of experience papers is the most constant one, even if it contributes only a small number of papers to the result set. 4.2 RQ2: Contribution and Focus Types In order to get an overview of the harvested papers, we performed a categorization to define contribution type facets (Table 5) and focus type facets (Table 6) of the publications. In the following, we provide two perspectives. In Figure 3, we provide a comprehensive map in which we relate the contribution- and focus type facets to the research type facets. In a second perspective, Figure 4 relates the contribution- to the focus type facets. 4.2.1 The Big Picture Figure 3 illustrates the big picture of the publication classification. On the right hand side, the figure lists the contribution type facets and shows that lessons learned (\(n = 290\), 46\%) and frameworks (\(n = 235\), 37\%) make the majority of the contributions. The other categories are barely represented: tools (\(n = 36\)), guidelines (\(n = 27\)), models (\(n = 24\)), theories (\(n = 12\)), and advice (\(n = 11\)). Notably, the chart shows two striking results: the majority of the solution proposals focuses on frameworks (\(n = 167\)), i.e., 26\% of all considered publications propose a new SPI-related framework. Second, the largest share of the philosophical papers is devoted to lessons learned (\(n = 155\)), i.e., 24\% of all publications report on learnings from SPI-related activities (e.g., from conducted SPI endeavors or from survey-based research). However, looking at the research type facet “Evaluation Research”, we find only 44 publications on the evaluation of frameworks and, respectively, 45 publications... on lessons learned\textsuperscript{6}. That is, the chart shows an imbalance between proposals and philosophical discussion, and respective evaluating research. However, this situation is a fundamental observation in the result set, as evaluation research accounts for only 16\% ($n = 102$) of all publications. The left side of Figure 3 shows the focus type facets. This part of the chart shows a more balanced distribution across the different categories. 201 out of 635 publications (32\%) are categorized “General SPI”, i.e., addressing general SPI activities, such as SPI on the company level, lessons learned in general, or non-standardized framework proposals. The second largest share ($n = 116$, 18.3\%) is devoted to publications addressing standard SPI- and maturity models, e.g., CMMI and ISO/IEC 15504; followed by publications of the category “Method-specific SPI” ($n = 115$, 18.1\%). The remaining categories (Assessment: $n = 84$, Success Factors: $n = 73$, and SME-specific SPI models: $n = 46$) together make 32\% of the result set. Except for publications addressing success factors, all other focus type facets show a balanced distribution regarding the research type facets, i.e., SPI-related topics are studied from different perspectives. \subsection*{4.2.2 Contribution & Focus} In order to get more insight into the result set, we also provide a map in which we relate the contribution type facet with the focus type facet. On the one hand, the map in Figure 4 shows the previously found focus on frameworks and lessons learned but, on the other hand, provides a more differentiated picture. Especially three combinations stand out among the others: general SPI and lessons learned ($n = 96$, 15\%), general SPI and frameworks ($n = 64$, 10.1\%), and standard SPI models and lessons learned ($n = 67$, 10.6\%). Figure 4 also shows \textsuperscript{6}Lessons learned in evaluation research refer to papers deriving lessons learned from practically conducted SPI projects rather than from survey-based research, i.e., lessons learned are the emphasized (major) outcome of a paper. \subsection*{4.3 RQ3: Trends in SPI-related Research} The third research question aims at analyzing the development of SPI over time and at identifying trends. Figure 2 illustrates the general publication flora showing a growing interest in SPI and related research starting in the mid 1990’s. Moreover, Figure 2 shows that—for years—solution proposals and philosophical papers make the majority of all publi- cations. Taking into account the maps in Figure 3 and 4, we see that proposing new frameworks and reporting on lessons learned shape the field of SPI so far. However, at this level only few trends become obvious: - The community is still on the quest for appropriate SPI frameworks (cf. Figure 3). - The investigation of success factors becomes a research topic to develop theories (cf. Figure 4). Further Trends. In order to analyze further trends, we enriched the set of collected metadata\(^7\) of the result set. This extended metadata set delivered the following findings: - There is a growing interest in agile methods and adopting agile principles for SPI (n = 27). - There is a growing number of secondary studies analyzing and structuring reported knowledge (n = 31). These studies are mainly used to derive/propose models and theories. - A considerable share of research is based on surveys (n = 73) thus grounding SPI-related research in personal experience/perception of the interviewees. These studies are also used to derive/propose models and theories. - There is a lack of replication research (n = 2), and SPI-related research is oftentimes only confirmed in student labs (cf. research type facet “solution proposal”) or by a single (demonstrating) case in industry (n = 19). Major Research Directions. In summary, we find some major directions of SPI research: 1) SPI becomes more relevant for SME’s thus leading to more proposals for SME-specific SPI and assessment models, e.g., \([29,33,37]\). 2) As companies adopting to agile methods and principles, agility becomes more relevant in the context of SPI, which causes a general discussion on various SPI facets, e.g., \([20]\). 3) The SPI-related body of knowledge comprises various models, experiences, and so forth calling for structuring and consolidation. Therefore, the interest in secondary studies increases, e.g., \([36,38]\). Nonetheless, we still lack evidence: Over the years, the field accumulated a considerable number of solution proposals, yet, missing evidence of their feasibility. Only the well-established standardized approaches like ISO/IEC 15504 and CMMI appear to be well understood. However, a number of publications explicitly aim at analyzing these standards to outline difficulties, e.g., \([34]\), or to motivate the need for new models, e.g., \([24,30]\). Our data shows the field of SPI being shaped by new solution proposals published on a per-year basis, but not providing hard evidence on feasibility, advantages, and disadvantages. So far, our data does not indicate a change in this trend. 4.4 Discussion In this section, we discuss our results and provide a (tentative) interpretation of the results. Our data shows a diverse picture and, furthermore, shows SPI a frequently researched topic (Figure 2). Moreover, research on SPI addresses a variety of aspects. However, the systematic maps (Figure 3 and Figure 4) show certain focus points: The majority of the investigated publications (approx. 75\%) focus on proposing new frameworks and on reporting lessons learned. Furthermore, our results show a significant imbalance between proposing new solutions and evaluating their feasibility. Among the different categories, the majority of evaluation research is conducted in the context of standardized SPI and maturity models (Figure 4, standard SPI models and lessons learned). For newly proposed models, we often find—if at all—only single-case validation (in industry or university-hosted labs); only few, e.g., \([29]\) provide a comprehensive evaluation. Another finding is the lack of theorizing approaches, which are often performed for specific domains (e.g., SME’s) or grounded in secondary studies only. In summary, although SPI is around for decades, we still miss a sound theory about SPI. We have a number of standardized and specific SPI models and frameworks. However, we lack evidence. One reason could be that SPI always involves change in behavior of individual persons and changes in the culture of an organization and, due to the varying contexts, SPI cannot be too descriptive. Therefore, frameworks and tools are proposed, which long for adaptation to the respective context. Yet, the constant change or evolution of the context could be considered a continuous stimulus to provide new frameworks that only have a short life cycle and are quickly replaced by other frameworks that aim to “better” solve this issue. This assumption is supported by the missing long-term and replication studies (the result set only contains 2 explicitly mentioned replication studies). Furthermore, missing is a critical discussion and comparison of available approaches, and their use and feasibility in practice. Although we found 31 secondary studies, these studies lay their focus on investigating success factors rather than providing structure and trying to generalize available knowledge, as for instance done in \([38]\). In a nutshell, our results show that SPI is a still emerging field characterized by solution proposals and experiences awaiting more effort to systematization. 4.5 Threats to Validity In this section, we evaluate our findings and critically review our study regarding the threats to validity. As a literature study, this study suffers from potential incompleteness of the search results and a general publication bias, i.e., positive results are more likely published than failed attempts. For instance, the result set does not contain studies that explicitly report on failure and draw their conclusions from respective lessons learned, and we thus cannot analyze proposals to answer the question for: What works and what does not? That is, our study encounters the risk to draw an incomplete and potentially too positive picture. Beyond that general threat, the internal validity of the study could be biased by personal ratings of the participating researchers. To address this risk, we relied on a proven procedure \([18]\) that utilizes different supporting tools and researcher triangulation to support dataset cleaning, study selection, and classification. Calling in extra researchers to analyze and/or confirm decisions increases internal validity. However, especially in the study classification for the focus type facets (which were derived from keyword lists), we realized some deviation in the rating. So far, we elaborated the reasons finding two major problem candidates to be addressed in future stages of the study: 1) general disagreement in the ratings—in this case, we need to revise the rating procedures; 2) inappropriateness of the focus type facets—in this case we either need to revise the focus type and small companies implement SPI (and what is the success rate), and so forth. However, this information is available by the result set, but requires the application of the systematic literature review instrument rather than the mapping study instrument. 5.2 Future Work In order to address the aforementioned limitation, future work includes an update of the study and an in-depth analysis of the result set. This work, inter alia, includes a critical discussion and revision of the different classification schemas (cf. Sect. 4.5), and extension of the mapping study including further categories such as rigorosity (cf. [23]), in-depth analysis of study results, e.g., creation of SPI model catalogs, investigating the published lessons learned in detail, and harvesting published studies to conduct comparative analyses and, finally, to develop testable hypotheses to foster the theory development for SPI. ACKNOWLEDGMENTS Conducting this study was a long-term endeavor that involved many people. We thank Michaela Tiefßler, Ragna Steenweg, Daniel Méndez Fernández for their support in testing the instruments for paper selection and dataset cleaning. Furthermore, we owe special thanks to the students of the “Hiwi-Pool” of the Technische Universität München, who supported us during the data collection and dataset completion and cleaning processes. 6. REFERENCES
{"Source-Url": "http://findresearcher.sdu.dk/portal/files/118421452/spi_mapping_web.pdf", "len_cl100k_base": 9271, "olmocr-version": "0.1.53", "pdf-total-pages": 11, "total-fallback-pages": 0, "total-input-tokens": 38046, "total-output-tokens": 11674, "length": "2e13", "weborganizer": {"__label__adult": 0.0003254413604736328, "__label__art_design": 0.00035953521728515625, "__label__crime_law": 0.00027751922607421875, "__label__education_jobs": 0.0021839141845703125, "__label__entertainment": 5.5730342864990234e-05, "__label__fashion_beauty": 0.00013697147369384766, "__label__finance_business": 0.0003337860107421875, "__label__food_dining": 0.00028133392333984375, "__label__games": 0.0004639625549316406, "__label__hardware": 0.00032067298889160156, "__label__health": 0.0003364086151123047, "__label__history": 0.0002200603485107422, "__label__home_hobbies": 6.312131881713867e-05, "__label__industrial": 0.00019240379333496096, "__label__literature": 0.00040268898010253906, "__label__politics": 0.0001804828643798828, "__label__religion": 0.0002906322479248047, "__label__science_tech": 0.00580596923828125, "__label__social_life": 0.0001112222671508789, "__label__software": 0.00888824462890625, "__label__software_dev": 0.97802734375, "__label__sports_fitness": 0.00020313262939453125, "__label__transportation": 0.000255584716796875, "__label__travel": 0.00014579296112060547}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 45206, 0.05081]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 45206, 0.3181]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 45206, 0.88803]], "google_gemma-3-12b-it_contains_pii": [[0, 1599, false], [1599, 5931, null], [5931, 11485, null], [11485, 15966, null], [15966, 21248, null], [21248, 23509, null], [23509, 27042, null], [27042, 29564, null], [29564, 35891, null], [35891, 39809, null], [39809, 45206, null]], "google_gemma-3-12b-it_is_public_document": [[0, 1599, true], [1599, 5931, null], [5931, 11485, null], [11485, 15966, null], [15966, 21248, null], [21248, 23509, null], [23509, 27042, null], [27042, 29564, null], [29564, 35891, null], [35891, 39809, null], [39809, 45206, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 45206, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 45206, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 45206, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 45206, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 45206, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 45206, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 45206, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 45206, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 45206, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 45206, null]], "pdf_page_numbers": [[0, 1599, 1], [1599, 5931, 2], [5931, 11485, 3], [11485, 15966, 4], [15966, 21248, 5], [21248, 23509, 6], [23509, 27042, 7], [27042, 29564, 8], [29564, 35891, 9], [35891, 39809, 10], [39809, 45206, 11]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 45206, 0.26538]]}
olmocr_science_pdfs
2024-12-09
2024-12-09
620d13d75391701adbeaa0c7ccbb4874c903340b
Software-Based Energy Profiling of Android Apps: Simple, Efficient and Reliable? Dario Di Nucci*, Fabio Palomba†∗, Antonio Prota*, Annibale Panichella†, Andy Zaidman†, Andrea De Lucia* *University of Salerno, Italy †Delft University of Technology, The Netherlands ‡SnT Centre, University of Luxembourg, Luxembourg Abstract—Modeling the power profile of mobile applications is a crucial activity to identify the causes behind energy leaks. To this aim, researchers have proposed hardware-based tools as well as model-based and software-based techniques to approximate the actual energy profile. However, all these solutions present their own advantages and disadvantages. Hardware-based tools are highly precise, but at the same time their use is bound to the acquisition of costly hardware components. Model-based tools require the calibration of parameters needed to correctly create a model on a specific hardware device. Software-based approaches do not need any hardware components, but they rely on battery measurements and, thus, they are hardware-assisted. These tools are cheaper and easier to use than hardware-based tools, but they are believed to be less precise. In this paper, we take a deeper look at the pros and cons of software-based solutions investigating to what extent their measurements depart from hardware-based solutions. To this aim, we propose a software-based tool named PETRA that we compare with the hardware-based MONSOON toolkit on 54 Android apps. The results show that PETRA performs similarly to MONSOON despite not using any sophisticated hardware components. In fact, in all the apps the mean relative error with respect to MONSOON is lower than 0.05. Moreover, for 95% of the analyzed methods the estimation error is within 5% of the actual values measured using the hardware-based toolkit. Index Terms—Energy Consumption; Mobile Apps; Estimation I. INTRODUCTION Nowadays, over 2 billions users rely on smartphones and tablets to perform their daily activities as reported by the Statistics Portal association [1]. Not only do users play games or send messages, they use mobile applications (a.k.a., apps) for every type of need, including social and emergency connectivity [2]. Due to this ever-increasing number of mobile devices and apps, energy consumption is becoming a critical factor in user satisfaction for both paid and free apps [3]. Energy related issues mainly involve the efficiency of hardware components such as the CPU and other electronic elements. However, Flinn and Satyanarayanan [4] pointed out that “there is growing consensus that advances in battery technology and low-power circuit design cannot, by themselves, meet the energy needs of future mobile computers” [4]. This observation has been confirmed by recent advances in green software engineering, which demonstrated how the source of energy leaks can be software-related as well [5], [6], [7], [8]. For instance, Sahin et al. [5] have shown that good design principles, and design patterns in particular, have a negative impact on the energy efficiency of mobile apps. Along the same line, previous studies have investigated the power efficiency consequences of refactoring, demonstrating the flip side of operations that are supposed to improve non-functional attributes of source code [7], [9]. Despite the aforementioned research efforts, Harman et al. [10] highlight that there is a lack of tools that quickly and efficiently measure the energy consumption of mobile applications. Existing tools fall into three main categories: (i) hardware-based, (ii) model-based, and (iii) software-based approaches. Together with their own advantages, such solutions present various limitations that adversely affect their practical applicability. While hardware-based tools are able to delineate the exact energy profile of a mobile app, they require ad-hoc hardware components that are expensive and difficult to set up. Model-based approaches try to define mathematical functions able to estimate the energy consumption of mobile apps on a given hardware device. However, such tools require careful calibration of the parameters to correctly estimate power consumption. Finally, software-based approaches estimate the power profile of a mobile application solely relying on the system’s functionalities of a device, as an example the CPU frequency. Thus, these tools can be considered hardware-assisted since they rely on measurements obtained by physical hardware components (e.g., cpu, battery, etc.), but without needing any specialized hardware tools. By nature, they are easier to use and cheaper than pure hardware-based solution. As a drawback, they are supposed to be less precise than hardware-based approaches [11]. In this paper, we aim at investigating to what extent software-based tools are less precise than hardware-based tools for energy consumption. In other words, is the higher cost of hardware-based solutions justified by a sensibly more accurate energy profiling? Can software-based solutions lead to close measurements without any cost overhead? To answer these questions, we built a novel tool for extracting the energy profile of mobile applications, which we coined PETRA (Power Estimation Tool for Android), specific for Android OS. PETRA relies on the publicly available Project Volta Android tools† and has the following characteristics: - **Efficiency and Granularity.** PETRA is able to quickly estimate the energy consumed by an app at the method †https://developer.android.com/about/versions/android-5.0.html level. It is worth noting that this level of granularity allows the developer to calculate the energy estimations per test case. The tool does not require any human effort. - **Hawthorne Effect and Impact of Sampling Frequency.** The technologies on which PETRA relies are an integral part of the core Android OS and the instrumentation has little influence on the estimation process. In this way, is possible to minimize the Hawthorne Effect in which the measurements are affected by the measurement process [10]. Moreover, since the tool does not rely on hardware components, it does not suffer from the sampling frequency highlighted by Saborido et al. [12]. - **Specialized Hardware Requirements.** PETRA does not need any particular hardware and provides simple output that can be easily analyzed. For the evaluation, we run PETRA on 54 mobile applications belonging to the publicly available dataset provided by Linares-Vasquez et al. [6]. Thus, we compare the energy measurements provided by PETRA against the actual energy consumption computed using the MONSOON hardware toolkit [13] for the same apps and using the same hardware/software setting (i.e., smartphone model, operating systems, etc.). The collected results showed that the energy estimations produced by PETRA are very close to the measurements obtained with the MONSOON tool, with an error which is within 5% in 95% of the source code units under analysis. A direct implication of our study is that we recommend both the research community and industry to further investigate software-based tools for energy profiling of mobile applications as a viable alternative to hardware-based ones. **Structure of the Paper.** Section II discusses the related literature in the context of power consumption measurement and empirical studies aimed at investigating the causes of energy leaks. Section III presents our software-based approach PETRA. In Section IV the design of the empirical study is described, while Section V reports the results achieved when comparing the performance of our tool with the ones achieved by a hardware-based approach. Section VI discusses the threats that could affect the validity of our study. Finally, Section VII concludes the paper. II. BACKGROUND AND MOTIVATION The attention toward energy efficiency issues have driven the research community in spending a lot of effort on the construction of new methods to extract the energy profiles of devices, as well as providing guidelines to help developers in writing green code. This section describes on the one hand the tools proposed in recent years to measure energy consumption, and on the other hand the empirical studies conducted in the context of software maintenance and evolution. A. Measuring the Energy Profile of Hardware Devices A first category of strategies to measure the energy consumption of devices is hardware-based since specific hardware toolkits are required to perform measurements. While such methodologies are quite popular in other research communities, such as high performance analysis [14] or large scale integration systems [15], they have been only partially explored in the context of software engineering. Flinn and Satyanarayanan [16] proposed a tool named POWERSCOPe. It is based on the adoption of a digital multi-meter connected to a computer, which is used to monitor the energy variations – recorded by the multi-meter – of processes that are running on a laptop. Hindle et al. devised GREENMINER [2], a hardware mining testbed based on an Arduino board with an INA219 chip [17]. Besides the extraction of the energy consumption of mobile devices, GREENMINER also provides a web application for (i) automating the testing of applications running on a device, and (ii) analyzing the results. Finally, other researchers exploited the MONSOON power monitor [13] to measure energy consumption of APIs of Android apps [6]. The costly hardware requirements needed for hardware-based energy profiling encouraged researchers to find alternative ways to approximate the energy consumption. A proxy measure can be computed by constructing models, which are based on the definition of specific functions to estimate the energy consumed by a device during its usage. Bourdon et al. [18] defined POWERAPI, an approach that leverages on analytical models characterizing the consumption of various hardware components (e.g., CPU). Noureddine et al. [19] introduced JALEN, a Java agent which uses statistical sampling for the energy estimations. The model proposed by Pathak et al. [20] [21] is based on system calls, and it was implemented in EPROF, an energy counterpart of gprof, the gnu profiler tool, for profiling application energy drain. V-EDGE [22] considers the battery voltage dynamics for generating a power model. It neither needs external power meters nor relies on the battery current sensing capability. Along the same line, Balasubramanian et al. [23] defined an energy consumption model, named TAILENDER, to estimate to what extent modules such as 3G and GSM contribute to the battery drain by mobile apps. Ding et al. [24] proposed SEMO, a monitoring tool powered by an energy model based on the usage of the battery and its temperature. Zhang et al. [25] proposed a model-based solution with POWERBooTER and POWERTutor. POWERBooTER is a technique for automated power model construction that relies on battery voltage sensors and knowledge of battery discharge behavior. It does not require external power meters. POWERTutor uses the model provided by POWERBooTER for generating online power estimation. Lastly, it is worth mentioning Microsoft’s JOULEMETER tool, which uses energy models specific for each hardware configuration. Finally, software-based approaches exclusively use the system functionalities to estimate the power consumption, without constructing any specific model or requiring any additional hardware. An example of this kind of functionality is ACPI (Advanced Configuration and Power 1http://softwareprocess.es/static/GreenMining.html 2http://tinyurl.com/jkvo9qa Interface), an industry specification for efficiently handling the power consumption in desktop and mobile computers. For this reason, these approaches can be considered hardware-assisted. In this category, Do et al. [26] developed PTOP, an approach proposed that takes into account CPU frequency, hard disk and memory consumption as sources of information to estimate the joules consumed by a process. ELENS [11] provides a more fine-grained estimation of energy consumption at method, path or line-of-source level. It relies on a combination of program analysis and energy modeling and it produces visual feedback to help developers in better understanding the application behavior. Differently from the techniques/tools discussed above, PETRA does not require any additional hardware equipment and therefore any strong experience in the setup of the test bed. It uses reliable tools coming from the Android Toolkit and does not exploit energy models that need to be calibrated. Finally, unlike the tools measuring energy consumption at process level, PETRA works at method-level granularity. In addition to that, most of the approaches proposed in the literature (including PTOP and ELENS) are not publicly available.\textsuperscript{4} B. Empirical Studies in Green Software Engineering In recent years an ever increasing number of empirical studies aimed at understanding the reasons behind energy leaks in source code have been carried out. On the one hand, researchers have investigated the possibility to predict the energy consumption of mobile devices relying on empirical data, paving the way for new prediction models able to alert developers of the presence of energy bugs [27], [28]. On the other hand, Zhang et al. [29] and Gupta et al. [30] have proposed dynamic analysis based approaches for detecting portions of source code affected by energy leaks, while Li et al. [31] have put forward a technique for detecting specific lines of code affected by an energy bug. Hindle [32] has investigated to what extent changes made by developers across software versions affect the energy consumption. He found that (i) software change can affect the power consumption and (ii) there seems to exist a relationship between software metrics and power consumption. Other researchers focused their attention on the relationship between the development practices adopted by programmers and the energy consumption. Sahin et al. [33] showed that code obfuscation can negatively affect energy consumption, but the observed difference with non-obfuscated code unlikely impacts end-users. The same authors have also reported on an analysis of the role of design patterns [5]. In particular, they found that some patterns (e.g., the Decorator pattern) negatively influence energy efficiency. Similar results have been found by Noureddine and Rajan [34]. Hasan et al. [8] analyzed the impact of the data structures used by the developers, specifically the influence of different Java Collections types. Results of their study showed that the use of the wrong type of data structure can increase the energy consumption by up to 300%. Other factors that have been studied that have a negative impact on energy efficiency are (i) the different sorting algorithms exploited [35], (ii) the use of lock-free data structures [36], (iii) the colors used in the GUI of software projects [37], (iv) the API usage of Android apps [6], and (v) the different refactoring applied to simplify the source code [7], [9]. Most of the studies mentioned above relied on hardware-based tools (e.g., MONSOON). The final goal of the approach proposed in this paper is to provide researchers and practitioners an easier way to approximate the energy consumption of the methods of a mobile app without specialized hardware requirements: this can possibly help (i) the research community in conducting more studies aimed at understanding and solving energy-related issues and (ii) practitioners to take energy efficiency into account when developing mobile apps. III. PETRA: A POWER ESTIMATION TOOL FOR ANDROID APPLICATIONS This section presents our novel software-based approach, coined PETRA (Power Estimation Tool for Android), suitably developed to measure the power consumption of mobile apps at a method-level granularity. As depicted in Listing 1, its main process is composed of three main blocks: (i) app preprocessing, (ii) energy profile computation, and (iii) output generation. In the following paragraphs, we detail each part independently. App Preprocessing. In the first step, PETRA needs to set the software environment before measuring the energy consumed when executing a mobile app. To this aim, it uses as input an executable version of the app under analysis in the form of an apk file. The app is identified by the apk location and the name of the app to profile, which correspond to apkLocation, and appName in Listing 1 respectively. Then, PETRA installs the apk on a mobile phone able to run it (e.g., a smartphone having an arbitrary version of the Android operating system) and enables the debuggable option. Enabling debugging is mandatory, because otherwise the instrumentation of the app needed to profile it, would not be possible. ``` computeEnergyConsumption(apkLocation, appName, tCase, nRuns) installApp(apkLocation); for (run=0; run<nRuns; run++){ clearAppCache(appName); resetBatteryStats(); startProfiler(); exerciseApp(appName, tCase); stopProfiler(); collectBatteryStatsData(); collectSystemTraceData(); loadPowerProfile(); for each method call in trace file { computeCallEnergyConsumption(); } saveResults(); stopApp(appName); } uninstallApp(apkLocation) ``` \textsuperscript{4}PETRA is available at \url{http://tinyurl.com/je2nxkd}. Energy Profile Computation. Once the app is properly set up, PETRA exercises the app under consideration using a test case given as input, i.e., tCase in Listing 1. This test case can be created with automated tools (e.g., MONKEYRUNNER or MONKEY) or with manual operations performed by the software engineer. Once the test case is run, the core process behind PETRA starts. For the profiling phase, we leverage the Project Volta Android tools, which are based on the self-modeling paradigm proposed by Dong and Zhong [38], i.e., the definition of a mobile system that automatically generates its energy model without any external assistance. Such tools are dmtracedump⁵, Batterystats⁶, and Systrace⁷. Specifically: - dmtracedump provides an alternate way to show trace log files. The files generated by dmtracedump are easy to parse and allow the developers to establish precisely, at microseconds granularity, when a method call has been invoked and when it returned. PETRA relies on this component in order to store the execution traces of the app under analysis. For each method call dmtracedump provides the entry and the exit time. The final output is a list of the executed method calls during the run. - Batterystats is an open source tool of the Android framework able to collect battery data from the device under evaluation. In particular, it is able to show which processes are consuming battery energy and which tasks should be modified in order to improve battery life. It is executable via the command line. The data collected can be analyzed as a log file or can be converted to an HTML visualization that can be viewed in a browser using Battery Historian⁶. PETRA uses the Batterystats log in order to retrieve the active smartphone components and their status in a specific time window. Furthermore, it can provide the information about the device voltage. Given this information, it is then possible to calculate the energy consumed by the smartphone during a time window. - Systrace is a tool that can be used to analyze application performance. It captures and displays the execution times of the active processes of a smartphone, combining data from the Android kernel, i.e., the CPU scheduler, disk activity, and application threads. The data can be viewed as an HTML report that shows the overview of the processes in a given time window. In PETRA, the information provided by Systrace is used to capture the frequency of the CPU in a given time window. Considering that CPUs have different consumptions as their frequency varies, this information completes the one provided by Batterystats improving the estimations. After gathering the information related to the active components with their status, the CPU frequencies and the method call invocations, the power profile file is loaded. The power profile values define the current consumption for a component along with an approximation of the battery drain caused by each component over time. For instance, it specifies how many MilliAmperes of current are required to run the CPU at a certain frequency. Every smartphone has its own power profile. It is worth noting that each device manufacturer must provide this information and that this info can be found in a defined location in the device⁸. Given the previous data, it is possible to compute the energy consumed for every method call invocation. First of all, given a method call invocation and its termination we can calculate the overall time window \( T_w \) as the arithmetic difference between the two time instants when these two events occurred. However, the energy consumed within one single time window is not constant but may change because of a CPU frequency variation or a component state change happened. Therefore, we divided the time windows in smaller time units, i.e., data frames \( T_\Delta \). When the entry to a method is registered, a new time window \( T_w \) and a new time frame \( T_\Delta \) start. Whenever a component changes its state, the existing time frame \( T_\Delta \) is terminated and a new one (for the new state) is started. When the exit point to a method is registered, then the corresponding time window \( T_w \) is terminated as well as the latest time frame \( T_\Delta \). In this way, each data frame \( T_\Delta \) is characterized by coherent component states (e.g., CPU frequency) and by a coherent (constant) energy drain. For example, if the CPU is working at the maximum frequency and none of the components change their state, the time windows \( T_w \) will be composed by only one time frame \( T_\Delta \) of the same duration, i.e., the difference between the method entry and exit. Therefore, we can calculate the current power intensity at each time frame \( T_\Delta \) as follows: \[ I_\Delta = \sum_{V \in C} I_{\Delta,c,s} \tag{1} \] where \( C \) is the set of smartphone hardware components, \( I_{\Delta,c,s} \) is the current intensity of the component \( c \) with the state \( s \) within the current time frame \( T_\Delta \). For example, 92.6 is the number of MilliAmperes consumed in one second by a Nexus 4 when the CPU frequency is fixed to 384Mhz. After calculating the current intensity, it is possible to calculate the energy consumed in a time frame, as follows: \[ J_\Delta = I_\Delta \times V_\Delta \times T_\Delta \tag{2} \] where \( J_\Delta \) is the consumed energy in Joule, \( I_\Delta \) is the current intensity in Ampere, \( V_\Delta \) is the device voltage in Volt and \( T_\Delta \) is the length of the time frame in seconds. Finally, the energy consumed by a method call can be calculated by summing up the energy consumed in each time frame in which the method call was active: \[ J = \sum_{T_\Delta \in T_w} (I_\Delta \times V_\Delta \times T_\Delta) \tag{3} \] Output Generation. The final output provided by PETRA is a csv file, containing the energy estimation for each method call. --- ⁵https://developer.android.com/studio/profile/tracerview.html ⁸https://source.android.com/devices/tech/power/values.html call. More precisely, it provides the signature of each executed method call, along with the consumption in Joule and the execution time in seconds. By default, PETRA uses Monkey to generate test cases, which are used to exercise the mobile app under analysis and to store the energy drain information for every exercised method call. It is important to highlight that the usage of Monkey is not mandatory, as other tools can be also used with PETRA. However, in order to have a fair comparison with the oracle data, we used Monkeyrunner (i.e., we used the same test cases). Finally, PETRA relies on the Android Activity Manager\(^9\), so the apk must be enabled for debugging. Furthermore, in order to provide a better estimation, PETRA exercises the app multiple times (nRuns in Listing 1). Note that in our experiments nRuns is fixed to 10 and that in order to avoid any bias due to multiple runs, at the start of each run the app cache is cleaned and Batterystats is reset (lines 4 and 5 in Listing 1). IV. EVALUATING THE ESTIMATIONS PROVIDED BY PETRA The goal of the study is to analyze the accuracy of PETRA in providing energy consumption estimations of mobile apps at method-level granularity with the purpose of investigating whether the proposed approach can be used as a valid alternative to hardware-based solutions. More specifically, the study aims at addressing the following research question: **RQ1:** How close are the estimations from PETRA to a hardware-based tool? A. Context Selection and Oracle Extraction The context of the study consisted of a set of 54 Android apps from the Google Play Store having different categories and scope. Table I reports for each app (i) an identifier we assigned to simplify referencing the app, (ii) its name, (iii) its Google Play Store identifier, (iv) the specific version taken into account, and (v) the number of APIs used by the app. The choice of using these apps is not random, but rather guided by the need of having a set of applications for which an oracle reporting the consumption measured at the method level with hardware-based tools is publicly available. Indeed, since we had no hardware-based tool available to perform measurements we had to look for alternative solutions. Some available datasets provide data about the energy consumption of software changes [39] or system calls [40]. However, these datasets are not suitable for our purpose because they (i) do not provide detailed measures for source code at the method level and (ii) contain data from desktop and web applications (e.g., Firefox) rather than mobile apps. For this reason, we relied on the dataset provided by Linares-Vasquez et al. [6], that reports the actual power consumption of the methods belonging to the APIs used by the 54 mobile apps considered in the study. The authors computed the measurements relying on the MONSOON toolkit [13]. Note that the dataset also contains the test data needed to exercise the app in the same manner as done by Linares-Vasquez et al. [6] (more details on the measurement process come later in this section). A direct consequence of our choice to rely on this dataset is that we had to limit the focus of our analysis to methods belonging to APIs. However, we still took into account the energy consumption of 414,899 API calls belonging to the 321 APIs used by the considered apps. Moreover, according to recent findings achieved by Li and Gallagher [41], method invocations represent the more influencing energy consuming operation and, therefore, it is particularly interesting the analysis of the context of API calls. B. Test Environment Setup and Energy Profiles Extraction Figure 1 shows our test environment. As PETRA is a software-based approach, it requires a simple test environment composed only of a smartphone and a PC. While seemingly simple, we need to ensure a well-isolated test environment in order to avoid biases. To this aim, we carefully followed the guidelines from previous work in the field [2], [6], [11], [42]. The subsequent subsections detail each setup choice. Choice of the Smartphone. Table II reports the characteristics of the phone used in the experiment. Specifically, we selected a factory resetted LG Nexus 4 having Android 5.1.1 Lollipop as the operating system, and equipped with a 1.5 GHz quad-core Snapdragon S4 Pro processor with 2 GB of RAM, and having a 2100 mAh, 3.8V battery. The choice is guided by the need to have the same smartphone used in the paper by Linares-Vasquez et al. [6] in order to conduct a fair evaluation. Moreover, it is worth noting that this particular hardware allows to be connected via a data cable, namely a cable where the USB charging can be disabled\(^10\). Thus, during the experiment no energy is transferred over the cable, allowing more stable measurements. \(^10\)http://android.stackexchange.com/questions/54902/disable-usb-charging TABLE I: The mobile apps considered in our evaluation <table> <thead> <tr> <th>#</th> <th>Name</th> <th>ID</th> <th>Version</th> <th># of APIs</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>Battery HD</td> <td>ch.smalltech.battery.free</td> <td>1.16</td> <td>3</td> </tr> <tr> <td>2</td> <td>Textgram</td> <td>codeadore.textgram</td> <td>2.3.15</td> <td>3</td> </tr> <tr> <td>3</td> <td>Write Now Notepad</td> <td>com.aerodroid.writenow</td> <td>1.1.5</td> <td>5</td> </tr> <tr> <td>4</td> <td>AndRecorder Free</td> <td>com.andconstruction.andrecord</td> <td>3</td> <td>2</td> </tr> <tr> <td>5</td> <td>Antivirus Free</td> <td>com.antivirus</td> <td>-</td> <td>2</td> </tr> <tr> <td>6</td> <td>Botanica</td> <td>com.app.botanica.layout</td> <td>1</td> <td>3</td> </tr> <tr> <td>7</td> <td>Sleep Sound Aid</td> <td>com.android.sleep</td> <td>20121007</td> <td>2</td> </tr> <tr> <td>8</td> <td>Battery Drainer</td> <td>com.batterydrainer</td> <td>1.4.0</td> <td>3</td> </tr> <tr> <td>9</td> <td>Better Browser</td> <td>com.browser.segrod.ui</td> <td>2.3</td> <td>2</td> </tr> <tr> <td>10</td> <td>AudioPlayer</td> <td>com.bytemystery.audioplayer</td> <td>1.2</td> <td>3</td> </tr> <tr> <td>11</td> <td>gReminders</td> <td>com.diegoyarza.greminders</td> <td>0.9.7</td> <td>3</td> </tr> <tr> <td>12</td> <td>De.Web Antivirus Light</td> <td>com.dwweb</td> <td>-</td> <td>2</td> </tr> <tr> <td>13</td> <td>Sniper shooter</td> <td>com.fun.games.for.free.snipershooter.free</td> <td>1.6.0</td> <td>2</td> </tr> <tr> <td>14</td> <td>Despicemal me (minion rush)</td> <td>com.gameofandroid.ANMPCgiftofDMHIM</td> <td>1.1.0</td> <td>2</td> </tr> <tr> <td>15</td> <td>10,000 Quotes DB (FREE!)</td> <td>com.hinmoquotesquotesmegacollection</td> <td>3.0.4</td> <td>3</td> </tr> <tr> <td>16</td> <td>Icey Slot</td> <td>com.jib.iceyslotz</td> <td>2.9</td> <td>1</td> </tr> <tr> <td>17</td> <td>Android Music Player</td> <td>com.prstudio.music</td> <td>4.0.03</td> <td>3</td> </tr> <tr> <td>18</td> <td>Android Antivirus</td> <td>com.labapps.antivirus</td> <td>2.0.1</td> <td>1</td> </tr> <tr> <td>19</td> <td>Bubble blast 2</td> <td>com.magnamobile.game.BubbleBlast2</td> <td>1.0.34</td> <td>2</td> </tr> <tr> <td>20</td> <td>Map quest</td> <td>com.mapquest.android.ace</td> <td>1.8.1</td> <td>3</td> </tr> <tr> <td>21</td> <td>Oxford AZ of English Usage</td> <td>com.mobosystems.mdct.embedded.wireless.oxford.englishusage</td> <td>4.3.059</td> <td>2</td> </tr> <tr> <td>22</td> <td>Livo Recorder Lite</td> <td>com.mpl.livelite</td> <td>3.7.0.a</td> <td>1</td> </tr> <tr> <td>23</td> <td>Simple Weather</td> <td>com.netthreads.android.weather</td> <td>1.1.3</td> <td>2</td> </tr> <tr> <td>24</td> <td>Opera Mini browser</td> <td>com.opera.mini.android</td> <td>7.5.3</td> <td>2</td> </tr> <tr> <td>25</td> <td>MasterCard ATM Hunter</td> <td>com.orbscom.ATMHunter</td> <td>1.4</td> <td>2</td> </tr> <tr> <td>26</td> <td>SimpleNews</td> <td>com.prss.simplenews</td> <td>1.4</td> <td>1</td> </tr> <tr> <td>27</td> <td>Punjab Radio</td> <td>com.prstudio.radio.punjabi</td> <td>1.0.4</td> <td>5</td> </tr> <tr> <td>28</td> <td>25000 Best Quotes</td> <td>com.puisantanapps.quotesapp.free</td> <td>1.0.7</td> <td>2</td> </tr> <tr> <td>29</td> <td>aTimer</td> <td>com.ralph4.timer</td> <td>1.3</td> <td>3</td> </tr> <tr> <td>30</td> <td>Star Wars Angry birds</td> <td>com.rvio.angrybirdstarwars.ads.tap</td> <td>1.3.0</td> <td>2</td> </tr> <tr> <td>31</td> <td>Classical Music Radio Lite</td> <td>com.rsclradio</td> <td>1.0.3</td> <td>3</td> </tr> <tr> <td>32</td> <td>Activity Express Task Manager</td> <td>com.sayhello2theworld.te</td> <td>1.22</td> <td>1</td> </tr> <tr> <td>33</td> <td>news swipe</td> <td>com.seovic.news</td> <td>1.0.0</td> <td>2</td> </tr> <tr> <td>34</td> <td>Video Poker</td> <td>com.sg.js.VidPoker</td> <td>1.2.1</td> <td>2</td> </tr> <tr> <td>35</td> <td>Galaxy Torch</td> <td>com.swijaya.galaxytorch</td> <td>1.4</td> <td>3</td> </tr> <tr> <td>36</td> <td>TED</td> <td>com.ted.android</td> <td>2.0.1</td> <td>3</td> </tr> <tr> <td>37</td> <td>Easy Birthday Reminders</td> <td>com.tencetapps.blays</td> <td>1.2.1</td> <td>2</td> </tr> <tr> <td>38</td> <td>World Travel Guide by Triposo</td> <td>com.triposo.droidguide.world</td> <td>2.1</td> <td>2</td> </tr> <tr> <td>39</td> <td>8,500+ Drink Recipes</td> <td>com.webworks.drinkcocktails</td> <td>1.0.6</td> <td>3</td> </tr> <tr> <td>40</td> <td>Droid Notepad</td> <td>com.williamkingdom.droidnotepad</td> <td>1.11</td> <td>2</td> </tr> <tr> <td>41</td> <td>5001 Amazing Facts Free</td> <td>com.ximad.wif</td> <td>3.2.0</td> <td>3</td> </tr> <tr> <td>42</td> <td>Inspiring Quotes</td> <td>com.xstudio.inspiringquotes</td> <td>1.2</td> <td>3</td> </tr> <tr> <td>43</td> <td>Battery Info</td> <td>com.zgame.batteryinfo</td> <td>1.6</td> <td>2</td> </tr> <tr> <td>44</td> <td>Anti Mosquito Sonic Repellent</td> <td>com.zodinplex.antimosquito</td> <td>-</td> <td>2</td> </tr> <tr> <td>45</td> <td>AdEq Equalizer Free</td> <td>de.ebbert.audioeq</td> <td>1.0.9</td> <td>4</td> </tr> <tr> <td>46</td> <td>Anime Radio Online</td> <td>free.animeradioonline.gutisoft</td> <td>1.06</td> <td>3</td> </tr> <tr> <td>47</td> <td>Wiii Radar</td> <td>girsas.wifiradar</td> <td>1.06</td> <td>2</td> </tr> <tr> <td>48</td> <td>Rome</td> <td>hu.pocketguide.bundledRome</td> <td>10-Jul-13</td> <td>3</td> </tr> <tr> <td>49</td> <td>Battery Info Always</td> <td>jpd.sys1.android.battery</td> <td>1.2.0</td> <td>2</td> </tr> <tr> <td>50</td> <td>Advanced Task Manager</td> <td>mobi.infofile.taskmanager</td> <td>2.1.2</td> <td>3</td> </tr> <tr> <td>51</td> <td>Anti dog mosquito whistle</td> <td>mz.anti.dog.cat.mosquito.insect.repellent.whistle</td> <td>1.3</td> <td>2</td> </tr> <tr> <td>52</td> <td>Meridian Media Player Revolte</td> <td>org.iii.romulus.meridian</td> <td>2.4.5</td> <td>2</td> </tr> <tr> <td>53</td> <td>Better Notepad</td> <td>org.strive.notes</td> <td>0.0.5</td> <td>2</td> </tr> <tr> <td>54</td> <td>Arcane legends</td> <td>sts.al</td> <td>1.0.7.0</td> <td>1</td> </tr> </tbody> </table> Isolating the execution of an app. To isolate the behavior of an application being executed on the smartphone, we adopted a number of precautions. In particular, we firstly disabled all the unnecessary apps and processes (e.g., Google Services) running on the phone to avoid race conditions. Then, we avoided asynchronous events, such as incoming messages or calls by removing the sim card from the phone. Finally, we held the phone steady to avoid energy measurements by sensors and WiFi signal changes. Extraction of the Energy Profiles of APIs. To extract the energy profiles of the apps in our dataset, we have to enable the debug mode. This entails manually adding android:debuggable="true" in the file AndroidManifest.xml and regenerating the apk file for each app (i.e. the executable), using ANDROID STUDIO [43]. Once we created these debuggable and executable versions of the apps, we applied PETRA to them. As explained in Section III, our approach receives as input a set of test cases for exercising the app under consideration and measuring the energy consumption at method-level granularity. In the context of this experiment, we exercised the apps in our dataset by using exactly the same [6]. This allows a fair comparison between the energy profiles extracted using our approach and the oracle provided using the MONSOON toolkit [13]. The output of this step consisted of a set of files reporting the execution traces of each app, accompanied by the information on the energy consumed by each method during that execution. It is important to note that in this stage we... collected the information for all the methods belonging to an application. However, to compare the energy profiles extracted by PETRA with the ones extracted using MONSOON [13], we needed to select only the methods belonging to an API. To this aim, we selected from the final output produced by PETRA only the Android public methods, removing also the calls to other Java APIs. Moreover, to be more confident about the energy profiles built by PETRA, we repeated the measurements 10 times. Similarly to Linares-Vasques et al. [6], we aggregated the results of the 10 runs (i.e., the joules consumed by the methods in each run) using the mean operator. Therefore, the final output consisted of a unique value representing the average energy consumed by the method belonging to an API exercised during the test execution. C. Data Analysis and Metrics Once extracted the energy profiles using PETRA, we answered RQ1 by comparing the energy profiles computed using PETRA with the oracle data [6]. To evaluate to what extent the energy consumption provided by our approach is close to the values measured with a hardware based tool, we employed a set of metrics widely used in the area of cost estimation [44] [45]. Specifically, we used the Mean Magnitude Relative Error (MMRE) [44] defined as follow: \[ MMRE = \frac{1}{N} \sum_{i=1}^{n} MRE_i \] (4) where \( n \) is the number of energy estimations computed by PETRA on each app (i.e., number of methods), and \( MRE \) indicates the Magnitude Relative Error [44] and has values in the range defined by the following formula: \[ MRE_i = \frac{|J_i - \hat{J}_i|}{J_i} \] (5) where \( J_i \) and \( \hat{J}_i \) are the energy estimations produced by MONSOON and PETRA respectively for the method \( i \). Besides determining the mean error in the estimations provided by our approach, we also computed the \( PRED(x) \) metric, namely the Relative Error Deviation Within \( x \) [46]. This measure gives an indication of how many methods have estimation errors with our approach within \( x \) of the estimation values provided by MONSOON. In particular, \( PRED(x) \) is defined as the average fraction of the \( MREs \) off by no more than \( x \) as defined by Jorgensen [47]. \[ PRED(x) = \frac{1}{n} \sum_{i=1}^{n} \begin{cases} 1 & \text{if } MRE_i \leq x \\ 0 & \text{otherwise} \end{cases} \] (6) In the field of cost estimation, the parameter \( x \) is usually set to 25, i.e., the estimated cost is within 25% of the actual cost of a project [45]. However, in our context an estimation error of 25% could be very large. For instance, a variation of 25% is very large when estimating the energy consumed by a data structure used in the source code [8]. An analysis done in this way would be too coarse-grained. Thus, we verified whether PETRA can achieve a lower estimation error, by setting \( x = 2; 5; 7; 10; 20 \). In this way, we were able to control how the estimation errors of our approach are distributed. Obviously, the estimation errors in \( PRED(5) \) are also included in \( PRED(2) \), the estimation errors in \( PRED(5) \) in \( PRED(7) \) and so on. This means that the distribution over the different \( PRED(x) \) measures is cumulative. For instance, if \( PRED(2) \) is equal to 0.91 and \( PRED(5) \) is 0.96, then 5% of the estimation errors are between 2% and 5%. Finally, we performed a fine-grained analysis aimed at understanding the types of errors achieved by PETRA during the energy profile estimations. To this aim, we (i) measured the ratio of over/under estimations provided by our approach, and (ii) provided motivations behind the estimation errors. V. Analysis of the Results For each app considered in the empirical study, Table III shows the \( MMRE \) and the distribution of the \( PRED(x) \) achieved when comparing the estimations provided by PETRA with those reported by the oracle data [6]. Table III also reports the percentage of over/under estimations given by PETRA. Finally, the row Average shows the results obtained when considering all the estimations as a unique dataset. A first point to discuss is the mean estimation error provided by our tool (column \( MMRE \)). From Table III we observe that for all 54 mobile apps the mean relative error (\( MMRE \)) is always lower than 0.05, being 0.01 on average. To have a practical idea of the magnitude of the error, an \( MMRE = 0.01 \) corresponds to a percentage of battery discharge of \( 3.1 \times 10^{-6} \%), and thus we can claim that PETRA misses the correct energy consumption by a small factor. For instance, let us consider the case of the SIMPLENEWS app (row #26 in Table III): during its execution, the app makes 15 calls to the API method `writeCommStatusAndClose` of the class `android.os.ParcelFileDescriptor`. This is done to update the status of the events requested when the application is running. The average energy consumption of the method invocation is $1.602 \times 10^{-5}$ Joules when computed. For the remaining 15 apps, we experienced an average error of 0.022. One of the worst estimations regards the app BATTERY HD (row #1 in Table III). This app monitors the battery discharge of mobile phones and tables, by proposing the user a set of statistics about the energy consumption of the apps installed on the device. The app also provides real-time monitoring of the apps that are active on the device, which is implemented through the invocation of the API method `ArrayAdapter.notifyDataSetChanged`. This method simply implements an Observer design pattern [48] that monitors the changes in the status of the applications currently opened on the device. As reported by Linarese-Vasquez et al. [6], this is a well-known energy bottleneck, object of several discussions among Android developers.\(^{12}\) \(^{12}\)http://stackoverflow.com/questions/15990849/ Indeed, on average the method consumes $2.43 \times 10^{-4}$ Joules, i.e., 35% more energy compared to the average consumption of the other methods. This confirms previous findings on the high energy consumption of (instance of) this design pattern [5]. In this particular case, PETRA estimates that $2.48 \times 10^{-4}$ Joules of energy are consumed by the API, thus leading to an error of $5.00 \times 10^{-6}$ Joules ($MRE = 0.02$). We further investigated the behavior of our tool in this case in order to understand the reason behind this error. Specifically, we found that every time a change status notification is sent (i.e., each call to the method notifyDataSetChanged), PETRA accumulates small errors, which leads to a total of $5 \times 10^{-6}$ Joules because of the 24 times the method has been called. Putting things into perspective, we see that although on one of the worst cases the estimation error is still small, the particular example that we highlighted does indicate a potential drawback of using software-based approaches for energy profiling. Indeed, a high frequency of method calls in a method under observation can result in an accumulation of estimation errors. **Observation 1.** In 72% of mobile apps the mean estimation error provided by PETRA is at most 0.01. Although in the other cases the difference is slightly larger, it still only reaches at most 0.04. Thus, the proposed software-based solution provides energy estimations that are quite close to the actual values. Observation 1 only provides a partial view on the performance of our tool as we also need a better understanding of the relative difference between the estimation of PETRA and the hardware based solution. This is why we use the $PRED(x)$ metric, which indicates the percentage of methods in each app with an error ($MRE$) lower than $x$. Table III shows that in 95% of the methods our tool is able to provide an estimation error within 5% of the actual values measured using the MONSOON toolkit. Moreover, in 85% of the methods our tool provides estimation within 2% of error. These data confirm what we found when analyzing the $MMRE$ metric: a software-based solution built using public Android APIs performs similarly to a hardware-based solution that computes the energy consumption of Android apps. The result is particularly evident on 23 apps of our dataset (43%), where we observed that all the estimations of PETRA falls back into 5% of the actual energy consumption (i.e., $PRED(5) = 1.00$). For example, the app BETTER NOTEPAD (row 53 in Table III) implements a notepad which allows the import/export of the notes and their sharing on the main social networks, besides common features such as writing/editing/deleting of notes. The app relies on a single external API, named android.os.Message, and in particular it called 5 times the method `sendToTarget` during its executions. The method is in charge to exchange messages with the `Handler` of the app, thus providing a way to monitor the correct execution of the application. In this case, PETRA perfectly estimated the actual energy consumption of the method twice (i.e., $1.27 \times 10^{-5}$ Joules), while on the remaining three calls the errors (MRE values) are 0.002 and 0.001, respectively. While the results for $PRED(5)$ already revealed the effectiveness of PETRA, it is also important to mention that only 2% of methods have estimation errors outside the 50% of the actual energy consumption. To understand the characteristics of the outliers, let us discuss the cases of SIMPLENEWS (row 26 in Table III) and NEWS—SWIPE (row 33 in Table III) apps, where we observed an unusual behavior of our tool. Indeed, in the former app only 32% of the estimations are within 5% of the actual values, while a still lower percentage of them (11%) is within the 5% of the oracle values in the NEWS—SWIPE app. Both the apps are newspaper readers that function as integrators of news items published on online websites. The need of retrieving news over the network implies a non-deterministic waiting time due to delay that querying the external websites induces. As a consequence, such communication overhead makes it difficult to compare different approaches as the experiments where done under different network conditions. While PETRA generally works well and provides estimations very close to the actual values, there are a few methods where such errors are higher than the ones discussed above. In particular, for 5% of methods the corresponding estimations are not within 5% of the oracle values. Further analyzing the factors behind such deviations, we observed that these are due to the usage of sensors (i.e., motion, environmental, and position sensors). Unfortunately, the measurement of the power consumption of sensors is still an open issue in software-based energy measurement [49]. In the case of PETRA these components are not analyzed by Android tools and as such, we inherit this weakness. We plan to analyze this aspect as a future work, in order to improve the performance of our tool. **Observation 2.** In 95% of the methods PETRA provides an estimation error within 5% of the actual values measured with the MONSOON toolkit, confirming the good performances of our tool. Errors in measurement mainly occur in cases where there is significant use of network capabilities or when the sensors are used. Finally, regarding the types of estimations provided by PETRA, we observed that our tool rarely underestimates the energy consumption (overall, in 11% of the cases), while 89% of the estimations are slightly higher than the actual values. This is mainly due to the fact that in each energy estimation some noise is summed up during the measurement (see, for instance, the case of the app SIMPLENEWS previously discussed). Thus, the estimation results are typically higher than the actual values. However, as previously shown, our tool is able to achieve a good compromise between the errors committed and the accuracy of the evaluations. On the other hand, the few underestimations are generally due to the usage of sensors. For instance, the class `SensorManager` used by the app ANDROID ANTIVIRUS (row #18 in Table III) is responsible for the management... of the environmental sensors needed to check the status of external factors possibly threatening the security of the device. In this case, PETRAs is not able to take into account the energy consumption of such sensors, therefore providing a lower estimation (i.e., $1.35 \times 10^{-5}$ Joules) with respect to the actual one (i.e., $1.37 \times 10^{-5}$ Joules). **Observation 3.** In 89% of the methods PETRAs overestimates the energy consumed. This is mainly due to the noise accumulated over the different APIs estimations. In the remaining 11% of the methods, our tool underestimates the actual energy consumption because of the presence of sensors. Once we evaluated the three different aspects described above (i.e., MMRE, PRED(x), and over/under estimations), we can provide an answer to our RQ. First of all, we can conclude that PETRAs provides estimations close to the actual ones: indeed, the mean relative error (MMRE) produced by our tool is always lower than 0.05 (0.01 on average). At the same time, 95% of the estimation errors are within 5% of the actual values computed using a hardware-based tool; this confirms that a software-based approach can actually perform similarly to the alternative hardware solution. Finally, our analyses highlighted some potential drawbacks of our tool. Indeed, the significant use of network capabilities as well as the usage of sensors can lead to higher estimation errors. **VI. THREATS TO VALIDITY** This section discusses the threats to the validity of our empirical evaluation, classifying them into construct, internal, external, and conclusion validity. The main threats related to the relationships between theory and observation (construct validity) are due to imprecisions in the measurements we performed. PETRAs relies on different sources of information, so imprecisions in those sources could affect the quality of the estimations. For example, the values contained in the power profile file, provided by the device manufacturer, define just an approximation of the battery drain caused by a component in a second. Moreover, PETRAs does not consider the consumption due to the usage of sensors and GPU. For this reason, PETRAs could not be the best solution for energy estimations of apps that strongly stress this kind of hardware. In order to limit the factors that can affect our results (internal validity) we disabled the mobile connections (not WiFi), did a factory reset of the device before starting the experiments, and avoided any unneeded processes on the device. Lastly, in order to avoid imprecisions due to battery degradation and provide more accurate results, we repeated the measurements 10 times and we aggregated the results using the mean operator, as was previously done by Linares-Vasquez et al. [6]. Regarding the generalization of our findings (external validity) we considered 54 apps of different categories from the Linares-Vasquez et al. dataset [6]. Relying on this dataset, we had to limit our analysis to methods belonging to APIs that could not represent the full variety of methods. For this reason, further studies aiming at replicating our work on larger datasets are desirable and part of our future agenda. Another threat could be related to the smartphone that we used in our study. It is worth to note that we used a LG Nexus 4 in order to compare our estimations with those provided by the oracle data [6]. Finally, the threats related to the relationship between the treatment and the outcome (conclusion validity) are represented by the analysis methods exploited in our study. We discuss our results applying widely used metrics (i.e., MMRE and PRED) able to compare our numerical outcomes with numerical oracles. **VII. CONCLUSION AND FUTURE WORK** This paper investigates the wide-spread assumption that energy consumption profiles calculated using software-based tools are less precise than the actual values as measured using hardware-based tools. To this end, we propose PETRAs, a new Android-specific tool for estimating the energy consumption of mobile applications. Our tool relies on public available tools, developed by Google in the context of Project Volta. We evaluated PETRAs on 54 mobile applications from the dataset provided by Linares-Vasquez et al. [6]. For each application, this dataset contains the energy consumption of methods belonging to APIs using the MONSOON hardware toolkit [13]. Our results showed that the estimations produced by PETRAs are very close to the actual values, more precisely: - **Error Magnitude.** The mean estimation error achieved using PETRAs is 0.04 with respect to actual value calculated using MONSOON. - **Error Reasons.** The measurement errors are mainly due to a significant use of network capabilities or sensors. - **Error Type.** 89% of the estimations are overestimations, mainly due to the accumulated noise achieved during the estimations. In the remaining cases, the use of sensors and network produces underestimations. These observations represent the main input for our research agenda. We will focus on designing and developing new techniques that better estimate the energy consumption of components such as sensors and network. As such, i) we will investigate Android tools able to give more precise information regarding the state of components (i.e., GPU Monitor and Network Monitor), ii) we will design new services able to capture those components not analyzed by Android tools, e.g. sensors. We should carefully design these services in order to avoid the Hawthorne Effect [10], that currently has little influence on our tool. Moreover, in order to assess these new techniques and to validate the currently achieved results, we plan to replicate our study on a larger set of applications, considering also other methods than API methods. REFERENCES
{"Source-Url": "https://pure.tudelft.nl/portal/files/32869556/dinucciSANER2017.pdf", "len_cl100k_base": 12713, "olmocr-version": "0.1.50", "pdf-total-pages": 13, "total-fallback-pages": 0, "total-input-tokens": 46248, "total-output-tokens": 16272, "length": "2e13", "weborganizer": {"__label__adult": 0.0004925727844238281, "__label__art_design": 0.00035381317138671875, "__label__crime_law": 0.0003705024719238281, "__label__education_jobs": 0.0005893707275390625, "__label__entertainment": 9.196996688842772e-05, "__label__fashion_beauty": 0.00024437904357910156, "__label__finance_business": 0.0004363059997558594, "__label__food_dining": 0.0003795623779296875, "__label__games": 0.0009675025939941406, "__label__hardware": 0.0069580078125, "__label__health": 0.0008268356323242188, "__label__history": 0.00040793418884277344, "__label__home_hobbies": 0.00017714500427246094, "__label__industrial": 0.0006289482116699219, "__label__literature": 0.00029206275939941406, "__label__politics": 0.00028824806213378906, "__label__religion": 0.0004277229309082031, "__label__science_tech": 0.12164306640625, "__label__social_life": 8.96453857421875e-05, "__label__software": 0.01169586181640625, "__label__software_dev": 0.85107421875, "__label__sports_fitness": 0.0003833770751953125, "__label__transportation": 0.0008153915405273438, "__label__travel": 0.00028324127197265625}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 63472, 0.03231]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 63472, 0.42629]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 63472, 0.87645]], "google_gemma-3-12b-it_contains_pii": [[0, 0, null], [0, 5570, false], [5570, 11656, null], [11656, 17414, null], [17414, 23616, null], [23616, 28594, null], [28594, 35109, null], [35109, 39695, null], [39695, 40977, null], [40977, 47237, null], [47237, 53319, null], [53319, 59866, null], [59866, 63472, null]], "google_gemma-3-12b-it_is_public_document": [[0, 0, null], [0, 5570, true], [5570, 11656, null], [11656, 17414, null], [17414, 23616, null], [23616, 28594, null], [28594, 35109, null], [35109, 39695, null], [39695, 40977, null], [40977, 47237, null], [47237, 53319, null], [53319, 59866, null], [59866, 63472, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 63472, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 63472, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 63472, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 63472, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 63472, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 63472, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 63472, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 63472, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 63472, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 63472, null]], "pdf_page_numbers": [[0, 0, 1], [0, 5570, 2], [5570, 11656, 3], [11656, 17414, 4], [17414, 23616, 5], [23616, 28594, 6], [28594, 35109, 7], [35109, 39695, 8], [39695, 40977, 9], [40977, 47237, 10], [47237, 53319, 11], [53319, 59866, 12], [59866, 63472, 13]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 63472, 0.22672]]}
olmocr_science_pdfs
2024-11-28
2024-11-28
c1f625e01085dcac1b414366d2de45bbdc0191c8
USER GUIDE CONTENTS - SOFA - how you can use it - Installing SOFA - SOFA won’t start - solutions - Getting started - Entering fresh data - My variables won’t go into SOFA - Setting variable details e.g. labels - Connecting to databases - Importing spreadsheet/csv data - Online surveys with Google Docs - Report tables - Statistical tests - Making charts - Filtering data - Recoding data - Non-Ubuntu/Debian Linux installation - Exporting data SOFA Support If you are looking for affordable commercial support, or if you want to support making Statistics Open For All, there is an option to suit you: "Your support, big or small, makes a difference" Grant Creator of SOFA Click here Released with open source AGPL3 licence © 2009-12 Paton-Simpson & Associates Ltd Using SOFA SOFA can be used to: - make charts e.g. Pie Charts - produce attractive report tables e.g. gender vs age - run basic statistical tests e.g. one-way ANOVAs - and generally increase your understanding of your data. SOFA is great for initial research and exploratory analysis - or as someone put it rather nicely, “statistical/mathematical doodling”. It doesn't have every statistical test you could possibly need, but for many purposes it has more than enough. And the plan is to gradually extend SOFA over time without compromising the emphasis on ease of use, beautiful output, and learn as you go. --- Wiki Except where otherwise noted, content on this wiki is licensed under the following license: CC Attribution-Noncommercial-Share Alike 3.0 Unported Installation Installer Packages SOFA Statistics has installer packages for: - **Windows** (covers XP, Vista, and Windows 7). A video of installation is here [Windows Installation](http://www.sofastatistics.com/videos.php#win_install) ![Windows Installation](http://www.sofastatistics.com/videos.php#win_install) The installer lets you skip adding all the extra packages if you have already installed them in a previous installation of SOFA Statistics. - **Ubuntu** deb package (covers Ubuntu and Linux Mint). Mac dmg package (covers Leopard and Snow Leopard) The Mac installer, like the Windows installer, lets you opt out of installing some packages e.g. Python if you already have a suitable version installed. If you have another Linux distro you should also be able to get SOFA running using a special installer script in the tar.gz file. See Non-Ubuntu/Debian Linux Installation [http://www.sofastatistics.com/wiki/doku.php?id=help:linux_installation] If you have any installation problems, please contact grant@sofastatistics.com. Installing a Newer Version This should Just Work 😊. The only quirk is that SOFA might rename your existing default_report.htm file to something like default_report_pre_version_x.htm to make sure everything new you make works in the new system. Newer versions of SOFA Statistics sometimes upgrade the underlying Javascript that displays charts in reports and existing charts may get broken by Javascript changes. This should become less of a practical issue over time as SOFA stabilises. Linux Mint Menu Issue For some mysterious reason, the SOFA Statistics shortcut (under Other) doesn’t work. But there is a simple workaround. Just drag the icon onto the desktop. That icon will work. There seems to be something a little quirky about the Mint Menu. Screenshot on Three Systems Wiki Except where otherwise noted, content on this wiki is licensed under the following license: CC Attribution-Noncommercial-Share Alike 3.0 Unported [http://creativecommons.org/licenses/by-nc-sa/3.0/] SOFA Won't Start Sorry! But we can probably fix it. Make sure you are installing the latest version of SOFA Statistics Sourceforge SOFA downloads [https://sourceforge.net/projects/sofastatistics/files/]. Newer versions are sometimes better at handling problems. Here are some things which might help: Using Sofastats Recovery Check to see if you have a local sofastats_recovery folder. E.g. - Windows - it should be in one of the following places unless you have custom configured where your home folder is: - C:\Documents and Settings\username\sofastats_recovery - C:\Documents and Settings\username\My Documents\sofastats_recovery - C:\Users\username\sofastats_recovery - C:\Users\username\Documents\sofastats_recovery - Mac OS X: - /Users/username/sofastats_recovery - Linux e.g. Ubuntu: - /home/username/sofastats_recovery If not, try to open SOFA using IDLE (see below). Next to your local sofastats_recovery folder should be a local sofastats folder. Delete your local “sofastats” folder and rename the “sofastats_recovery” folder to “sofastats”. When you restart SOFA Statistics, everything should now work. The “sofastats_recovery” folder only includes a clean install of SOFA. Any modifications you have made will be lost if you wipe the “sofastats” folder. You can always keep a copy of your original “sofastats” folder so you can recover individual items e.g. the internal SOFA database from “sofastats/_internal/sofa_db”. 1. Delete the sofastats folder 2. Rename the sofastats_recovery folder to sofastats Open SOFA using IDLE to see any error messages To use IDLE you will to install Python (version 2.6 is needed for SOFA - installers available here http://www.python.org/download/releases/2.6.6/) (http://www.python.org/download/releases/2.6.6/). You can use IDLE to open and then run SOFA. Step 1 - Find SOFA’s start.py file. In Windows it will usually be in C:\Program Files\sofastats. Ubuntu users should look at /usr/share/pyshared/sofastats. For other Linux see /usr/share/sofastats. In Macs look for /Applications/SOFA Statistics.app Step 2 - Right click start.pyw (or start.py) file and select Edit with IDLE Step 3 - There should be two windows open - click on the one with lots of coloured text in it and either press F5 or from the menu select Run>Run Module Step 4 - Look at the messages displayed. Is there anything that might explain the problem? Email grant@sofastatistics.com for help, preferably with a screen-shot of the message. In Ubuntu, you can open the terminal and try: ```python python2.6 /usr/share/pyshared/sofastats/start.py ``` e.g. `python2.6 /usr/share/pyshared/sofastats/start.py` In other Linux distros, assuming you ran the install script, you can open the terminal and try: ```bash sofastats ``` or failing that: ```bash python2.6 <your path to the sofastats folder>/start.py ``` ```bash e.g. python2.6 /usr/share/start.py ``` **Python Broken?** Reinstall SOFA as usual but, when you get to the Python step, select the Repair option. **Wrong version of Python** SOFA Statistics currently requires Python 2.6. Any additional packages installed by the SOFA installer must also be attached to python26 not python27 etc. If your system has multiple versions of Python installed, the icon or launcher must explicitly refer to 2.6. On Windows, one test you can try is to click on Start then Run and run the following: ``` C:\Python26\python.exe “C:\Program Files\sofastats\start.pyw” ``` The same approach can be tried on Mac and Linux from the terminal - explicitly tell the system which version of Python to use to launch SOFA. NB the start.py file is the one you need if not on Windows. ```bash python2.6 /home/username/sofastats/start.py ``` **Ask for Help** - Community discussion group - [http://groups.google.com/group/sofastatistics](http://groups.google.com/group/sofastatistics) - Direct email to lead developer - Open email to SOFA developer [mailto:grant@sofastatistics.com?subject=I%20am%20interested%20in%20SOFA] **Specific Errors** **Problems with comtypes** Comtypes is installed as part of the SOFA installation process. If you have any comtypes problems, try reinstalling it manually e.g. by double clicking “comtypes-0.6.2.win32.exe” in “C:\Program Files\sofastats\sofalibs”. Make sure it is associated with Python 2.6 (not 2.7 etc if you already have other versions of Python - see **Wrong version of Python**). Did that step succeed? On Windows XP you can see it in a folder like below. Is it present on your system? Under python26 not python27? - Community discussion group - [http://groups.google.com/group/sofastatistics](http://groups.google.com/group/sofastatistics) - Direct email to lead developer - Open email to SOFA developer [mailto:grant@sofastatistics.com?subject=I%20am%20interested%20in%20SOFA] If not, could it have been accidentally skipped? There is a video showing SOFA being installed on Windows at [Windows Installation](http://www.sofastatistics.com/videos.php#win_install). Are there any clues there? And what happens if you just try to run the command import comtypes (see image below)? NB after typing in import comtypes you hit Enter on your keyboard. ![Image showing Python Shell with import comtypes highlighted](image) **AttributeError: 'module' object has no attribute 'DATA_DETS'** This problem may have happened on Windows when some old pyc files survived the upgrade. Solution: delete all pyc files (e.g. get_data.pyc) from your SOFA program folder e.g. C:\Program Files\sofastats. SOFA will rebuild the pyc files and they will be based on the latest code. How is this problem possible? If the pyc files were generated during the last install, but the py files are older than that install date. **Database locked** Does rebooting help? If not, it may be necessary to start again with a fresh copy of the default database. If you’re lucky, you haven’t put anything into the default database yet, or your data was derived from a spreadsheet and you can re-import it. It is still not clear what causes this problem or how to properly fix it but there is a workaround of sorts. After closing SOFA, locate your default sofa database (e.g. "C:\Users\username\sofastats\internal\sofa_db"). Rename it to “sofa_db_hide”, take a fresh copy of sofa_db from your sofa_recovery folder, and put it in the sofa\internal folder. Re-start SOFA and re-import any data etc. Hopefully there will be a better solution at some point. **Contents** [http://www.sofastatistics.com/userguide.php] Wiki Except where otherwise noted, content on this wiki is licensed under the following license: CC Attribution-Noncommercial-Share Alike 3.0 Unported [http://creativecommons.org/licenses/by-nc-sa/3.0/] Getting Started Demonstration Data Before analysing your own data, it can be helpful to play with the demonstration data provided with SOFA Statistics. Click the “Enter/Edit Data” button to get started. This brings up the data selection dialog. Here you can look at existing data tables or make new ones. Here we just want to look at the demonstration data table “demo_tbl”. Click on “Open”. Here you can see the data we will be test analysing using SOFA Statistics. Note the pale blue column - the background colour indicates the field is read-only. Typically, read-only fields are autonumbered or timestamps. Making a Simple Report Table On the main SOFA form, click on “Report Tables”, Let’s start with a simple report table of Age Group vs Country. NB all of this data is fictitious and designed to allow features of the program to be demonstrated. 1. For “Table Type” select “Crosstabs”. A cross tabulation shows one or more variables against one or more other variables e.g. Age Group in the rows and Country in the columns. 2. We need to add a row so click on “Add” under the “Rows” label 3. Select “Age Group” and either double click it or select “OK”. Under the “Columns” label click on “Add” and add Country. In the demonstration pane below you will see a rough illustration of what the table will look like. If you want to see the actual table, click on “Run”. If “Add to report” is ticked, the output will also be saved to the end of the output file specified at the bottom of the form. **Extra Configuration of Report Table** Next you may want to configure the rows and/or columns. Let's add a total column and columns for row and column percentages. 1. Click on “Config” under the “Columns” label 2. Tick “Total” under the “Misc” heading 3. Tick “Column %” and “Row %” under the “measures” heading 4. Click on “OK” to see changes in demonstration table. NB to see actual results, click on “Run”. If you click “Run” with “Add to report” ticked, you can view the result by clicking on the “View” button. This will open your default web browser so you can see the output. The styling of your table can also be changed - here are some examples of different report tables: Documentation on making report tables is extended in Making Report Tables. Anova Click on the “Statistics” button on the main SOFA form. Then click on the “CONFIGURE TEST” button (ANOVA should already be selected). Let’s look at whether there is a difference between the average ages in the 3 different countries. NB all the data here is fictitious and only for example purposes. 1. Select the variable that is averaged (the one we think might vary between groups). In this case, select “Age”. 2. Select the variable with the groups. In this case, select “Country” and then select “Group A” and “Group B”. 3. Click on “Run” to see results. In this case, there is probably a real difference (p has a very small value). Looking at the mean age for each group and the distribution for each group will help us decide how important the difference is for the purpose at hand. NB a difference can be statistically significant and clinically/politically/practically etc insignificant. Final Comments There is a lot more to SOFA Statistics than what is demonstrated here. Hopefully this is enough to encourage you to try different features out. Of course, if you have any questions, ask them in the community discussion group Discussion Group [http://groups.google.com/group/sofastatistics] Wiki Except where otherwise noted, content on this wiki is licensed under the following license: CC Attribution-Noncommercial-Share Alike 3.0 Unported [http://creativecommons.org/licenses/by-nc-sa/3.0/] **Entering Fresh Data** SOFA Statistics lets you enter your data directly. Or you can import it from a spreadsheet or csv file. Or you can connect directly to a database. This demonstration shows how to enter fresh data. Start by clicking on the “Enter/Edit Data” button on the main SOFA form. In the “Configure Data Table” dialog: 1. Give your table a name. NB spaces are not allowed in the table name. 2. Add fields - each with a name and a data type (“Numeric” (numbers), “String” (which means text), or “Date”. 3. Click on the “Update” button to save your changes and open the table ready for data entry. Any tables you make yourself are added to the default SOFA database “sofa_db”. To open your new table, click on “Enter/Edit Data”, select your table and click on the “Open” button. The Sofa_Id is an autonumber to enable SOFA to keep track of everything. It can't be edited. You can edit the other fields. NB to hit the “Enter” key on your keyboard to save a row and open and empty one ready for more data entry. Note how the Sofa_Id is autfilled in. My Variables Won't Go Into SOFA If you have trouble analysing your variables in SOFA Statistics, check that: 1. Your data is structured the right way for the analysis you want. For example, if SOFA needs a column for gender and a column for height, there will be a problem if your data has a column for male height and a column for female height. 2. Any variables you need to analyse as numbers e.g. for correlation analyses or histograms, have actually been entered/imported as numeric data not as text. Structuring data for analysis The first step is to think about what you want to find out about the data. Here are some examples. Types of SOFA Statistics analysis Differences between groups Instead of one column per condition or group there needs to be a group column and a measures column. Example of a bad format (for SOFA): <table> <thead> <tr> <th>Male</th> <th>Female</th> </tr> </thead> <tbody> <tr> <td>186</td> <td>167</td> </tr> <tr> <td>179</td> <td>170</td> </tr> </tbody> </table> Example of a good format (for SOFA): <table> <thead> <tr> <th>Gender</th> <th>Height</th> </tr> </thead> <tbody> <tr> <td>Male</td> <td>186</td> </tr> <tr> <td>Female</td> <td>167</td> </tr> <tr> <td>Male</td> <td>179</td> </tr> <tr> <td>Female</td> <td>170</td> </tr> </tbody> </table> In this case, the ranked or averaged variable would be Height, the Group By variable would be Gender, and groups a and b would be Male and Female respectively. Or if we were looking at the fictitious weight data in the demonstration data and we wanted to know if it differed between two countries: Relationships between two different variables E.g. looking at linear correlation: <table> <thead> <tr> <th>Age</th> <th>Weight</th> </tr> </thead> <tbody> <tr> <td>56</td> <td>86</td> </tr> <tr> <td>22</td> <td>55</td> </tr> </tbody> </table> In the appropriate SOFA dialog you would select one variable as A and the other as B. Results of Pearson's Test of Linear Correlation for "Age" vs "Weight" p value: 0.000 Pearson's R statistic: 0.519 Difference between two "paired" variables E.g. looking to see if there is a difference between fuel consumption before a fuel gadget was added and afterwards: NB each row would be the data for one vehicle (or one type of vehicle etc depending on what was being studied). <table> <thead> <tr> <th>Consumption (before)</th> <th>Consumption (after)</th> </tr> </thead> <tbody> <tr> <td>12.5</td> <td>11.7</td> </tr> <tr> <td>16.1</td> <td>16.0</td> </tr> </tbody> </table> Or a difference in weight before and after a diet: NB each row would be the data for one person. <table> <thead> <tr> <th>Weight</th> <th>Post-diet Weight</th> </tr> </thead> <tbody> <tr> <td>87</td> <td>90</td> </tr> <tr> <td>59</td> <td>59</td> </tr> </tbody> </table> In the appropriate SOFA dialog you would select one variable as A and the other as B. Restructuring your data The most common problem is when your data has the data for different groups in different variables. E.g. height data for two genders: <table> <thead> <tr> <th>Male</th> <th>Female</th> </tr> </thead> <tbody> <tr> <td>186</td> <td>167</td> </tr> <tr> <td>179</td> <td>170</td> </tr> </tbody> </table> The easiest way to handle this might be to change the data in a spreadsheet and import it in the restructured form. 1. Insert group by column 2. Transfer first variable (Male) by renaming it to the measure (Height) and populating the group by column (Gender) for that variable 3. Transfer second variable by pasting height values below and completing the Gender column with the variable (Female) 4. Delete the variable not needed (Female in this case) NB You could have used 1 for Male and 2 for Female if you preferred and added value labels to Gender once the data was imported into SOFA Statistics. See Setting variable details e.g. labels. The same process can be used if there are multiple groups e.g. countries instead of genders. **Numbers stored in a text variable** If you imported your data into SOFA from a spreadsheet, the solution is probably to change the appropriate column data types to numeric and reimport the data. SOFA tries to warn you if it doesn't detect enough numeric variables for the analysis you are conducting e.g. you need at least two numeric variables to conduct a Pearson's R linear correlation analysis. <table> <thead> <tr> <th>Group A:</th> <th>Sofa_id (sofa_id)</th> </tr> </thead> <tbody> <tr> <td>Start making your selections</td> <td></td> </tr> </tbody> </table> There are not enough suitable variables available quantity data type can be used in this analysis. This problem sometimes occurs when numeric data is stored in the spreadsheet as text. In such cases the solution is to format the spreadsheet and re-import it. Wiki Except where otherwise noted, content on this wiki is licensed under the following license: CC Attribution-Noncommercial-Share Alike 3.0 Unported [http://creativecommons.org/licenses/by-nc-sa/3.0/] Setting variable details e.g. labels Anywhere you can see a variable, you should be able to right click on it and access its settings. E.g. from a variable added to a report table configuration: Or a variable in a drop down list in a charts dialog: Clicking on the variable with the right mouse button will pop up a settings dialog: This dialog allows you to set: - Variable label e.g. “Age Group”. This label will be displayed in reports instead of the variable name e.g. “agegroup”. - Notes. You can store any information here about the variable. - Data Type. The options are “Nominal (names only)”, “Ordinal (rank only)”, and “Quantity (is an amount)”. This information lets SOFA present appropriate lists of variables for specific tests e.g. quantity variables such as age or height for histograms but not country or gender. - Value labels e.g. “Male” for 1 and “Female” for 2. SOFA output will display the value labels. Connecting to Databases Unlike many statistics programs, in SOFA Statistics you can connect directly to data you have in any supported SQL-type database (currently MS Access, MySQL, MS SQL Server, PostgreSQL, and SQLite). NB if you have data in a spreadsheet or stored as csv see Importing spreadsheet/csv data. To connect to an SQL-type database, SOFA Statistics needs the necessary login details e.g. password. Rather than having to enter these repeatedly, you can store the login details as part of a project configuration. Most typically, you will only be wanting to connect to one database server e.g. MySQL. SOFA Statistics lets you store details for as many as you like e.g. if some of your data is in SQLite and some is in MS Access then you just enter connection login details for both. 1. Click on “Select Project” 2. Click on “New” to configure new project or “edit” to edit an existing project. NB the SOFA default project cannot be edited. 3. Enter the required details. Tip - hovering over text boxes will often suggest a likely value e.g. “localhost” for host. 4. Click the “Update” button to save your settings The selected project settings are displayed on the main SOFA form A video is available showing how to connect directly to your SQL data: Connecting to your SQL data video [http://www.sofastatistics.com/videos.php#sql_connect] Wiki Except where otherwise noted, content on this wiki is licensed under the following license: CC Attribution-Noncommercial-Share Alike 3.0 Unported [http://creativecommons.org/licenses/by-nc-sa/3.0/] Importing Spreadsheet/CSV Data Prepare Your Data Clean the Spreadsheet/CSV file - **One data type per column.** If you want a column analysed as a number e.g. 60, 102.5, 3, etc remove text such as “n/a”, “removed” etc. SOFA can cope with mixed data types by getting you to choose an overall type as you import (unless you select text, data of the other types is converted to missing values). But you will have to decide what to do for each and every column every time you import the data. So it is probably best to clean it before attempting an import. - **One header row (or none) only,** SOFA can’t handle multiple header rows so tidy that up first - **Unique field names.** SOFA can handle duplicate field names (it appends 001, 002 etc to make the names unique) but it is probably better to make the names yourself. - **Remove empty rows and columns at beginning.** They may make the layout more appealing but SOFA expects the first row to be either the header row or the first data row. <table> <thead> <tr> <th>A</th> <th>B</th> <th>C</th> <th>D</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>Car</td> <td>Colour</td> <td>Origin</td> </tr> <tr> <td>2</td> <td>Fiat</td> <td>Red</td> <td>Italy</td> </tr> <tr> <td>3</td> <td>Ford</td> <td>Blue</td> <td>Denmark</td> </tr> <tr> <td>4</td> <td>Honda</td> <td>Red</td> <td>Australia</td> </tr> <tr> <td>5</td> <td>Jaguar</td> <td>Silver</td> <td>UK</td> </tr> </tbody> </table> - **Remove additional worksheets.** SOFA is only set up to import a single worksheet. Structure the Data for Analysis SOFA expects your data to be organised in a particular way. E.g. should I have gender as a field with 1s and 2s in it and height as another field or should I have a column of results e.g. height, for each gender? SOFA only works with the first structure. Check Structuring Data For Analysis if not sure or if there are problems. Importing Local Data SOFA Statistics currently supports importing data from Excel spreadsheets, ODS spreadsheets (OpenOffice Calc and Gnumeric etc), csv files and Google Docs spreadsheets. NB you do not need to import data from SQL-type databases (currently MS Access, PostgreSQL, MySQL, MS SQL Server, and SQLite). See Connecting to databases. 1. Click on the “Import Data” button on the main SOFA form 2. To import local data, click on “Browse” and select csv, xls, or ods file 3. Provide the data with a unique name by which SOFA Statistics can identify the data. Then click on the “Import” button to import the data into the default SOFA database “sofa_db” with the table name provided. A video is available showing how to import CSV data: Importing CSV data video [http://www.sofastatistics.com/videos.php#importing_csv] **Importing Google Docs Online Spreadsheets** 1. Click on the “Import Data” button on the main SOFA form 2. Click on the “Google spreadsheet” button 3. Enter the correct email and password details to sign into your Google account The existing spreadsheets are listed and then you can select a worksheet. If there is only one spreadsheet and one worksheet there is no need to make a selection. 4. Click on the “Download” button to download the data onto your local machine. 5. The data is saved in a local SOFA folder as an ods format file. 6. Change the SOFA Table Name and then click on the “Import” button. A video is available showing how to import Google Docs data: Importing Google Docs spreadsheets video [http://www.sofastatistics.com/videos.php#importing_google] Wiki Online Surveys with SOFA and Google Docs Spreadsheets Overview SOFA makes it easy to survey people and analyse the results. Just make a simple survey form in Google Docs, send a link to the people you want to survey (perhaps individually, perhaps in a newsletter), and import the data into SOFA Statistics from the underlying Google Docs Spreadsheet ready to make tables etc. You can even embed the survey in a web page. Configure Survey - Start at Google Docs [http://docs.google.com] - Select “Form” - Add questions The options are limited compared to many survey tools but they should be adequate for a quick and simple survey. - Click “Done” - Click on the Theme button near the top and select a visual theme for the survey Distribute Survey The survey page displays the link to the survey. You can email the link You can view the published form here: http://spreadsheets.google.com/viewform?formkey=dEAzIUBiU1loNjViYXlNQjY2Q0ZlNE9BQU either manually, or using the “Email this form” button. - Or you can embed the survey in a webpage Results Automatically Stored in Spreadsheet Survey results are automatically stored in the spreadsheet that Google Docs automatically makes when you configure your form. The new spreadsheet will appear in your list of spreadsheets. Importing into SOFA for Analysis Use the standard approach to importing from Google Docs spreadsheets. Extra Data Preparation Google Docs Spreadsheets store multi-choice responses as text rather than numbers. This is probably not a problem if the data is categorical (order doesn't matter) but if you are analysing Likert scales e.g. “Very Unhappy”, “Unhappy”, “Neutral”, “Happy”, “Very Happy”, you want the results reported in the correct order. To achieve this we must recode the data so that “Very Unhappy” becomes 1, “Unhappy” becomes 2 etc. Fortunately, SOFA has a GUI for recoding values. See Recoding data for details. Analysis There will be many ways to report and analyse your data. The example below is a simple Frequency Table. Note how the labels have been applied to the recoded numbers. Making Report Tables Making a Simple Crosstab Table On the main SOFA form, click on “Report Tables”. Let’s start with a simple report table of Age Group vs Country. NB all of this data is fictitious and designed to allow features of the program to be demonstrated. 1. For “Table Type” select “Crosstabs”. A cross tabulation shows one or more variables against one or more other variables e.g. Age Group in the rows and Country in the columns. 2. We need to add a row so click on “Add” under the “Rows” label 3. Select “Age Group” and either double click it or select “OK”. Under the “Columns” label click on “Add” and add Country. In the demonstration pane below you will see a rough illustration of what the table will look like. If you want to see the actual table, click on “Run”. If “Add to report” is ticked, the output will also be saved to the end of the output file specified at the bottom of the form. **Extra Configuration of Report Table** Next you may want to configure the rows and/or columns. Let’s add a total column and columns for row and column percentages. 1. Click on “Config” under the “Columns” label 2. Tick “Total” under the “Misc” heading 3. Tick “Column %” and “Row %” under the “measures” heading 4. Click on “OK” to see changes in demonstration table. NB to see actual results, click on “Run”. If you click “Run” with “Add to report” ticked, you can view the result by clicking on the “View” button. This will open your default web browser so you can see the output. The styling of your table can also be changed - here are some examples of different report tables: Making a Row Stats Table Instead of frequencies and percentages, Row Summaries Tables have means, medians, standard deviations etc. Select “Row Stats” as the report Table Type. Under the “Rows” label, click on the “Add” button. The “Variables” dialog will display all numeric variables. Choose one or more. Click on “OK” button. Under the “Rows” label click on the “Config” button. Select the measures you wish to report on. Mean is preselected by default. Click “OK”. Optionally, you can add a column variable e.g. “Age Group”. Column variables for “Row Stats” report tables can have totals. NB Click on the “Run” button to produce the output. Also note that all the data in the “demo_tbl” is fictitious. Making a Data List Table Sometimes you just want to display some data, possibly with a totals row and perhaps with the first column as a label column. 1. Start by selecting “Data List” as the report Table Type. 2. Optionally select “Totals Row?” and “First col as label?”. NB Totals are only kept for numeric columns. 3. Click on the “Add” button under the “Columns” label. 4. Select one or more variables to display. They will display in the order added. Additional variables can be added by clicking on the “Add” button again. To get the desired order it may be necessary to use the “Add” button multiple times. 5. Click on the “OK” button. A video is available showing how to make report tables: Making report tables video [http://www.sofastatistics.com/videos.php#report_tables] Wiki help/report_tables.txt · Last modified: 2011/01/11 03:38 by admin Except where otherwise noted, content on this wiki is licensed under the following license: CC Attribution-Noncommercial-Share Alike 3.0 Unported [http://creativecommons.org/licenses/by-nc-sa/3.0/] Statistical Tests Available in SOFA Statistics ![SOFA Statistics Test Selection](image) A video is available showing how SOFA Statistics can help you select and interpret the appropriate statistical test: [Statistical test selection video](http://www.sofastatistics.com/videos.php#stats_help) - ANOVA (Analysis of Variance) - Chi Square Test - Correlation - Pearson’s R - Correlation - Spearman’s R - Kruskal-Wallis H - Mann-Whitney U - Independent t-test - Paired t-test - Wilcoxon Signed Ranks Overview SOFA Statistics support making a range of different charts: - simple bar charts - clustered bar charts - pie charts - line charts - area charts - histograms - scatter plots - box plots To make a chart, select the chart type, make any settings specific to that type of chart, and click on the “Show Results” button. Area charts - wide if needed Area charts can display as wide as necessary to show the data. Histograms and human-friendly bin ranges SOFA Statistics endeavours as much as possible to use human-friendly bins e.g. 10 - <20 rather than 9.86-19.54. **Histograms and human-friendly bin ranges** When it is not practical to show every point, SOFA Statistics shows the scatter plot as a single, non-interactive image: **Scatter plots and number of data points** Unless the number of data points is too high, SOFA shows each item in a scatter plot as a dynamic item you can interact with: Usually, SOFA displays dot borders to make it easier to see the data but sometimes they simply get in the way. Fortunately, it is possible to turn them off if required. - **Dot borders?** Chart series SOFA lets you produce charts in series e.g. bar charts by a second variable e.g. gender A video is available showing how to make charts: Making charts video [http://www.sofastatistics.com/videos.php#charts] Filtering Data Sometimes you want to conduct analyses on a subset of your data e.g. on males only. In SOFA you can apply temporary filters to your data. Remember: Filters will remain in place until you close SOFA or deliberately remove them. 1. Select the table you want to filter 2. Click on the “Filter” button (or right click on the table) and enter details into the Apply Filter dialog. 3. Once you have applied your filter, the table name will appear with "(filtered)" at the end until the filter is removed (or SOFA is closed). 4. Output will show the filter which has been applied. - You can also modify your filter and apply much more flexible constraints. And if your filter is faulty, helpful examples are provided which are appropriate to the type of database you are connecting to (SQLite, MySQL etc). A video is available showing how to filter your data: Filtering data video [http://www.sofastatistics.com/videos.php#filtering] Wiki Except where otherwise noted, content on this wiki is licensed under the following license: CC Attribution-Noncommercial-Share Alike 3.0 Unported [http://creativecommons.org/licenses/by-nc-sa/3.0/] Recoding Data Introduction Sometimes you need to change your data before you can analyse it. For example, you might have a field called age but you want to look at the percentages in different age groups. You might want 0-19 in one group, 20-29 in another, 30-39 in another, 40-64 in another, and finally 65+ in another. How do you get from data like this: <table> <thead> <tr> <th>Sofa_Id</th> <th>Age</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>1.0</td> </tr> <tr> <td>2</td> <td>54.0</td> </tr> <tr> <td>3</td> <td>67.0</td> </tr> <tr> <td>4</td> <td>43.0</td> </tr> <tr> <td>5</td> <td>99.0</td> </tr> <tr> <td>6</td> <td>12.0</td> </tr> <tr> <td>7</td> <td>23.0</td> </tr> <tr> <td>8</td> <td>56.0</td> </tr> </tbody> </table> To a report table like this: <table> <thead> <tr> <th>Age Group</th> <th>Freq</th> <th>Col %</th> </tr> </thead> <tbody> <tr> <td>&lt; 20</td> <td>309</td> <td>20.6%</td> </tr> <tr> <td>20-29</td> <td>189</td> <td>12.6%</td> </tr> <tr> <td>30-39</td> <td>176</td> <td>11.7%</td> </tr> <tr> <td>40-64</td> <td>300</td> <td>20.0%</td> </tr> <tr> <td>65+</td> <td>436</td> <td>29.1%</td> </tr> <tr> <td>TOTAL</td> <td>1500</td> <td>100.0%</td> </tr> </tbody> </table> The easiest way is to use the built-in recoding functionality of SOFA Statistics (see below). This makes it easy, for example, to map ranges of values to single values. If you are wanting to do something more complex, e.g. averaging the values from multiple fields, it is possible to do so using a spreadsheet before importing/reimporting, or SQLite Database Browser. Finally, if the dataset is small, there is the option of manual data entry. Recoding in SOFA 1. Click on the “Enter/Edit Data” button on the main SOFA form. 2. Select a table in the default SOFA database “sofa_db” other than the read-only “demo_tbl” 3. Click on the “Design” button because we are going to alter the design of the table by adding an agegroup field based on the “age” field 4. Click on the “Recode” button 5. Select the variable to recode (in this case, “age”) and enter a new variable name you wish to recode into (in this case, “agegroup”) 6. Fill in the details I. Ranges use the keyword TO e.g. “150 TO 250”. All keywords must be upper case, so “TO” will work but “to” will not. II. “MIN” and “MAX” can be used in ranges e.g. “MIN TO 100”, or “100 TO MAX”. You can even use “MIN TO MAX” if you want to leave out missing values. III. “REMAINING” and “MISSING” are the two remaining keywords you can use e.g. if you want all missing values to become 99 you would have a line with From as “MISSING”, and To as 99. IV. Only one condition is allowed per line. So if you want to recode < =5 and 10+ to 99 you would have one line with “MIN TO 5” as From and 99 as To and another line with “10 TO MAX” as From and 99 as To. Clicking on the “Help” button gives access to built-in and online help. 7. Click on the “Recode” button to modify the table. 8. Please Note - this was a once-off recode - it won't be applied automatically when new rows are added or cells are edited. 9. The table design has been altered. 10. If you open the table, you will see that the data has been altered as well. The labels you added are now part of your project and are automatically applied to fields of that name. 11. Now your data is ready to analyse by age group. More Sophisticated Recoding Sometimes you need to do something involving multiple variables e.g. making a new variable from the average of three other variables. Or you may have some other, more sophisticated data manipulation requirements. The easiest way to do this is in a spreadsheet before importing (or reimporting) the data. Using Spreadsheet Functions Creating a standard function makes this very easy. Using SQLite Database Browser Another option is to manipulate data already inside SOFA. SOFA stores its data in an SQLite database called sofa_db. It will be stored in a folder like “C:\Documents and Settings\username\sofastats\_internal” or “/home/username/sofastats/_internal”. You can alter the data directly using the free and open source program SQLite Database Browser [http://sqlitebrowser.sourceforge.net/] Adding a New Variable The following syntax works in SQLite (common field types are INTEGER, TEXT, and NUMERIC): ALTER TABLE mytable ADD newvar INTEGER Populating a New Variable with Data The following syntax shows how flexible this approach is: UPDATE mytable SET newvar = Total/2 or UPDATE mytable SET newvar = (var1 + var2 + var3)/3 You can also use this approach to alter values in an existing variable. You can also restrict the changes using a WHERE clause e.g. UPDATE mytable SET existingvar = "Invalid data" WHERE var1 > 100 OR var2 > 100 Anything Else You Can Imagine Once you have started using SQL there is very little you cannot do in data manipulation. The SQLite SQL syntax documentation is here: SQL As Understood By SQLite [http://www.sqlite.org/lang.html] Wiki Except where otherwise noted, content on this wiki is licensed under the following license: CC Attribution-Noncommercial-Share Alike 3.0 Unported [http://creativecommons.org/licenses/by-nc-sa/3.0/] Non-Ubuntu/Debian Linux Installation Introduction Deb packages are supplied for download on the main SOFA website. To cater to other flavours of Linux, a tar.gz is also provided. Inside, you will find README.txt and INSTALL.sh. - Step 1 is to use your distro package manager to install all the required support packages e.g. matplotlib (for chart plotting). Details of required packages are in the next subsection. - Step 2 is to run INSTALL.sh as described in README.txt. The process is quite simple and has been achieved in two very different distros. SOFA works on Fedora 14: ![Fedora 14 interface](image1) and openSUSE 11.3: ![openSUSE 11.3 interface](image2) This page is the go-to place for information on how to successfully install SOFA on non-Ubuntu Linux systems. For direct discussion, please post at SOFA Statistics google discussion group [http://groups.google.com/group/sofastatistics]. And if you manage to get SOFA working on other distros please email me (grant@sofastatistics.com) the relevant package details etc and a screen-shot (preferably one which reveals the distro involved). **Packages Required (Dependencies)** **NOTE to self - keep README.txt up-to-date in /home/g/projects/SOFA/debmaker/KEEPME** **UPDATE - now using python-psycopg2 instead of python-pygresql** **UPDATE - now need python-xdg and python-crypto as well** In Ubuntu SOFA now requires: - python (>= 2.6.2) - wx-common (>= 2.8.9.2) - python-wxversion (>= 2.8.9.2) - python-wxgtk2.8 (>= 2.8.9.2) - python-numpy (>= 1:1.2.1) - python-pygresql2 (>= 1.0.1) - python-mysqldb (>= 1.2.2) - python-psycopg2 (>= 2.0) - python-matplotlib (>= 0.98.5.2) - python-webkit (>= 1.0.0) - python-xdg (>= 0.15) - python-crypto (>= 2.0.1) In Fedora 14 I installed the following successfully for older versions of SOFA -: - Python was already there - wxPython-2.8.11… and that brought with it some other packages needed. - numpy-1.1.4.1… - python-sqlite2-1:2.3.5… - MySQL-python-1.2.3… - PyGreSQL-3.8.1… (presumably needs to change to python-psycopg2 or openSUSE equivalent) - python-xdg-0.15… (or a higher number e.g. 0.19 - not actually included in my tests but needed from SOFA 1.1.5 onwards) - python-matplotlib-1.0.0… - for more recent versions of fedora you will need to separately install python-matplotlib-wx (otherwise you get a message about "No module named backend_wxagg") - not sure what I did about python-webkit - wasn't requiring python-crypto when I tested this so you'll need to figure this bit out. A friend using Fedora 17 needed - python-crypto - pywebkitgtk - python-matplotlib-wx In openSUSE 11.3 I installed the following successfully AFTER I had added the community devel:languages:python and education repositories: - python-wxGTK 2.8.10.1… - python-numpy (NB to upgrade the existing version 1.3… to the later education repo version 1.5… - see Python matplolib on openSUSE [http://forums.opensuse.org/english/dev/programming-scripting/416182-python-matplotlib.html#post2229592]) - python-mysql 1.2.2-90.1 - PyGreSQL 3.8.1… (presumably needs to change to python-psycopg2 or openSUSE equivalent) - python-matplotlib 1.0.0… - python-xdg-0.19… (or a higher number - not actually included in my tests but needed from SOFA 1.1.5 onwards) - python-sqlite2 2.6.0… - python-webkit (upgraded) - python-webkitgtk 1.1.8… (to avoid error about backend_wxagg module being missing) - wasn't requiring python-crypto when I tested this so you'll need to figure this bit out. I expect in other major distros there is a similar process of finding packages that seem right, trying, and adding more if necessary. It certainly should be possible to get SOFA working on the major distros. **Running SOFA** Make a launcher with the following details: - Name: SOFA Statistics You can run sofa from the command line with a single command sofastats (assuming you ran INSTALL.sh). If you want to set it up manually, details are in the Appendix: **Installation and Configuration for Specific User** When SOFA is run, it checks to see if the user has a sofastats folder and adds it if they don't e.g. /home/username/Documents/sofastats/sofastats. It also makes a sofastats_recovery folder. If you are able to get SOFA to launch at all, but there is a problem of some sort, look at the output.txt file in your /home/username/Documents/sofastats/_internal folder. It may be, for example, that you forgot to install matplotlib. **Appendix** **Simple Launch from Command Line** Make a text file called runsofastats.sh with the following ```bash #!/bin/bash python /usr/local/share/sofastats/start.py ``` And save it e.g. to your home folder. If bash is not located in /bin/bash on your system, use the command ```bash which bash ``` to find it. Then make a symlink to it located in /usr/local/bin (NB give everyone rights to run it) ```bash su root ln -s /home/username/runsofastats.sh /usr/local/bin/sofastats chmod a+x /usr/local/bin/sofastats ``` Now you can run SOFA Statistics from the command line by typing in ``` sofastats ``` See Linux by example - how to create symlink? [http://linux.byexamples.com/archives/19/how-to-create-symlink/] **File Locations** Here is where things should go during installation (in Ubuntu it is /usr/share/pyshared/sofastats): ``` /usr/local/share/sofastats /usr/local/share/sofastats/boomslang /usr/local/share/sofastats/css /usr/local/share/sofastats/db_plugins /usr/local/share/sofastats/googleapi /usr/local/share/sofastats/googleapi/atom /usr/local/share/sofastats/googleapi/gdata /usr/local/share/sofastats/googleapi/gdata/docs /usr/local/share/sofastats/googleapi/gdata/oauth /usr/local/share/sofastats/googleapi/gdata/spreadsheet /usr/local/share/sofastats/googleapi/gdata/tlsinfo /usr/local/share/sofastats/googleapi/gdata/tlsinfo/integration /usr/local/share/sofastats/googleapi/gdata/tlsinfo/utils /usr/local/share/sofastats/images /usr/local/share/sofastats/_internal /usr/local/share/sofastats/locale /usr/local/share/sofastats/locale/gl_ES /usr/local/share/sofastats/locale/gl_ES/LC_MESSAGES /usr/local/share/sofastats/projs /usr/local/share/sofastats/reports /usr/local/share/sofastats/reports/sofa_report Extras /usr/local/share/sofastats/scripts /usr/local/share/sofastats/vdts/ /usr/local/share/sofastats/xlrd/ ``` In the following example, I downloaded the sofa source code into the Downloads folder in Fedora 14. Then extract contents of sofastats_1.1.5.tar.gz into the Downloads folder. The next lot of commands were performed as root (NB the */ after sofa.main) NB nothing will work without the dependencies installed. Running: ```bash su root # Change directory to the downloaded SOFA Stats directory cd Downloads/sofa/sofastats_1.1.5 # Copy the SOFA Stats main directory to /usr/local/share cp -r sofastats /usr/local/share # Copy the SOFA Stats main directory to /usr/local/share cp -r sofa.main/* /usr/local/share/sofastats cp runsofastats.sh /usr/local/share/sofastats # Note: this will not work unless the dependencies are installed. ``` will return a traceback because wxversion or whatever isn't available. So the next step is installing the dependencies. After installing wxPython, but before adding the other dependencies, running sofa prematurely will result in a message about a problem with the first round of local importing. Wiki Exporting Data Future versions of SOFA Statistics should support exporting data directly. In the meanwhile, the following approach works well: 1. Download and install the excellent free and open source SQLite Database Browser application ([http://sqlitebrowser.sourceforge.net/](http://sqlitebrowser.sourceforge.net/)) 2. Use SQLite Database Browser to open the internal SOFA database (e.g. /home/username/sofastats/_internal/sofa_db or C:\Documents and settings\username\sofastats\_internal\sofa_db) 3. Open the export dialog 4. Select the appropriate table and export it
{"Source-Url": "http://www.sofastatistics.com/misc/sofastats_docs%20June%202012.pdf", "len_cl100k_base": 12054, "olmocr-version": "0.1.50", "pdf-total-pages": 56, "total-fallback-pages": 0, "total-input-tokens": 83947, "total-output-tokens": 14225, "length": "2e13", "weborganizer": {"__label__adult": 0.00035262107849121094, "__label__art_design": 0.0009055137634277344, "__label__crime_law": 0.0003979206085205078, "__label__education_jobs": 0.0067291259765625, "__label__entertainment": 0.0002231597900390625, "__label__fashion_beauty": 0.00019502639770507812, "__label__finance_business": 0.001041412353515625, "__label__food_dining": 0.0004105567932128906, "__label__games": 0.0015897750854492188, "__label__hardware": 0.0011911392211914062, "__label__health": 0.00047397613525390625, "__label__history": 0.0005536079406738281, "__label__home_hobbies": 0.00037384033203125, "__label__industrial": 0.0007205009460449219, "__label__literature": 0.000415802001953125, "__label__politics": 0.0004208087921142578, "__label__religion": 0.0004589557647705078, "__label__science_tech": 0.0811767578125, "__label__social_life": 0.0004799365997314453, "__label__software": 0.37548828125, "__label__software_dev": 0.525390625, "__label__sports_fitness": 0.0003867149353027344, "__label__transportation": 0.0003986358642578125, "__label__travel": 0.00028133392333984375}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 47201, 0.02293]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 47201, 0.4263]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 47201, 0.83581]], "google_gemma-3-12b-it_contains_pii": [[0, 771, false], [771, 1542, null], [1542, 2058, null], [2058, 2508, null], [2508, 3372, null], [3372, 3632, null], [3632, 5714, null], [5714, 6411, null], [6411, 8458, null], [8458, 10366, null], [10366, 10981, null], [10981, 11354, null], [11354, 12290, null], [12290, 12563, null], [12563, 13546, null], [13546, 14113, null], [14113, 14909, null], [14909, 15178, null], [15178, 16907, null], [16907, 18318, null], [18318, 19686, null], [19686, 20022, null], [20022, 20671, null], [20671, 21752, null], [21752, 22291, null], [22291, 24409, null], [24409, 25188, null], [25188, 25795, null], [25795, 26531, null], [26531, 26745, null], [26745, 27184, null], [27184, 27887, null], [27887, 27887, null], [27887, 28677, null], [28677, 29392, null], [29392, 29625, null], [29625, 30202, null], [30202, 30847, null], [30847, 31316, null], [31316, 31815, null], [31815, 32278, null], [32278, 32920, null], [32920, 33022, null], [33022, 33197, null], [33197, 33866, null], [33866, 34405, null], [34405, 36001, null], [36001, 37130, null], [37130, 38199, null], [38199, 39244, null], [39244, 40049, null], [40049, 43018, null], [43018, 45776, null], [45776, 46624, null], [46624, 47201, null], [47201, 47201, null]], "google_gemma-3-12b-it_is_public_document": [[0, 771, true], [771, 1542, null], [1542, 2058, null], [2058, 2508, null], [2508, 3372, null], [3372, 3632, null], [3632, 5714, null], [5714, 6411, null], [6411, 8458, null], [8458, 10366, null], [10366, 10981, null], [10981, 11354, null], [11354, 12290, null], [12290, 12563, null], [12563, 13546, null], [13546, 14113, null], [14113, 14909, null], [14909, 15178, null], [15178, 16907, null], [16907, 18318, null], [18318, 19686, null], [19686, 20022, null], [20022, 20671, null], [20671, 21752, null], [21752, 22291, null], [22291, 24409, null], [24409, 25188, null], [25188, 25795, null], [25795, 26531, null], [26531, 26745, null], [26745, 27184, null], [27184, 27887, null], [27887, 27887, null], [27887, 28677, null], [28677, 29392, null], [29392, 29625, null], [29625, 30202, null], [30202, 30847, null], [30847, 31316, null], [31316, 31815, null], [31815, 32278, null], [32278, 32920, null], [32920, 33022, null], [33022, 33197, null], [33197, 33866, null], [33866, 34405, null], [34405, 36001, null], [36001, 37130, null], [37130, 38199, null], [38199, 39244, null], [39244, 40049, null], [40049, 43018, null], [43018, 45776, null], [45776, 46624, null], [46624, 47201, null], [47201, 47201, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, false], [5000, 47201, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 47201, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 47201, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 47201, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 47201, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 47201, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 47201, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 47201, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 47201, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 47201, null]], "pdf_page_numbers": [[0, 771, 1], [771, 1542, 2], [1542, 2058, 3], [2058, 2508, 4], [2508, 3372, 5], [3372, 3632, 6], [3632, 5714, 7], [5714, 6411, 8], [6411, 8458, 9], [8458, 10366, 10], [10366, 10981, 11], [10981, 11354, 12], [11354, 12290, 13], [12290, 12563, 14], [12563, 13546, 15], [13546, 14113, 16], [14113, 14909, 17], [14909, 15178, 18], [15178, 16907, 19], [16907, 18318, 20], [18318, 19686, 21], [19686, 20022, 22], [20022, 20671, 23], [20671, 21752, 24], [21752, 22291, 25], [22291, 24409, 26], [24409, 25188, 27], [25188, 25795, 28], [25795, 26531, 29], [26531, 26745, 30], [26745, 27184, 31], [27184, 27887, 32], [27887, 27887, 33], [27887, 28677, 34], [28677, 29392, 35], [29392, 29625, 36], [29625, 30202, 37], [30202, 30847, 38], [30847, 31316, 39], [31316, 31815, 40], [31815, 32278, 41], [32278, 32920, 42], [32920, 33022, 43], [33022, 33197, 44], [33197, 33866, 45], [33866, 34405, 46], [34405, 36001, 47], [36001, 37130, 48], [37130, 38199, 49], [38199, 39244, 50], [39244, 40049, 51], [40049, 43018, 52], [43018, 45776, 53], [45776, 46624, 54], [46624, 47201, 55], [47201, 47201, 56]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 47201, 0.08544]]}
olmocr_science_pdfs
2024-11-30
2024-11-30
8c331d86451bc5f1334e198dc4d2f3cbec913e94
GenetScope - NetSim 2 Software User’s Manual July 2006 DRAFT Version 1.1 EXECUTIVE SUMMARY The NetSim 2 is an object-oriented discrete-event system modeling and simulation (M&S) environment to support simulation and analysis of voice and data communication scenarios for High Frequency Global Communication Systems (HFGCS). The application runs on Java™-based platforms, including both Windows and Linux and allows a user to model a wide range of HFGCS communications and connectivity operations through its own Graphic User Interfaces (GUI). NetSim 2 has been developed not only to improve the implementation of original Automatic Link Establishment (ALE) protocol in its predecessor, NetSim 1, but to provide the advanced M&S framework, Discrete-Event System Specification (DEVS) for HF network models to be reusable and scaleable systematically by adding more complex functionalities and protocols throughout the future development cycle. The earlier Netsim version (developed in 1997) was used to analyze any given scenario, whether of past or in future based on ICEPAC prediction data. The current version aims to take a quantum leap by providing the capabilities to not only analyze any scenario, but provide recommendation to re-design the SCOPE command itself. The underlying DEVS theoretical framework with its advanced features of real-time simulation visualization and ability to configure simulation on-the-fly gives the analyst the power to understand the impact of any design-parameter and how the system transitions to the new parameter-set in real-time without restarting the simulation. This aids in changing the corresponding parameter in the deployed SCOPE command system as the analyst can study the transition effects. This capability to study transition effects by changing the parameter set in real-simulation-time has been recently developed and is unique to the DEVS framework. DEVS with its power of Experimental Frame helps focus the top-level design issues like how many ground stations are best, how many internal levels are minimally needed, what is the capacity of the system or what is the threshold SNR that the system needs to continue to perform, optimally. This User’s Manual gives the system overview of NetSim 2 environment and documents the steps to setup and run experimentation of HFGCS network models. The example communications scenarios are described for a user to run the system for exercise. JAVA is registered trademark of Sun Microsystems, Inc. in the United States and other countries. DEVJSJAVA, Copyright 2002 Arizona Board of Regents on behalf of The University of Arizona # TABLE OF CONTENTS 1. **OVERVIEW** .................................................................................................................. 8 1.1 PURPOSE .......................................................................................................................... 8 1.2 ARCHITECTURE AND BACKGROUND .......................................................................... 8 1.3 FEATURES ...................................................................................................................... 11 1.4 LIMITATIONS .................................................................................................................. 12 2. **ENVIRONMENT SETUP** .............................................................................................. 13 2.1 Experimental Frame ...................................................................................................... 15 2.2 Defining Fixed Stations .................................................................................................. 20 2.3 Defining Mobiles Station ............................................................................................... 26 2.5 Defining Simulation Time Duration and Propagation model ......................................... 37 2.6 Configuration File ......................................................................................................... 39 2.7 Running Simulation ........................................................................................................ 40 2.8 Logs Analysis Tab .......................................................................................................... 41 2.9 Performance Analysis Tab ............................................................................................. 42 3. **SIMULATION LOGS** .................................................................................................... 43 4. **SCENARIO GENERATION** .......................................................................................... 48 4.1 Example 1 “BaseWithAnt” ............................................................................................. 48 4.2 Example 2 “CONUS with Traffic” ................................................................................ 48 4.3 Example 3 “Global with Traffic” .................................................................................. 49 4.4 Developing Scenario’s ................................................................................................... 49 5. **APPENDIX** .................................................................................................................. 51 5.1 Installation Instructions ................................................................................................. 51 5.2 Directory Structure ....................................................................................................... 51 <table> <thead> <tr> <th>Section</th> <th>Page</th> </tr> </thead> <tbody> <tr> <td>5.3 Bug reports with contact information</td> <td>52</td> </tr> <tr> <td>Credits</td> <td>53</td> </tr> <tr> <td>Copyright Notice</td> <td>53</td> </tr> <tr> <td>License Information</td> <td>53</td> </tr> <tr> <td>Disclaimer</td> <td>53</td> </tr> </tbody> </table> (This page intentionally left blank.) 1. OVERVIEW 1.1 PURPOSE The purpose of NetSim 2 is to provide a user-friendly discrete-event M&S environment for a user to test the performance of the ALE system under various loads and specifications. 1.2 ARCHITECTURE AND BACKGROUND SCOPE Command is a highly automated, high-frequency (HF) communication system that links US Air Force command and control (C2) functions with globally deployed strategic and tactical airborne platforms. SCOPE Command replaces existing USAF high-power HF stations with a communication system featuring operational ease of use, dependability, and seamless end to end connectivity comparable to commercial telephone services. The network consists of 15 worldwide HF stations (Figure 1) interconnected through various military and commercial telecommunications media (Figure 2). It increases overall operational and mission capabilities while reducing operation and maintenance costs. ![Figure 1: Geographic locations of Fixed stations](image) The HF radio equipments include Collin's Spectrum DSP Receiver/Exciter, Model RT-2200. The radios feature Automatic Link Establishment (ALE) and Link Quality Analysis (LQA) capability and are adaptable to future ECCM waveforms FSK, MIL-STD-188-110B and STANAG 5066. The transmit subsystem includes 4-kW solid-state power amplifiers, a high-power transmit matrix, and combination receive/multicoupler antenna matrix. A typical SCOPE Command station includes operator consoles (HFNC), circuit switching equipment (DES, DSN, LCO), HF radios (ALEs), RF matrixes (RTs), and antennas (RXs, TXs). A non-blocking digital electronic switch (DES) connects the station to the local military and/or commercial telecommunication services. The switch features unlimited conferencing, modular sizing, digital switch network, precedence function, and capacity for up to 2016 user lines. Figure 2: Communication flow diagram for SCOPE command SCOPE Command uses a modular, open-system design to automatically manage and control all network operations, including those at split-site stations. To achieve maximum flexibility, the system uses commercially available standards-based software and a multitasking operating system. This approach permits 14 out of 15 network stations to operate "lights out" (unmanned) and to be economically controlled from a central location. The control system also includes LAN software, servers, and routers to support unlimited LAN/WAN. Figure 3: System Entity structure for SCOPE command system showing the fixed and mobile (aircraft) stations The program includes a Systems Integration Lab (SIL) and test-bed facility located in Rockwell Collins' Texas facility. The SIL is used to predict the impact and risk that any changes or upgrades will have on system performance, integrity or costs before actual implementation begins. The SIL includes a fully functional SCOPE Command station for performing baseline design verification, interface compatibility and functional verification tests. Joint Interoperability Test Command (JITC) is the only government agency that is assigned the task to validate and authorize IT systems for military operations. The HF SCOPE command system has also been evaluated by JITC. In collaboration with Dr. Eric Johnson, a simulator was developed in the C language around 1997 that was validated and eventually used by both the government and the industry to conduct experiments and run scenarios. The simulator was an exhaustive and comprehensive effort with respect to the details it implemented and served its purpose well. However, in today's circumstances, the same simulator is obsolete due to the heterogeneous nature of today's network traffic, in which E-mail occupies a considerable percentage of traffic. The simulator is now being upgraded at the ACIMS lab in order to make it more useful for current demands. These demands stem from the possibility of expansion of current infrastructure of SCOPE command. Questions arise such as how many stations need be added to service a required workload. Also needing to be investigated are tradeoffs such as whether it is more economical to add more stations or increase the number of internal radio-levels within stations to meet the anticipated demands. Air-traffic has increased manifold since 1997, along with the computing technology. Consequently, the transition effects need to be monitored more closely and the overall system response time\(^1\) needs to be documented. The significant parameters have to be identified that have the most impact on system performance. To more easily address such questions, an effort is being made to modularize Johnson’s 15K lines of code into component based structure depicted in Figure 3.. Once componentized, the components are made DEVS compliant resulting in a DEVS-based simulation package to support the systems engineering needs of the SCOPE command.\(^2\) As we need to study the effect of changes/upgrades introduced to the existing SCOPE command system, we built the Experimental Frame, based on DEVS principles for our modular DEVS-netsim simulation model, named as GENETSCOPE. Figure 4 shows the block architecture of the simulation model. The right hand box is the system phenomenon that contains the Automatic Link Establishment (ALE), STANAG 5066 protocols used for establishing links and exchanging data messages between mobile stations and fixed stations. The left hand side box is the experimental frame that generates various scenarios and parameters under study. The scenarios and parameters are fed into the model and performance characteristics are obtained from it which are then visualized and analyzed in real-time as per the extended MVC architecture described in Section 5. \(^1\) Response time of a system is defined as the time taken by the system to display significant effect caused by any update in the configuration parameters. \(^2\) A methodology using intermediate XML processing to automate much of the process of 'componentizing' legacy simulation code will be reported soon. SCOPE Architecture implementation using enhanced Mode-View-Controller paradigm The Figure 5 below shows the simulation architecture using the concepts laid out in the paper. With reference to Figure 4, the Ionosphere model used in the architecture is ICEPAC data. It is worth stressing that initial Netsim model written in C language has this database tightly coupled with the model. In our present implementation, we made it modular so that it can be replaced by any other database that could provide the channel propagation values through the ionosphere, for ex. VOACAP. The DEVS Layer comprises both of model as well as the DEVS simulation environment. The Experimental Frame layer contains the controls required to modify/update the model as well as simulator as per enhanced MVC. The simulation visualization is modular in construction and reflects the updates in Experimental Frame layer and the DEVS layer. 1.3 FEATURES The GUI of NetSim 2 is arranged in a tabbed notebook fashion, separating each part of the system into its own page. The major components are Fixed Sites, Mobiles (i.e. aircraft), Frequencies that will be used for communication, and simulation parameters. A fifth page provides a list of worldwide locations, which can be selected as needed for placement of fixed communication sites or points as part of aircraft flight paths. This version GenetScope 1.1 contains the Antenna configurations as shown below <table> <thead> <tr> <th>Antenna Number</th> <th>Antenna Type</th> <th>GUI sign</th> <th>TX</th> <th>RX</th> <th>Filename</th> <th>Comment</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>LTO</td> <td>LTO</td> <td>X</td> <td>X</td> <td>Samples\sample32</td> <td>Fixed station antenna</td> </tr> <tr> <td>2</td> <td>HTO</td> <td>HTO</td> <td>X</td> <td>X</td> <td>Samples\sample09</td> <td>Fixed station antenna</td> </tr> <tr> <td>3</td> <td>RLP</td> <td>RLP</td> <td>X</td> <td>X</td> <td>Samples\sample05</td> <td>Fixed station antenna</td> </tr> <tr> <td>4</td> <td>Rosette</td> <td>ROS</td> <td>X</td> <td>X</td> <td>Samples\sample32 (1)</td> <td>Fixed station antenna</td> </tr> <tr> <td>5</td> <td>Dipole</td> <td>DIP</td> <td>X</td> <td>X</td> <td>Samples\sample23</td> <td>Mobile</td> </tr> <tr> <td>6</td> <td>Vertical Monopole</td> <td>VTM</td> <td>X</td> <td>X</td> <td>Samples\sample10</td> <td>Mobile</td> </tr> <tr> <td>7</td> <td>Whip</td> <td>WHP</td> <td>X</td> <td>X</td> <td>DEFAULT\SWWHIP.VOA</td> <td>Mobile</td> </tr> <tr> <td>8</td> <td>Probe</td> <td>PRB</td> <td>X</td> <td>X</td> <td>DEFAULT\SWWHIP.VOA(2)</td> <td>Mobile (aircraft)</td> </tr> <tr> <td>9</td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> </tr> <tr> <td>10</td> <td>Other</td> <td></td> <td>X</td> <td>X</td> <td></td> <td>User input</td> </tr> </tbody> </table> Notes (1) Use LTO antenna until a better antenna can be found. (2) Use Whip Antenna until a better antenna can be found. Fixed station antennas should be selectable by any system. Fixed stations should offer antennas 1-4 and 10 as selections. 1.4 LIMITATIONS The NetSim 2 environment requires PC with a Pentium 4 or greater processor, with at least 512 MB RAM. Recommended RAM is about 1GB. Depending on the details required in log-files (especially EventLog), the minimum hard-disk capacity required for an individual simulation run is between the ranges 20-1000MB. GenetScope model limitations: 1. The current model developed in Phase I of the project is bounded by the functionality in the older Netsim version designed by Dr. Johnson in C++. It has been translated and developed using the DEVS theory and implemented in Java. No new ALE functionality has been added in the current version. 2. All the stations in any scenario work on default AFALE scanlist. However, provisions to program different scanlist have been added into the configuration GUI. The associated functionality will be implemented in the next version-build of GenetScope, possibly in Phase II of the project. 3. The model is in developmental Beta stage and validation of simulation results with real-time JITC data is undergoing. Error reporting is highly recommended. 4. No terrestrial networks have been introduced in the current version. They are left for Phase III of the project. 2. ENVIRONMENT SETUP About Clicking the About button will present the related information, version and involved personnel associated with this project. Help Clicking the Help button will open the pdf version of this document Manual in Internet Explorer window. Start Page Start Page contains Hi Frequency Global Communication Systems (HFGCS) logo, a label that says “Developed by Arizona Center for Integrative Modeling and Simulation”, and a button named “start”. Push the “start” button to continue the environment setup or another tab named “Experimental Frame” is shown. Click the “Experimental Frame” tab. ![Figure 6: GenetScope Logo and starting the session](image-url) 2.1 Experimental Frame The Experimental Frame panel provides the facility to create a new configuration file or load an existing configuration file that is stored in the repository with its timestamp. The configuration files have the extension of .cfg and the filename contains the timestamp of its creation time. More details about the configuration file naming and storing conventions can be seen in sections ahead. The left section (as shown in figure below) provides four functionalities: 1. Create a new configuration file 2. Simulate an already saved configuration directly, without any modification to the configuration file 3. Load an existing configuration file stored in repository as shown in the list (in figure) 4. View Existing Logs for any configuration, if the configuration has been simulated earlier. 5. Refresh the repository to show the recent additions in the repository during the current session. In order to execute the functionalities above kindly follow the steps below: Create a new configuration file 1. Click the button "Make New Configuration" as shown in figure. This will prepare the right section of the pane and load the default experimental frame parameter settings. It will also make the button “Configure Experiment” in the right bottommost (scroll down to see the button). This button will be disabled otherwise. 2. Set the parameters as per scenario requirements. As described in the architecture section the Experimental frame gives the user to set the general design parameters guiding any scenario. The user can specify top-level design parameters like: a. Level in a fixed station b. No. of fixed stations c. No. of mobile stations d. No. of messages transmitted per hour e. Duration of voice calls f. Sounding interval g. SNR threshold ![Figure 9: Basic operations related to saved Configuration files](image) **Figure 9:** Basic operations related to saved Configuration files Figure 10: Some parameters considered for Experimental Frame These values percolate to the individual fixed and mobile station configurations and the rest of the scenario is bounded by these top-level design requirements. Further, the default values are set as per the following: - Level in Fixed Station: 1 - Fixed Station: 14 - Mobile Station: 10 - Msg/Hr: 2 - Data Msg: 10 KB - Voice Duration: 60 sec - Ground Station Sound Interval: 90 mins - Aircraft Sound Interval: 90 min - SNR Threshold: -6 dB Once the values are set, push the “Configure Experiment” to store the values. Figure 11: Enabled ‘Configure Experiment’ Button and appearance of ‘System Configuration’ tab at the top This will result in appearance of a new tab named ‘System Configuration’. The new tab will allow the detailed configuration of the complete scenario. Simulating a saved configuration file 1. Scroll down the repository list in the left section. Select the configuration file to simulate. 2. Click on the ‘Simulate Configuration’ button. 3. This will bring up the Run/Simulate tab at the top. 4. Click on the new appeared tab and proceed towards running the simulation. Figure 12: Appearance of ‘Run/Simulate’ tab Load an existing configuration file 1. Scroll down the repository list in the left section. Select the configuration file to load or update. 2. Click on the "Load/Update" button in the left section of the pane 3. The right section will reflect the stored values in the configuration file. The "Configure Experiment" button will also get enabled at this point. 4. Press "Configure Experiment" to move to System configuration tab as described above. The System Configuration will load the existing information contained in the selected file. If you need to update the values for the experimental frame, it should be done before clicking this button. Refreshing Repository to show stored configuration files 1. Click on the button "Refresh Repository" to view the updated repository if you have saved/created any new configuration files in the current session. 2. The list above will reflect the current status of repository. 2.2 Defining Fixed Stations The main page of System configuration begins with a “Fixed Station” tab. The tab consists of four parts such as the list of stations, station info panel, station info tabbed pane, and modification of stations data. Before starting this panel, the data structure of stations should be created and the values should be set. 1. The list of stations The number of fixed stations is obtained from the previous step. Default number of “fixed station” is 14. The stations with “Checked” checkboxes are active in the simulation while “Unchecked” stations are inactive. User can check or uncheck the fixed stations. Figure 14: Snapshot of Fixed Station configuration Pane showing various sub-panels 2. Station info panel This panel displays station call, ALE Activity, Latitude, Longitude, Location, and lookup. Station call is entered by a user. If any station on the list of stations is checked or unchecked, the station call of the station is displayed on the text field. ALE Activity is a combo box that contains the two values, i.e., “Active” or “Passive”. Latitude, Longitude, and Location can be typed by a user. The “Lookup” button sets all the fields of station info panel and station info tabbed pane with all station information regarding the station call. In order to view the information and configuration of any fixed station, enter the three alphabet call-sing of the fixed station in ‘Station Call’ text field and press Lookup button. This will show the details related to that particular station. All the tabs in the ‘Station Info tabbed pane’ will reflect the information associated with that station. Figure 15: Showing the related info about a fixed station when Lookup is pressed 3. Modify stations data If some changes are to be made by a user, the station data can be updated by clicking the “update” button. The user can delete any station using a “delete” button. Users can make stations and save information of stations using a “add” button. 4. Station info tabbed pane This pane is composed of five tabs named “Message Traffic”, “Ale Levels”, “Ale Parameters”, “Scan List”, and “Gnd InfraStructure” - **Message Traffic**: This tab allows for setting up the traffic stream parameters originating from this fixed station. It will take the default values as set under the Experimental Frame section but user can override the internal details of the traffic stream. Each row is a single traffic stream. The user can program more than one traffic streams origination from the station. The details of any single traffic stream can be programmed as under: - **Use**: the first row is checked by default reflecting atleast one traffic stream. You can program different traffic streams and uncheck the box for updating any existing configuration file. - **Msg Size**: The value in the experiment frame is internally set up. If you want to change, put any value in the text box. The value entered is either seconds or bytes depending on the value of traffic type under “Type” column. Voice traffic is taken in seconds and Data traffic in bytes. - **Msgs/hr:** The value in the experiment frame is internally set up. If you want to change, put any value in the text box. Type: Voice or Data. With Voice as traffic type, it implies 2 calls per hour (as shown in figure below) and with Data it reflects number of data messages sent per hour. - **Type:** The default value is shown as programmed in the Experimental Frame section. The user can change this value on per station basis. - **Precedence:** The user can select any of the five priority levels on per station basis. The available priorities are Flash Over, Flash, Immediate, Priority and Routine. The default value is Flash Over. - **Start at (min):** The user can specify when this particular traffic stream will become operational from the start of simulation time. This feature is currently NOT implemented in Version 1.0. ![Figure 16: Pane showing various parameters needed for a traffic stream](image) - **Ale Levels:** This tab will allow for configuring the ALE levels in the chosen fixed station. The value is bounded by the Experimental frame. The user is allowed to specify the details of each individual level in this pane. It also provides information about the antennas used at each individual level. The antenna parameters are defaulted in this version of Netsim-2. Following are the parameters considered: - Number of ALE Radio Sets : the total number of levels(maximum 16 levels) - Power (Watts) : antenna power - Antenna Type - Antenna Pointing Angle(degrees) - Mission - Priority - Angle(degrees) - Gain(db) The columns empty below are intended for future version of the Netsim-2 except the Antenna Type columns. The current version does support antenna configurations and its effects on SNR. Various antenna types can be described as follows. If no selection is made LTO is default in Fixed stations and Whip is default in mobile stations. <table> <thead> <tr> <th>Antenna Number</th> <th>Antenna Type</th> <th>GUI sign</th> <th>TX</th> <th>RX</th> <th>Comment (3)</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>LTO</td> <td>LTO</td> <td>X</td> <td>X</td> <td>Fixed station antenna</td> </tr> <tr> <td>2</td> <td>HTO</td> <td>HTO</td> <td>X</td> <td>X</td> <td>Fixed station antenna</td> </tr> <tr> <td>3</td> <td>RLP</td> <td>RLP</td> <td>X</td> <td>X</td> <td>Fixed station antenna</td> </tr> <tr> <td>4</td> <td>Rosette</td> <td>ROS</td> <td>X</td> <td>X</td> <td>Fixed station antenna</td> </tr> <tr> <td>5</td> <td>Dipole</td> <td>DIP</td> <td>X</td> <td>X</td> <td>Mobile</td> </tr> <tr> <td>6</td> <td>Vertical Monopole</td> <td>VTM</td> <td>X</td> <td>X</td> <td>Mobile</td> </tr> <tr> <td>7</td> <td>Whip</td> <td>WHP</td> <td>X</td> <td>X</td> <td>Mobile</td> </tr> <tr> <td>8</td> <td>Probe</td> <td>PRB</td> <td>X</td> <td>X</td> <td>Mobile (aircraft)</td> </tr> <tr> <td>9</td> <td></td> <td></td> <td></td> <td></td> <td></td> </tr> <tr> <td>10</td> <td>Other</td> <td></td> <td>X</td> <td>X</td> <td></td> </tr> </tbody> </table> Figure 17: Pane showing individual details of every level in the Fixed station - **Ale Parameters**: These are the default ALE parameters that are being used for ALE protocol. The user is not recommended to change these parameters unless the scenario demands studies related to ALE protocol itself. For convenience purposes, these values can NOT be changed in the current version. The only programmable value here is Sounding Interval, which is specified in the Experimental Frame and is reflected here. **Figure 18:** figure showing default ALE protocol parameters - **Scan List:** This tab provides the user to select any available Scan list. A Scan list is defined as a set of frequencies being used by that particular station to communicate with other stations. The defaulted choice is AFALE Scan list. There are four Scan list supported by Netsim-2. Each Scan list has unique channel list independent of other types and each channel internally translates to a single frequency. If one of the radio boxes is clicked, then text area displays the channel list of the radio box. ALE Freq table shows the channel, frequencies of each channel, and check boxes that mean if checked, the channel in the first row is used and if not, the channel is available. The channel used by a type can not be selected by other types. **Figure 19:** Figure showing scanlist operations at the station. - **Gnd Infrastructure:** This panel is left for further development in the near future. 2.3 Defining Mobiles Station The second tab in the System Configuration section allows for detailed configuration of mobile stations or aircrafts carrying ALE radio sets. The main screen for Mobile stations shows various types of aircrafts that can participate in any particular scenario. The user can select different types of aircrafts for the current scenario. However, the total number of aircrafts added is bounded by the number of mobiles specified in the Experimental Frame section. In the event of mismatching the user is presented with warning messages as shown in figures below. ![Figure 21: Warning message if mobile station count selected does not equal that of Experimental Frame count](image) The user is recommended to verify the count from the Experimental Frame mobile station count and select that many stations from the Mobiles tab. The total mobile station configuration is executed in three steps as described below: Step 1: Mobiles 1. Choose “Mobiles” tab to open Mobiles station setting 2. Choose the combo box which is next to the name of aircraft, and then select the number of aircraft. 3. After you have finished the selection, push the button “Enter Details”. In order to aid the user to verify if he has selected the correct number of mobile planes, the pane above shows both the Experimental Frame value and the number that the user has selected in above combo boxes. The user can go to the next process only when these two numbers exactly match. One word of caution in the current version is that the user has to look into the flight details more closely, if he is updating an already saved configuration file. There exists no problem if the user is increasing the mobile station count, but if he chooses to diminish the mobile station count, he is recommended to verify the flight details and update too as a part of configuration process. The ability to delete any selected mobile station from an existing configuration file will be added in the next Build. **Figure 22:** Main Mobile Station selection pane Step 2: Aircraft Details 1. The selected Aircraft is “C5”, and the number of “C5” is “one” 2. The selected Aircraft is “C130”, and the number of “C130” is “two” 3. If all the numbers of aircraft has been selected, n push “Enter Details” This step allows for specification of call signs to the types of aircrafts chosen in the previous step. The mobile stations are identified by these call signs for all the configuration and simulation from this step onwards. **Sequence: Mobile > Aircraft Details > Flight Detail** 1. The values of “Call Sign”, “Start Time”, and “Flight Details” need to be filled in for the selected aircraft type. Ex) Call Sign: Enter any name for the mobile station identification. Ex) Sam, Steve, Bon Start Time: Enter the take off time. Ex: 120 (minutes after the simulation start time). 2. Click the “Flight Detail” button to fill out the details of the selected aircraft. 3. The “Flight Detail” dialog with the Call Sign name is popped up. **Figure 23:** Pane showing the call-sign and start up details of the chosen flight planes **Step 3: Flight Details** Clicking on Flight Details tab will pop up a new dialog box that aids in configuration specifics about this particular mobile station. The user can provide details about the message traffic originating from it, its flight path, ALE radio parameters, the address list that is the prioritized in order of calling to fixed stations, and frequency lists. Showing following is the sequence in which they are configured. **Sequence: Message Traffic > Flight Path > ALE > Address List > Scan List** The five tabs are shown to be set up for the flight details. Each tab is described in the following steps. 1. **Flight Path** This tab provides the functionality to program the flight path of any particular mobile station. The user is required to double-click in the Locations column. ![Figure 24: Pane showing the Flight Path planning configuration](image) This will enable the text area in that cell. Kindly enter one or two words descriptive of the location serving as waypoint (shown in the left figure below). Press tab-key or Enter to search with this location name and press Lookup Location button. Pressing the lookup button will popup the locations that contain that particular word. In the right figure below, all the location containing the word “Dover” (from the left figure) are listed (as they exist in the locations database). Select the exact location and press Ok. ![Figure 25: Put any keyword related to the desired waypoint and press either Tab or Enter](image) ![Figure 26: Pressing Lookup shows all places containing the keyword in left figure](image) Pressing OK will populate the Latitude and Longitude for the entered Destination waypoint. In order to add a location that fails to lookup, you need to add it thru the 'Location' tab under System Configuration settings tab. Figure 27: Loaded waypoint with Latitude Longitude information from the database Brief overviews of other values associated with this tab are as follows: A. Lat/Long: pre-defined (not-editable) B. Location: pre-defined (not-editable). It is editable only for Lookup purposes as described above. C. Speed: The speed for the mobile aircraft is in nautical miles/hour i. Put Speed in the upper row. ex. 450 ii. Set up ALE mode in the lower row. Except Silent D. ALE Mode: Four modes are available for the aircraft at arrival of this waypoint location. i. Off (O): Turns the ALE radio off. (No traffic, no sounding, no listening) ii. Silent (S): Turns ON the ALE radio (No traffic, no sounding) iii. No Traffic (N): Turns off the traffic (No traffic) iv. Active (A): Fully operational (Sounding, Listening, sending Traffic) NOTE: Be cautious about the sequencing of ALE modes while planning the Flight-path. All the mobile planes start as Silent (S) as default, on which the user has no control over. In the above example, the sequence is: SAAAS. If the user plans to use O in the sequence, S must follow O i.e. OS is an orderly pair. The aircraft must first appear on the scene as Silent and then change its mode to Active or No Traffic or stay as Silent. If user wishes to begin the Flight-path by switching the radio silent and turning it ON after certain waypoints then the sequence formed is SOSAS or SOOSANS etc. E. Duration (hr): This represents the time at which the aircraft arrives at this waypoint and changes its ALE mode. For example, in the example above, the aircraft at 0.15 hr from the simulation start time arrives at Waypoint Dover DE and become ‘Active’. Similarly, the aircraft reaches second waypoint Falmouth ME after 2 hours of previous waypoint and remains ‘Active’. 2. Mobile Message Traffic This section tab defines the traffic streams originating from this mobile station. The description is same as fixed station Message Traffic tab described in earlier sections. For ease, the configuration procedure in delineated again. • Use: the first row is checked by default reflecting atleast one traffic stream. You can program different traffic streams and uncheck the box for updating any existing configuration file. • Msg Size: The value in the experiment frame is internally set up. If you want to change, put any value in the text box. The value entered is either seconds or bytes depending on the value of traffic type under “Type” column. Voice traffic is taken in seconds and Data traffic in bytes. • Msgs/hr: The value in the experiment frame is internally set up. If you want to change, put any value in the text box. Type: Voice or Data. With Voice as traffic type, it implies 2 calls per hour (as shown in figure below) and with Data it reflects number of data messages sent per hour. • Type: The default value is shown as programmed in the Experimental Frame section. The user can change this value on per station basis. • Precedence: The user can select any of the five priority levels on per station basis. The available priorities are Flash Over, Flash, Immediate, Priority and Routine. The default value is Flash Over. • Start at (min): The user can specify when this particular traffic stream will become operational from the start of simulation time. This feature is currently NOT implemented in Version 1.0. Figure 28: Pane showing the originating Traffic streams from mobile station with call sign Sam 3. Mobile Levels The user can specify the antenna that is onboard the mobile aircraft. If no option is selected Whip antenna is selected by default. 4. ALE The value set up in the Experimental Frame is reflected in the “Sounding interval” field in the panel. Others are not required to be set up in the current version. 5. **Address List** This tab provides the user to configure the priorities of fixed stations when the mobile station wishes to make a call to ‘ground station’. It is defaulted to the number of fixed stations (selected during Experimental Frame configuration) aligned in random order of priority. The user can change this list as per scenario requirement. Each of the row below is drop down combo box each having all 14 stations. The defaulted value is 14 stations, hence 14 rows. 6. **Scan List** The Scan list tab is identical to the tab mentioned earlier in Fixed station configuration section. It is defaulted to AFALE scanlist. Kindly refer to that section for more information about operation. Figure 31: Pane showing various parts associated with configuration of the Scanlist When all the individual tabs have been programmed press OK button on the right bottom to load the information into the data structures. This will close this frame and the control will return back to the Aircraft Details tab. When all the aircraft details have been populated press Done button to save the information towards writing into the configuration file. Pressing Done button will close the Aircraft details tab and the mobile station configurations are complete. Figure 32: Press Done when all the details have been entered thru Flight Detail Panes 2.4 Defining Channels and Locations Frequency/Channel database The frequencies available in the system are shown. User can choose the Scan list in the Comments combo box. There are currently 100 channels defined that correspond to 100 frequencies. Various other constraints like power on which they operate, restricted access and their categorization are also provided here. This is the master channel table and each channel is configured to lie in at most one scanlist. The mapping is provided in Comments section where the user can specify whether the channel belongs to either of the following: 1. NIPRNET 2. SIPRNET 3. CAPNET 4. Published 5. Discrete 6. Not in use Figure 33: Master Channel-Frequency table and their classification in various Scanlists Locations This top-level tab shows the location database used by the model. The geographical locations specified here can be used to program the flight path of any mobile station. The user can add, delete any location and it is saved in the local database for future use. A location once deleted cannot be retrieved back; the location data is shown in the table. The basic operations on the list are performed as under: A. Add i. Click the lower row you want to add. ii. Push Add button. iii. Once the empty row will be shown, put the value in the each box. B. Delete i. Select the row you want to delete ii. Push Delete button C. Save Once you edited all value, push the Save button. (It will take for a while) Figure 34: Pane showing the complete Location database with functionality of adding/removing/updating any location 2.5 Defining Simulation Time Duration and Propagation model Once the Fixed stations, Mobile stations, master Channel list, Locations database are set, the scenario generation is almost complete. The only thing remaining now is to specify the time and duration of simulation. This can be specified from the ‘Setup’ tab shown below. The simulation start time is specified in 24 hour notation. The duration is determined by specifying the End time of the simulation in 24 hour notation. The GUI identifies the operational Sun Spot Number (SSN) based on the year-month-day. The identified SSN is then used to gather ionospheric propagation data. The user can either choose ICEPAC or VOACAP. In case of no selection, ICEPAC is chosen as default. The analyst can enter any descriptive text concerning this simulation configuration. ![Simulation setup tab for the scenario loaded/configured](image) **Figure 35:** Simulation setup tab for the scenario loaded/configured Once the time-date are configured, pressing the 'Write files' button will result in a configuration file in .cfg format saved in hard-disk (opened thru Wordpad application). In addition to writing up the configuration file, the configuration is also loaded to the simulation model to enable the simulation with current configured scenario. Information will pop up displaying that the configuration is now complete, validated according to the Experimental Frame settings and stored at what particular location. **Figure 36:** Error messages if the user enters a month or year not supported by the Model **Figure 37:** Confirmation message notifying that configuration is complete, stored and ready to be simulated Clicking on the Write Files button will add the Run/Simulate tab at the top level indicated in the figure below. At this juncture, the scenario is completely configured, saved in a dedicated folder for this simulation run and ready for simulation. 2.6 Configuration File The process described in previous section results in saving a configuration file identified by its timestamp as suffix and is saved in the application’s ‘Configuration’ folder. The file’s name is automatically configured based on the timestamp, e.g., config4.4.12.21.05.cfg where the numbers translate to 4:04am on 12/21/05. The sample shown below consists of 2 Fixed stations and 1 mobile station. Others description details are not required as per the current document. ``` F 1 6 1 2 60 V 90 60 -20 S 16:00:00 1:00:00 3 33 V # @ Enter descriptive text to provide information about the scenario # with SSN = 33 # # F MCC 38.650 -121.383 -114 A WestCoast ALE 1 RT 1 PA 1 ANT 1 ASP VTM Bcast C 2 4 8 10 11 14 17 19 AFALE C 3 6 9 12 16 21 22 NIPRNET C 1 5 7 13 15 18 20 SIPRNET C 90 91 92 93 94 95 96 97 CAPNET #D F HIK 21.317 -157.867 -114 A Hickam ALE 1 RT 1 PA 1 ANT 1 ASP ROS Bcast C 2 4 8 10 11 14 17 19 AFALE C 3 6 9 12 16 21 22 NIPRNET C 1 5 7 13 15 18 20 SIPRNET C 90 91 92 93 94 95 96 97 CAPNET #D F OFF 41.267 -95.950 -114 A Offutt ALE 1 RT 1 PA 1 ANT 1 ASP LTO ``` 2.7 Running Simulation Run/Simulate This tab provides four functionalities 1. **Run Abstract Model**: This model is a high level abstract representation of the model and useful for quick estimation. This is not operational in the current version. 2. **Run Detailed Model/Resume Simulation**: The second button simulates the configured detailed model. Pressing the button once will start the simulation and change the button to inactive state. It will also enable the third button (Pause). 3. **Pause**: This button interrupts the simulation in between. Pressing this button once will render it inactive and activates the second and fourth button. The second button shows ‘Resume Simulation’ which on clicking resumes the simulation from that point onwards or the user can press Terminate button. 4. **Terminate**: This button is only activated once Pause is pressed. This protects the simulation engine from crashing when heavy processing is underway. Pressing this button will remove the Run/Simulate tab from the application and the gathered simulation results are stored in the Logs directory. This button also terminates the current session and the user is led back to the Experimental Frame where he can start fresh with second simulation session that can involve creation of new configuration file, running an old configuration file or reloading a saved configuration file. The Run/Simulate tab can be re-established for a different configuration scenario once a running simulation is terminated. Various fields and information on the simulation pane is self-explanatory. Figure 38: Real-time Simulation Visualization Pane 2.8 Logs Analysis Tab This particular tab gets activated and shown when the user ‘terminates’ the simulation. Various logs are displayed. More details are provide in Section 3. Log Analysis tab shows 6 log files, Channel log, ALE Log, Linking Log, Models Log, Message Log, LQA Log. The internal engine reads and parses the textual log files, then shows in the table format. “Print” button is disabled in this version. 2.9 Performance Analysis Tab Performance analysis tab was developed to answer to the user’s possible question. There are tentative five questions in this version. The conversion textual log file to XML log file has been processed in this version. The answer is derived from the XML Log files. If user clicks the question, the chart will be popped up. In this version, only one question “Give Channel occupancy list for hour x” will be working. 3. SIMULATION LOGS Once the simulation is terminated, it displays the logs and performance results in two new tabs i.e. ‘Logs Analysis’ and ‘Performance Analysis’ tab. The simulation results in generation of log files stored in the application’s ‘LOGS/configFile’ folder as .txt files. All the logs can be exported to Microsoft Excel for better analysis. Logs are tab delimited. The log file names are automatically time stamped in the same manner as the scenario configuration file where the numbers have their usual meaning. If the configuration file is named **base223.0.3.10.06.cfg**, the six log files are stored in “Logs/base223.0.3.10.06/” folder and are displayed in the GUI in Logs Analysis tab as follows: 1. AleLog This is the ALE radio log file and it shows which ALE radios are in which state during the course of simulation run. The columns provide information in this sequence: StationID—Level—AtTime—OnChannel—toDestination—Status A typical snapshot of this log file is shown below: ![ALELog example](image) As can be seen above station 150 calls on channel 6 to station 1 at 01:06::02.400 s. It engages in linking procedure and gets linked after 3-way handshake and both stations get linked at 01:06:13.190 s. Finally 150 starts the 1 minute Voice traffic and comes out of the linked phase and returns to scanning at 01:07:19.388 s. 2. **ChannelLog** This log provides information about the channel occupancy and activity over the simulation run. The columns provide information in this sequence: **Channel—Start Time—End Time—Src—Destination—Power** It tells us about which channel has been used at what particular time and who are the two stations engaged in communication procedures. A typical snapshot of this log is shown below: With reference to the AleLog above the corresponding channel occupancy can be looked into more detail through this logfile. 0 in Destination column implies that it is ‘Sound’. Start and End time refer to the Transmission’s beginning and completion. 3. **LQALog** This particular log file is of most interest to the simulation run. It reports the LQA scores by all the station on an hourly basis as the transmission are heard at its end. The value shown in the table is the representation of Signal to Noise ration heard at that station during that hour. It is in a table format where the receiver station constructs a table with Channels on x-axis and heard stations on y-axis. The following image shows the LQA table for ALE 170 that resides at Station MCC and ALE 152 that resides as Station ADW, at level 1 in a given scenario configuration at hour 1 of simulation run. 4. **LinkingLog** This log provides information about the links that were established over the course of simulation. The figure below is self-explanatory, with Qual reflecting the LQA score (quality) and Time taken the duration for ALE link establishment procedure execution. 5. **MobilesLog** This log provides the information related to the flight path traversed by any mobile plane with the time-stamp. The log can be sorted based on column CallSign to plot the trajectories of any specific mobile plane. 6. **MsgLog_base223.0.3.10.06.txt** This log provides information about any messages that were attempted. They are reported in this log if the station fails to deliver the message (after repeated attempts too). However, it doesn’t show the retries. Only the final outcome is reported with the reason of failure. If the message is delivered then it is reported too. Check the first message at 42:12.793 in the figure below mirroring the link established thru AleLog and LinkingLog. <table> <thead> <tr> <th>Channel Log</th> <th>AE Log</th> <th>Linking Log</th> <th>MobileLog Log</th> <th>Message Log</th> <th>LOA Log</th> </tr> </thead> <tbody> <tr> <td>Msg ID</td> <td>Dest</td> <td>Src</td> <td>Prt</td> <td>Len(s)</td> <td>Arrived</td> </tr> <tr> <td>150000</td> <td>1</td> <td>50</td> <td>10</td> <td>80</td> <td>00:28:00:09:00:20:00:03:09:00:25:12:26</td> </tr> <tr> <td>150001</td> <td>1</td> <td>50</td> <td>10</td> <td>80</td> <td>00:46:00:09:00:45:00:08:09:00:45:12:26</td> </tr> <tr> <td>150002</td> <td>1</td> <td>50</td> <td>200</td> <td>88</td> <td>01:08:00:13:01:09:09:00:16:01:07:26:36</td> </tr> </tbody> </table> Some of the reasons if the message fails to deliver is absence of channel after repeated tries. This is reported as “NO_CHANNEL”. In the above snapshot, all the messages are reported delivered with their message type as either Voice or Data. 7. **PropLog.base223.0.3.10.06.txt** The purpose of this log is to document the ICEPAC software access and Verify the returned values from ITSH software as and when they are used in the simulation model. This is for exhaustive analysis of the simulation analysis in conjunction with above logs. The details are not meant for the user and hence omitted. 8. **Errog.base223.0.3.10.06.txt** This particular log focuses on the errors that might be reported during the simulation run. This log is entirely for development purposes and for any feedbacks that designers might want the developers to know. 9. **Eventog.base223.0.3.10.06.txt** This log is also meant for debugging and development purposes. It is not required in production runs. It is recommended that this log be not generated during the production runs as it is a huge log amount to few gigabytes for a typical simulation run. It accounts for ever single event that is generated and processed as the simulation proceeds forward. Again for clarity purposes, the details are not provided herein. 4. Scenario Generation Hopefully, the user of the simulation has an objective in building a particular scenario. - What are the propagation conditions over the Atlantic during a specified time period? - How many aircraft in a region are affected by the loss of a single ground station? - What happened last year, or next year when we change frequencies in the scanlist? As noted, specific questions will result in a designed scenario’s to answer those questions. Once a scenario is built changes can be made to time, traffic, SSN, or any of a number of variables to see the effects. By comparing the user logs the user can determine the effects of even small changes to the scenario. During the development of the simulation, several basic scenarios were used to examine a number of particular validation issues. Each of these scenarios’s had a defined objective. Each of the following examples are provided in the configuration directory. 4.1 Example 1 “BaseWithAnt” “Base” was developed to examine the propagation conditions over the CONUS region, flight dynamics, ALE protocol and linking, and basic traffic flow and management. Given those objectives, the scenario was setup as follows: - Six ground stations (ADW, OFF, MCC, JNR, AED, HIK) - Single Aircraft flying between Tinker AFB, OK, to Dover AFB, DE. - Traffic 2-3 messages per hour of 1 to 5 minute duration - Daylight, with predicted SSN - Different Antenna at different stations (to check if all antenna configurations are working fine). Once the basic objectives were established, the scenario was developed, ran, analyzed, modified, ran, analyzed, etc. Analysis was based on the basic, first run and data obtained, and changes in the scenario were then compared to determine the effects of the changes. 4.2 Example 2 “CONUS with Traffic” “CONUS with Traffic” was developed to examine the effects of increased traffic over the CONUS region. Again areas like flight dynamics, propagation, and traffic levels were analyzed. • All ground stations (14) • Multiple Aircraft flying between locations CONUS. • Traffic 2-3 messages per hour of 1 to 5 minute duration • Daylight, with predicted SSN Again like the “Base” scenario a baseline was established and changes were compared to the basic data. Changes to a particular scenario should be limited to only one or two of the variables, with multiple changes it would be hard to determine what changes affected the output or result of the scenario. By making multiple runs of the scenario with defined changes in the scenario the cause and effect of the changes can be more readily determined. ### 4.3 Example 3 “Global with Traffic” “Global with Traffic” was developed to examine the network with aircraft and traffic dispersed around the globe. The differences in propagation around the globe, the ability of the network as a whole to support world wide traffic and effects of aircraft transiting between different coverage areas. • All ground stations (14) • Multiple Aircraft flying between locations world wide • Traffic 2-3 messages per hour of 1 to 5 minute duration • Start 16 GMT, with predicted SSN Like the previous examples, specific objectives were established and the results were analyzed. ### 4.4 Developing Scenario’s In planning to develop a scenario, the user may expand on one of the example scenarios or develop a new scenario with their specific objectives in mind. One thing to remember is that the GenetScope/NETSIM 2 model, simulates each radio specified in the scenario, sounding, traffic, the number of aircraft each add detail and thus the complexity of the simulation. As such a very detailed scenario may take several/many hours to run. So practicality dictates the best practices in designing and developing a scenario. The opposite also applies; to short of a scenario may not provide any or enough detail to answer the questions posed by the user. The simulation models the real-world, in both propagation, and ALE functionality. The JITC can provide assistance in developing scenarios or analyzing the results of a scenario. One additional point to remember is that the log files used for analysis are named after the scenario, so if you modify the scenario but save it with the same name, the files will be written over. It is suggested that log files be moved to an archive directory. The Configuration files may be renamed to be more descriptive and it is recommended that the comment field on the setup screen be used to define the scenario and any objectives. These comments are saved with the configuration files. 5. Appendix 5.1 Installation Instructions 1. Execute the GenetScope2.exe file by double-clicking it. 2. Specify a root folder for the files to get copied or the default folder will be C:\ProgramFiles\ACIMS\GenetScope-Netsim2 3. Click Start->Programs->ACIMS->GenetScope-Netsim2 OR GenetScope2 icon on the Desktop to start the application. 5.2 Directory Structure. The application is tightly integrated with the directory structure below. The user is very strongly recommended to not change the structure of this directory. Failure to do so might deem the application not executable. The project directory contains the following subdirectories/files: 1. Readme 2. GS1.0W.exe: Main application 3. GS1.0 - This folder contains basic application Config files 5. Configuration - This folder all the generate or saved configuration scenario files with extension .cfg. The files can be opened in Wordpad for viewing and manual edition. However, it is not recommended to manually edit the Config files. Three basic configuration files are available as described in the previous section. The user can build on these files for reference. a. Sample Archives - This directory contains the original three base files that must not be changed. They are to be left as originals in case the user changes them in the parent folder. The files stored in this sub-folder will not be visible in the application GUI. 6. inst_files - This folder contains the required setup files for GenetScope application. None of the files should be changed. 7. itshfbc - This folder contains the files required to run the ITSH propagation software for dynamic SNR values required by GenetScope application. None of the files in the directory should be changed. 8. Logs - This folder contains the simulation logs for production runs. If the user wishes to run the simulation again for the same configuration file, it is very strongly recommended that the user save the simulation logs of the previous run as they will get overwritten. The Logs folder contains various sub-folders with the name of the Configuration file. For example, if the configuration file name is ‘BaseWithAnt.cfg”, the Logs folder will contain a folder called “BaseWithAnt” that will contain all the logs described earlier. 5.3 Bug reports with contact information The GenetScope version 1.0.14 is in Beta status. Problems like locked-in might occur in which the simulation clock stops before the end of simulation time. In the event of such occurrence, the analyst is request to run the simulation again in “Debug” mode and send the log files to the ACIMS development center. The log files along with usual log files that must be mailed are: 1. EventLog 2. ExceptionLog 3. ErrorLog 4. Prop Log The Email addresses are as follows: **Saurabh Mittal** Lead Developer [saurabh@ece.arizona.edu](mailto:saurabh@ece.arizona.edu) **Seahoon Cheon** Team Member [Cheon@ece.arizona.edu](mailto:Cheon@ece.arizona.edu) **Chungman Seo** Team Member [cseo@ece.arizona.edu](mailto:cseo@ece.arizona.edu) All the personnel above work at: **Arizona Center of Integrative Modeling and Simulation** Rm 318, ECE Department, University of Arizona, Tucson 85721, AZ [www.acims.arizona.edu](http://www.acims.arizona.edu) Credits The original NETSIM-SC program and code were developed by Dr. Eric Johnson, New Mexico State University. The GenetScope code was developed by the Arizona Center for Integrative Modeling and Simulation (ACIMS) at the University of Arizona, Tucson, Arizona. Copyright Notice Copyright Arizona Board of Regents on behalf of The University of Arizona; All Rights Reserved USE & RESTRICTIONS. This software (i.e., DEVSJAVA) with ID number UA1885 is disclosed to the Office of Technology Transfer of the University of Arizona. Software is developed by University of Arizona. TUCSON, ARIZONA, USA Copyright (c) 1996-2000. All rights reserved. DEVSJAVA in part or in whole IS NOT transferable to any other party, individual or entity without explicit permission from the University of Arizona's Office of Technology Transfer or Arizona Board of Regents. NO WARRANTY THIS SOFTWARE IS PROVIDED "AS IS" AND WITHOUT WARRANTY OF ANY KIND, EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY OR FITNESS FOR A SPECIAL PURPOSE. IN NO EVENT SHALL THE ARIZONA BOARD OF REGENTS ON BEHALF OF THE UNIVERSITY OF ARIZONA BE LIABLE FOR ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. License Information This software GenetScope/NETSIM2 and associated DEVSJAVA are licensed to the United States Department of Defense, Defense Information Systems Agency (DISA), Joint Interoperability Test Command (JITC). Disclaimer The software contained within was developed by an agency of the U.S. Government. DISA/JITC has no objection to the use of this software for any purpose subject to appropriate copyright protection in the U.S. No warranty, expressed or implied, is made by DISA/JITC or the U.S. Department of Defense as to the accuracy, suitability and functioning of the program and related material except for its intended purpose, nor shall the fact of distribution constitute any endorsement by the Department of Defense. The GenetScope/NETSIM2 model and its JAVA code are unclassified.
{"Source-Url": "http://acims.asu.edu/wp-content/uploads/2012/02/GenetScope-Netsim2_Manual.pdf", "len_cl100k_base": 13571, "olmocr-version": "0.1.53", "pdf-total-pages": 53, "total-fallback-pages": 0, "total-input-tokens": 85520, "total-output-tokens": 15418, "length": "2e13", "weborganizer": {"__label__adult": 0.0005693435668945312, "__label__art_design": 0.0004475116729736328, "__label__crime_law": 0.0004906654357910156, "__label__education_jobs": 0.0016660690307617188, "__label__entertainment": 0.0002944469451904297, "__label__fashion_beauty": 0.00026988983154296875, "__label__finance_business": 0.0007252693176269531, "__label__food_dining": 0.0004658699035644531, "__label__games": 0.0022735595703125, "__label__hardware": 0.0148773193359375, "__label__health": 0.0003764629364013672, "__label__history": 0.0007905960083007812, "__label__home_hobbies": 0.000244140625, "__label__industrial": 0.0032196044921875, "__label__literature": 0.00034236907958984375, "__label__politics": 0.0005125999450683594, "__label__religion": 0.0006256103515625, "__label__science_tech": 0.308349609375, "__label__social_life": 0.00016820430755615234, "__label__software": 0.10125732421875, "__label__software_dev": 0.55615234375, "__label__sports_fitness": 0.0006604194641113281, "__label__transportation": 0.005031585693359375, "__label__travel": 0.0003273487091064453}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 61202, 0.04577]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 61202, 0.2322]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 61202, 0.87261]], "google_gemma-3-12b-it_contains_pii": [[0, 74, false], [74, 74, null], [74, 2631, null], [2631, 2631, null], [2631, 5677, null], [5677, 5988, null], [5988, 6026, null], [6026, 7656, null], [7656, 8569, null], [8569, 12072, null], [12072, 13170, null], [13170, 15463, null], [15463, 16294, null], [16294, 16711, null], [16711, 17828, null], [17828, 18662, null], [18662, 19245, null], [19245, 19821, null], [19821, 20792, null], [20792, 21430, null], [21430, 22436, null], [22436, 23757, null], [23757, 25444, null], [25444, 27079, null], [27079, 28254, null], [28254, 29195, null], [29195, 30540, null], [30540, 32001, null], [32001, 32974, null], [32974, 34638, null], [34638, 36598, null], [36598, 37021, null], [37021, 37727, null], [37727, 38370, null], [38370, 39399, null], [39399, 39981, null], [39981, 40947, null], [40947, 41911, null], [41911, 43033, null], [43033, 44542, null], [44542, 45089, null], [45089, 45534, null], [45534, 46731, null], [46731, 47568, null], [47568, 48471, null], [48471, 49111, null], [49111, 50994, null], [50994, 52990, null], [52990, 55193, null], [55193, 55576, null], [55576, 57791, null], [57791, 58919, null], [58919, 61202, null]], "google_gemma-3-12b-it_is_public_document": [[0, 74, true], [74, 74, null], [74, 2631, null], [2631, 2631, null], [2631, 5677, null], [5677, 5988, null], [5988, 6026, null], [6026, 7656, null], [7656, 8569, null], [8569, 12072, null], [12072, 13170, null], [13170, 15463, null], [15463, 16294, null], [16294, 16711, null], [16711, 17828, null], [17828, 18662, null], [18662, 19245, null], [19245, 19821, null], [19821, 20792, null], [20792, 21430, null], [21430, 22436, null], [22436, 23757, null], [23757, 25444, null], [25444, 27079, null], [27079, 28254, null], [28254, 29195, null], [29195, 30540, null], [30540, 32001, null], [32001, 32974, null], [32974, 34638, null], [34638, 36598, null], [36598, 37021, null], [37021, 37727, null], [37727, 38370, null], [38370, 39399, null], [39399, 39981, null], [39981, 40947, null], [40947, 41911, null], [41911, 43033, null], [43033, 44542, null], [44542, 45089, null], [45089, 45534, null], [45534, 46731, null], [46731, 47568, null], [47568, 48471, null], [48471, 49111, null], [49111, 50994, null], [50994, 52990, null], [52990, 55193, null], [55193, 55576, null], [55576, 57791, null], [57791, 58919, null], [58919, 61202, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, false], [5000, 61202, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 61202, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 61202, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 61202, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 61202, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 61202, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 61202, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 61202, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 61202, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 61202, null]], "pdf_page_numbers": [[0, 74, 1], [74, 74, 2], [74, 2631, 3], [2631, 2631, 4], [2631, 5677, 5], [5677, 5988, 6], [5988, 6026, 7], [6026, 7656, 8], [7656, 8569, 9], [8569, 12072, 10], [12072, 13170, 11], [13170, 15463, 12], [15463, 16294, 13], [16294, 16711, 14], [16711, 17828, 15], [17828, 18662, 16], [18662, 19245, 17], [19245, 19821, 18], [19821, 20792, 19], [20792, 21430, 20], [21430, 22436, 21], [22436, 23757, 22], [23757, 25444, 23], [25444, 27079, 24], [27079, 28254, 25], [28254, 29195, 26], [29195, 30540, 27], [30540, 32001, 28], [32001, 32974, 29], [32974, 34638, 30], [34638, 36598, 31], [36598, 37021, 32], [37021, 37727, 33], [37727, 38370, 34], [38370, 39399, 35], [39399, 39981, 36], [39981, 40947, 37], [40947, 41911, 38], [41911, 43033, 39], [43033, 44542, 40], [44542, 45089, 41], [45089, 45534, 42], [45534, 46731, 43], [46731, 47568, 44], [47568, 48471, 45], [48471, 49111, 46], [49111, 50994, 47], [50994, 52990, 48], [52990, 55193, 49], [55193, 55576, 50], [55576, 57791, 51], [57791, 58919, 52], [58919, 61202, 53]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 61202, 0.07806]]}
olmocr_science_pdfs
2024-12-06
2024-12-06
5daf6c07180927b65820d024bf8087fcc4a502cc
Down to the Bare Metal: Using Processor Features for Binary Analysis Ralf Hund, Carsten Willems, Dennis Felsch, Andreas Fobian, Thorsten Holz Abstract A detailed understanding of the behavior of exploits and malicious software is necessary to obtain a comprehensive overview of vulnerabilities in operating systems or client applications, and to develop protection techniques and tools. To this end, a lot of research has been done in the last few years on binary analysis techniques to efficiently and precisely analyze code. Most of the common analysis frameworks are based on software emulators since such tools offer a fine-grained control over the execution of a given program. Naturally, this leads to an arms race where the attackers are constantly searching for new methods and techniques to detect such analysis frameworks in order to successfully evade analysis. In this paper, we focus on two aspects. As a first contribution, we introduce several novel mechanisms by which an attacker can delude an emulator. In contrast to existing detection approaches that perform a dedicated test on the environment and combine the test with an explicit conditional branch, our detection mechanisms introduce code sequences that have an implicitly different behavior on a native machine when compared to an emulator. Such differences in behavior are caused by the side-effects of the particular operations and imperfections in the emulation process that cannot be mitigated easily. Even powerful analysis techniques such as multi-path execution cannot analyze our detection mechanisms since the emulator itself is deluded. Motivated by these findings, we introduce a novel approach to generate execution traces. We propose to utilize the processor itself to generate such traces. More precisely, we propose to use a hardware feature called branch tracing available on commodity x86 processors in which the log of all branches taken during code execution is generated directly by the processor. Effectively, the logging is thus performed at the lowest level possible. We present implementation details for both Intel and AMD x86 CPUs and evaluate the practical viability and effectiveness of this approach. 1 Introduction During a typical attack against a computer system, an attacker first exploits some kind of (software) vulnerability to gain access to the system. Once she has control over the compromised machine, the next step is to install some kind of malicious software (abbr. malware) that, for example, steals sensitive information or hides the presence of the attacker on the system. Both software vulnerabilities and malware are thus closely linked and we need to have a precise understanding of their semantics to combat this threat. Most importantly, detailed analysis reports about the tools used by an attacker are required to fix vulnerabilities in operating systems or applications, and to develop new protection techniques and tools. Nowadays, antivirus companies analyze tens of thousands of malware samples on a daily basis [45] with new exploits being released frequently. Thus, there is a clear need for automated approaches to analyze these threats. As a result, a lot of research has been done on efficiently and precisely analyzing malicious code both in academia and industry (e.g., [2,3,7,8,11,12,23,30,44,48]) and many tools and techniques for automated analysis are currently available. The analysis of malicious and vulnerable code can be implemented in several ways and on several semantic levels. Broadly speaking, the methods can be divided into static and dynamic approaches, each having their own (dis-) advantages. For example, static analysis is often complicated with code obfusca- tion and encryption [25, 35, 43], whereas dynamic analysis is typically only capable of efficiently examining a limited number of execution paths [30]. A very detailed behavioral view of code can be obtained by examining every single instruction, but this approach produces a huge amount of data, which has to be mined for valuable information. On the contrary, monitoring only the system calls performed by the program achieves a smaller analysis data set, but results in a high abstraction level and can be evaded in many different ways [14], leading to incomplete analysis results. From a performance perspective, single stepping a program to perform an instruction-level analysis is much slower than intercepting only system calls. Furthermore, malware analysis can be implemented on a native machine (also called *bare metal approach*) or in an emulated/virtualized one. When using a native machine, we are faced with several problems. Most importantly, the analysis system may get infected by malicious code and it has to be reverted back to a clean state after the analysis process has finished. Furthermore, most machines only offer rudimentary monitoring facilities and additional mechanisms have to be implemented first. Sophisticated approaches use techniques like dynamic translation (e.g., *Cobra* [48]) or hardware virtualization extensions (e.g., *Ether* [11]) to achieve such monitoring. In contrast, emulators pose a powerful trade-off between performance and convenience with respect to native machines, but they lack transparency and correctness. Many malware authors have come up with a variety of detection mechanisms that uncover the presence of such artificial environments [14, 15, 34, 36, 39] and several systematic studies on detecting virtual machines or CPU/system emulators have been performed [28, 29, 36]. Once the malware has detected the presence of the analysis environment, it can behave differently leading to incorrect analysis reports. Apart from these explicit detection techniques employed by malware, there are also different CPU instructions [39] and real-life conditions (e.g., timing aspects or specific artifacts like the username of the analysis machine) under which a binary might behave differently when executed inside an emulated environment as opposed to a native system. In this paper, we continue this line of work and present mechanisms an attacker can use to implement code that behaves differently in the presence of an analysis environment. Our mechanisms are novel as they do not perform any explicit test on the analysis environment. Instead, we use instruction sequences that have different semantics on a real machine when compared to an emulated one. More precisely, such instruction sequences have an implicitly different behavior on a native machine with respect to an emulator due to the side-effects of particular operations and imperfections in the emulation process that cannot be mitigated easily (e.g., self-modifying code or caching effects). Effectively, our techniques delude the emulator and thus we call this approach a *delusion attack*. We use delusion attacks as our motivation and propose to utilize hardware features of commodity x86 processors to overcome the (accidental or intended) incorrectness of dynamic analysis in an emulated environment. More precisely, we introduce a promising approach to analyze the behavior of binary programs by using a processor feature called *Branch Tracing (BT)*. With this hardware primitive (available on both Intel and AMD CPUs [18]), the processor *itself* keeps track of all branches taken during code execution. The logging is thus performed at the lowest level possible, making our approach robust to attacks. Our performance overhead is also significantly lower in contrast to other approaches that use hardware features such as single stepping [11]. To demonstrate the effectiveness and applicability of our approach, we show how our method is sufficient to analyze malicious PDF documents. In an empirical evaluation, we demonstrate that the branch tracing results can be used to automatically cluster similar vulnerabilities which are exploited within the analyzed documents: a set of 4,869 PDF documents can be clustered into eight different root causes based on the analysis results of our tool. Most notably, our framework can also deal with advanced exploits that use concepts like structured exception handler (SEH) for control flow diversion and even return-oriented programming [41]. **Related Work** As discussed previously, there is a large body of published work on malware analysis and detection of different execution environments. Complementary to our work are recent approaches that compare the behavior of a sample in different (analysis) environments [2, 21, 22]. Such techniques could also be used to detect our delusion attacks, but they incur huge runtime overheads as a single sample has to be executed in at least two analysis environments. Vasudevan et al. introduce a way to use branch tracing on AMD CPUs to record host execution trace to an external, trusted system [47]. In contrast, we also show how BT can be used on Intel CPUs and perform several empirical experiments to demonstrate the practical usefulness of this approach. Contributions The main contributions of this technical report can be summarized as follows: • We introduce several delusion attacks for software emulators. These instruction sequences behave differently when executed on a native machine as opposed to an emulator. Delusion attacks work by exploiting some implicit imperfections in the emulation process. • Motivated by delusion attacks, we introduce an approach to perform behavior analysis that takes advantage of the branch tracing feature of commodity x86 CPUs. Our approach performs the logging of the actual behavior on the lowest level possible since we directly instrument the CPU to generate traces. We illustrate this analysis process and provide technical implementation details for both Intel and AMD CPU architectures. • We have implemented a fully-working prototype of our approach and show in an empirical evaluation the usefulness of our approach by performing a crash analysis of malicious PDF documents. 2 Background In this section, we review existing techniques that are used by malware analysis frameworks. We shed light on the advantages and disadvantages of each approach and provide some examples of tools and methods that have been proposed in the literature. This serves as a discussion of related work and motivates our delusion attacks that we introduce in Section 3. 2.1 Debuggers Every modern operating system offers the possibility to debug a specific process from another process. For example, Windows provides the so called Windows Debugging API and Linux provides the `ptrace()` system call. These debugging facilities can be used to set breakpoints at specific code locations or certain memory read/write accesses. Furthermore, it is possible to set a debuggee into single-stepping mode and thus perform instruction-level tracing. All this functionality is implemented with the help of certain hardware CPU features such as the trap flag or the int 3 breakpoint instruction. This enables the analysis of a program on a very fine-grained level. However, debugger-based solutions are slow and easy to detect, since the analyzer interacts heavily with the process environment, its memory layout, and the instruction scheduling as well. Furthermore, the scope of such analyzers is typically limited to usermode binaries only. While there are also kernel-debugging interfaces, they are usually even slower and harder to automate. Another drawback is the limited amount of hardware debugging resources, e.g., the number of hardware breakpoints. In contrast, software breakpoints require overwriting certain instructions in memory, which is easy to detect and may cause problems in the presence of self-modifying code. An example of a debugger-based analysis framework is Ether, which uses single-stepping and hardware virtualization extensions to implement instruction level tracing. 2.2 Binary Instrumentation Another class of malware analysis frameworks uses binary instrumentation to add monitoring capabilities inline into the observed program. To that end, the analyzed code is patched, i.e., other instructions are inserted before or after existing code, or code is redirected and executed in an entirely new memory region. Normally, the modified code itself takes no notion of the presence of instrumentation and executes identically as in a normal environment. The rewriting can either be done statically (i.e., the executable file is patched before execution) or dynamically (i.e., the code is patched in memory before/while executing). In addition, instrumentation can also be achieved by overwriting only certain function pointers. For example, this is common practice in several function call tracing frameworks to hook library calls. Notable examples of binary instrumentation-based frameworks are PIN [26], Valgrind [31], DynamoRIO [6], CWSandbox [50], and Anubis [3]. The advantage of binary instrumentation over debugger-based solution is that it is typically faster since no time-consuming interrupts and process switches between the debugger and the debuggee are needed. This comes with the disadvantage of the non-trivial task of implementing a sound and complete rewriting engine. Binary rewriters also run on equal terms with the emulated code and can thus be detected and attacked easily. Finally, current frameworks only provide a single-process view and cannot be used to analyze the entire system. 2.3 Software Emulators Software emulation-based solutions are oftentimes more appealing for malware analysis since, in contrast to the previously described techniques, they provide full control over the emulated system: the analyzer can intervene at any point in the execution of the analyzed code. There are also no restrictions on analyzing privileged code within the guest. Furthermore, emulators provide isolation between the analyzer and the malware. **BOCHS** [24] is a PC emulator that emulates an x86/x64 processor with a set of common attached devices (graphics card, network card, etc.). It is an emulator in the classical sense in that the emulated code is fetched, decoded, and emulated instruction-wise — implemented in one large loop of the **BOCHS** code. This enables a precise emulation of the guest system, but has the drawback that execution is typically slow in comparison to a real system. **BOCHS** is often used for malware analysis in conjunction with the disassembler IDA Pro [40], which ships with built-in support for that purpose. This combination can efficiently be used to (partially) execute malware within the emulator to analyze it. Similar to Bochs, **QEMU** [4] is a generic full system emulator. However, by using an intermediate language and a technique called dynamic translation, it achieves support for a variety of host and target platforms along with good performance. **QEMU** is thus considerably faster than other emulators. The dynamic translation engine works as follows: whenever new code is executed in the emulator, **QEMU** translates the corresponding block of instructions (i.e., the instructions until the next branch) into an internal intermediate language. From this representation, the code is optimized to reduce unnecessary overhead (e.g., setting certain flags that are not further evaluated anyway) and then translated into the final, architecture dependent target code. The resulting block of code is called translation block (TB). TBs are cached so that the translation process is ideally only executed once. Guest code memory accesses are translated into safe memory accesses in the target code such that they cannot escape from the isolated, emulated memory space. Self-modifying code is detected with the help of a page fault exception handler. To this end, executable pages of the emulated guest are marked as non-writable. Whenever translated code attempts to overwrite code that corresponds to a TB, an exception within **QEMU** happens and the emulator invalidates all affected TBs. **QEMU** forms the basis of several malware analysis platforms, such as the dynamic analyzer of BitBlaze [44] (called TEMU) and Anubis [3]. Amongst other things, TEMU and Anubis extend **QEMU** by providing taint propagation tracking [32], a technique that allows to backtrack which input values influenced the value of a certain register, memory location, or similar storage units. In order to do so, every translated write operation has to be instrumented and dependencies between memory values have to be saved in a dedicated internal memory region. Taint propagation tracking thus comes with a significant performance penalty. These frameworks also introduce OS awareness through virtual machine introspection [16]. This provides access to runtime information such as running processes or loaded drivers, and also allows to hook specific events in the emulated system. such as certain API calls. Since both systems rely on the emulation code of QEMU, they are both prone to design- or implementation-related flaws of QEMU. 2.4 Virtualizers Another class of analysis frameworks runs the analyzed code within virtualizers such as VMware, VirtualBox, or XEN. The code is executed on the native machine, typically by using the recently introduced hardware virtualization features of Intel (Intel-VT) and AMD (AMD-V). While these frameworks provide isolation between the analyzer and the analyzed program, they eventually have to rely on the monitoring techniques already described previously in order to provide their functionality. This stems from the fact that virtualizers are not as powerful as emulators per se in that they cannot intervene at any point in execution without using additional techniques (such as binary rewriting). For example, Ether is based on the hardware virtualizer XEN and uses single-stepping in the guest to provide instruction level tracing [11]. 3 Implicit Methods to Delude Software Emulators Obviously, attackers have an incentive to evade automated malware analysis frameworks. Thus, there is an arms race in this area where the attackers are constantly searching for new methods and techniques to detect such analysis frameworks. To this end, different techniques to detect emulators were introduced in the last few years [14, 15, 34, 36, 39] and several systematic studies on detection approaches were performed [28, 29, 36]. As a result, there is a large body of work on detection approaches and attackers have plenty of ways to detect the presence of a virtual environment. In the following, we introduce another approach in which code implicitly behaves differently on a native machine compared to an emulated one, a technique we call delusion attack. 3.1 Motivation To motivate the benefit of utilizing hardware features for dynamic program analysis, we propose a new class of emulator detection techniques. Current methods consist of two different steps: first, the existence of a non-native system environment is probed and then, depending on the outcome of the test, different actions are performed. These detection attempts are easy to spot and mitigate during (manual or automated) examination of the performed operations [48]. In contrast, our methods have no explicit check and do not contain a conditional branch that takes one control path on a native machine and another on an emulated one. Even powerful analysis techniques like multi-path execution [30] cannot analyze this kind of code sequences since the emulator itself does not execute the correct code. We call this delusion attacks to emphasize the fact that such code sequences effectively delude emulators in the way code is interpreted. All our examples that we present follow the same methodology: a sequence of instructions is executed and as an implicit effect, either a malicious or a benign function is called. In a real attack, the malicious instructions are executed directly inline instead of calling a separate function. For the sake of simplicity we use two dedicated subfunctions in our examples: MALICIOUSCODE (that should be executed on a native system) and BENIGNCODE (to be executed in an emulator). The examples were implemented and validated against real hardware as well as the targeted emulators. There are hundreds of different processor types (including the different stepping of CPUs) available that vary in small implementation details. Due to this fact, we were not able to test all of them in an empirical evaluation. Hence, we focus our analysis on common Intel and AMD CPUs and, as a result, we cannot claim that these techniques are universally usable and provide a way for a guaranteed emulator delusion. The goal of this work is to show that there are still and – most probably – will always be methods to exploit behavior differences of emulators in order to force different execution for the same piece of code. As a result, we argue that it is not safe to trust analysis results that are gathered with the help of emulators since a program might behave differently on a native machine. Note that traditional detection techniques could be modified in such a way that conditional code branches are transformed into \textit{branchless code} as well. Therefore, the boundary between those and our new delusion methods is blurred to a certain extent. Nevertheless, we are confident that our techniques are significantly harder to detect and mitigate compared to previous approaches. ### 3.2 Basic Principle: Self-Modifying Code and Atomicity Several of our attacks are based on self-modifying code (SMC). Correct handling of SMC is a non-trivial and complicated task when not done by the CPU itself, but by an emulator. Thus we expect that an attacker can use SMC to detect the presence of an emulator. On a native system, the modification of data within a code segment has to trigger different actions. Most importantly, the old version of the modified code has to be flushed from the instruction prefetch queue and from the instruction caches. Depending on the underlying cache organization and the number of processors available within the system, also the other CPUs have to be informed and take care of this problem accordingly. Contemporary systems contain sophisticated measures to detect SMC correctly and there have been many flaws in the past that required the developer to perform specific actions in order to realize properly working code. For example SMC typically only operated correctly if (after modifying the memory) either a jump operation to that modified code or a memory-serializing operation (e.g., \texttt{cpuid} instruction) had been performed. Additional problems occurred with instructions that had already been loaded into the instruction prefetch queue: since only the linear address of a modified memory location was checked, it was possible to use two different linear addresses for code and data access, which both are associated with the same physical memory. Modern CPUs can handle these older problems with SMC correctly. In an emulator, however, the CPU facilities for SMC detection obviously cannot be utilized. Hence, they have to be emulated and implemented in software as well. One way is to check every memory write operation against a list of addresses that possibly contain instructions or vice versa when an instruction is about to be executed. Apparently, this implies a huge overhead of execution performance and space required for managing the related data structures. Thus, most emulators use page fault handling for SMC detection. To this end, all executable memory pages are marked as read-only. If the emulated code performs a write attempt to such a memory area, the page fault handler is triggered. It performs the following actions if the target memory should be writable, i.e., if it was marked read-only by the emulator and not by the application itself: 1. all other threads are suspended, 2. the memory protection is modified to writable, 3. the faulting write instruction is executed again, 4. the memory protection is changed to read-only, and 5. all other threads are resumed. This approach is problematic due to the fact that emulated instructions are normally not executed atomically, but they are translated into several sub-instructions. Therefore, the faulting write operations may already be partially executed and then have to be re-executed after the memory is made writable. This behavior can be exploited for delusion purposes as shown in the following subsection. ### 3.3 REP MOVs Instruction The first delusion method uses the \texttt{rep movs} instruction, which copies a number of bytes, words, or double words within an implicit loop. The source memory location is specified by the \texttt{esi} register, the destination location by \texttt{edi}, and the amount of copy iterations by the value of \texttt{ecx}. This value is decremented with each copy iteration and used as a stop condition once it reaches zero. Accordingly, the value of \texttt{ecx} equals to 0 when the complete loop is finished. To delude an emulator, the copy destination can be set to the memory address of the \texttt{rep movs} instruction itself. As an effect, this instruction is overwritten by the first copy iteration. On a real machine, the copy loop is performed atomically, so this instruction overwriting has no actual effect on the loop execution. After the copy operation is completed, \texttt{ecx} is zero and the \texttt{rep movs} instruction, as well as the consecutive ones, are overwritten. In an emulator, however, the situation is different: due to the detection mechanism already the first loop iteration triggers the page fault handler when trying to write to memory that contains code. The emulator makes the destination memory writable and re-executes the memory write operation. Afterwards, the instruction is re-read from memory, in order to not miss any SMC. Since now the re-fetched instruction is no longer \texttt{rep movs}, a different behavior arises when compared to a real machine. For example, if the instruction is overwritten with \texttt{nop} operations, only one single copy loop iteration is performed: only the \texttt{rep movs} instruction is overwritten and the following instructions remain untouched. Furthermore, the \texttt{ecx} register is only decremented by one. This different behavior can be exploited by the delusion code shown in Figure 1. Note that the \texttt{movsd} instruction copies one double word per iteration. On a real machine, two copy iterations are performed and, therefore, two double words are copied from \texttt{NEW} to \texttt{OLD}. After finishing, the memory at \texttt{OLD} +0x4 contains the call to the \texttt{MALICIOUSCODE}. Accordingly, the malicious code is executed. Hence, on an emulated machine, the copy operation stops after overwriting the \texttt{rep movs} and the call to \texttt{BENIGNCODE} is not modified and, therefore, the benign code will be executed. \texttt{QEMU} and \texttt{BOCHS} can be successfully deluded with this technique. We would like to stress that the deviating behavior can be fixed in the emulators. However, this would require special handling for a variety of instructions that can be used in conjunction with \texttt{rep}. This not only takes considerable effort to implement, but would reduce the performance of string copy operations in general. As an implementation detail note that not all CPU types behave similar when executing the code shown above. We found that some versions of the latest Intel i7 CPUs react on the modification of the \texttt{rep movs} instruction and terminate the loop prematurely. In contrast, most other CPUs interpreted this code sequence in the way discussed above. ### 3.4 LEAVE Instruction Our second method also exploits the SMC detection mechanism of emulators based on page fault handling. It requires virtual memory and utilizes the x86/64 machine instruction \texttt{leave}, which behaves like the two instructions \texttt{mov esp, ebp} and \texttt{pop ebp} combined into a single operation. On a real machine, the \texttt{leave} instruction is always executed atomically. However, within an emulator it is possible to force an only partial execution. If for instance the \texttt{ebp} register initially is set to an inaccessible virtual memory address, this address will be correctly copied into \texttt{esp}, but the \texttt{pop} operation will trigger a page fault. If the emulator does not take special care of this situation, the \texttt{esp} value contains the overwritten value from \texttt{ebp} when entering the invoked exception handler. Obviously, on a real machine \texttt{esp} has not changed at all, since the \texttt{leave} operation could not be executed completely. Figure 2 shows a small code snippet that demonstrates how to utilize this different behavior. The code makes the following assumptions: 1. \texttt{exc_handler} is set as the \texttt{exception handler}, 2. \texttt{invalid_addr} points to an unallocated memory page, i.e., reading from this address causes a protection fault, and, 3. the page located before \texttt{invalid_addr} is allocated. As described above, the code exploits the fact that under special circumstances the \texttt{esp} register is modified on an emulator, while it is untouched on a real machine. The idea now is to set up two different stack locations and store differing function pointers within each location. The proper preparation of the stacks is performed at the beginning of the \texttt{start} function. For the emulator, it prepares the memory immediately before \texttt{invalid_addr} and for the native system the current stack is used. Since the stored function address is 4 bytes in size and the involved exception handler uses 0x10 bytes function parameters, an offset of \(-0x10-0x4\) is used. Afterwards, the \texttt{ebp} register is loaded with \texttt{invalid_addr} and the \texttt{leave} instruction is executed. Since the memory pointed to by \texttt{ebp} is invalid, a protection fault is triggered in any case. Within an emulator, the \texttt{esp} register is already updated with the \texttt{ebp} value as an effect of the partial \texttt{leave} execution. On the contrary, on a real system this register is not modified at all. Before the exception handler is executed, the system pushes four parameters onto the current stack position, which contain further exception information. As depicted in Figure 3, different stack locations are used when the exception handler is called, depending on the current \texttt{esp} value. As a result, the function pointer stored immediately before the pushed parameters is either that of \texttt{BENIGNCODE} (within an emulator) or \texttt{MALICIOUSCODE} (on a real system). The exception handler now simply returns to that specific function and thus leads to a different behavior. While we have found \texttt{QEMU} to be prone to this delusion attempt, \texttt{BOCHS} surprisingly handles this situation correctly and cannot be deluded by this method. An attacker can thus use this technique only on \texttt{QEMU} to detect the presence of an emulated environment. ### 3.5 INVD Instruction Besides SMC, there are other aspects of a system that are hard (if not impossible) to deal with when building an emulator. One example are the many different kinds of caches available on a contemporary computer system. Some of these caches only contain data, others only instructions, and there are also combined caches that store both data and instructions. Furthermore, some caches are integrated into the CPU itself and others are placed outside (i.e., somewhere between the processor and the main memory). Emulators cannot use these hardware facilities explicitly, since they need total control over the accessed data and the executed instructions. More precisely, emulators implicitly share the cache with the host operating system, since they also use the RAM for storing data and instructions. Nevertheless, \textit{inside} the emulated system there is no explicit cache support and all cache-related instructions have no effect when being executed. Disabling all cache-related functionalities inside... the emulated machine is the only reasonable way, since the simulation of caching facilities would degrade the performance of memory accesses even more and that would be counterproductive to the reason for using caches at all. This missing ability to emulate cache is exploited by our third delusion technique. It works by utilizing write-back cache, which has no effect on an emulated machine. First of all, the instructions residing in a cached memory location are modified. On a real machine, the modification only affects the cache and the propagation to RAM is delayed for a while. On an emulated machine – and on each machine without caching – the modification is written directly to RAM. Now, immediately after modifying the memory, the cache is invalidated. On a real machine, this undoes the previous modification, while on an emulated one it (again) has no effect. Finally, the instructions within that memory buffer are executed and a different behavior between native and emulated machines is achieved. The actual code for this method is shown in Figure 4. For sake of simplicity, the instructions for enabling the caching for memory region \( A \) are left out. The code starts with writing back all potentially pending cache modifications to the RAM via the \texttt{wbinvd} instruction. Then the \texttt{call ebx} instruction is modified to \texttt{call eax}, which changes the call target from \texttt{MALICIOUSCODE} to \texttt{BENIGNCODE}. Afterwards, the instruction \texttt{invd} undoes this modification on a real machine, but not within an emulator. Finally, the call is executed to the resulting call target. Although it is easy to detect such a scenario since \texttt{wbinvd} is an uncommon instruction, it takes vast effort to perfectly emulate the effects of \texttt{wbinvd}. This would require to provide a write history buffer that holds the recently written values to roll back the invalidation, which results in a significant performance degradation of the entire emulator. The instruction also needs elevated privileges (ring-0). However, this poses no problem since a full-system emulator can also be used to analyze privileged code. We verified that this kind of delusion attack works against both \texttt{BOCHS} and \texttt{QEMU}. ![Figure 3: Memory Map for the \texttt{leave} example.](image3) ![Figure 4: Delusion with the help of the \texttt{invd} instruction.](image4) 4 Binary Analysis with Branch Tracing Motivated by the examples of detecting emulated environments, we now introduce an approach to observe the actual operations performed by a CPU. We then do not need to take into account the effects of SMC, caching effects, or other kinds of delusion and/or detection attacks. Effectively, this is the lowest level an analysis framework can be based on since we directly observe the behavior of the code when running on a CPU, i.e., we obtain a precise trace of the runtime behavior of the code. 4.1 General Approach To implement such a tracing framework, we take advantage of the branch tracing (BT) facilities available on x86/64 architectures from Intel and AMD. Though the implementation details for both platforms differ, the general approach is the same. Since only the Intel specifications contains detailed information on this topic [18], we mostly refer to the names and mechanism descriptions in that specification. In addition, we also learned how to employ BT on the AMD platform through reverse engineering and empirical experiments, and thus we are able to present implementation details for this platform as well. We note that Intel and AMD both publish public documentation regarding light-weight processor performance monitoring mechanisms [1, 19]. While these mechanisms allow tracing of retired branch instructions, they are severely restricted in the information that can be captured. For example, Intel CPUs only log the last 4 to 16 branches. While AMD CPUs do not place any restrictions in terms of the number of branch instructions that can be profiled, they can only capture branches in user-mode (ring-3) and cannot capture far jumps, returns, syscall/sysexit, exceptions, SMM mode etc [1]. As discussed before, the traditional way to trace a binary program operates on the instruction level. This can be achieved by either utilizing specific hardware features (e.g., single-stepping the CPU or virtualization features [11, 38]) or by emulation [3, 44]. For the single-stepping case, some specific debug control registers are set such that the CPU stops execution after each performed instruction and invokes an exception handler. This handler then can be used to examine or modify the processor registers or the memory, e.g., the heap or stack memory. Before returning control to the interrupted piece of code, the tracing can be re-enabled, since it is normally deactivated automatically after each handler invocation. Virtualization features of modern CPUs can be used to also generate single stepping traces, but this approach has a severe performance penalty in practice. A more coarse-grained tracing granularity has been employed in the last years: when tracing on the function-/system-call level, execution is not stopped after each single operation, but only when specific functions are called. Often the set of monitored function calls is restricted to a subset of critical system calls. On interception, several actions can be taken. Typically, the call parameters are first examined and optionally modified. Then, the originally called function is executed or simulated. Finally, the result values are examined and/or modified appropriately. There exist several techniques for function level tracing. While native systems mostly apply API hooking [3, 44, 50], the usage of virtual machines empowers the analyst to perform virtual machine introspection (VMI) [3, 11, 16]. The granularity of tracing on the branch level is located between those of instructions and function calls. The interception happens on each taken branch, i.e., on each conditional and unconditional jump, call, interrupt, and exception. In the preceding the term tracing was used to describe a technique in which execution of a process is actually stopped after each instruction, branch, or, function call. However, with BT logging the execution is actually not interrupted, but only log information is stored at each interception point which results in a significantly smaller overhead. In practice, the performance overhead of BT logging is smaller than interrupting the actual execution (either via single-stepping the CPU or using virtualization features). Branch tracing provides a rather coarse overview of the behavior exposed by a given binary: the data which is collectable by BT logging is less comprehensive: the trace only contains the addresses of the source and target instructions of the branches. Nevertheless, even by viewing only addresses, it is possible to completely reconstruct the execution/decision path that was taken during execution as we will show in Section 5. In the following, we describe the BT mechanism in detail for both Intel and AMD platforms and discuss how this feature can be used on these two different x86/x64 hardware platforms. 4.2 Branch Tracing on Intel Depending on the actual CPU, Intel offers several different modes for branch tracing, which can be combined in several ways. The Intel reference manuals [18] state that branch trace stepping was already introduced with the P6 family and branch trace logging was added with newer CPUs like the Intel Xeon or Core Solo/Duo technology. Accordingly, all commodity processor types support the methods described in the following but it seems like the potential of this obscure feature was overlooked in the past. All branch tracing modes are enabled and configured via several control bits of the IA32_DEBUGCTL MSR (see Figure 6 in the Appendix). The different modes of operation are described in the following paragraphs. When using Last Branch Recording (LBR), the CPU maintains an internal MSR stack of Last Branch Records that are organized as a ring buffer: when all locations of the stack have been written, the oldest position is overwritten next and so on. Depending on the CPU type, a different number of LBR stack elements are available, e.g., 4 on a Core2Duo CPU and 16 on the Nehalem architecture. To activate the recording, the LBR bit of the IA32_DEBUGCTL has to be set. Several branch source and target addresses are then written into the MSR_LASTBRANCH_i_FROM_IP and MSR_LASTBRANCH_i_TO_IP registers respectively, where i denotes the i'th stack entry. The current stack pointer is stored in MSR_LASTBRANCH_TOS, i.e., it contains the index of the most recently written stack location. LBR is very fast since it only accesses CPU registers, but it is restricted due to the limited stack size. Instead of recording branch information into MSRs, they can also be logged to some monitoring device or the system memory. This can be enabled via the trace message enable (TR) flag of IA32_DEBUGCTL. As an effect, branch trace messages (BTMs) are generated and placed onto the system bus. If further the branch trace store (BTS) flag is set, the BTMs are also written to a dedicated buffer in memory. Like the LBR stack, this BTS buffer can also be used as a ring buffer or it can be configured to raise an interrupt each time the last slot is written to. The contents of a BTM (as shown in Figure 7 in the Appendix) are rather similar to those of the LBRs: there is a branch-from address, a branch-to address, and one additional control word that currently only contains one valid bit that determines if the branch has been predicted by the processor logic or not. Obviously, logging of each branch within a system produces a huge amount of data and storing this information to memory imposes a dramatic performance penalty. In order to reduce the amount of data, logging can be restricted to only cover branches that were executed in user mode (ring-3) or kernel mode (ring-0). The branch trace off in privileged/user code control bits BTS_OFF_OS and BTS_OFF_USR can be used to achieve this. The last available operation mode is last branch stepping. When the single-step on branches (BTF) control bit of IA32_DEBUGCTL is enabled, an enabled trace flag TF in the EFLAGS register forces the CPU to invoke a debug exception at each branch. In the general case (i.e., when the BTF bit is not set), the TF flag invokes an exception after each single instruction. 4.3 Branch Tracing on AMD The general approach of branch tracing on AMD machines is similar to BT on Intel systems, but there are several technical implementation differences. Since BT on the AMD platform is mostly an undocumented feature with only a few published documents talking about its architecture [27,47], the information presented in the following is a result of system-level exploration and reverse engineering. We are mostly interested in the logging of BTMs and thus we only present this mode of operation. All analysis and experiments have been performed on a Barcelona Quad-Core B3 stepping CPU and thus some technical details of our results might need to be adjusted when applying them to another AMD CPU due to differences in their specific implementation. Similar to the Intel architecture, everything is controlled via specific MSRs. Firstly, a memory region has to be specified that is used to store the BTMs. This is done by writing the physical address of the first byte of the buffer to the MSR \texttt{AMD MSR BT BASE} (0xC0011007). The end address of this buffer has to be specified via \texttt{AMD MSR BT LIMIT} (0xC0011009). The logging of BTMs is then enabled by setting an appropriate control value into the \texttt{AMD MSR BT CONTROL} (0xC0011010) register. For the system we used during our analysis phase (\textit{AMD Barcelona Stepping B3 Quad-Core}), a value of 0x20230340 enables the logging. After activation, each record is written to the next free slot of the specified buffer, which is specified by an index pointer in \texttt{AMD MSR BT PTR} (0xC0011008). Accordingly, the value of this register should be initialized with 0 and then is automatically incremented by one with each generated BTM. Once the end of the buffer is reached, an interrupt is raised. The interrupt handler is then responsible to reset the \texttt{AMD MSR BT PTR} back to the position of the next to be written BTM. The format of each BTM differs from the records created on an Intel system. Each message consists of 96 bits, which contain a 64 bit address value, a 16 bit segment selector, and additional 16 reserved bits. There are two basic message categories: (i) branch destination message, and (ii) branch bitmap message. The branch destination message records the destination branch address for a given conditional or unconditional branch, while the branch bitmap message records the conditional branches that have been taken before a branch destination message. Together, they help in identifying the source and destination addresses for any branch taken by the CPU. 5 Application of Branch Tracing In this section we describe several experiments that demonstrate the effectiveness of BT over traditional analysis approaches and show its wide applicability. We first show that the addresses contained in the BTMs are sufficient to reconstruct precise code paths taken during execution in the context of a practical and challenging application called \textit{binning}. Here, we are interested in automatically grouping crash reports resulting from malware exploiting a vulnerability into different representative classes. After that we present how BTs can be enriched with additional information to obtain a deeper insight into executing code and demonstrate how complex return-oriented programming attacks [41] can be detected and analyzed with this approach. Finally, we describe a practical delusion attack that underlines the necessity of a robust tracing facility such as BT since traditional analysis approaches are unable to produce correct results. 5.1 Experiment 1: Binning of Malicious PDF Documents One powerful application of BT is the grouping of crash reports gained by fuzzing [17, 33]. This kind of automated vulnerability analysis very often produces a large number of application crashes that are ultimately caused by the same software vulnerability. Since the post-verification of each single crash is very time consuming, an analyst wants to reduce the amount of reports to be examined as good as possible. For that purpose a technique called \textit{binning} is used, in which the crash reports are automatically grouped into different classes, each one consisting of crashes that are a result of the same root cause. This saves a lot of time, since an analyst only has to manually analyze one instance of each resulting bin. One efficient way to realize binning is to compare the execution paths that have led to the crashes. Obviously, the specific part of a BT log that was protocolled just before an error has occurred contains all the necessary information for reconstructing the control path leading to the fault. The same technique can also be used to group a set of (possibly unknown) exploits by the root cause vulnerability they exploit. \textbf{Trace Generation:} For evaluating this method, we have extended a tool called \textit{CWXDetector} [49] that is capable of detecting exploitation attempts and extracting shellcode used during the exploit. The tool uses a detection approach that is generic in the sense that it captures the fact that unauthorized code is being executed and is thus capable of detecting shellcode that is embedded and invoked from arbitrary types of data or programs. For example, the tool can be used to extract shellcode from malicious Microsoft Office documents or shellcode that is contained in network traffic. One of its limitations is that it does not become active before the execution of the first shellcode instruction. As an effect, no information can be gained about the exploited vulnerability that led to the execution of malicious code. One way to gain more insight about the actual root cause of the exploitation is to utilize BT in combination with this tool. This enables to virtually “look into the past” once the shellcode execution is detected: the concrete execution path that led to the malicious instruction can be reconstructed and examined in detail. For the evaluation, we have added BT support to CWXDetector and examined a set of 4,869 malicious PDF documents. This malware corpus was originally collected by a well-known AV vendor in January 2011 from different sources [49] and it is known that each file in this corpus exploits some kind of vulnerability in Acrobat Reader 9.00. Hence, we could be sure that opening each file within that particular Acrobat Reader version would lead to a successful exploit. What we got as result of this experiment is a set of 4,869 different exploit reports with BT logs that cover the last 10,000 branches taken before the first shellcode instruction was executed. Note that we could also generate similar reports with other kinds of analysis tools (e.g., Ether or single stepping), but the performance overhead of BT is significantly smaller. Example: An example of a BT log excerpt is shown in Listing 1. The trace shows an excerpt of the behavior observed during the analysis phase based on the recorded branches. As discussed in Section 4, for each branch we obtain a log message that contains the branch source code location and the branch target. In between these branches, we do not obtain any direct insights into what code was executed within a basic block. Nevertheless, this coarse overview of the branches taken by a program already contains enough information for our purposes as we demonstrate in the following. | 1704 | from 0x781804d7 (MSVCR80. strcat+0x87) | 1704 | to 0x781804de (MSVCR80. strcat+0x8e) | | 1703 | from 0x781804f6 (MSVCR80. strcat+0xa6) | 1703 | to 0x781804d9 (MSVCR80. strcat+0x89) | | 101 | from 0x781804f6 (MSVCR80. strcat+0xa6) | 101 | to 0x781804f6 (MSVCR80. strcat+0xa6) | | 100 | from 0x80541f57 (ntkrlpa.KiExceptionExit+0xab) | 100 | to 0x791e45c (ntdll.KiUserExceptionDispatcher) | | 99 | from 0x791e455 (ntdll.KiUserExceptionDispatcher+0xa9) | 99 | to 0x791e450 (ntdll.KiUserExceptionDispatcher+0xa9) | Listing 1: Excerpt of a Branch Trace generated for a malicious PDF file Binig Approach: Based on the collected data, we then clustered the BT reports into distinct bins, one for each exploited vulnerability. In order to achieve reasonable results for the binning, the logged data first has to be normalized in several ways. First, we used the relative addresses instead of the absolute ones, since the base address of modules could change over time due to techniques such as Address Space Layout Randomization (ASLR) [5,42]. Second, we collapsed loops, since we did not want to assign different bins to files that only differ in the number of loop iterations (e.g., due to differences in the size of the input data). To this end, we implemented an altered version of the approach from Tubella and Gonzalez [46], which main concept is that every backward jump forms a loop. Third, we also removed those parts from the traces that are related to the internal exception handling routines of the Windows system. Exceptions are frequently used by exploits in the last stage before control is transferred to the actual shellcode. By removing these parts from the traces, we prevent different exploits to be mistakenly put in the same bin because of this effect. Finally, we ignored those BTs of the actual executed shellcode since for binning these are not related to the vulnerability that was exploited. The shellcode is still logged and can be analyzed separately. As clustering algorithm we have used DBSCAN [13] and as distance function a modified version of the Jaro-Winkler distance [20,51]. This function originally is used to measure the difference between two strings and calculates a similarity score based on several conditions. Mainly it is influenced by the amount of common characters and the amount of transpositions between them. Additionally, it prioritizes the prefixes of the compared strings, i.e., strings with a similar prefix get a higher score than those with only a similar suffix. This reflects our observation that branch traces (that are always considered backwards) require a common prefix if they reflect the same vulnerability. Experiments have shown that best results could be achieved if we prioritize the last 50 branches. For performance reasons we have further limited the overall amount of considered branches to 80. Preliminary tests have shown that nearly all characteristic variations of BT logs happen within these first 80 branches. The DBSCAN algorithm has two configuration parameters that influence its behavior and quality: the minimum cluster size $k$, which discriminates noise from valid cluster objects, and the neighborhood radius $\epsilon$, that specifies the maximum distance of two objects to belong to the same cluster. The choice of $k$ is merely a matter of taste (as long as it is greater than 1) and can be used to control the size of the resulting noise-cluster. Experiments have shown that $k = 3$ produces best results. In contrast, the value of $\epsilon$ has a severe effect on the number of resulting clusters, as can be seen in Figure 5. For very low values we get 12 different clusters and by increasing $\epsilon$ some of them merge into combined ones. From a value of 0.1 on we are left with 8 clusters and further increasing the neighborhood radius has no more effect on its number. However, for higher values the amount of the noise objects still decreases, because some of them fall into existing clusters. Note that the logarithmic scaling of the figure conceals that growing element size of these clusters. We have manually analyzed randomly picked objects from the merging clusters and in all cases determined that they are based on the same root cause that is simply exploited in a different manner. For example there was a buffer overflow in a stack variable and one exploit diverts the control flow when the `memcpy` function is called with that buffer and another when `strcat` is executed. It is debatable if this is the same vulnerability or not. Nevertheless, by tweaking the $\epsilon$ radius one can determine how these cases are treated by the clustering algorithm. For the following comparison with other tools we have chosen $\epsilon = 0.1$, resulting in 8 different clusters and less than 10 outliers in the noise group. **Comparison With Other Approaches:** For further evaluation of our results, we compared them against those from the PDF analysis framework Wepawet [9]. This tool combines machine learning techniques with emulation and uses signatures of known CVEs to classify malicious documents and labels them appropriately. Note that many PDF documents do not only exploit one single vulnerability. Instead, they trigger different exploits, depending on the used PDF viewer application. For those samples Wepawet may not only generate one single label, but in- stead output a list of several CVEs. Furthermore, sometimes no known exploit can be detected at all and no label is generated. We have analyzed each sample with Wepawet, which resulted in seven different detected vulnerability signatures (CVE-2007-5659, CVE-2010-2883, SA33901, CVE-2009-0927, CVE-2009-4324, CVE-2008-2992, CVE-2010-0188). After removing those CVEs from the resulting list, which only address exploits of Acrobat Reader versions other than 9.00, we are left with only five vulnerabilities (CVE-2010-2883, SA33901, CVE-2009-0927, CVE-2010-0188, CVE-2009-4324). While most of our clusters have been consistent with the Wepawet results, we found two general differences. First, there was a small number of samples for which Wepawet did not return any CVE number (at least after removing the CVEs that do not affect the used Acrobat version). In contrast, our BT approach was able to successfully cluster those samples into six different clusters. We have manually verified a subset of those samples and learned that other samples from the same cluster seem to exploit the same vulnerability. Second, there have been some outliers that Wepawet detected as being malicious but labeled incorrectly. Again, we were able to manually verify that our clustering has grouped them correctly with other samples that exploited the same vulnerability. **Performance Evaluation:** Obviously, there is a performance impact when using BT. Nevertheless, all of the analyzed PDF documents actually executed their shellcode within a reasonable time: we set an upper limit for each analysis run of ten minutes and all runs finished in this time. More specifically, the fastest analysis took 11 seconds with BT (only 2s without BT), the slowest took 406s (117s without BT), and the average time was 129s (11s without BT). These measurements show that we have encountered a performance degradation factor of around 12 compared to the same system without BT. Apparently, this is magnitudes faster than performing single stepping on a native machine or with the help of hardware-assisted virtualization [11]. **Discussion:** Our clustering approach and its evaluation have some limitations that we need to discuss. First, we cannot preclude that two different vulnerabilities are merged due to the fact that some function pointer is preliminary overwritten by different means, but then later called from the same calling site. If the number of executed branches between modifying the pointer and calling it exceeds a certain amount, our approach is blinded. Second, though we are using a sophisticated loop detection mechanism, that is also able to collapse nested loops with varying loop iterations, it is not perfect and may fail to successfully collapse in certain situations. Finally, the biggest problem arises from the missing known truth about our samples. We are not able to manually analyze thousands of malicious PDF documents and there are no sources capable of delivering trustworthy information about the contained exploit, especially not AV products and other heuristic-based scanners. Therefore, we can only provide accurately generated evaluation data and reason about their validity. However, by comparing our results to those from Wepawet and further manually analyzing selected samples from our set, we are confident that our approach works properly. 5.2 Experiment 2: Enriching BT Logs The aforementioned approach utilizes the BT log data in a straightforward way (i.e., by comparing the instruction addresses of different crashes). The derivable amount of information can be highly enriched by disassembling the particular instructions that are located at the branch sources and destinations. This enriched data can for example be used to detect code related to return-oriented programming (ROP) [41] and reconstruct the performed instruction sequences. Listing 2 shows an example of a BT log enriched with this kind of information where all RET and CALL branches are marked. If a RET without a corresponding CALL is detected, it is labeled as ROP-RET and this heuristic enables us to generically detect ROP code [10]. In the example, we can easily spot how the ROP code abuses existing, legitimate code chunks to prepare and actually perform calls to the API function `CreateFileMappingA` and `MapViewOfSection`. As Listing 2 shows, the BT log is not only enriched by the CALL and RET sites, but our tool for branch tracing also takes advantage of the publicly available debug symbols from Microsoft. Obviously, for files from other vendors, these symbols are typically not available and, hence, it is more complicated to understand the semantics of the called functions and to isolate the root cause of a given vulnerability. Nevertheless, if such a tool is assisted by the (private) debug symbols, it is very easy to identify the actual code locations. Though not explicitly mentioned, we already applied this kind of ROP detection during our first experiment described above. Since we did not want to take the branches of the actual shellcode into account, we had thus removed all branches that occurred before the first ROP call. In total, we found 1,721 samples in our corpus that utilized an initial ROP stage and 3,148 which did not. 5.3 Experiment 3: Practical Delusion Attack with a PDF File Finally we demonstrate a delusion attack with the help of a malicious PDF document. For that purpose, we have generated a specially crafted file that utilizes one of the delusion techniques introduced in Section 3. This document shows a different behavior when executed on a native machine compared to execution in a virtual environment like QEMU (and as a result also in malware analysis frameworks such as BitBlaze [44] or Anubis [3]). We used the Metasploit Framework [37] to create the PDF document. For exploiting the CVE 2010-0188 vulnerability of the Adobe Acrobat Reader 9.00, we chose the exploit/windows/fileformat/adobe/libtiff module. We then created a modified version of the existing payload module windows/messagebox, in which we utilized the rep movs technique introduced in Section 3.3. The modifications of the payload module are listed in the Appendix B and the PDF document itself can be downloaded from http://bit.ly/xtgRBE. We have analyzed this PDF document with the help of Anubis (which is based on QEMU) as well as with our BT approach. As expected, the malicious functionality (in our case just a simple message dialog) was only triggered when the document was opened on a real machine. Within the emulator, the PDF viewer simply closed and did not show any suspicious behavior. More precisely, it is not possible to achieve any insights into the malicious functionality since no such functionality is triggered at all. Note that even powerful analysis approaches like multi-path execution [30] cannot spot suspicious code regions since there is no explicit branch that is generally not taken during emulation. By using branch tracing, we were able to successfully observe and analyze the PDF shellcode. 6 Limitations In this section we discuss the limitations of BT in general and of our specific prototype. First, the data obtainable by BT is rather coarse. Only the source and destination addresses of program branches and no information about runtime memory or register values can be gathered. Nevertheless, this is sufficient to reconstruct the complete execution path of an application. Section 5.1 demonstrates how this kind of information can be used to generate reasonable and useful analysis results. One way to increase the quality of the BT logs is to enrich them with disassembly information as we have shown in Section 5.2. Another concern is the robustness of our approach against detection and evasion. Our current prototype could be detected by applying timing measurements to observe the introduced performance penalty. If the attacker is operating in ring-0, she is further able to deactivate or manipulate the BT settings directly. Besides deactivating the tracing feature there is no way to circumvent it, since the logging is done by the CPU itself. Nevertheless, these are drawbacks of our current implementation and could be addressed by incorporating a hardware-assisted hypervisor. With that help each read or write access of the related MSRs or the time stamp counter could be detected and simulated. However, incorporating external timing sources still allows to reveal the existence of BT, a general limitation that we share with all other automated analysis frameworks [3,11,44]. 7 Conclusion To obtain a detailed understanding of the behavior of exploits and malicious software, many different analysis techniques and frameworks have been developed in the past few years. A huge fraction of these systems is based on the utilization of software emulators since emulators enable a fine-grained control over the sample. As a result, attackers have constantly developed new methods and techniques to detect such analysis frameworks and armored their malicious programs appropriately. In this paper, we have presented new ways how an attacker can delude an emulator. Unlike other contemporary detection techniques our methods do not combine an explicit environment check with a conditional branch. Instead they constitute implicitly different behavior on a native compared to an emulated machine caused by drawbacks of the particular operations and imperfections in the emulation process that cannot be mitigated easily. This kind of delusion attacks motivates a new approach for dynamic code analysis: CPU-assisted branch tracing. This technique offers a granularity between instruction- and function-level monitoring and can be realized with reasonable performance overhead. In our view, the greatest advantage is the fact that the logging is performed by the processor itself and, hence, cannot be deluded since we obtain information about the actual executions performed by the CPU. In several practical experiments we showed that the obtained BT traces contain enough information to assist different tasks in malware analysis and vulnerability research. Acknowledgement This work was supported by the Ministry of Economic Affairs and Energy of the State of North Rhine-Westphalia (grant 315-43-02/2-005-WFBO-009) and the German Federal Ministry of Education and Research (BMBF grant 01BY1205A – JSAgents and BMBF grant 16BY1207B – iTES). References Figure 6: IA32_DEBUGCTL Model Specific Registers of the Intel Core architecture [18]. Figure 6 shows the individual bits of the IA32_DEBUGCTL Model Specific Register. The functionality (single-stepping on branches, last branch recording, etc.) can be enabled by setting the corresponding bit in this register. Figure 7 shows the format of a Branch Trace Message that is generated and stored each time a branch is taken. B Modified Payload Module Listing 3 shows the modifications of the windows/messagebox Metasploit module implemented for our delusion attack with a malicious PDF file. The extended payload now calls a new function `differ` that either directly returns (on a real machine) or terminates the running process (on an emulated one). This is achieved by using the `rep movs` technique introduced in Section 3.3 to overwrite the saved return address on the stack when running within an emulator. Figure 7: Format of a Branch Trace Message (BTM) for x64 systems [18]. Listing 3: Modified Metasploit Payload Module
{"Source-Url": "https://www.syssec.ruhr-uni-bochum.de/media/emma/veroeffentlichungen/2012/12/04/TR-HGI-2012-001.pdf", "len_cl100k_base": 13411, "olmocr-version": "0.1.53", "pdf-total-pages": 22, "total-fallback-pages": 0, "total-input-tokens": 56261, "total-output-tokens": 16878, "length": "2e13", "weborganizer": {"__label__adult": 0.0006170272827148438, "__label__art_design": 0.0005407333374023438, "__label__crime_law": 0.0028629302978515625, "__label__education_jobs": 0.0007386207580566406, "__label__entertainment": 0.00016510486602783203, "__label__fashion_beauty": 0.00026535987854003906, "__label__finance_business": 0.0002532005310058594, "__label__food_dining": 0.0003943443298339844, "__label__games": 0.0019092559814453125, "__label__hardware": 0.0102081298828125, "__label__health": 0.0006103515625, "__label__history": 0.0004839897155761719, "__label__home_hobbies": 0.00018644332885742188, "__label__industrial": 0.0011692047119140625, "__label__literature": 0.0003917217254638672, "__label__politics": 0.0004582405090332031, "__label__religion": 0.0006384849548339844, "__label__science_tech": 0.2440185546875, "__label__social_life": 0.00010406970977783204, "__label__software": 0.03765869140625, "__label__software_dev": 0.6953125, "__label__sports_fitness": 0.00031065940856933594, "__label__transportation": 0.0005993843078613281, "__label__travel": 0.00019729137420654297}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 74536, 0.0325]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 74536, 0.48678]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 74536, 0.92275]], "google_gemma-3-12b-it_contains_pii": [[0, 0, null], [0, 3727, false], [3727, 8442, null], [8442, 12205, null], [12205, 16861, null], [16861, 21026, null], [21026, 25321, null], [25321, 28597, null], [28597, 32172, null], [32172, 34580, null], [34580, 38993, null], [38993, 43298, null], [43298, 47796, null], [47796, 52364, null], [52364, 55474, null], [55474, 59804, null], [59804, 62528, null], [62528, 66241, null], [66241, 69734, null], [69734, 73508, null], [73508, 74419, null], [74419, 74536, null]], "google_gemma-3-12b-it_is_public_document": [[0, 0, null], [0, 3727, true], [3727, 8442, null], [8442, 12205, null], [12205, 16861, null], [16861, 21026, null], [21026, 25321, null], [25321, 28597, null], [28597, 32172, null], [32172, 34580, null], [34580, 38993, null], [38993, 43298, null], [43298, 47796, null], [47796, 52364, null], [52364, 55474, null], [55474, 59804, null], [59804, 62528, null], [62528, 66241, null], [66241, 69734, null], [69734, 73508, null], [73508, 74419, null], [74419, 74536, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 74536, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 74536, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 74536, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 74536, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 74536, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 74536, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 74536, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 74536, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 74536, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 74536, null]], "pdf_page_numbers": [[0, 0, 1], [0, 3727, 2], [3727, 8442, 3], [8442, 12205, 4], [12205, 16861, 5], [16861, 21026, 6], [21026, 25321, 7], [25321, 28597, 8], [28597, 32172, 9], [32172, 34580, 10], [34580, 38993, 11], [38993, 43298, 12], [43298, 47796, 13], [47796, 52364, 14], [52364, 55474, 15], [55474, 59804, 16], [59804, 62528, 17], [62528, 66241, 18], [66241, 69734, 19], [69734, 73508, 20], [73508, 74419, 21], [74419, 74536, 22]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 74536, 0.02646]]}
olmocr_science_pdfs
2024-12-06
2024-12-06
b1cf600395014ac00b6879c47f18b08604a778cd
[REMOVED]
{"Source-Url": "http://www.fit.vutbr.cz/~lengal/pub/tacas17-ws1s-lazy.pdf", "len_cl100k_base": 14636, "olmocr-version": "0.1.53", "pdf-total-pages": 17, "total-fallback-pages": 0, "total-input-tokens": 68218, "total-output-tokens": 17283, "length": "2e13", "weborganizer": {"__label__adult": 0.0004949569702148438, "__label__art_design": 0.000820159912109375, "__label__crime_law": 0.0005021095275878906, "__label__education_jobs": 0.0015745162963867188, "__label__entertainment": 0.0002346038818359375, "__label__fashion_beauty": 0.0002903938293457031, "__label__finance_business": 0.00043082237243652344, "__label__food_dining": 0.0006680488586425781, "__label__games": 0.0014400482177734375, "__label__hardware": 0.0015115737915039062, "__label__health": 0.0009102821350097656, "__label__history": 0.0006375312805175781, "__label__home_hobbies": 0.00021719932556152344, "__label__industrial": 0.0010595321655273438, "__label__literature": 0.0011396408081054688, "__label__politics": 0.0005574226379394531, "__label__religion": 0.0009975433349609375, "__label__science_tech": 0.393798828125, "__label__social_life": 0.00017058849334716797, "__label__software": 0.00878143310546875, "__label__software_dev": 0.58203125, "__label__sports_fitness": 0.0003960132598876953, "__label__transportation": 0.001125335693359375, "__label__travel": 0.0002799034118652344}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 60383, 0.05747]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 60383, 0.61431]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 60383, 0.87627]], "google_gemma-3-12b-it_contains_pii": [[0, 3397, false], [3397, 7561, null], [7561, 11371, null], [11371, 15146, null], [15146, 20472, null], [20472, 24812, null], [24812, 28242, null], [28242, 30191, null], [30191, 33813, null], [33813, 37163, null], [37163, 40884, null], [40884, 44701, null], [44701, 48539, null], [48539, 53158, null], [53158, 56151, null], [56151, 59496, null], [59496, 60383, null]], "google_gemma-3-12b-it_is_public_document": [[0, 3397, true], [3397, 7561, null], [7561, 11371, null], [11371, 15146, null], [15146, 20472, null], [20472, 24812, null], [24812, 28242, null], [28242, 30191, null], [30191, 33813, null], [33813, 37163, null], [37163, 40884, null], [40884, 44701, null], [44701, 48539, null], [48539, 53158, null], [53158, 56151, null], [56151, 59496, null], [59496, 60383, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 60383, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 60383, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 60383, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 60383, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 60383, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 60383, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 60383, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 60383, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 60383, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 60383, null]], "pdf_page_numbers": [[0, 3397, 1], [3397, 7561, 2], [7561, 11371, 3], [11371, 15146, 4], [15146, 20472, 5], [20472, 24812, 6], [24812, 28242, 7], [28242, 30191, 8], [30191, 33813, 9], [33813, 37163, 10], [37163, 40884, 11], [40884, 44701, 12], [44701, 48539, 13], [48539, 53158, 14], [53158, 56151, 15], [56151, 59496, 16], [59496, 60383, 17]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 60383, 0.12583]]}
olmocr_science_pdfs
2024-12-09
2024-12-09
7e142670b75373c63a57ac50a18a0cdae1436f9e
Assessing PSP effect in training disciplined software development: A Plan–Track–Review model Wen-Hsiang Shen a, Nien-Lin Hsueh a, Wei-Mann Lee b,* a Department of Information Engineering and Computer Science, Feng Chia University, 100 Wenhwa Road, Taichung 40724, Taiwan, ROC b Department of Information Technology, The Overseas Chinese University, 100 Chiaokwong Road, Taichung 40721, Taiwan, ROC A R T I C L E I N F O Article history: Received 17 November 2009 Received in revised form 2 August 2010 Accepted 28 September 2010 Available online xxxx Keywords: Personal software process (PSP) Software process improvement (SPI) Effect assessment Plan–Track–Review A B S T R A C T Context: In training disciplined software development, the PSP is said to result in such effect as increased estimation accuracy, better software quality, earlier defect detection, and improved productivity. But a systematic mechanism that can be easily adopted to assess and interpret PSP effect is scarce within the existing literature. Objective: The purpose of this study is to explore the possibility of devising a feasible assessment model that ties up critical software engineering values with the pertinent PSP metrics. Method: A systematic review of the literature was conducted to establish such an assessment model (we called a Plan–Track–Review model). Both mean and median approaches along with a set of simplified procedures were used to assess the commonly accepted PSP training effects. A set of statistical analyses further followed to increase understanding of the relationships among the PSP metrics and to help interpret the application results. Results: Based on the results of this study, PSP training effect on the controllability, manageability, and reliability of a software engineer is quite positive and largely consistent with the literature. However, its effect on one's predictability on project in general (and on project size in particular) is not implied as said in the literature. As for one's overall project efficiency, our results show a moderate improvement. Our initial finding also suggests that a prior stage PSP effect could have an impact on later stage training outcomes. Conclusion: It is concluded that this Plan–Track–Review model with the associated framework can be used to assess PSP effect regarding a disciplined software development. The generated summary report serves to provide useful feedback for both PSP instructors and students based on internal as well as external standards. © 2010 Elsevier B.V. All rights reserved. 1. Introduction Ever since its introduction by Humphrey at the Software Engineering Institute (SEI) in 1995, the personal software process (PSP) has been adopted and proven effective in software engineering training in both academic and industrial environments [1]. Its effects, in terms of software process improvement (SPI), include better project estimation accuracy, fewer defects, defects caught earlier, and improved productivity [2–4]. When PSP is used on campus, it can not only motivate students, benefit instructors, but also be adopted in both undergraduate and graduate software engineering courses [4–7]. Some even argue that with a modest disciplined SPI, a substantial effect can be generated from PSP training [8–10]. Regardless of these positive effects, however, earlier PSP studies also suggest that the PSP has such drawbacks as tedious logging tasks, data being error-prone, and a need for tailored adaptation. For example, as students must record their estimated program size, time, and number of defects for each program assignment, the motivation tends to be lowered, and thus leading to a loss of data integrity and authenticity. Besides, a full 2-week training period would be either infeasible or less cost-effective in the industrial arena. Although tailored PSP adaptation may be reinforced, still other consequences like ease of use, discounted effectiveness, instructor loading, and student privacy issues can arise and thus hinder its widespread diffusion [11–14]. While this diffusion puzzle remains unresolved, the more recent PSP studies were also interested in the investigation of disciplined software engineering values and how they might be developed via PSP training [15,16]. Needless to say, these efforts are not easy. Since the PSP is involved with numerous measures and each one of them may occur in only certain phases or aspects, the researchers’ approaches and methodologies used in PSP effect assessment vary tremendously. For example, from a project management approach, researchers tend to focus on estimation accuracy related PSP measures [14,17]. But when taking from the software quality perspective, researchers place more attention on defect related examinations [18–20]. Aiming at resolving these issues, the following research questions can guide and limit the scope of this study: 1. In what way should the PSP issue be approached and exactly what software engineering goals can be reached by PSP training? 2. Which software engineering values and PSP metrics should be used to assess the said PSP effect? 3. How can these measures be assessed accurately and later interpreted with meaningful feedback for PSP users? To accomplish these goals, the rest of this paper is organized as follows: Section 2 addresses the theoretical framework based on a systematic review of the related literature that might derive an appropriate effect assessment model. Section 3 describes the PSP system and the methodologies used to test this model. Section 4 presents the result of PSP effect. Section 5 discusses the implications that might be derived from the result. Section 6 concludes the research with suggested future studies. 2. Theoretical framework 2.1. PSP and the industrial software engineering standards Based on the standards like those of capacity maturity model (CMM) and ISO9001 that are used to certify a software company, the PSP can be considered as its equivalent on an individual basis. In [21], Paulk compares ISO9001 with CMM and finds a number of similarities between the two standards. Among them, the bottom line is “to say what you do; to do what you say.” While these requirement definition and documentation work typifies the behavior of a disciplined software engineer in the industry, it could be easily achieved by a training tool like the PSP where it relies on “a well-defined, planned, and measured” process approach [22]. But, what a software company demands on its engineers is a lot more than the baseline discipline. As seen in a longitudinal study of an effective SPI assessment, six factors are considered critical [23]. They include budgeting, scheduling, quality, productivity, customer satisfaction, and employee satisfaction. While the last two measures belong to the long-term goals of TQM and may rely on tools like TSP and CMM, the first four goals can be met by PSP training since it can result in such effects as “better estimation accuracy, improved process and product quality, and increased productivity” [4]. As CMM (initially designed to assess the maturity of software development process) can be used to improve the software process of a large company [24,25], the PSP can also be equally effective in small and median sized business firms [as seen in (26,27)]. Even when IT has evolved rapidly in the last decade, the PSP remains a current and an effective SPI tool in both industrial and academic environments. As seen in [28], both the PSP (a process-based approach) and the agile method (like Extreme Programming, Scrum, Crystal, a people-based approach) can be successfully adopted in the modern world to improve software quality and productivity. Studies in the academia also indicate that the PSP can not only fit in a “traditional” software engineering curriculum [7], but could also be appreciated by the “net” generation when real-world scenarios are incorporated into the course [29]. 2.2. PSP life cycle phases in a stage-wise view As the life cycle phases of PSP (see Fig. 1) evolve from the baseline personal process level to project management, quality management, and the cyclic integration level, the effect of a disciplined software process also occurs on a gradual basis. To better understand the training effect in terms of engineering values, it would be more crystallized by scaling them down into the Plan–Organize, the Track–Manage, and the Review–Optimize stages. Similar to Hilburn’s term of “organize and plan,” the first (Plan–Organize) stage demands software developers to define, measure, and prioritize target tasks in order to prepare and establish the baseline for later software process improvement [30,22]. These training tasks of estimation, planning, and scheduling, when viewed from the industrial or the cost effectiveness perspectives can foster such engineering values as measurability (or scalability) and predictability (even precision) [11,14,30]. Since creativity may also need to build on discipline and planning can lead to software efficiency and superiority, these disciplined software development values must be trained for each software individual in the initial Plan and Organize stage [2]. In the Track–Manage stage, as Hilburn terms “performance tracking and quality management,” the engineering skills deal not only with the identification of the number, type, and whereabouts of defects, but also with the skill of removing them (i.e. debugging on a program basis) to better manage and control the cost of software quality [30,31]. The engineering values that can be developed from this stage through PSP training, therefore, are traceability and controllability of defects and manageability of software process. In association with the CMM level, these values establish an engineer’s foundation to reaching the second CMM equivalent (the managed) level on a personal basis. In the Review–Optimize stage, it essentially deals with PSP tasks like design review, code review, and postmortems. The engineering values addressed in this stage are reliability and efficiency. In stead of a product based approach, both of these values are considered in a process based sense with the belief that efficient and superior process and methodology can actually be developed via series of reviews and analyses of PSP templates and reports. When these skills are equipped, engineers can not only deliver software product with quality assurance, but also increase the potentiality of reaching the highest CMM level (the optimized, on an organization basis) [1,32]. Although the terms of “track & review” may often be linked together (just as Plan and Track sometimes are), for the purpose of this study, it is necessary to separate these terms to delineate and help to inspect the PSP effects as they evolve throughout the life cycle phases. While the stage-wise approach encompasses all three stages, those engineering values not directly derived from PSP training (like prior knowledge and skills) or may derive from which only after a successive adoption of it (like persistency) are beyond the scope of this study. 2.3. Pertinent PSP metrics According to Humphrey and Hayes [3,33], there are only three basic PSP measures: size, time, and defects. All other PSP measures are derived from these basic measures. For the purpose of this study, the terms of PSP metrics (or variables) are hereby defined and categorized with respect to the goals of a disciplined software development process. The detailed list is seen in Table 1. Within the literature, estimation related PSP effect measures are identified as SEA, TEA, and DEA. Of these measures, SEA refers to the estimation accuracy of program size, TEA to that of program development time, and DEA for defects [3,16,33]. While the estimation accuracy measures serve as indicators of an engineer’s ability to measure and predict software development, his or her ability to complete a project within the deadline is also critical in PSP effect assessment. Borrowing from Prechelt’s estimation accuracy calculation method [36], a fourth estimation measure APR, meaning the ratio of actual time to planned time, is further added to the list. The inclusion of the APR measure is also consistent with Humphrey’s earned value concept and Boehm’s COCOMO model and GOALS concepts [37,38]. In addition to predictability, measures that depart from the defect perspective including DRR, YLD, and DDS are also identified as crucial in PSP effect assessment. Whereas DRR refers to the ratio of defects removed during the compile and test time, YLD refers to the percent of defects removed before the first compile, and DDS represents total defects removed per thousand lines of code (as defect density) [3,20]. For final PSP effect assessment, LPH (defined as lines of code per hour) and AFR (as prior to post effort ratio) must also be included as pertinent effect measures that depict process review results. As disciplined software engineers must show capabilities of managing defects and processes, such productivity efficiency (LPH) and total quality management (AFR) indicators can best describe if they possess the proficiency in developing a disciplined software product. The references attached on the rightmost column in Table 1 serve to support the above discussion. Still other factors like individual capability factors of coding, knowledge of software engineering, and the review rate (another PSP measure for lines of code reviewed per hour) are also considered as crucial in PSP effect assessment by the researchers [10,15,34]. However, since these factors are either later found insignificant in SPI assessment or hardly trainable in a single PSP life cycle, they are excluded from the list of this study. ### Table 1 <table> <thead> <tr> <th>Measure</th> <th>Definition</th> <th>Implied capability</th> <th>Engineering value</th> <th>References</th> </tr> </thead> <tbody> <tr> <td>SEA</td> <td>Size estimation accuracy</td> <td>Ability to measure software size</td> <td>Measurability</td> <td>[3,9,16,33,34]</td> </tr> <tr> <td>TEA</td> <td>Time estimation accuracy</td> <td>Ability to predict development time</td> <td>Predictability</td> <td>[3,16,33,34]</td> </tr> <tr> <td>APR</td> <td>Actual time to plan time ratio</td> <td>Ability to meet project deadline</td> <td>Predictability/controllability/traceability</td> <td>Researcher developed</td> </tr> <tr> <td>DEA</td> <td>Defect estimation accuracy</td> <td>Ability to predict defect frequency</td> <td>Controlability</td> <td>[3,16,30,33,35]</td> </tr> <tr> <td>DRR</td> <td>Defect remove rate in compile and test phase</td> <td>Ability to decrease defect in compile and test</td> <td>Manageability</td> <td>[3,16,30,33,35]</td> </tr> <tr> <td>YLD</td> <td>Yield in percent of defects injected before the first compile that are removed before the first compile</td> <td>Ability to control defect emergence</td> <td>Manageability</td> <td>[3,16,30,33,35]</td> </tr> <tr> <td>DDS</td> <td>Number of defects removed per thousand lines of code developed</td> <td>Ability to decrease defect density</td> <td>Reliability</td> <td>[3,11,33–35]</td> </tr> <tr> <td>LPH</td> <td>Total new and changed LOC developed divided by the total development hours</td> <td>Ability to increase productivity</td> <td>Efficiency</td> <td>[3,9,16,30,35]</td> </tr> <tr> <td>AFR</td> <td>Time spent in design review and code review as a percentage of time spent in compile and test</td> <td>Ability to manage risk</td> <td>Reliability/efficiency</td> <td>[3,8,30,33,35]</td> </tr> </tbody> </table> ### Table 2 <table> <thead> <tr> <th>Stage</th> <th>Entry level</th> <th>Intermediate level</th> <th>Exit level</th> </tr> </thead> <tbody> <tr> <td>Plan</td> <td>SEA</td> <td>TEA</td> <td>APR</td> </tr> <tr> <td>Track</td> <td>DEA</td> <td>DRR</td> <td>YLD</td> </tr> <tr> <td>Review</td> <td>DDS</td> <td>LPH</td> <td>AFR</td> </tr> </tbody> </table> Based on the previous discussion, a Plan–Track–Review model with the associated PSP effect measures can be organized in Table 2. The cross-wise measures are arranged with respect to the Plan, Track, and Review–optimize categories with varying degrees of engineering value for each stage. In the Plan stage, PSP tasks including requirement definition, code standard setup, and program size and development time estimation are assessed. The goal of this stage is to improve an engineer’s capability of measurability, predictability and precision... pertaining to his or her software process development. Therefore, the PSP effect measures that fit to this stage include SEA, TEA, and APR, where SEA can be viewed as an entering assessing measure for planning and APR an exiting measure for this planning stage. As for the Track stage, though some effect may foster from PSP tasks of coding, compile, and testing, the specific effect examination is focused on credits of defect estimation, identification, and its removal. With this respect, engineering values in this stage are involved with defect traceability and controllability, and process manageability. The associated PSP effect measures are, therefore, DEA, DRR, and YLD. The Review stage deals essentially with the effects of design review and code review. Since both software quality and productivity must be assessed at this time, the engineering values of process reliability and efficiency are considered, leading to the inclusion of such PSP metrics as DDS, LPH, and AFR. Within this stage, DDS is viewed as an entering variable and an initial assessment measure on overall software quality, LPH on productivity, and AFR on review efficiency (also an exiting measure that concludes all PSP life cycle phases). In comparison with Hayes’ life cycle segmentation [3], the Plan–Track–Review model is a much simpler one. Literally, this term resembles such terms used in the literature as Plan–Design–Review in [2], Plan–Implementation–Maintenance in [31], and Plan–Track–Analyze in [5]. In essence, our model is much consistent with the life cycle phases described in Boehm’s spiral model. Viewing from the project management field, our model is similar in many ways with Deming’s Plan–Do–Study–Act cycle and a modified version by Hamilton called Plan–Do–Check–Act cycle [39]. In addition, regarding PSP effect assessment, a Plan–Track–Review model application can be helpful in understanding the stage-wise PSP effect and in delineating credits from among trainers, trainees, and PSP as a training tool. 2.5. The assessment methodologies and the criteria reference Understanding and interpreting PSP training effect is one thing; the deriving of a unified scheme that can accurately assess PSP effect is quite another. Regarding PSP effect assessment, several quandaries need to be overcome. Among which, the first problem is to decide whether we should apply a group or an individual approach and to decide the choice of data ranges. Within the existing literature, the majority of empirical studies rely on the methodologies used by Hayes and Over [3] and Wesslén [4]. According to Hayes, the PSP is designed for individual software engineers and its performance should be examined on an individual basis from level to level [3]. Although group trend can better present the overall effect growth, it is the individual progress that counts. However, since PSP0 through PSP2 phases use aggregate means while PSP3 uses only one assignment data, it would be more logical to apply a comparison of PSP0 with PSP2 than that of PSP0 with PSP3. The second problem is about the calculation of estimation accuracy related variables that interpret the degrees to which the estimates match the actual results. These variables are involved with all estimation metrics, including program size, process time, and defects. As a general rule of thumb, the estimation calculation method also applies for all of these metrics. However, the methods used for these calculations are quite inconsistent in the literature. For example, as Humphrey [33,37] uses the calculation formula of \[ \text{Estimation accuracy} = \frac{(\text{Actual} - \text{Planned})}{\text{Planned}}. \] Hayes and Over [3] use \[ \text{Estimation accuracy} = \frac{(\text{Planned} - \text{Actual})}{\text{Planned}}. \] Although the second formula gives more intuitive understanding of the signs of overestimation (a plus) and underestimation (a minus), its associated result interpretation should be treated cautiously to avoid a confusion. That is, when Kamatar and Hayes [17] describe their estimation accuracy of 6.7% overestimate, the percentage is a minus in Humphrey’s calculation, but a plus in Hayes’. Still Prechelt and Unger [36] uses a third formula by calculating the quotient of actual and planned measures to obtain his size estimation accuracy value in a percentage ratio form. The assessing criteria bring a third problem. While it is customary to adopt statistical significances as criteria for assessment, some researchers prefer experiential cuts for PSP effect results. For example, researchers use a greater than 2 for AFR, within an approximation range of ±20%, or simply a group yield (YLD in this paper) of 40%. Among the empirical studies, perhaps Hayes’ Median Improvement Factor method can be adopted best as an improvement reference in that a median refers to a ratio of more than fifty percent and the improvement factor value is explanatory in itself. Based on the literature, a set of tendency criteria for nine PSP effect variables with associated references is given in Table 3. More detailed issues including the result presentation and interpretation are discussed in the following sections. 3. Methodology 3.1. Course setting and data collection The empirical study was taken during Fall, 2008 with a sample size of 16 graduate students in an 18-week PSP course. Among the subjects, 13 were master level and 3 were doctoral level students. The course was a dedicated PSP course with the objective of training students in establishing software engineering discipline for their future software project development work. Within the 18 weeks, the first 4 weeks covered the baseline PSP concepts, the logging methods, and the code standard setups. The following 10 weeks were used for program development with discussion on topics that occurred from PSP0 thru PSP3. The remaining 4 weeks were used for report generation and feedbacks. In the PSP course, all students were required to fulfill Humphrey’s 10-assignment programs. As their programming languages, fourteen subjects wrote in Java and two in C++. The assignment interval is about 1 week off each. Since more than two thirds of the students had part-time jobs and almost all had also other course loadings, the study represents a software development scenario in general (though slightly different from the industry) [20,50]. Upon the completion of the course, PSP data were gleaned with variables calculated following Humphrey and Hayes’ formula with only minor modification needed in this study. A survey (based on concepts from [41–43], in that order) was also distributed and its result collected at the end of the course to further understand student reactions on PSP adoption. To ensure the validity of this study, the students neither had any prior knowledge of this study nor were penalized for their performance. The PSP data used for effect assessment was collected as-is and was organized into three sets to comply with the specific <table> <thead> <tr> <th>Estimation criteria</th> <th>Effect variables</th> <th>References</th> </tr> </thead> <tbody> <tr> <td>Approaching zero</td> <td>SEA, TEA, DEA</td> <td>[3,17,30,33,36,40]</td> </tr> <tr> <td>Decreasing</td> <td>DRR, DDS</td> <td>[2,3,8,30,33,40]</td> </tr> <tr> <td>Increasing</td> <td>YLD, LPH</td> <td>[2,3,17,30,33,40]</td> </tr> <tr> <td>Less than 1</td> <td>APR</td> <td>Researcher developed</td> </tr> <tr> <td>Greater than 2</td> <td>AFR</td> <td>[3,30,33,40]</td> </tr> </tbody> </table> testing ranges. The first set was used to detect if an improvement was present covering three PSP phase levels (from PSP0 to PSP2). The second set takes PSP data between programming assignment seven through nine (i.e. 7A–9A as denoted in the literature and for the rest of this paper) to assess those measures occurred only in PSP2. The third is the whole data set based on aggregate mean for all four PSP phases to explore the relationship among PSP metrics. 3.2. Initial improvement assessments In dealing with PSP effects, most researchers adopt the data as-is and use either a histogram, box-plot, or line chart to display the effect result [2,3,16,30,36,40]. To avoid a biased observation and an erroneous assessment, both mean and median based assessments were used and thus both box-plot charts and line charts were used to describe the distribution and the improvement trends. The rationale is that the box-plot charts can show the distribution and central tendency with medians, but a line chart that uses mean values can better contrast the group effect trend for all measures among the PSP levels. In terms of the interpretation of the estimation accuracy result, an absolute value form (a fourth formula adding to previous discussion) was employed in this study to calculate estimation accuracy variables. That is, a 300% overestimate (~300%) and a 200% underestimate (~200%) was not totaled to ~100% as in Humphrey’s calculation [3], but as a 500% away from hit. Bearing this in mind, three estimation accuracy variables, namely SEA, TEA, and DEA were converted to their absolute value forms and applied a stricter assessment rule throughout this study. While the absolute value approach is justifiable from the industrial standard, it also helps to assess and interpret the improvement result. Within the literature, this stricter calculation approach was first mentioned in Hayes’ study [3], but actually used by Wesslén [4] in estimation-related assessments. 3.3. t-Test and ANOVA While the tendency analysis approach better depicts the effect growth through PSP life cycle phases, a series of t-tests can better judge whether the variables meet the SPI criteria with a statistical significance. Since t-test must compare the pre-test and post-test values under the same scheme, most researchers avoid a comparison between two program assignments. Additionally, an ANOVA approach was used to detect if significant improvement existed in any tow adjacent PSP phase levels (e.g. PSP0–PSP1). As suggested in [44], the phase-level comparison approach with the repeated measures and aggregate means can increase the statistical power of a study. In this study, each PSP effect variable was thus tested except for DEA and AFR which occurred only in PSP2 and PSP3. The range choices for t-test, then, are PSP0 versus PSP2 for seven variables and 7A–9A for two variables (DEA and AFR), both ranges leaving out 10A (or PSP3) as it involves a cyclic integration effect. Technically, the t-test process can also be replaced by the one-way analysis of variance (ANOVA) method in which more paired comparison details can be displayed with a Post-Hoc test. These details, according to Wesslén [4], can be useful in understanding phase-level improvements and in delineating learning effect from process effect. 3.4. Exploring impacts among stages and PSP metrics Although the Plan–Track–Review model is derived from a systematic review of the related literature, its fitness can be exemplified by applying PSP data. Since the subjects of this empirical study setting were homogeneous and the only treatment is a full PSP with all 10-assignment, its application result can be meaningful in examining the model fitness. The verification process involves a series of regression and a path analysis. Whereas the regression analysis is used to test if any later stage variable can be accounted for by previous stage variables, a path analysis diagram is used to help visualize the flow and internal effect among PSP metrics. The data collected from these exploration processes can not only be useful in giving clues to the impacts among PSP effect metrics but also worthwhile in interpreting the application results. Within the process, each later stage variable is tested against all previous stage variables to derive a significant regression model. For example, when DDS is used as a dependent variable, DEA, DRR, YLD, SEA, TEA, and APR are used collectively as independent variables to try out if a significant regression exists. Those significant regressions are then further used to draw a quasi path analysis diagram. Although the purpose varied from those studies which uses path analyses to find an intermediate effect variable [45,46], the method used to derive the result is similar to that of the Partial Least Square method in Green’s study [47]. 3.5. The assessment procedure Finally, a consistent assessment scheme should apply for all nine variables. To exemplify the assessing procedure used in this study, the steps of the simplified and unified procedure are listed as follows: - **step 1**: choose an interval range for each variable, - **step 2**: apply proper test and derive test significances, - **step 3**: compare test result with the expected tendency, - **step 4**: assess if an improvement result existed based on step 3 and step 2, - **step 5**: calculate the median improvement factor for each variable, - **step 6**: interpret the result in engineering values to obtain feedback for each variable, repeat the above steps from 1 through 6 until all variables are assessed. In step 1, it is preferable to adopt a phase interval range than an assignment range to avoid comparison within small size samples. In step 2, either a t-test or ANOVA is applicable, but the t-test significance results should be retained for later reference. In step 3, the expected tendency refers to the improvement directions that are consistent with the literature. Since all estimation accuracy data are now normalized, the uni-directional tendency comparison rule applies to all nine variables. The real assessment begins in step 4, where both tendency and t-test results need to be weighted. The purpose of the fifth step is to obtain a class-peer reference base, where the median improvement factor stands for the behavior of more than half of the subjects [3]. Additionally, external references based on a larger norm can be used as a contrast with the final assessment result. Finally in step 6, the assessment result can be further interpreted in engineering values (see Table 1) to obtain personal or class strength and weakness information for each PSP effect measure. A notion must be made is, one must not literally tie the terms of “increasing” and “decreasing” with the variables defined here in describing an assessment result. For example, since those estimation accuracy related variables (SEA, TEA, and DEA) used in this paper are normalized to absolute values, a decreasing trend means a tendency of approaching to zero and is thus considered as an improvement, not as a “decreased accuracy.” 4. Result findings 4.1. Effect distribution and trend analysis result To exemplify the model application and the feasibility of the simplified assessment procedure, the result of five measures are presented in Figs. 2–6. The rest of the effect measures can also be derived in the same way, but not included here for brevity. In this subsection, two sets of PSP data were used. The first three figures were derived from the data set that covered three PSP phase levels (from PSP0 to PSP2), and the last two (i.e. the result of DEA and AFR effect) used the data set counting from 7A through 9A. The box-plot chart results on the left side display the distribution tendency with median position marks. The right side of the figures, however, presents the result of group trend calculated by aggregate means. It should be noted that on judging if an improvement existed, both charts must be weighed to avoid a possible biased mean resulting from outliers (displayed as whiskers in box-plot charts). As indicated in Fig. 2, the improvement of size estimation accuracy is not visible as the group trend “increased” from PSP0 to PSP2. The effort estimation improvement is also minimal since the group trend decreased only slightly in Fig. 3. The improvement of student capability in meeting schedule (APR, or earned value in Humphrey’s term), however, is quite visible as it declined steadily using leverage at PSP1 where PSP process treatment of schedule planning was introduced. From the box-plot chart side of the three figures, they suggest a relatively stable and consistent behavior of the student progress for all Plan stage training factors but size estimation. As seen on the left side of Figs. 2–4, all boxes are relatively condensed (or slightly dispersed) except for SEA at PSP1 (more loosely dispersed) when size estimation process tool was first introduced and used to improve the guessing result, which could lead to severe project estimation error in an industrial perspective. Another notion is that all three figures assume a positive Y-axis since the estimation accuracy values were converted to absolute values. The assessment method is thus based on a stricter industrial standard rather than the assessment method used in the literature. Specifically, both program size and coding effort estimation should be approaching the zero, and that the ability ratio of meeting schedule should be approaching one. In Figs. 5 and 6, since these two measures existed only in PSP2 and PSP3 levels, the tendency evaluation took 7A–9A as interval range (i.e. based on the second data set). As reflected by both box-plot and line charts in Fig. 5, an improvement of defect estimation is highly visible. Similarly, an improvement of the prior to post effort ratio can also be identified in Fig. 6. In contrasting with the two figures, however, a few interesting phenomena are observed. For example, the boxes of 7A and 9A are smaller for DEA, but their counterparts are larger for AFR. Conversely, the box-plot chart behavior of 8A is quite the opposite to those of 7A and 9A. Finally, we can see that the line chart of Fig. 5 is roughly the reverse to that of Fig. 6. Although these phenomena represent the result from a single application, they can be logically interpreted by the varieties of coding experience, review rate, or learning effect. Whichever interpretation, it should be noted that the results could not be due to process treatment changes as they all occurred in PSP2, where the design and code review process tool was first introduced. The improvement results, in general, are more or less consistent with those appeared in the existing literature. 4.2. ANOVA results with Post-Hoc tests Again in this subsection, the first and the second data sets were used to assess the incremental improvement effects. A series of one-way analysis of variance (ANOVA) were used to detect if a statistically significant improvement was existent for all nine variables. The result indicates that only four measures showed such differences and they are given in Table 4. Again, the phase-level testing rule applies for seven variables and the assignment interval range rule applies for two variables. According to the result of the first three measures in the table, students’ overall defect density, process yield, and defect removal rate had all improved significantly from PSP0 to PSP2. Based on such evidence, it suggests that significant software quality improvement can be achieved through PSP training. The significant defect estimation accuracy improvement result is also consistent with the literature, but under a different assessing range interval from 7A to 9A. The Post-Hoc test results are not presented here. But according to our analyses, the incremental progresses on software quality are basically consistent with the literature. However, the results of incremental progresses on estimation accuracy are largely inconsistent with the literature since no significance was found even... in between PSP0 and PSP2. Although it may be too early to draw a conclusion, but this suggests a longer PSP training period may be needed for project planning and estimation. Within the significant variables, we also find that significant improvement of defect estimation accuracy (DEA) is found only in the 7A–9A pair, but not in two other adjacent pairs. The complete t-test result for all nine variables with associated significances, however, is provided later in Table 6. 4.3. Regression analysis result On regression analyses using each later stage variable as a dependent variable and all previous stage variables as independent (or predicting) variables, four significant regressions were found and the result summary is given in Table 5. During the regression analyses, all variable values were counted throughout the four PSP life cycle levels (i.e. using the third data set of this study). Since each observation used in a regression analysis took all variables at a given time, the collective relationship between any two variables in terms of former to later stage predictability becomes meaningful. But, any other forwarding or mixed (inter- or intra-) stage regression would be impractical in analyzing the existence of former stage impact on later stage PSP effect metrics. As indicated in the table, all four models are significant and that each dependent variable can be statistically accountable by its previous stage variables. That is, the dependent variables can be predicted by using previous stage independent variables. On further inspection of the statistically significant coefficients of predicting variables for each regression model, a series of regression equations are derived as follows: \[ \begin{align*} AFR & = 0.009 \times \text{DEA} + 0.004 \times \text{DRR} + 0.407 \\ LPH & = 0.093 \times \text{YLD} + 0.083 \times \text{DRR} + 0.148 \times \text{SEA} + 0.3304 \\ DDS & = 0.162 \times \text{YLD} + 0.997 \times \text{DRR} + 0.221 \times \text{DEA} + 0.4156 \\ DRR & = 0.54656 \times \text{APR} + 0.501 \times \text{SEA} + 0.22242 \end{align*} \] From Eq. (3), only DEA and DRR are identified as significant predictors, suggesting that one’s behavior of defect estimation and remove rate can significantly affect his/her prior to post effort ratio. In Eq. (4), it suggests that one’s productivity can be determined by one’s defect yield, defect remove rate, and even size estimation accuracy. This is logical as one’s former period ability to accurately predict project size could also affect his/her later period productivity. ![Fig. 6. Box plot and line charts for appraisal–failure ratio trend.](image) <table> <thead> <tr> <th>Variable</th> <th>Interval range</th> <th>df</th> <th>( F )</th> <th>( p )</th> </tr> </thead> <tbody> <tr> <td>DDS</td> <td>PSP0–PSP2</td> <td>(2.45)</td> <td>9.106</td> <td>&lt;0.001</td> </tr> <tr> <td>YLD</td> <td>PSP0–PSP2</td> <td>(2.45)</td> <td>35.637</td> <td>&lt;0.001</td> </tr> <tr> <td>DRR</td> <td>PSP0–PSP2</td> <td>(2.45)</td> <td>12.634</td> <td>&lt;0.001</td> </tr> <tr> <td>DEA</td> <td>AID7–AID9</td> <td>(2.45)</td> <td>3.978</td> <td>0.026</td> </tr> </tbody> </table> Table 5 <table> <thead> <tr> <th>Dependent variable</th> <th>Predicting variables</th> <th>( R^2 )</th> <th>( p )</th> </tr> </thead> <tbody> <tr> <td>AFR</td> <td>DEA, DRR, YLD, SEA, TEA, APR</td> <td>0.332</td> <td>0.001</td> </tr> <tr> <td>LPH</td> <td>DEA, DRR, YLD, SEA, TEA, APR</td> <td>0.319</td> <td>0.001</td> </tr> <tr> <td>DDS</td> <td>DEA, DRR, YLD, SEA, TEA, APR</td> <td>0.130</td> <td>0.038</td> </tr> <tr> <td>DRR</td> <td>DEA, DRR, YLD, SEA, TEA, APR</td> <td>0.349</td> <td>0.001</td> </tr> </tbody> </table> Table 6 <table> <thead> <tr> <th>Stage</th> <th>Variable</th> <th>Mean-based result (this study)</th> <th>Median based result and external references</th> </tr> </thead> <tbody> <tr> <td></td> <td></td> <td>Progress trend</td> <td>Significance</td> </tr> <tr> <td>Plan</td> <td>SEA</td> <td>13.2 → 20.5</td> <td>–</td> </tr> <tr> <td></td> <td>TEA</td> <td>29.8 → 26.2</td> <td>–</td> </tr> <tr> <td></td> <td>APR</td> <td>1.16 → 1.01</td> <td>–</td> </tr> <tr> <td>Track</td> <td>DEA</td> <td>63.6 → 25.0</td> <td>.010*</td> </tr> <tr> <td></td> <td>DRR</td> <td>119.2 → 43.6</td> <td>&lt;0.001**</td> </tr> <tr> <td></td> <td>YLD</td> <td>5.7 → 47.9</td> <td>&lt;0.001**</td> </tr> <tr> <td>Review</td> <td>DDS</td> <td>121.8 → 70.9</td> <td>.015*</td> </tr> <tr> <td></td> <td>LPH</td> <td>23.1 → 24.9</td> <td>–</td> </tr> <tr> <td></td> <td>AFR</td> <td>1.12 → 1.15</td> <td>–</td> </tr> </tbody> </table> * Stands for \( p < .05 \). ** Stands for \( p < .001 \). In Eq. (5), all three attributes in the Track stage (but none from the Plan stage) have a significant impact on DDS, suggesting the overall quality effect may be strongly based on one’s Track stage performance. The sixth equation is an interesting one since the result indicates that the defect remove rate is predictable by both the size and an alternate time estimation measure, which lends support to a possible carry over effect from the Plan stage to the Track stage. However, the small accountability ($R^2 = 0.130$) also gives clues that a wide range of other factors including individual knowledge and experience \[34,49\] are yet missing in our Plan stage. 4.4. The path analysis diagram To further understand the meaning of the regression analysis result, a quasi path analysis diagram is drawn in Fig. 7. For clarity’s sake, all paths drawn here bear significance and those not are discarded. Each $R^2$ labeled underneath its associated effect variable represents a goodness of fit. The asterisks along with the path coefficients indicate their significance levels in which one asterisk represents for $p < 0.05$, two asterisks for $p < 0.01$ and three for $p < 0.001$. As indicated by the path coefficients in the diagram, when DRR decreases, DDS will decrease as well, but LPH and AFR will increase. This is consistent with the literature in that as the defect ratio of compile-test phase gets smaller, the overall defect density will also decrease, and in turn this promotes the productivity and consequently the prior to post effort ratio tends to go high. Within the diagram, the most robust regression model can be seen in the DDS pattern, to which three contributing variables (DEA, DRR, and YLD) together can interpret the total variance to 94.9%. Although there remain a dangling TEA and some intuitively paradoxical paths (e.g. from SEA to LPH), the diagram itself can roughly reflect the dynamics of the stage pattern and the effect relationships that lie within. 4.5. PSP effect result summary The overall PSP effect result summary is given in Table 6, which includes both mean and median based assessment results. The mean portion is comprised of student progress trend and its improvement with statistical significance (if any). The median based improvements are based on their median improvement factors with both internal (i.e. this study) and external (Wesslén’s in 2000, and Hayes’ in 1997) references. As indicated in the report, software quality-related PSP effect is obvious as all four variables (DEA, DRR, YLD, DDS) matched the SPI criteria with statistical significance. But other improvements are less obvious as they either did not improve or improved with no statistical significance. The improvement results of two other sub-quality factors extracting from the DRR measure, namely the DRRC and DRRT (as indicators of process quality and product quality respectively \[3,4\]), are not included. The mean results of these measures are the same with the two studies, and the median counterpart is also more or less comparable with the external reference results. Viewing from the median based assessment result in the table, more than 50% of the students improved with a median improvement factor greater than one for all effect measures but SEA (0.67, as indicated in parentheses). Although this result neither supports nor denies the commonly accepted PSP training effect, the result suggests that at least half of the students improved on eight out of nine software engineering goals through this training. Weighing from the Plan–Track–Review perspective, the results suggest, in general, that the students performed well in the Track stage, only moderately in the Review stage, and poorly in the Plan stage. When these results are further interpreted in terms of their specific engineering values (as shown in Table 1), they imply that a few disciplined software development effects can actually be achieved from PSP training. For example, a software practitioner can become more skillful in defect control and software process management as disclosed by the DRR and YLD indicators in Table 6. Secondly, a practitioner can also ameliorate his or her defect predictability (DEA) and software product reliability (DDS) to a certain extent. Lastly, there is also a possibility that one might develop one’s abilities to predict project time, to meet project schedule, and to improve software productivity as seen in the results of TEA, APR, and LPH. As for the abilities to estimate project size (SEA) or to manage overall project risk (AFR), however, no positive PSP training merits can be implied from this study. In further contrast with external references, the results tend to be more agreeable with those of ![Quasi path analysis diagram of variable flow.](image) Wesslén’s (a similar graduate level academic setting), but less so with those of Hayes’ (an industrial setting). 5. Discussion 5.1. Threats to validity 5.1.1. Threats to internal validity When using PSP data as an empirical study, four types of validity threats must be considered: namely, the conclusion, internal, construct, and external validity threats [50]. The first two of these threats are data related validity issues. As mentioned by Johnson and Disney, about 5% of PSP data may be defective, and less than ten percent of them are identified as logging errors [51]. Other than logging errors, outliers (whiskers) can also skew the statistical result if either totally discarded or blindly included [52]. The worst kind is a possible data corruption resulting from “intentional” data errors, which may make the results look better [50]. To avoid these threats, the course instructor (one of the authors of this study, also a certified PSP trainer) was cautious and promised that he would not flunk any student as long as he or she studied hard and honestly worked through the ten assignments. The truth is, all PSP data as well as the survey result were collected upon the completion of the course, and the students neither had any prior knowledge of this study, nor were penalized for poor performance (i.e. all passed the course). On each assignment submission, however, the course instructor was strict in checking if any calculation, omission, or transfer error existed in the assignment. To ensure data validity, a data inconsistency check was performed by essentially counting the total number of defects injected with the number removed as suggested in [52]. Since no data consistency errors were identified for all 160 assignments, the internal validity is sound in this study. In [10,52], Paulk has also discussed in great details on the outlier issue. The outliers can be identified in a number of ways, including the popular inter-quartile method which calculates the upper (Q3) and lower (Q1) inter-quartile limits. The outliers are also easily visualized in a box-plot chart (as seen in Figs. 2–6). Although outliers can seriously influence the mean value and thus the estimate, the median counterpart is less likely affected. Due to the limited sample size used in this study, a series of backup data sets that exclude the outliers were used for cross-examinations, but not for the result assessment. It is also the same reason that both mean and median assessment schemes (and approaches) are used throughout this paper. 5.1.2. Threats to external validity Typically, a large sample size can increase the precision of an estimate. But this is neither justified mathematically nor considered as a sole factor for a sampling choice. That is, the homogeneity of the subjects can also increase the representativeness of our sample. Moreover, when the assessment result is used to compare and contrast with a much stronger reference base (for example n = 298 in [3] and n = 131 in [4]), the size of a small pool becomes less critical. Pedagogically speaking, since a part of our purpose is to provide useful feedback for an individual learner against one’s peers, perhaps the meaning of an internal peer comparison based on a smaller pool appears to be more critical than an external reference based on a large sample size. Other than the descriptive statistical analyses portion, it should also be noted that the sample size used in the regression and path analyses is actually 64 and not just 16 (the number of the subjects). For model validation and the generalization of the results, however, the small sample size is still an issue. Further studies and more evidence are needed. 5.2. Implications of the inconsistent estimation results The insignificant estimation accuracy results (i.e. SEA, TEA) reflected in this study could be due to a number of reasons and the following discussion may offer some explanations. At the beginning, we had suspected that they might be due to the absolute value form. But a set of confirmatory analyses denied this assumption. The outlier cause will not stand either since the result did not show any difference when the backup data sets (those excluding the outliers via the inter-quartile method) were tested. The chance of data logging error is also minimal since most students reflected that they were capable of logging and confident about their logging integrity (see survey questions 2–4). While the estimation effect results of the study disagree with most studies in the existing literature, they are also partially supported by some studies under similar settings. For example, other researchers also found an insignificant effort estimation improvement [43], and an insignificant size estimation improvement [8,54]. Although there might also be a PROBE reliability issue (mentioned in [55]), we suspect that the inconsistency is mainly due to that our students lacked real-world experience (as compared to Wesslén’s study) and that a significant effect could not be achieved through a short period of time (i.e. requiring a longer learning curve) for planning and estimation training. Conversely, the significant PSP effect results on software quality may suggest that both process and product quality can be improved via PSP training within a relatively shorter period of time. Whereas it is too early to draw conclusion from this single application, our goal aims to look for further evidence to fully interpret the result and to explore other underlying factors and implications. 5.3. Observations from a PSP course instructor After teaching software engineering topics for many years, we believe that the so-called “discipline” needs to be trained in order to meet the challenges of contemporary software development tasks [56]. This can also be disclosed by the fact that students kept on coming back for re-training on industrial requests. While also deserving the blame, we suspect that there is no silver bullet (see [57]) and the institutionalization of such discipline could not be established without a successive tool adoption, not even with a tool like the PSP. Other observations along with implications of the survey result (see Appendix A) are given below. First of all, the PROBE method does cause a problem for most PSP learners, even for a graduate student. This can be reflected by that the course instructor who spent a great deal of time in teaching and assisting the students to improve their logging errors. The survey result also indicates that although most students appreciated the PSP, they decided not to use such technologies as size estimates and effort logging in the future. This further points out the pending need for a modified logging tool for the PSP (like LEAP or HackyStat as suggested in [131]). There is also evidence that these more convenient tools are already adopted academically and proven effective, to name a few [58–60]. The students also expressed that they particularly liked the coding template and the postmortem part of the PSP, from which they could benefit valuable information of their personal weaknesses (e.g. types of errors). As seen in the survey result, the majority of students (more than eighty percent) had perceived the importance of the code review process and was committed to adopt it in the future. This information also serves to support our opinion on the inclusion of the AFR measure as a crucial indicator of software process quality and efficiency. As for a feasible PSP curriculum design, it is recommended to arrange it at the graduate than an undergraduate level (as justified in [61]. The rationale behind is that an undergraduate student is normally lack of coding (and much less project) experience. It is also recommended that the assignments of a PSP course can be tailored to imitate the real-world software projects. While the already tight curriculum restricts the length of a full PSP, a partial adoption of PSP in many other computer courses can also be effective if only that the tedious logging load and the programming difficulties could be ameliorated (as seen in [58,62]). An experience report on PSP application in database courses and a list of suggestions to instructors by Humphrey serve to agree with these points [11,63]. 5.4. Industrial application When applying our assessment model to the industry, a few issues need to be considered. For instance, a full length PSP is hardly feasible and the program assignments definitely need to be tailored to meet the industrial needs. Ideally, a project comprising a set of assignments that resemble typical challenges of a software company should be designed for PSP training. In industry, a practitioner also needs to learn programming on the fly in order to meet their tight project schedule. The real coding discipline should be emphasized on skills of using external library, not on coding from the scratch or on effort in struggling with irrelevant assignment contents (i.e. the mathematical problems offered by Humphrey). The number of assignments and the length of training can also be lessened to fit the software company. Whichever case, the assignments should cover all PSP phases (or the Plan–Track–Review stages) in order to foster the said PSP training effects. Another drawback with the PSP is that it does not provide an acceptance test mechanism for the “end products” (assignments). In our study the acceptance test was conducted by the students themselves. But in the real world this is done by the real customer. Alternatively, an external “customer proxy” could help in counting the defects (in an extended sense) in the final outcome against the requirements posed at the beginning. If this customer proxy could not be onsite throughout the project period, he/she should at least be involved two to four times to ensure that the team builds the right thing (like the method used in Honig’s study [29]). As for the assessment of a practitioner’s PSP training effect, we recommend to concentrate on those exiting metrics (see Table 2) in the Plan–Track–Review model. For example, as the industrial standard aims at meeting project schedule in the Plan stage, the APR might be a better indicator than TEA. A training officer can also apply flexible weights on different metrics whenever he/she deems appropriate. Finally, since the PSP is for a continuous improvement of personal software process, it is recommended to arrange PSP training regularly and continuously to ensure that a practitioner can meet both essential and accidental software challenges. 6. Conclusion In this article, we have proposed an assessment model to test against the commonly accepted PSP training effects. As demonstrated by the empirical data collected from a PSP course, we have applied the model in the classroom. The assessment results of student performance regarding PSP training effect are presented with our interpretation and discussion. A PSP effect result summary is also included to provide feedback for students as well as educators based on industrial, academic, and class-peer standards. Although some of the assessment techniques are not very much different from the existing literature, the new viewpoints and concepts incorporated in this study can increase understanding of the results of applying the PSP. Unlike other similar studies, this paper has taken a Plan–Track–Review approach, in which nine PSP metrics are identified as critical and pertinent to software engineering values. Within the proposed assessment model, an initial regression result also indicates the possibility that former stage effect may have an impact on later stage PSP metrics. While the long-term and short-term PSP training effects are unclear and other possible factors are missing in this study, our future work aims to refine the assessment model and to clarify some of these concerns. Finally, we regret that the already tight higher education curriculum has hindered the PSP diffusion, and thus limited the sample size in recent empirical PSP studies like this one. However, we strongly advocate replications of similar studies to ensure that our students are truly prepared for their future software development challenges. Acknowledgements The authors would like to express thanks to those students who diligently studied the course and unselfishly provided the data in this study. The authors would also like to thank the anonymous reviewers whose most insightful comments are much helpful to the improvement of an earlier version. Appendix A. Survey result See Tables 7 and 8. Table 7 <table> <thead> <tr> <th>Question</th> <th>1 (%)</th> <th>2 (%)</th> <th>3 (%)</th> <th>4 (%)</th> <th>5 (%)</th> <th>Average</th> </tr> </thead> <tbody> <tr> <td>1 I understand the PSP topics covered in class and used in the logs</td> <td>0</td> <td>0</td> <td>0</td> <td>73.33</td> <td>26.67</td> <td>4.3</td> </tr> <tr> <td>2 I am capable of completing the PSP logs</td> <td>0</td> <td>0</td> <td>13.33</td> <td>73.33</td> <td>13.33</td> <td>4.0</td> </tr> <tr> <td>3 I devoted sufficient time to completing the PSP logs</td> <td>0</td> <td>0</td> <td>40</td> <td>40</td> <td>20</td> <td>3.8</td> </tr> <tr> <td>4 The information recorded in my PSP logs is accurate</td> <td>0</td> <td>0</td> <td>33.33</td> <td>53.33</td> <td>13.33</td> <td>3.8</td> </tr> <tr> <td>5 The PSP topics covered were helpful for doing quality work in the course</td> <td>0</td> <td>0</td> <td>0</td> <td>33.33</td> <td>66.67</td> <td>4.7</td> </tr> <tr> <td>6 I can see that the PSP topics covered would be helpful for doing quality work in future jobs</td> <td>0</td> <td>0</td> <td>0</td> <td>46.67</td> <td>53.33</td> <td>4.5</td> </tr> <tr> <td>7 I plan to use the PSP concept in future programming work</td> <td>0</td> <td>0</td> <td>13.33</td> <td>60</td> <td>26.67</td> <td>4.1</td> </tr> </tbody> </table> References
{"Source-Url": "http://www.ic.unicamp.br/~wainer/outros/systrev/28.pdf", "len_cl100k_base": 13195, "olmocr-version": "0.1.50", "pdf-total-pages": 12, "total-fallback-pages": 0, "total-input-tokens": 36492, "total-output-tokens": 15665, "length": "2e13", "weborganizer": {"__label__adult": 0.000621795654296875, "__label__art_design": 0.0008783340454101562, "__label__crime_law": 0.0004773139953613281, "__label__education_jobs": 0.032501220703125, "__label__entertainment": 0.00012791156768798828, "__label__fashion_beauty": 0.0003368854522705078, "__label__finance_business": 0.0006575584411621094, "__label__food_dining": 0.0005822181701660156, "__label__games": 0.0010528564453125, "__label__hardware": 0.0008263587951660156, "__label__health": 0.0005168914794921875, "__label__history": 0.0004241466522216797, "__label__home_hobbies": 0.00020706653594970703, "__label__industrial": 0.0006017684936523438, "__label__literature": 0.0006275177001953125, "__label__politics": 0.000392913818359375, "__label__religion": 0.0006475448608398438, "__label__science_tech": 0.007808685302734375, "__label__social_life": 0.00027942657470703125, "__label__software": 0.0066070556640625, "__label__software_dev": 0.9423828125, "__label__sports_fitness": 0.0005064010620117188, "__label__transportation": 0.0008444786071777344, "__label__travel": 0.0003311634063720703}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 65961, 0.04685]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 65961, 0.43058]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 65961, 0.936]], "google_gemma-3-12b-it_contains_pii": [[0, 4470, false], [4470, 12177, null], [12177, 16528, null], [16528, 24186, null], [24186, 31316, null], [31316, 36333, null], [36333, 36695, null], [36695, 41006, null], [41006, 45824, null], [45824, 53469, null], [53469, 59523, null], [59523, 65961, null]], "google_gemma-3-12b-it_is_public_document": [[0, 4470, true], [4470, 12177, null], [12177, 16528, null], [16528, 24186, null], [24186, 31316, null], [31316, 36333, null], [36333, 36695, null], [36695, 41006, null], [41006, 45824, null], [45824, 53469, null], [53469, 59523, null], [59523, 65961, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 65961, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 65961, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 65961, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 65961, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 65961, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 65961, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 65961, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 65961, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 65961, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 65961, null]], "pdf_page_numbers": [[0, 4470, 1], [4470, 12177, 2], [12177, 16528, 3], [16528, 24186, 4], [24186, 31316, 5], [31316, 36333, 6], [36333, 36695, 7], [36695, 41006, 8], [41006, 45824, 9], [45824, 53469, 10], [53469, 59523, 11], [59523, 65961, 12]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 65961, 0.20364]]}
olmocr_science_pdfs
2024-11-30
2024-11-30
a6b321c72a4f8ef4116393815f31d3544d330631
Visualizations II Customizing plots in ggplot2 Joey Stanley Doctoral Candidate in Linguistics, University of Georgia joeystanley.com orcid.org/0000-0002-9185-0048 Presented at the UGA Willson Center DigiLab Friday, February 23, 2018 This is the sixth installment of the R workshop series in Spring 2018, and the second of three workshops that introduces how to make visualizations using the ggplot2 package. This document will cover additional topics in ggplot2 that let you customize plot in various ways: (1) adding and changing titles and axis labels; (2) custom colors; (3) renaming and reordering things; (4) legends; (5) faceting; (6) themes; and a custom section on saving plots. Download this PDF from my website at joeystanley.com/r2018 1 INTRODUCTION In the last workshop, we looked at the basics of data visualization and data types and introduced the library `ggplot2`. Specifically, we looked at scatter plots and how we can plot shapes, color, size, and text. We looked at plotting one variable, whether it be categorical with a barplot or continuous with a histogram. Finally, we looked at boxplots and violin plots, and started to show how to overlay multiple plots in one image. Today’s workshop will focus less on the different kinds of plots and instead will show how you can modify things to suit your needs. Specifically, we’ll take a closer look at modifying colors, reordering and renaming categorical variables, adding titles, modifying axes, legends, faceting, themes, and saving plots. It sounds like a lot, but it shouldn’t be too bad. After today, you’ll go from a the basic, default plots to something you might want to include in a presentation or paper. 1.1 TODAY’S DATASET Last week we looked at McDonald’s menu items. Today, we’ll look at another dataset made available through Kaggle.com that contain nutritional information of 80 different kinds of cereal. I’ve removed some of the columns to simplify the dataset and made it available on my website, so you can read it in straight from there. cereal <- read.csv("http://www.joeystanley.com/data/cereal.csv") ``` #> name mfr | type | shelf #> 100% Bran G:22 C:74 | Min. :1.000 #> 100% Natural Bran K:23 H: 1 | 1st Qu.:1.500 #> All-Bran N: 6 | Median :2.000 #> All-Bran with Extra Fiber P: 9 | Mean :2.227 #> Almond Delight Q: 7 | 3rd Qu.:3.000 #> Apple Cinnamon Cheerios R: 8 | Max. :3.000 #> (Other) :69 #> weight | cups | rating | calories #> Min. :0.50 | Min. :0.2500 | Min. :18.04 | Min. :50.0 #> 1st Qu.:1.00 | 1st Qu.:0.6700 | 1st Qu.:32.69 | 1st Qu.:100.0 #> Median :1.00 | Median :0.7500 | Median :40.11 | Median :110.0 #> Mean :1.03 | Mean :0.8207 | Mean :42.39 | Mean :107.1 #> 3rd Qu.:1.00 | 3rd Qu.:1.0000 | 3rd Qu.:50.28 | 3rd Qu.:110.0 #> Max. :1.50 | Max. :1.5000 | Max. :93.70 | Max. :160.0 #> sugars | protein | fat | sodium #> Min. :0.00 | Min. :1.0000 | Min. :0.0 | Min. :0.0 #> 1st Qu.:3.00 | 1st Qu.:2.0000 | 1st Qu.:0.0 | 1st Qu.:135.0 ``` As you can see we have a relatively simple dataset with a few categorical variables and mostly continuous variables. We’ll use this for our plots today. To get us started, let’s see if the amount of sugar correlates with the cereal’s rating. ```r library(ggplot2) ggplot(cereal, aes(sugars, rating)) + geom_point() ``` Surprisingly, the general trend is that the more sugar a cereal has, the lower the rating is. Another way of looking at it is that cereals with zero sugar have the highest rating, between 1 and 7 grams per serving have a medium rating, and 8 or more has a low rating. Correlation is not causation, but the trend is interesting to see. The first thing we might want to do with a plot is to add a title or change the axis labels. We saw the code for these in our Shiny workshop a couple weeks ago and luckily, this is pretty straightforward. For a title, all you need to do is add a layer to your plot using the `ggtitle` function, and then put the title you want to see in quotes. ```r ggplot(cereal, aes(sugars, rating)) + geom_point() + ggtitle("Cereal rating and amount of sugar per serving") ``` We can also modify the axes of our plot by adding the `xlab` or `ylab` layers and, in quotes, put what you want the axes to be. Here are the kinds of changes I've had to do in the past that you might need to do as well: 1. When the columns of your data frame are something abbreviated, you can put the full name in a professional-looking plot. So, you can change "mpg" to "miles per gallon". 2. Sometimes your column names are super long. An actual example I've seen is "education_level_by_number_of_years", which could easily be shorted to "education (years)". 3. Often, all you'll need to do is change from lowercase to uppercase or vice versa ("sugars" to "Sugars"). 4. You may want to add a unit of measurement, so that "height" can be changed to "height (in feet)" 5. R doesn’t like spaces in column names, but you’ll probably want them in your plots, so you can change "serving size" to "serving size". With ggplot2, you can make these changes so that they’re reflected in your plot only without having to rename parts of your data frame. ```r ggplot(cereal, aes(sugars, rating)) + geom_point() + ggtitle("Cereal rating and amount of sugar per serving") + xlab("Sugar per Serving") + ylab("Average Rating") ``` Now, what’s interesting is that the above code is actually the shortcut functions. Instead, we can do the same thing by putting this same information inside of a function called `labs`, with `x`, `y`, and `title` being arguments to the function. ```r ggplot(cereal, aes(sugars, rating)) + geom_point() + labs(x = "Sugar per Serving", y = "Average Rating", title = "Cereal rating and amount of sugar per serving") ``` The benefit of using this method is that we can also add subtitles and captions the same way. ggplot(cereal, aes(sugars, rating)) + geom_point() + labs(x = "Sugar per Serving", y = "Average Rating", title = "Cereal rating and amount of sugar per serving", subtitle = "In case the title wasn't long enough...", caption = "Figure 1: More sugar means a lower rating.") For now, we're stuck with the title and subtitle being left-aligned at the top and the caption being at the bottom right. Next week we'll learn how to modify these. For simplicity, we'll leave off the labels, but you can always go back and add it later on. So now, let's see if we can start to see how we can modify other aspects of plots in ggplot2. 3 Colors 3.1 On Categorical Data We'll start with colors, since this seems to be the most visible aspect of a plot. Last week, we saw how to change all the points by adding the color argument in geom_point itself, or we can add it within the aes() argument to have one color per manufacturer. ggplot(cereal, aes(sugars, rating)) + geom_point(color = "darkblue") Later in this workshop, we’ll see how to modify the legend to make it clearer, but for now let’s overlook the fact that it’s not clear what the abbreviations stand for. We’ll get to that in the next section. So these default colors are good for some purposes. They’re evenly spaced around the color wheel so that they’re maximally distinct. But for lots of reasons, we may want to change them. For example, we might not be satisfied with the default color scheme and want to supply our own. We can do so with the function `scale_color_manual` and as an argument, provide a list of colors. Note that the order of the colors in your legend will be determined by the order you list them in `scale_color_manual`, so the first one is the top and the last one listed is the bottom. Here’s an example of a not-so-good color scheme: ```r ggplot(cereal, aes(sugars, rating)) + geom_point(aes(color = mfr)) + scale_color_manual(values = c("yellow", "blue", "green", "red", "orange", "purple")) ``` Being able to modify colors is useful not only to change all the colors, but it’s also good for highlighting a single category. Let’s switch to a barplot that lists the number of cereal items per manufacturer: ```r ggplot(cereal, aes(mfr)) + geom_bar() ``` If you’re familiar with cereal brands, you might deduce “K” stands for “Kellog’s”. We can highlight this by making them red and all the others a dark gray. The way this is done is by simply repeating the color names in the list in `scale_color_manual`: ```r ggplot(cereal, aes(mfr)) + geom_bar(aes(color = mfr)) + scale_color_manual(values = c("grey25", "red", "grey25", "grey25", "grey25", "grey25")) ``` Oops! What happened here? Keep in mind that last week we learned that to color points in a scatterplot, you need to use `color` but for barplots you need to use `fill`. Consequently, we need to use the related function, `scale_fill_manual` to accomplish this task: ```r ggplot(cereal, aes(mfr)) + geom_bar(aes(fill = mfr)) + ``` Of course, if you don’t like the way this looks, you can always modify the `color` argument still (as well as the size of the outline and width of the bars) and everything will behave as you expected. ```r ggplot(cereal, aes(mfr)) + geom_bar(aes(fill = mfr), color = "black", size = 2, width = 0.75) + ``` ### 3.1.1 Now you try! #### 3.1.1.1 The challenge 1. Try putting in different variables for the scatterplot and see what kinds of things you discover about cereal. When you find something interesting, perhaps about a single company, highlight just the dots for that manufacturer. Feel free to modify other aspects of the plot as you see fit. 2. Just as you can manually change the colors using `scale_color_manual`, you can also change the size of the points using `scale_size_manual`. In fact, you can change any of the aspects we’ve seen so far using `scale_*_manual` where the * is the part you’re trying to change. To use these, you have to use those properties in the `aes()` function because you’re overriding the defaults. In other words, if you want to highlight a particular manufacturer’s size dot, you have to have `size = mfr` in `geom_point`. Try making a barplot that uses some of these additional overriding functions. #### 3.1.1.2 The solution Here’s something I found interesting. There’s a slight trend such that the more protein a cereal has, the higher its rating is. But it seems like Nestle cereals are at the top of the pack while General Mills are lower. ```r ggplot(cereal, aes(protein, rating)) + geom_point(aes(color = mfr)) + scale_color_manual(values = c("blue3", "darkgrey", "forestgreen", "darkgrey", "darkgrey", "darkgrey")) ``` Of course, this may just be that Nestle cereals have higher ratings than General Mills across the board. You may have to do some more plots to see for sure. For the barplot, I've went ahead and modified the fill, outlines color, and size of the bar corresponding to Kellog's and I added General Mills to for fun. I wasn’t able to modify the width manually, so I kept that the same. Also, I set outline width to zero to remove it entirely on the other four ```r ggplot(cereal, aes(mfr)) + geom_bar(aes(fill = mfr, color = mfr, size = mfr, width = 0.75) + scale_fill_manual(values = c("blue3", "red", "grey25", "grey25", "grey25", "grey25")) + scale_color_manual(values = c("darkblue", "firebrick4", "black", "black", "black", "black")) + scale_size_manual(values = c(2, 2, 0, 0, 0, 0)) ``` Using these `scale_*_manual` functions, it becomes easy to change many aspects of your plot. You can do this to change color schemes, or highlight particular points. 3.2 On continuous data What we’ve seen so far is how to change colors for categorical variables. Sometimes we have continuous data, but we don’t like the default black to blue: \[ \text{ggplot}(\text{cereal}, \text{aes}(\text{sugars, rating})) + \\ \text{geom_point(aes(color = rating))} \] The way we change this is similar to how we changed the categorical variables, but we use `scale_color_gradient` instead. Here, we can specify what the color for the lowest and highest values should be. R will automatically create a nice color gradience for you. \[ \text{ggplot}(\text{cereal}, \text{aes}(\text{sugars, rating})) + \\ \text{geom_point(aes(color = rating)) +} \\ \text{scale_color_gradient(low = "red", high = "goldenrod2")} \] So it’s easy to change color schemes if you don’t like the default black to blue. I sometimes have a hard time choosing good colors (like try "red" to "blue"). 3.3 Color Brewer When I create my own color schemes, the colors I try are usually too harsh. Fortunately, some smart people, particularly those who make maps, have developed color schemes that are easy on the eyes. Some of them are good for printing black-and-white and are color-blind friendly as well. You can see these schemes by going to colorbrewer2.org. Luckily for us, ggplot2 has a built in function to work with these themes, `scale_color_brewer` and `scale_fill_brewer`. If you’re working with categorical variables, you’ll need to specify `type = "qual"` (for qualitative). You can use the default palette ("Accent"), or you try some of the other ones ("Dark2", "Pastel1", "Pastel2", "Set1", "Set2", or "Set3"). These colors tend to be a bit lighter, so they’ll pop out better when we learn how to make the background white instead of grey later in this workshop. ```r ggplot(cereal, aes(mfr)) + geom_bar(aes(fill = mfr), color = "grey25") + scale_fill_brewer(type = "qual", palette = "Pastel1") ``` For continuous variables, the process is similar, but you need to use `scale_color_distiller` or `scale_fill_distiller` instead. You’ll need to specify `type = "seq"` (for sequential) and use one of the many types they have available. The multi-hue options are "BuGn", "BuPu", "GnBu", "OrRd", "PuBu", "PuBuGn", "PuRd", "YlGn", "YlGnBu", "YlOrBr", and "YlOrRd" and the single-hue options are "Blues", "Greens", "Greys", "Oranges", "Purples", and "Reds". ```r ggplot(cereal, aes(sugars, rating)) + geom_point(aes(color = rating)) + scale_color_distiller(type = "seq", palette = "YlGnBu") ``` The downside to using the Scale Brewer colors is that it’s a bit harder to modify them manually once you use them. It’s possible, but it’ll probably involve going to their website and copy and pasting the hexadecimal color codes and passing them into `scale_color_manual`. ### 3.3.1 Your turn! #### 3.3.1.1 The challenge 1. Try using a categorical color scheme in `scale_color_distiller` and a continuous theme in `scale_color_brewer` and see what happens. #### 3.3.1.2 The solution Fortunately, the folks at Color Brewer have made it so the continuous color schemes look great, even on categorical data. With six categorical variables, it’s spread a little thin within the color scheme, but they’re still distinct. ```r ggplot(cereal, aes(mfr)) + geom_bar(aes(fill = mfr), color = "grey25") + scale_fill_brewer(type = "qual", palette = "Greys") ``` Going the other way, ggplot2 is smart and will take the discrete colors of a categorical theme and fill in the gaps to create a continuous color scheme. \[ \text{ggplot}(\text{cereal}, \text{aes}(\text{sugars}, \text{rating})) + \text{geom_point}(\text{aes(\text{color} = \text{rating})) + scale_{\text{color}}_{\text{distiller}}(\text{type} = \text{"seq"}, \text{palette} = \text{"Set2"})} \] This is what they do on weather maps by the way. As it goes from cold to hot, the colors go from like a white to blue to green to red. Here it’s a bit unnecessary, but it might be useful for you and your data. ### 3.4 Final Remarks on Color So that’s how you can modify colors in your plots. Colors are one of the most important parts of your plot, other than the data itself. A good use of color schemes can really make a plot look great so it’s worth the time to learn to use them well. ### 4 Renaming and Reordering Reordering things is a pretty simple process, as we’ll see in this section, but renaming them is a bit trickier. The way to do this is actually not in ggplot2 but to modify the dataframe itself and then feed this new data frame into `ggplot`. There are two ways to do this: the hard way using base R functions or the easy way using `tidyverse` functions. For reference, here’s how you do it in base R. ```r # First make a copy cereal_renamed <- cereal # Copy and paste this complicated code one-by-one levels(cereal_renamed$mfr)[levels(cereal_renamed$mfr)=="K"] <- "Kellog's" ``` levels(cereal_renamed$mfr)[levels(cereal_renamed$mfr)=="G"] <- "General Mills" levels(cereal_renamed$mfr)[levels(cereal_renamed$mfr)=="P"] <- "Post" levels(cereal_renamed$mfr)[levels(cereal_renamed$mfr)=="Q"] <- "Quaker Oats" levels(cereal_renamed$mfr)[levels(cereal_renamed$mfr)=="R"] <- "Ralston Purina" # bought by General Mills levels(cereal_renamed$mfr)[levels(cereal_renamed$mfr)=="N"] <- "Nabisco" # bought by Post # Plot it ggplot(cereal_renamed, aes(mfr)) + geom_bar() So it works! the problem is there’s a lot of code there to do what should be a pretty simple task. You’ll see this a lot more later, but tidyverse functions provide a nice way to make these kinds of things easier. If you haven’t installed it already, you’ll need to load the forcats library, which you should have already if you’ve downloaded tidyverse. install.packages("forcats") # If you haven’t already With that loaded, we can use fct_recode to change them all. Note that in the base R code, the old name is on the left and the new name is on the right. Here it’s the opposite. # Load the package library(forcats) # Make a copy again cereal_renamed <- cereal # Modify them like this. cereal_renamed$mfr <- fct_recode(cereal_renamed$mfr, "Kellog's" = "K", "General Mills" = "G", "Post" = "P", "Quaker Oats" = "Q", "Ralston Purina" = "R") "Ralston Purina" = "R", "Nabisco" = "N") # Plot it ggplot(cereal_renamed, aes(mfr)) + geom_bar() The \texttt{fct_recode} function does this a lot better if you ask me. Either way, the point is that now we have different names in the plot, which ultimately makes it much easier to read and interpret. What you may want to do at this point is change the order. By default, R will order your categorical variables alphabetically. This is a good default, but you might want to change that in your own plot. Let's start with our barplot we had before. One way to reorder these is to put them in order of frequency. There is a way to do this automatically, but that'll have to wait until we get to the Tidyverse workshops because it's a bit more involved than \texttt{fct_recode}. Fortunately, we can just do it by hand, which doesn't take too much work. Like renaming, we actually take care of this by modifying the dataframe itself and then sending it off to \texttt{ggplot}. We modify the \texttt{mfr} column so that it's a factor with levels that you specify. The order of this list is the order they'll appear in your plot. Do keep in mind that you'll have to use the new names if you've changed them. cereal_ordered <- cereal_renamed cereal_ordered$mfr <- factor(cereal_ordered$mfr, levels = c("Kellog's", "General Mills", "Post", "Quaker Oats", "Ralston Purina", "Nabisco")) ggplot(cereal_ordered, aes(mfr)) + geom_bar() That’s really all there is to it. If you don’t like the order of things, it’s pretty easy to change it once you’ve got the code. 5 LEGENDS A critical part of data visualization is the legend. Sometimes the legend is completely unnecessary but other times it’s the key to understanding the plot. We’ll look at some examples of each and see how we can improve the visualization. 5.1 REMOVING THE LEGEND Let’s take a bar plot of the manufacturers and color it using Color Brewer. ```r ggplot(cereal_ordered, aes(mfr)) + geom_bar(aes(fill = mfr), color = "grey25") + scale_fill_brewer(type = "qual", palette = "Pastel1") ``` This is nice example where the legend is not necessary. All the information from the legend itself is already contained in the plot. Fortunately, it's easy to remove the legend using the `theme` function. This function is actually a monster with dozens and dozens of arguments because it's the key to modifying pretty much everything on the plot, but we'll get to that next week. For now, if we set `legend.position` argument to "none" it'll remove it. ```r ggplot(cereal_ordered, aes(mfr)) + geom_bar(aes(fill = mfr), color = "grey25") + scale_fill_brewer(type = "qual", palette = "Pastel1") + theme(legend.position = "none") ``` This not only removes the legend, but it actually stretches out the plot a little bit to fill the whole space. Side note, instead of using "none", you can also change the legend's location by using "top", "bottom", or "left". But for this plot, it's probably best to just remove it entirely. In fact, we can probably remove the colors since they don’t actually serve a purpose, but that’s up to you. ### 5.2 Modifying the Order Previously, we saw how to modify the order that the manufacturers appeared in the barplot. The legend automatically updates. We can actually modify the legend independently of the bars. Let’s take a barplot we did earlier that emphasized Kellog’s. This time we’ll use the `cereal_renamed` object so we can get the actual names. ```r ggplot(cereal_renamed, aes(protein, rating)) + geom_point(aes(color = mfr)) + scale_color_manual(values = c("blue3", "darkgrey", "forestgreen", "darkgrey", "darkgrey", "darkgrey")) ``` Here’s a good example of when we might want to reorder the legend. Of course we can do it using the technique in the Renaming and reordering section above. (We also need to modify the order of the colors in `scale_color_manual` since now the forest green one is second.) ```r cereal_ordered2 <- cereal_ordered mfr <- factor(cereal_ordered2$mfr, levels = c("General Mills", "Nabisco", "Kellog's", "Post", "Quaker Oats", "Ralston Purina")) ggplot(cereal_ordered2, aes(protein, rating)) + geom_point(aes(color = mfr)) + scale_color_manual(values = c("blue3", "forestgreen", "darkgrey", "darkgrey", "darkgrey", "darkgrey")) ``` The problem with this is we either have to 1) modify the original dataset (`cereal`), which is sometimes something you don’t want to do, or 2) keep track of several very similar objects (`cereal_renamed`, `cereal_ordered` and now `cereal_reordered2`). Instead, we can add another argument to `scale_color_manual`, the `breaks` argument and simply list the order we want to see. The tricky part about this is that the order of colors in the `values` list has to match the original order. The reason for this is that the \texttt{breaks} makes a superficial change, but the order stays the same under the hood. \begin{verbatim} \begin{verbatim} \texttt{ggplot(cereal_renamed, aes(protein, rating)) + geom_point(aes(color = mfr)) + scale_color_manual(breaks = c("General Mills", "Nabisco", "Kellog's", "Post", "Quaker Oats", "Ralston Purina"), values = c("blue3", "darkgrey", "forestgreen", "darkgrey", "darkgrey", "darkgrey"))} \end{verbatim} \end{verbatim} This is admittedly a bit annoying, but you only have to worry about it once and then it'll always be the same after that in your plots. 5.3 Modifying the Legend Text One super annoying part of about the legend as it is now is that we see the abbreviation “mfr” as the title. That’s the name of the column in our spreadsheet, and it’s handy to have it short because, well, less typing. But in a professional visualization, you’ll probably want to spell it out. You can modify the original data, but it might just be easier to make a superficial change. This can happen in the \texttt{scale_color_manual} function again, with the argument \texttt{name}. \begin{verbatim} \texttt{ggplot(cereal_renamed, aes(protein, rating)) + geom_point(aes(color = mfr)) + scale_color_manual(name = "Manufacturer", breaks = c("General Mills", "Nabisco", "Kellog's", "Post", "Quaker Oats", "Ralston Purina"), values = c("blue3", "darkgrey", "forestgreen", "darkgrey", "darkgrey", "darkgrey"))} \end{verbatim} So now we have three arguments in `scale_color_manual`: `name`, `breaks`, and `values`. The order that they appear makes no difference. But I like to put the `name` at the top since it appears at the top in the final plot. We can also modify the legend labels. We saw how to change the underlying data above in the Renaming and reordering section. But just as you sometimes want to make an order change just for the purpose of a single plot, you can rename things superficially while keeping the underlying data intact. To illustrate this, I’ll use the original `cereal` dataset, which has the one-letter abbreviations for the manufacturers, and I’ll change them in the plot (and I’ll make them lowercase to show that they’re different). To accomplish this, I add the `labels` argument to the `scale_color_manual`. ```r # Plot with no changes to the legend (other than color) ggplot(cereal, aes(protein, rating)) + geom_point(aes(color = mfr)) + scale_color_manual(values = c("blue3", "darkgrey", "forestgreen", "darkgrey", "darkgrey", "darkgrey")) ``` ``` # Plot with all changes in title, order, labels, and colors ggplot(cereal, aes(protein, rating)) + ``` Thus, with a little bit of typing, you can modify whatever you want with the legend. 5.3.1 Your turn! 5.3.1.1 The challenge 1. Everything about manually changing things in the legend in `scale_color_manual` also applies to `scale_fill_manual` and `scale_fill_brewer`. Try making barplot with the original cereal dataset but manually modify the name, order, and labels (and colors unless you use Color Brewer). The result should be such that the legend is in your custom order but bars are still in alphabetical order (with one-letter abbreviations underneath). Not a useful plot, but a useful exercise. 5.3.1.2 The solution I decided to use `scale_fill_brewer`, so I didn’t need to manually set the colors. 5.4 **BONUS: SPECIAL CHANGES FOR COLOR BREWER** If you're using Color Brewer for your colors, you have a couple additional changes you can make to your legend. If you're plotting a continuous variable, you normally get a continuous scale in your legend: ``` library(ggplot2) ggplot(cereal, aes(sugars, rating)) + geom_point(aes(color = rating)) + scale_color_distiller(type = "seq", palette = "PuRd") ``` You can actually add the `guide = "legend"` argument, and it'll turn it into a categorical-looking legend. To be clear, the dots on the graph still use a continuous color scheme, but the legend is at least a little bit cleaner. ``` library(ggplot2) ggplot(cereal, aes(sugars, rating)) + geom_point(aes(color = rating)) + scale_color_distiller(type = "seq", palette = "PuRd", guide = "legend") ``` For some reason though, this has the effect of reversing the order so that high numbers are at the bottom. We can flip the way they appear in the legend by taking out `guide = "legend"` and using `guide = guide_legend(reverse = TRUE)` instead. Slightly cumbersome, but it gets the job done. ```r ggplot(cereal, aes(sugars, rating)) + geom_point(aes(color = rating)) + scale_color_distiller(type = "seq", palette = "PuRd", guide = guide_legend(reverse=TRUE)) ``` Of course now if we want to change it so that high numbers get the darker color, we have to add `direction = 1` to reverse the order. ```r ggplot(cereal, aes(sugars, rating)) + geom_point(aes(color = rating)) + scale_color_distiller(type = "seq", palette = "PuRd", guide = guide_legend(reverse=TRUE), direction = 1) ``` By the way, if direction = 1 doesn’t make any changes in other plots, try direction = -1 instead. I can’t figure out which one to use. Anyway, because Color Brewer does seem cool things, it takes a little more work to get things done, but the result is a pretty good looking plot. 5.5 CREDIT TO R COOKBOOK Much of the material from this section was borrowed from Winston Chang’s http://www.cookbook-r.com, specifically the page on legends in ggplot2. I refer to this page all the time in my own research, and there’s so much more that is covered there that I couldn’t get to here. Be sure to check it out. 6 FACETING Let’s say we make a plot and it gets a little cumbersome because there are lots of points being shown. This is particularly true when you have text being displayed instead of points. Sometimes it’s nice to split the plot up into meaningful groups and look at each group individually. For example, let’s say we want to see how much fiber a cereal has and compare it to how it’s rating is. But we want to be able to see the name of the cereal itself, so we use geom_text instead of geom_point. ```r ggplot(cereal_renamed, aes(fiber, rating)) + geom_text(aes(label = name)) ``` Ugh. That’s a little messy. Maybe it might help if we could look at each manufacturer individually. The long way to do this is to create six different datasets by subsetting the original, and then doing six different plots, and finding a way to plot them all in one in a grid-like layout. But that’s way too much work. Fortunately, ggplot2 has a way to do this with just one simple line of code: `facet_wrap`. Here, we can put the name of the column we want to split it up by—but it has to be after a tilde “~” (that squiggle thing left of the number “1” key). The reasons behind this are beyond the scope of this workshop, but just know you have to put it there. The result is exactly what we need. ```r ggplot(cereal_renamed, aes(fiber, rating)) + geom_text(aes(label = name)) + facet_wrap(~mfr) ``` Here we can see that each manufacturer has its own plot, and the order is determined by the underlying order in the dataset. Here’s it’s alphabetical, but you can change that the same way that was shown above. If you look closely, you’ll see that the x- and y-axes are the same for each plot. In other words, it’s clear to see that Nabisco cereals have a generally higher rating than most of the other ones and that Kellogg’s All Bran with Extra Fiber is true to its name and easy has the most fiber (and the highest rating). This is good because it makes comparisons across manufacturers easy. But if we don’t care about differences between manufacturers, and just want to look at differences within them, we can have each plot zoom in to just the data that’s being shown. We do this by adding the `scales = "free"` argument to `facet_wrap`. ```r ggplot(cereal_renamed, aes(fiber, rating)) + geom_text(aes(label = name)) + facet_wrap(~mfr, scales = "free")``` This plot shows the exact same data, but it highlights different things. For example, we can see clearly see the differences between Quaker Oats cereals, which was harder to see when they were all squished together before. We can also change the number of rows and columns. By default, it’ll do roughly a square layout with approximately equal numbers of rows and columns. If you want them all to be side-by-side (perhaps you’re making a poster), you can set `nrow = 1` or if you want them all vertical, you can set `ncol = 1`. ```r ggplot(cereal_renamed, aes(fiber, rating)) + geom_text(aes(label = name)) + facet_wrap(~mfr, scales = "free", nrow = 1) ``` ```r ggplot(cereal_renamed, aes(fiber, rating)) + geom_text(aes(label = name)) + facet_wrap(~mfr, scales = "free", ncol = 1) ``` More commonly, you’ll want to specify something in between here, but it’s a good trick to be aware of. 6.1.1 Your turn! 6.1.1.1 The challenge 1. What happens if you use `facet_wrap` on some variable that’s already used in your plot? For example, what if you modify the above plot to have the manufacturers each with their own color? 2. What happens if you do a bar plot with fiber and manufacturer, but facet it by manufacturer? Is this a useful thing? 6.1.1.2 The solution If you use the same variable for color and faceting, it does what you expect. The colors just don’t add much to the plot. ```r ggplot(cereal_renamed, aes(fiber, rating, color = mfr)) + geom_text(aes(label = name)) + facet_wrap(~mfr, scales = "free") ``` Instead it might be more useful to add another variable for color. ```r ggplot(cereal_renamed, aes(fiber, rating, color = protein)) + geom_text(aes(label = name)) + scale_color_distiller(type = "seq", palette = "Reds", direction = 1) + facet_wrap(~mfr, scales = "free") ``` If you use a facet wrap on the same variable as the columns, it doesn’t really help much and it turns into a pretty lame graph. ```r ggplot(cereal_renamed, aes(mfr)) + geom_bar() + facet_wrap(~mfr) ``` The last topic today is how to finally change the overall theme of your plot. By now, you might want a background that isn’t grey. Fortunately, ggplot2 comes with several themes preinstalled, so it’s easy to switch between them. First, what I’ll do is actually save a plot as an R object. I’ll choose the barplot that we made earlier with the Color Brewer colors. When we save it as an object (by prefacing the `ggplot` call with `p <-`), it doesn’t plot right away. Instead, you have to type the name of the object (we’re calling it `p`, but it whatever you want). ```r p <- ggplot(cereal_ordered, aes(mfr)) + geom_bar(aes(fill = mfr), color = "grey25") + scale_fill_brewer(type = "qual", palette = "Pastel1") ``` The reason for this is that I don’t have to sit there and copy and paste all the code in every time. I can just add layers to this `p` and it’ll update the whole thing. My go-to theme is called `theme_bw()` for just “black and white.” The biggest difference is that now the background is white instead of gray But it also adds a thin black border around the whole thing and has faint grey grid lines instead of white ones. ```r p + theme_bw() ``` The classic theme has no grid and the top and right parts of the box are gone too, just leaving the x and y axes. `p + theme_classic()` The light theme is very similar to `bw`. The biggest difference is the outside box is lighter. `p + theme_light()` If you really like the gray, you can go for the dark theme, which has a darker background and a darker gray for the grid lines. ```r p + theme_dark() ``` In fact, if you really like default background, you can set it specifically. This is the default for a reason because that specific shade of gray has been chosen to make colors stand out more. ```r p + theme_gray() ``` The minimal theme is even simpler than light. It doesn't have the outside border but it does retain the inside grid. \[ p + theme\_minimal() \] Finally, you can go completely blank with void. This may seem a little weird, but it does have useful purposes, like when creating maps. \[ p + theme\_void() \] Something to keep in mind with themes is that they override any other theme layer you might have included. For example, if you want to remove the legend and then use the `classic` theme, it’s still there: ```r p + theme(legend.position = "none") + theme_classic() ``` No this isn’t a bug. The reason for this is because `theme_*` is actually a shortcut for a whole bunch of other theme elements. As a result, there are two theme functions, so the second one overrides the first one. Fortunately, we can fix this by just reversing the order of `theme` and `theme_classic`: ```r p + theme_classic() + theme(legend.position = "none") ``` If you don’t like any of these themes, or you want to change just one aspect of them (the width of the lines, the color of the background, the gridlines, etc.), you can! That’s what we’ll be doing next week is diving deep into the theme function and seeing what kinds of things you can do to change your plot, and how to wrap all these changes up into a custom theme. 8 Bonus: Saving plots Everything we’ve done so far is just a temporary image that will disappear when you close R. Crucially, it’s not going to show up in your powerpoints or papers. There is a way to save plots by clicking things in RStudio, but the whole purpose of this workshop is to do things via code because it’s a lot easier to reproduce it. The way to save things is to use the function `ggsave` immediately after creating a plot. You can specify the path to where you want it saved by typing a full or relative path. Note that Windows users will need a double back slash (`\`) while Mac users need a single forward slash (`/`). Also be sure to specify the name of the file itself and the filetype (".png", ".jpg", etc.). You can specify the width and height in inches to control the size, which is super useful for making comparison charts. And you can specify the resolution using `dpi` (“dots per inch”). The default, which is the standard for many publications, is 300. ```r p + theme_classic() + theme(legend.position = "none") # For Macs ggsave("/Users/joeystanley/Desktop/plots/barplot.png", dpi = 300, height = 7, width = 7) # For Windows ggsave("C:\Users\joeystanley\Desktop\plots\barplot.png", dpi = 300, height = 7, width = 7) ``` 9 Final Remarks The last two workshops have shown us that ggplot2 is a workhorse and can do a lot things. Today we saw how to change the big things in your plots (titles, axes, colors, names, orders, legends, facets, themes) and how it’s relatively straightforward to make these changes. With these tools under your belt, you’re on your way to making some really professional-looking visualizations.
{"Source-Url": "http://3f6iwu1mrif02clvg22bwb9j-wpengine.netdna-ssl.com/wp-content/uploads/sites/9/2019/01/180223-ggplot2-part2.pdf", "len_cl100k_base": 9789, "olmocr-version": "0.1.53", "pdf-total-pages": 40, "total-fallback-pages": 0, "total-input-tokens": 82129, "total-output-tokens": 11754, "length": "2e13", "weborganizer": {"__label__adult": 0.000408172607421875, "__label__art_design": 0.0070953369140625, "__label__crime_law": 0.0003952980041503906, "__label__education_jobs": 0.00760650634765625, "__label__entertainment": 0.0002884864807128906, "__label__fashion_beauty": 0.0002770423889160156, "__label__finance_business": 0.0009627342224121094, "__label__food_dining": 0.0004453659057617187, "__label__games": 0.0007243156433105469, "__label__hardware": 0.0008406639099121094, "__label__health": 0.000408172607421875, "__label__history": 0.0008029937744140625, "__label__home_hobbies": 0.0003762245178222656, "__label__industrial": 0.0006160736083984375, "__label__literature": 0.0006418228149414062, "__label__politics": 0.00032258033752441406, "__label__religion": 0.000713348388671875, "__label__science_tech": 0.056427001953125, "__label__social_life": 0.0003910064697265625, "__label__software": 0.379638671875, "__label__software_dev": 0.53955078125, "__label__sports_fitness": 0.0002455711364746094, "__label__transportation": 0.0004298686981201172, "__label__travel": 0.0004405975341796875}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 37866, 0.0212]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 37866, 0.53556]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 37866, 0.8722]], "google_gemma-3-12b-it_contains_pii": [[0, 750, false], [750, 3074, null], [3074, 3732, null], [3732, 5113, null], [5113, 5962, null], [5962, 6973, null], [6973, 7967, null], [7967, 8633, null], [8633, 9453, null], [9453, 10824, null], [10824, 11782, null], [11782, 12682, null], [12682, 14288, null], [14288, 15143, null], [15143, 16644, null], [16644, 18002, null], [18002, 19439, null], [19439, 20065, null], [20065, 21657, null], [21657, 22844, null], [22844, 24547, null], [24547, 25714, null], [25714, 26426, null], [26426, 27242, null], [27242, 28085, null], [28085, 29286, null], [29286, 30093, null], [30093, 31057, null], [31057, 31720, null], [31720, 31861, null], [31861, 31964, null], [31964, 32869, null], [32869, 33072, null], [33072, 34239, null], [34239, 34493, null], [34493, 34869, null], [34869, 35177, null], [35177, 35815, null], [35815, 37466, null], [37466, 37866, null]], "google_gemma-3-12b-it_is_public_document": [[0, 750, true], [750, 3074, null], [3074, 3732, null], [3732, 5113, null], [5113, 5962, null], [5962, 6973, null], [6973, 7967, null], [7967, 8633, null], [8633, 9453, null], [9453, 10824, null], [10824, 11782, null], [11782, 12682, null], [12682, 14288, null], [14288, 15143, null], [15143, 16644, null], [16644, 18002, null], [18002, 19439, null], [19439, 20065, null], [20065, 21657, null], [21657, 22844, null], [22844, 24547, null], [24547, 25714, null], [25714, 26426, null], [26426, 27242, null], [27242, 28085, null], [28085, 29286, null], [29286, 30093, null], [30093, 31057, null], [31057, 31720, null], [31720, 31861, null], [31861, 31964, null], [31964, 32869, null], [32869, 33072, null], [33072, 34239, null], [34239, 34493, null], [34493, 34869, null], [34869, 35177, null], [35177, 35815, null], [35815, 37466, null], [37466, 37866, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 37866, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 37866, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 37866, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 37866, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 37866, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 37866, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 37866, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 37866, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 37866, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 37866, null]], "pdf_page_numbers": [[0, 750, 1], [750, 3074, 2], [3074, 3732, 3], [3732, 5113, 4], [5113, 5962, 5], [5962, 6973, 6], [6973, 7967, 7], [7967, 8633, 8], [8633, 9453, 9], [9453, 10824, 10], [10824, 11782, 11], [11782, 12682, 12], [12682, 14288, 13], [14288, 15143, 14], [15143, 16644, 15], [16644, 18002, 16], [18002, 19439, 17], [19439, 20065, 18], [20065, 21657, 19], [21657, 22844, 20], [22844, 24547, 21], [24547, 25714, 22], [25714, 26426, 23], [26426, 27242, 24], [27242, 28085, 25], [28085, 29286, 26], [29286, 30093, 27], [30093, 31057, 28], [31057, 31720, 29], [31720, 31861, 30], [31861, 31964, 31], [31964, 32869, 32], [32869, 33072, 33], [33072, 34239, 34], [34239, 34493, 35], [34493, 34869, 36], [34869, 35177, 37], [35177, 35815, 38], [35815, 37466, 39], [37466, 37866, 40]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 37866, 0.0]]}
olmocr_science_pdfs
2024-12-06
2024-12-06
db150ba6287e56345ccc8569488b5120df7ad453
CSE341: Programming Languages Winter 2013 Unit 7 Summary Standard Description: This summary covers roughly the same material as class and recitation section. It can help to read about the material in a narrative style and to have the material for an entire unit of the course in a single document, especially when reviewing the material later. Please report errors in these notes, even typos. This summary is not a sufficient substitute for attending class, reading the associated code, etc. Contents Ruby Logistics .................................................................................................................................................. 1 Ruby Features Most Interesting for a PL Course ............................................................................................... 2 The Rules of Class-Based OOP ....................................................................................................................... 3 Objects, Classes, Methods, Variables, Etc. ....................................................................................................... 3 Visibility and Getters/Setters ......................................................................................................................... 6 Some Syntax, Semantics, and Scoping To Get Used To .................................................................................. 7 Everything is an Object .................................................................................................................................... 7 The Top-Level .................................................................................................................................................... 8 Class Definitions are Dynamic ....................................................................................................................... 8 Duck Typing ....................................................................................................................................................... 8 Arrays ................................................................................................................................................................. 9 Passing Blocks ................................................................................................................................................ 11 Using Blocks .................................................................................................................................................... 12 The Proc Class ................................................................................................................................................ 12 Hashes and Ranges ......................................................................................................................................... 13 Subclassing and Inheritance ........................................................................................................................... 14 Why Use Subclassing? ..................................................................................................................................... 16 Overriding and Dynamic Dispatch ................................................................................................................ 16 The Precise Definition of Method Lookup .................................................................................................... 18 Dynamic Dispatch Versus Closures ................................................................................................................ 20 Implementing Dynamic Dispatch Manually in Racket .................................................................................... 21 Ruby Logistics The course website provides installation and basic usage instructions for Ruby and its REPL (called irb), so that information is not repeated here. Note that for consistency we will require Ruby version 1.9.x (for any x), although this is for homework purposes – the concepts we will discuss do not depend on an exact version, naturally. There is a great amount of free documentation for Ruby at http://ruby-doc.org and http://www.ruby-lang.org/en/documentation/. We also recommend, Programming Ruby 1.9, The Pragmatic Programmers’ Guide although this book is not free. Because the online documentation is excellent, the other course materials may not describe in detail every language feature used in the lectures and homeworks although it is also not our goal to make you hunt for things on purpose. In general, learning new language features and libraries is an important skill after some initial background to point you in the right direction. Ruby Features Most Interesting for a PL Course Ruby is a large, modern programming language with various features that make it popular. Some of these features are useful for a course on programming-language features and semantics, whereas others are not useful for our purposes even though they may be very useful in day-to-day programming. Our focus will be on object-oriented programming, dynamic typing, blocks (which are almost closures), and mixins. We briefly describe these features and some other things that distinguish Ruby here — if you have not seen an object-oriented programming language, then some of this overview will not make sense until after learning more Ruby. • Ruby is a pure object-oriented language, which means all values in the language are objects. In Java, as an example, some values that are not objects are null, 13, true, and 4.0. In Ruby, every expression evaluates to an object. • Ruby is class-based: Every object is an instance of a class. An object’s class determines what methods an object has. (All code is in methods, which are like functions in the sense that they take arguments and return results.) You call a method “on” an object, e.g., obj.m(3,4) evaluates the variable obj to an object and calls its m method with arguments 3 and 4. Not all object-oriented languages are class-based; see, for example, JavaScript. • Ruby has mixins: The next course-unit will describe mixins, which strike a reasonable compromise between multiple inheritance (like in C++) and interfaces (like in Java). Every Ruby class has one superclass, but it can include any number of mixins, which, unlike interfaces, can define methods (not just require their existence). • Ruby is dynamically typed: Just as Racket allowed calling any function with any argument, Ruby allows calling any method on any object with any arguments. If the receiver (the object on which we call the method) does not define the method, we get a dynamic error. • Ruby has many dynamic features: In addition to dynamic typing, Ruby allows instance variables (called fields in many object-oriented languages) to be added and removed from objects and it allows methods to be added and removed from classes while a program executes. • Ruby has convenient reflection: Various built-in methods make it easy to discover at run-time properties about objects. As examples, every object has a method class that returns the object’s class, and a method methods that returns an array of the object’s methods. • Ruby has blocks and closures: Blocks are almost like closures and are used throughout Ruby libraries for convenient higher-order programming. Indeed, it is rare in Ruby to use an explicit loop since collection classes like Array define so many useful iterators. Ruby also has fully-powerful closures for when you need them. • Ruby is a scripting language: There is no precise definition of a what makes a language a scripting language. It means the language is engineered toward making it easy to write short programs, providing convenient access to manipulating files and strings (topics we will not discuss), and having less concern for performance. Like many scripting languages, Ruby does not require that you declare variables before using them and there are often many ways to say the same thing. • Ruby is popular for web applications: The Ruby on Rails framework is a popular choice for developing the server side of modern web-sites. Recall that, taken together, ML, Racket, and Ruby cover three of the four combinations of functional vs. object-oriented and statically vs. dynamically typed. Our focus will be on Ruby’s object-oriented nature, not on its benefits as a scripting language. We also will not discuss at all its support for building web applications, which is a main reason it is currently so popular. As an object-oriented language, Ruby shares much with Smalltalk, a language that has basically not changed since 1980. Ruby does have some nice additions, such as mixins. Ruby is also a large language with a “why not” attitude, especially with regard to syntax. ML and Racket (and Smalltalk) adhere rather strictly to certain traditional programming-language principles, such as defining a small language with powerful features that programmers can then use to build large libraries. Ruby often takes the opposite view. For example, there are many different ways to write an if-expression. The Rules of Class-Based OOP Before learning the syntax and semantics of particular Ruby constructs, it is helpful to enumerate the “rules” that describe languages like Ruby and Smalltalk. Everything in Ruby is described in terms of object-oriented programming, which we abbreviate OOP, as follows: 1. All values (as usual, the result of evaluating expressions) are references to objects. 2. Given an object, code “communicates with it” by calling its methods. A synonym for calling a method is sending a message. (In processing such a message, an object is likely to send other messages to other objects, leading to arbitrarily sophisticated computations.) 3. Each object has its own private state. Only an object’s methods can directly access or update this state. 4. Every object is an instance of a class. 5. An object’s class determines the object’s behavior. The class contains method definitions that dictate how an object handles method calls it receives. While these rules are mostly true in other OOP languages like Java or C#, Ruby makes a more complete commitment to them. For example, in Java and C#, some values like numbers are not objects (violating rule 1) and there are ways to make object state publicly visible (violating rule 3). Objects, Classes, Methods, Variables, Etc. (See also the example programs posted with the lecture materials, not all of which are repeated here.) Class and method definitions Since every object has a class, we need to define classes and then create instances of them (an object of class C is an instance of C). (Ruby also predefines many classes in its language and standard library.) The basic syntax (we will add features as we go) for creating a class Foo with methods m1, m2, ... mn can be: ```ruby class Foo def m1 ... end def m2 (x,y) ... ``` Class names must be capitalized. They include method definitions. A method can take any number of arguments, including 0, and we have a variable for each argument. In the example above, m1 takes 0 arguments, m2 takes two arguments, and mn takes 1 argument. Not shown here are method bodies. Like ML and Racket functions, a method implicitly returns its last expression. Like Java/C#/C++, you can use an explicit `return` statement to return immediately when helpful. (It is bad style to have a return at the end of your method since it can be implicit there.) Method arguments can have defaults in which case a caller can pass fewer actual arguments and the remaining ones are filled in with defaults. If a method argument has a default, then all arguments to its right must also have a default. An example is: ```ruby def myMethod (x,y,z=0,w="hi") ... end ``` Calling methods The method call `e0.m(e1, ..., en)` evaluates `e0, e1, ..., en` to objects. It then calls the method `m` in the result of `e0` (as determined by the class of the result of `e0`), passing the results of `e1, ..., en` as arguments. As for syntax, the parentheses are optional. In particular, a zero-argument call is usually written `e0.m`, though `e0.m()` also works. To call another method on the same object as the currently executing method, you can write `self.m(...)` or just `m(...)`. (Java/C#/C++ work the same way except they use the keyword `this` instead of `self`.) In OOP, another common name for a method call is a *message send*. So we can say `e0.m e1` sends the result of `e0` the message `m` with the argument that is the result of `e1`. This terminology is “more object-oriented” — as a client, we do not care how the receiver (of the message) is implemented (e.g., with a method named `m`) as long as it can handle the message. As general terminology, in the call `e0.m args`, we call the result of evaluating `e0` the *receiver* (the object receiving the message). Instance variables An object has a class, which defines its methods. It also has *instance variables*, which hold values (i.e., objects). Many languages (e.g., Java) use the term *fields* instead of instance variables for the same concept. Unlike Java/C#/C++, our class definition does not indicate what instance variables an instance of the class will have. To add an instance variable to an object, you just assign to it: if the instance variable does not already exist, it is created. All instance variables start with an @, e.g., `@foo`, to distinguish them from variables local to a method. Each object has its own instance variables. Instance variables are mutable. An expression (in a method body) can read an instance variable with an expression like `@foo` and write an instance variable with an expression `@foo = newValue`. Instance variables are private to an object. There is no way to directly access an instance variable of any other object. So `@foo` refers to the `@foo` instance variable of the current object, i.e., `self.@foo` except `self.@foo` is *not* actually legal syntax. Ruby also has class variables (which are like Java’s static fields). They are written @@foo. Class variables are not private to an object. Rather, they are shared by all instances of the class, but are still not directly accessible from objects of different classes. **Constructing an object** To create a new instance of class `Foo`, you write `Foo.new (...)` where (...) holds some number of arguments (where, as with all method calls, the parentheses are optional and when there are zero or one arguments it is preferred to omit them). The call to `Foo.new` will create a new instance of `Foo` and then, before `Foo.new` returns, call the new object’s initialize method with all the arguments passed to `Foo.new`. That is, the method `initialize` is special and serves the same role as constructors in other object-oriented languages. Typical behavior for `initialize` is to create and initialize instance variables. In fact, the normal approach is for `initialize` always to create the same instance variables and for no other methods in the class to create instance variables. But Ruby does not require this and it may be useful on occasion to violate these conventions. Therefore, different instances of a class can have different instance variables. **Expressions and Local Variables** Most expressions in Ruby are actually method calls. Even `e1 + e2` is just syntactic sugar for `e1.+ e2`, i.e., call the + method on the result of `e1` with the result of `e2`. Another example is `puts e`, which prints the result of `e` (after calling its `to_s` method to convert it to a string) and then a newline. It turns out `puts` is a method in all objects (it is defined in class `Object` and all classes are subclasses of `Object` — we discuss subclasses later), so `puts e` is just `self.puts e`. Not every expression is a method call. The most common other expression is some form of conditional. There are various ways to write conditionals; see the example code posted with the lecture materials. As discussed below, loop expressions are rare in Ruby code. Like instance variables, variables local to a method do not have to be declared: The first time you assign to `x` in a method will create the variable. The scope of the variable is the entire method body. It is a run-time error to use a local variable that has not yet been defined. (In contrast, it is not a run-time error to use an instance variable that has not yet been defined. Instead you get back the `nil` object, which is discussed more below.) **Class Constants and Class Methods** A class constant is a lot like a class variable (see above) except that (1) it starts with a capital letter instead of `@@`, (2) you should not mutate it, and (3) it is publicly visible. Outside of an instance of class `C`, you can access a constant `Foo` of `C` with the syntax `C::Foo`. An example is `Math::PI`. A class method is like an ordinary method (called an instance method to distinguish from class methods) except (1) it does not have access to any of the instance variables or instance methods of an instance of the class and (2) you can call it from outside the class `C` where it is defined with `C.method_name args`. There are various ways to define a class method; the most common is the somewhat hard-to-justify syntax: ``` def self.method_name args ... end ``` Class methods are called static methods in Java and C#. --- 1 Actually, `Math` is a module, not a class, so this is not technically an example, but modules can also have constants. Visibility and Getters/Setters As mentioned above, instance variables are private to an object: only method calls with *that object* as the receiver can read or write the fields. As a result, the syntax is `@foo` and the self-object is implied. Notice even other instances of the same class cannot access the instance variables. This is quite object-oriented: you can interact with another object only by sending it messages. Methods can have different *visibilities*. The default is *public*, which means any object can call the method. There is also *private*, which, like with instance variables, allows only the object itself to call the method (from other methods in the object). In-between is *protected*: A protected method can be called by any object that is an instance of the same class or any subclass of the class. There are various ways to specify the visibility of a method. Perhaps the simplest is within the class definition you can put *public*, *private*, or *protected* between method definitions. Reading top-down, the most recent visibility specified holds for all methods until the next visibility is specified. There is an implicit *public* before the first method in the class. To make the contents of an instance variable available and/or mutable, we can easily define getter and setter methods, which by convention we can give the same name as the instance variable. For example: ```ruby def foo @foo end def foo= x @foo = x end ``` If these methods are public, now any code can access the instance variable `@foo` indirectly, by calling `foo` or `foo=`. It sometimes makes sense to instead make these methods *protected* if only other objects of the same class (or subclasses) should have access to the instance variables. As a cute piece of syntactic sugar, when calling a method that ends in a `=` character, you can have spaces before the `=`. Hence you can write `e.foo = bar` instead of `e.foo = bar`. The advantage of the getter/setter approach is it remains an implementation detail that these methods are implemented as getting and setting an instance variable. We, or a subclass implementer, could change this decision later without clients knowing. We can also omit the setter to ensure an instance variable is not mutated except perhaps by a method of the object. As an example of a “setter method” that is not *actually* a setter method, a class could define: ```ruby def celsius_temp= x @kelvin_temp = x + 273.15 end ``` A client would likely imagine the class has a `@celsius_temp` instance variable, but in fact it (presumably) does not. This is a good abstraction that allows the implementation to change. Because getter and setter methods are so common, there is shorter syntax for defining them. For example, to define getters for instance variables `@x`, `@y`, and `@z` and a setter for `@x`, the class definition can just include: ```ruby attr_reader :y, :z # defines getters attr_accessor :x # defines getters and setters ``` A final syntactic detail: If a method \( m \) is private, you can only call it as \( m \) or \( m(args) \). A call like \( x.m \) or \( x.m(args) \) would break visibility rules. A call like \( \text{self}.m \) or \( \text{self}.m(args) \) would not break visibility, but still is not allowed. Some Syntax, Semantics, and Scoping To Get Used To Ruby has a fair number of quirks that are often convenient for quickly writing useful programs but may take some getting used to. Here are some examples; you will surely discover more. - There are several forms of conditional expressions, including \( e1 \text{ if } e2 \) (all on one line), which evaluates \( e1 \) only if \( e2 \) is true (i.e., it reads right-to-left). - Newlines are often significant. For example, you can write ```ruby if e1 e2 else e3 end ``` But if you want to put this all on one line, then you need to write `if e1 then e2 else e3 end`. Note, however, indentation is never significant (only a matter of style). - Conditionals can operate on any object and treat every object as “true” with two exceptions: \texttt{false} and \texttt{nil}. - As discussed above, you can define a method with a name that ends in \texttt{=} for example: ```ruby def foo= x @blah = x * 2 end ``` As expected, you can write \( e.foo=17 \) to change \( e \)'s \@blah instance variable to be 34. Better yet, you can adjust the parentheses and spacing to write \( e.foo=17 \). This is just syntactic sugar. It “feels” like an assignment statement, but it is really a method call. Stylistically you do this for methods that mutate an object’s state in some “simple” way (like setting a field). - Where you write \texttt{this} in Java/C#/$C\text{++}$, you write \texttt{self} in Ruby. - Remember variables (local, instance, or class) get automatically created by assignment, so if you misspell a variable in an assignment, you end up just creating a different variable. Everything is an Object Everything is an object, including numbers, booleans, and \texttt{nil} (which is often used like \texttt{null} in Java). For example, \(-42.abs\) evaluates to 42 because the \texttt{Fixnum} class defines the method \texttt{abs} to compute the absolute value and \(-42\) is an instance of \texttt{Fixnum}. (Of course, this is a silly expression, but \( x.abs \) where \( x \) currently holds \(-42\) is reasonable.) All objects have a \texttt{nil?} method, which the class of \texttt{nil} defines to return \texttt{true} but other classes define to return \texttt{false}. Like in ML and Racket, every expression produces a result, but when no particular result makes sense, nil is preferred style (much like ML's () and Racket's void-object). That said, it is often convenient for methods to return self so that subsequent method calls to the same object can be put together. For example, if the foo method returns self, then you can write x.\texttt{foo(14)}.\texttt{bar("hi")} instead of \begin{verbatim} x.\texttt{foo(14)} x.\texttt{bar("hi")} \end{verbatim} There are many methods to support \textit{reflection} — learning about objects and their definition during program execution — that are defined for all objects. For example, the method \texttt{methods} returns an array of the names of the methods defined on an object and the method \texttt{class} returns the class of the object.\footnote{This class is itself just another object. Yes, even classes are objects.} Such reflection is occasionally useful in writing flexible code. It is also useful in the REPL or for debugging. \textbf{The Top-Level} You can define methods, variables, etc. outside of an explicit class definition. The methods are implicitly added to class \texttt{Object}, which makes them available from within any object's methods. Hence all methods are really part of some class.\footnote{This is not entirely true because modules are not classes.} Top-level expressions are evaluated in order when the program runs. So instead of Ruby specifying a main class and method with a special name (like \texttt{main}), you can just create an object and call a method on it at top-level. \textbf{Class Definitions are Dynamic} A Ruby program (or a user of the REPL) can change class definitions while a Ruby program is running. Naturally this affects all users of the class. Perhaps surprisingly, it even affects instances of the class that have already been created. That is, if you create an instance of \texttt{Foo} and then add or delete methods in \texttt{Foo}, then the already-created object “sees” the changes to its behavior. After all, every object has a class and the (current) class (definition) defines an object’s behavior. This is usually dubious style because it breaks abstractions, but it leads to a simpler language definition: defining classes and changing their definitions is just a run-time operation like everything else. It can certainly break programs: If I change or delete the \texttt{+} method on numbers, I would not expect many programs to keep working correctly. It can be useful to add methods to existing classes, especially if the designer of the class did not think of a useful helper method. The syntax to add or change methods is particularly simple: Just give a class definition including method definitions for a class that is already defined. The method definitions either replace definitions for methods previously defined (with the same name method name) or are added to the class (if no method with the name previously existed). \textbf{Duck Typing} Duck typing refers to the expression, “If it walks like a duck and quacks like a duck, then it’s a duck” though a better conclusion might be, “then there is no reason to concern yourself with the possibility that it might not be a duck.” In Ruby, this refers to the idea that the class of an object (e.g., “Duck”) passed to a method is not important so long as the object can respond to all the messages it is expected to (e.g., “walk to x” or “quack now”). For example, consider this method: ```ruby def mirror_update pt pt.x = pt.x * -1 end ``` It is natural to view this as a method that must take an instance of a particular class `Point` (not shown here) since it uses methods `x` and `x=` defined in it. And the `x` getter must return a number since the result of `pt.x` is sent the `*` message with `-1` for multiplication. But this method is more generally useful. It is not necessary for `pt` to be an instance of `Point` provided it has methods `x` and `x=`. Moreover, the `x` and `x=` methods need not be a getter and setter for an instance variable `@x`. Even more generally, we do not need the `x` method to return a number. It just has to return some object that can respond to the `*` message with argument `-1`. Duck typing can make code more reusable, allowing clients to make “fake ducks” and still use your code. In Ruby, duck typing basically “comes for free” as long you do not explicitly check that arguments are instances of particular classes using methods like `instance_of?` or `is_a?` (discussed below when we introduce subclassing). Duck typing has disadvantages. The most lenient specification of how to use a method ends up describing the whole implementation of a method, in particular what messages it sends to what objects. If our specification reveals all that, then almost no variant of the implementation will be equivalent. For example, if we know `i` is a number (and ignoring clients redefining methods in the classes for numbers), then we can replace `i+i` with `i*2` or `2*i`. But if we just assume `i` can receive the `+` message with itself as an argument, then we cannot do these replacements since `i` may not have a `*` method (breaking `i*2`) or it may not be the sort of object that `2` expects as an argument to `*` (breaking `2*i`). Arrays The `Array` class is very commonly used in Ruby programs and there is special syntax that is often used with it. Instance of `Array` have all the uses that arrays in other programming languages have — and much, much more. Compared to arrays in Java/C#/C/etc., they are much more flexible and dynamic with fewer operations being errors. The trade-off is they can be less efficient, but this is usually not a concern for convenient programming in Ruby. In short, all Ruby programmers are familiar with Ruby arrays because they are the standard choice for any sort of collection of objects. In general, an array is a mapping from numbers (the indices) to objects. The syntax `[e1,e2,e3,4]` creates a new array with four objects in it: The result of `e1` is in index 0, the result of `e2` is in index 1, and so on. (Notice the indexing starts at 0.) There are other ways to create arrays. For example, `Array.new(x)` creates an array of length `x` with each index initially mapped to `nil`. We can also pass blocks (see below for what blocks actually are) to the `Array.new` method to initialize array elements. For example, `Array.new(x) { 0 }` creates an array of length `x` with all elements initialized to 0 and `Array.new(5) { |i| -i }` creates the array `[0,-1,-2,-3,-4]`. The syntax for getting and setting array elements is similar to many other programming languages: The expression `a[i]` gets the element in index `i` of the array referred to by `a` and `a[i] = e` sets the same array As you might suspect in Ruby, we are really just calling methods on the Array class when we use this syntax. Here are some simple ways Ruby arrays are more dynamic and less error-causing than you might expect compared to other programming languages: - As usual in a dynamically typed language, an array can hold objects that are instances of different classes, for example [14, "hi", false, 34]. - Negative array indices are interpreted from the end of the array. So a[-1] retrieves the last element in the array a, a[-2] retrieves the second-to-last element, etc. - There are no array-bounds errors. For the expression a[i], if a holds fewer than i+1 objects, then the result will just be nil. Setting such an index is even more interesting: For a[i]=e, if a holds fewer than i+1 objects, then the array will grow dynamically to hold i+1 objects, the last of which will be the result of e, with the right number of nil objects between the old last element and the new last element. - There are many methods and operations defined in the standard library for arrays. If the operation you need to perform on an array is at all general-purpose, peruse the documentation since it is surely already provided. As two examples, the + operator is defined on arrays to mean concatenation (a new array where all of the left-operand elements precede all of the right-operand elements), and the | operator is like the + operator except it removes all duplicate elements from the result. In addition to all the conventional uses for arrays, Ruby arrays are also often used where in other languages we would use other constructs for tuples, stacks, or queues. Tuples are the most straightforward usage. After all, given dynamic typing and less concern for efficiency, there is little reason to have separate constructs for tuples and arrays. For example, for a triple, just use a 3-element array. For stacks, the Array class defines convenient methods push and pop. The former takes an argument, grows the array by one index, and places the argument at the new last index. The latter shrinks the array by one index and returns the element that was at the old last index. Together, this is exactly the last-in-first-out behavior that defines the behavior of a stack. (How this is implemented in terms of actually growing and shrinking the underlying storage for the elements is of concern only in the implementation of Array.) For queues, we can use push to add elements as just described and use the shift method to dequeue elements. The shift method returns the object at index 0 of the array, removes it from the array, and shifts all the other elements down one index, i.e., the object (if any) previously at index 1 is now at index 0, etc. Though not needed for simple queues, Array also has an unshift method that is like push except it puts the new object at index 0 and moves all other objects up by 1 index (growing the array size by 1). Arrays are even more flexible than described here. For example, there are operations to replace any sequence of array elements with the elements of any other array, even if the other array has a different length than the sequence being replaced (hence changing the length of the array). Overall, this flexible treatment of array sizes (growing and shrinking) is different from arrays in some other programming languages, but it is consistent with treating arrays as maps from numeric indices to objects. What we have not shown so far are operations that perform some computation using all the contents of an array, such as mapping over the elements to make a new array, or computing a sum of them. That is because the Ruby idioms for such computations use blocks, which we introduce next. Passing Blocks While Ruby has while loops and for loops not unlike Java, most Ruby code does not use them. Instead, many classes have methods that take blocks. These blocks are almost closures. For example, integers have a times method that takes a block and executes it the number of times you would imagine. For example, ``` x.times { puts "hi" } ``` prints "hi" 3 times if x is bound to 3 in the environment. Blocks are closures in the sense that they can refer to variables in scope where the block is defined. For example, after this program executes, y is bound to 10: ``` y = 7 [4,6,8].each { y += 1 } ``` Here [4,6,8] is an array with with 3 elements. Arrays have a method each that takes a block and executes it once for each element. Typically, however, we want the block to be passed each array element. We do that like this, for example to sum an array’s elements and print out the running sum at each point: ``` sum = 0 [4,6,8].each { |x| sum += x puts sum } ``` Blocks, surprisingly, are not objects. You cannot pass them as “regular” arguments to a method. Rather, any method can be passed either 0 or 1 blocks, separate from the other arguments. As seen in the examples above, the block is just put to the right of the method call. It is also after any other “regular” arguments. For example, the inject method is like the fold function we studied in ML and we can pass it an initial accumulator as a regular argument: ``` sum = [4,6,8].inject(0) { |acc,elt| acc + elt } ``` (It turns out the initial accumulator is optional. If omitted, the method will use the array element in index 0 as the initial accumulator.) In addition to the braces syntax shown here, you can write a block using do instead of { and end instead of } . This is generally considered better style for blocks more than one line long. When calling a method that takes a block, you should know how many arguments will be passed to the block when it is called. For the each method in Array, the answer is 1, but as the first example showed, you can ignore arguments if you have no need for them by omitting the |...|. Many collections, including arrays, have a variety of block-taking methods that look very familiar to functional programmers, including map. As another example, the select method is like the function we called filter. Other useful iterators include any? (returns true if the block returns true for any element of the collection), all? (returns true if the block returns true for every element of the collection), and several more. Using Blocks While many uses of blocks involve calling methods in the standard library, you can also define your own methods that take blocks. (The large standard library just makes it somewhat rare to need to do this.) You can pass a block to any method. The method body calls the block using the yield keyword. For example, this code prints "hi" 3 times: ```ruby def foo x if x yield else yield yield end end foo true { puts "hi" } foo false { puts "hi" } ``` To pass arguments to a block, you put the arguments after the `yield`, e.g., `yield 7` or `yield(8,"str")`. Using this approach, the fact that a method may expect a block is implicit; it is just that its body might use `yield`. An error will result if `yield` is used and no block was passed. The behavior when the block and the `yield` disagree on the number of arguments is somewhat flexible and not described in full detail here. A method can use the `block_given?` primitive to see if the caller provided a block. You are unlikely to use this method often: If a block is needed, it is conventional just to assume it is given and have `yield fail` if it is not. In situations where a method may or may not expect a block, often other regular arguments determine whether a block should be present. If not, then `block_given?` is appropriate. Here is a recursive method that counts how many times it calls the block (with increasing numbers) before the block returns a true result. ```ruby def count i if yield i 1 else 1 + (count(i+1) {|x| yield x}) end end ``` The odd thing is that there is no direct way to pass the caller’s block as the callee’s block argument. But we can create a new block `{|x| yield x}` and the lexical scope of the `yield` in its body will do the right thing. If blocks were actually function closures that we could pass as objects, then this would be unnecessary function wrapping. The Proc Class Blocks are not quite closures because they are not objects. We cannot store them in a field, pass them as a regular method argument, assign them to a variable, put them in an array, etc. (Notice in ML and Racket, we could do the equivalent things with closures.) Hence we say that blocks are not “first-class values” because a first-class value is something that can be passed and stored like anything else in the language. However, Ruby has “real” closures too: The class `Proc` has instances that are closures. The method `call` in `Proc` is how you apply the closure to arguments, for example `x.call` (for no arguments) or `x.call(3,4) . To make a `Proc` out of a block, you can write `lambda { ... }` where `{ ... }` is any block. Interestingly, `lambda` is not a keyword. It is just a method in class `Object` (and every class is a subclass of `Object`, so `lambda` is available everywhere) that creates a `Proc` out of a block it is passed. You can define your own methods that do this too; consult the documentation for the syntax to do this. Usually all we need are blocks, such as in these examples that pass blocks to compute something about an array: ```ruby a = [3,5,7,9] b = a.map { |x| x + 1} i = b.count { |x| x >= 6} ``` But suppose we wanted to create an array of blocks, i.e., an array where each element was something we could “call” with a value. You cannot do this in Ruby because arrays hold objects and blocks are not objects. So this is an error: ```ruby c = a.map { |x| {|y| x >= y} } # wrong, a syntax error ``` But we can use `lambda` to create an array of instances of `Proc`: ```ruby c = a.map { |x| lambda { |y| x >= y} } ``` Now we can send the `call` message to elements of the `c` array: ```ruby c[2].call 17 j = c.count { |x| x.call(5) } ``` Ruby’s design is an interesting contrast from ML and Racket, which just provide full closures as the natural choice. In Ruby, blocks are more convenient to use than `Proc` objects and suffice in most uses, but programmers still have `Proc` objects when needed. Is it better to distinguish blocks from closures and make the more common case easier with a less powerful construct, or is it better just to have one general fully powerful feature? ### Hashes and Ranges The `Hash` and `Range` classes are two standard-library classes that are also very common but probably a little less common than arrays. Like arrays, there is special built-in syntax for them. They are also similar to arrays and support many of the same iterator methods, which helps us re-enforce the concept that “how to iterate” can be separated from “what to do while iterating.” A hash is like an array except the mapping is not from numeric indices to objects. Instead, the mapping is from *(any)* objects to objects. If `a` maps to `b`, we call `a` a *key* and `b` a *value*. Hence a hash is a collection that maps a set of keys (all key in a hash are distinct) to values, where the keys and values are just objects. We can create a hash with syntax like this: ```ruby {"SML" => 7, "Racket" => 12, "Ruby" => 42} ``` As you might expect, this creates a hash with keys that here are strings. It is also common (and more efficient) to use Ruby’s symbols for hash keys as in: ``` {:sml => 7, :racket => 12, :ruby => 42} ``` We can get and set values in a hash using the same syntax as for arrays, where again the key can be anything, such as: ``` h1["a"] = "Found A" h1[false] = "Found false" h1["a"] h1[false] h1[42] ``` There are many methods defined on hashes. Useful ones include `keys` (return an array of all keys), `values` (similar for values), and `delete` (given a key, remove it and its value from the hash). Hashes also support many of the same iterators as arrays, such as `each` and `inject`, but some take the keys and the values as arguments, so consult the documentation. A range represents a contiguous sequence of numbers (or other things, but we will focus on numbers). For example `1..100` represents the integers 1, 2, 3, ..., 100. We could use an array like `Array.new(100) { |i| i}`, but ranges are more efficiently represented and, as seen with `1..100`, there is more convenient syntax to create them. Although there are often better iterators available, a method call like `0..n.each { |i| e}` is a lot like a for-loop from 0 to n in other programming languages. It is worth emphasizing that duck typing lets us use ranges in many places where we might naturally expect arrays. For example, consider this method, which counts how many elements of `a` have squares less than 50: ``` def foo a a.count { |x| x*x < 50} end ``` We might naturally expect `foo` to take arrays, and calls like `foo [3,5,7,9]` work as expected. But we can pass to `foo` any object with a `count` method that expects a block taking one argument. So we can also do `foo (2..10)`, which evaluates to 6. --- **Subclassing and Inheritance** *Basic Idea and Terminology* Subclassing is an essential feature of class-based OOP. If class `C` is a subclass of `D`, then every instance of `C` is also an instance of `D`. The definition of `C` inherits the methods of `D`, i.e., they are part of `C`'s definition too. Moreover, `C` can extend by defining new methods that `C` has and `D` does not. And it can override methods, by changing their definition from the inherited definition. In Ruby, this is much like in Java. In Java, a subclass also inherits the field definitions of the superclass, but in Ruby fields (i.e., instance variables) are not part of a class definition because each object instance just creates its own instance variables. Every class in Ruby except `Object` has one superclass. The classes form a tree where each node is a class and the parent is its superclass. The `Object` class is the root of the tree. In class-based languages, this is called the class hierarchy. By the definition of subclassing, a class has all the methods of all its ancestors in the tree (i.e., all nodes between it and the root, inclusive), subject to overriding. Some Ruby Specifics - A Ruby class definition specifies a superclass with `class C < D ... end` to define a new class C with superclass D. Omitting the `< D` implies `< Object`, which is what our examples so far have done. - Ruby’s built-in methods for reflection can help you explore the class hierarchy. Every object has a `class` method that returns the class of the object. Consistently, if confusingly at first, a class is itself an object in Ruby (after all, every value is an object). The class of a class is `Class`. This class defines a method `superclass` that returns the superclass. - Every object also has methods `is_a?` and `instance_of?`. The method `is_a?` takes a class (e.g., `x.is_a? Integer`) and returns true if the receiver is an instance of `Integer` or any (transitive) subclass of `Integer`, i.e., if it is below `Integer` in the class hierarchy. The method `instance_of?` is similar but returns true only if the receiver is an instance of the class exactly, not a subclass. (Note that in Java the primitive `instanceof` is analogous to Ruby’s `is_a`.) Using methods like `is_a?` and `instanceof` is “less object-oriented” and therefore often not preferred style. They are in conflict with duck typing. A First Example: Point and ColorPoint Here are definitions for simple classes that describe simple two-dimensional points and a subclass that adds a color (just represented with a string) to instances. ```ruby class Point attr_accessor :x, :y def initialize(x, y) @x = x @y = y end def distFromOrigin Math.sqrt(@x * @x + @y * @y) end def distFromOrigin2 Math.sqrt(x * x + y * y) end end class ColorPoint < Point attr_accessor :color def initialize(x, y, c="clear") super(x, y) @color = c end end ``` There are many ways we could have defined these classes. Our design choices here include: - We make the `@x`, `@y`, and `@color` instance variables mutable, with public getter and setter methods. - The default “color” for a `ColorPoint` is "clear". - For pedagogical purposes revealed below, we implement the distance-to-the-origin two different ways. The `distFromOrigin` method accesses instance variables directly whereas `distFromOrigin2` uses the getter methods on `self`. Given the definition of `Point`, both will produce the same result. The **initialize** method in **ColorPoint** uses the **super** keyword, which allows an overriding method to call the method of the same name in the superclass. This is not required when constructing Ruby objects, but it is often desired. **Why Use Subclassing?** We now consider the style of defining colored-points using a subclass of the class **Point** as shown above. It turns out this is good OOP style in this case. Defining **ColorPoint** is good style because it allows us to reuse much of our work from **Point** and it makes sense to treat any instance of **ColorPoint** as though it “is a” **Point**. But there are several alternatives worth exploring because subclassing is often overused in object-oriented programs, so it is worth considering at program-design time whether the alternatives are better than subclassing. First, in Ruby, we can extend and modify classes with new methods. So we could simply change the **Point** class by replacing its **initialize** method and adding getter/setter methods for **@color**. This would be appropriate only if every **Point** object, including instances of all other subclasses of **Point**, should have a color or at least having a color would not mess up anything else in our program. Usually modifying classes is not a modular change — you should do it only if you know it will not negatively affect anything in the program using the class. Second, we could just define **ColorPoint** “from scratch,” copying over (or retyping) the code from **Point**. In a dynamically typed language, the difference in semantics (as opposed to style) is small: instances of **ColorPoint** will now return false if sent the message **is_a?** with argument **Point**, but otherwise they will work the same. In languages like Java/C#/C++, superclasses have effects on static typing. One advantage of not subclassing **Point** is that any later changes to **Point** will not affect **ColorPoint** — in general in class-based OOP, one has to worry about how changes to a class will affect any subclasses. Third, we could have **ColorPoint** be a subclass of **Object** but have it contain an instance variable, call it **@pt**, holding an instance of **Point**. Then it would need to define all of the methods defined in **Point** to forward the message to the object in **@pt**. Here are two examples, omitting all the other methods (**x=**, **y=**, **distFromOrigin**, **distFromOrigin2**): ```ruby def initialize(x,y,c="clear") @pt = Point.new(x,y) @color = c end def x @pt.x # forward the message to the object in @pt end ``` This approach is bad style since again subclassing is shorter and we want to treat a **ColorPoint** as though it “is a” **Point**. But in general, many programmers in object-oriented languages overuse subclassing. In situations where you are making a new kind of data that includes a pre-existing kind of data *as a separate sub-part of it*, this instance-variable approach is better style. **Overriding and Dynamic Dispatch** Now let’s consider a different subclass of **Point**, which is for three-dimensional points: Here, the code-reuse advantage is limited to inheriting methods \texttt{x, x=, y, and y=} as well as using other methods in \texttt{Point} via \texttt{super}. Notice that in addition to overriding \texttt{initialize}, we used overriding for \texttt{distFromOrigin} and \texttt{distFromOrigin2}. Computer scientists have been arguing for decades about whether this subclassing is good style. On the one hand, it does let us reuse quite a bit of code. On the other hand, one could argue that a \texttt{ThreeDPoint} is \textit{not} conceptually a (two-dimensional) \texttt{Point}, so passing the former when some code expects the latter could be inappropriate. Others say a \texttt{ThreeDPoint} is a \texttt{Point} because you can “think of it” as its projection onto the plane where \texttt{z} equals 0. We will not resolve this legendary argument, but you should appreciate that often subclassing is bad/confusing style even if it lets you reuse some code in a superclass. The argument against subclassing is made stronger if we have a method in \texttt{Point} like \texttt{distance} that takes another (object that behaves like a) \texttt{Point} and computes the distance between the argument and \texttt{self}. If \texttt{ThreeDPoint} wants to override this method with one that takes another (object that behaves like a) \texttt{ThreeDPoint}, then \texttt{ThreeDPoint} instances will \textit{not} act like \texttt{Point} instances: their \texttt{distance} method will fail when passed an instance of \texttt{Point}. We now consider a \textit{much} more interesting subclass of \texttt{Point}. Instances of this class \texttt{PolarPoint} behave equivalently to instances of \texttt{Point} except for the arguments to \texttt{initialize}, but instances use an internal representation in terms of polar coordinates (radius and angle): class PolarPoint < Point def initialize(r,theta) @r = r @theta = theta end def x @r * Math.cos(@theta) end def y @r * Math.sin(@theta) end def x= a b = y # avoids multiple calls to y method @theta = Math.atan(b / a) @r = Math.sqrt(a*a + b*b) self end end def y= b a = y # avoid multiple calls to y method @theta = Math.atan(b / a) @r = Math.sqrt(a*a + b*b) self end def distFromOrigin @r end # distFromOrigin2 already works!! end Notice instances of PolarPoint do not have instance variables @x and @y, but the class does override the x, x=, y, and y= methods so that clients cannot tell the implementation is different (modulo round-off of floating-point numbers): they can use instances of Point and PolarPoint interchangeably. A similar example in Java would still have fields from the superclass, but would not use them. The advantage of PolarPoint over Point, which admittedly is for sake of example, is that distFromOrigin is simpler and more efficient. The key point of this example is that the subclass does not override distFromOrigin2, but the inherited method works correctly. To see why, consider the definition in the superclass: def distFromOrigin2 Math.sqrt(x * x + y * y) end Unlike the definition of distFromOrigin, this method uses other method calls for the arguments to the multiplications. Recall this is just syntactic sugar for: def distFromOrigin2 Math.sqrt(self.x() * self.x() + self.y() * self.y()) end In the superclass, this can seem like an unnecessary complication since self.x() is just a method that returns @x and methods of Point can access @x directly, as distFromOrigin does. However, overriding methods x and y in a subclass of Point changes how distFromOrigin2 behaves in instances of the subclass. Given a PolarPoint instance, its distFromOrigin2 method is defined with the code above, but when called, self.x and self.y will call the methods defined in PolarPoint, not the methods defined in Point. This semantics goes by many names, including dynamic dispatch, late binding, and virtual method calls. There is nothing quite like it in functional programming, since the way self is treated in the environment is special, as we discuss in more detail next. The Precise Definition of Method Lookup The purpose of this discussion is to consider the semantics of object-oriented language constructs, particularly calls to methods, as carefully as we have considered the semantics of functional language constructs, particularly calls to closures. As we will see, the key distinguishing feature is what self is bound to in the environment when a method is called. The correct definition is what we call dynamic dispatch. The essential question we will build up to is given a call $e_0.m(e_1,e_2,...,e_n)$, what are the rules for “looking up” what method definition $m$ we call, which is a non-trivial question in the presence of overriding. But first, let us notice that in general such questions about how we “look up” something are often essential to the semantics of a programming language. For example, in ML and Racket, the rules for looking up variables led to lexical scope and the proper treatment of function closures. And in Racket, we had three different forms of let-expressions exactly because they have different semantics for how to look up variables in certain subexpressions. In Ruby, the variable-lookup rules for local variables in methods and blocks are not too different from in ML and Racket despite some strangeness from variables not being declared before they are used. But we also have to consider how to “look up” instance variables, class variables, and methods. In all cases, the answer depends on the object bound to self — and self is treated specially. In any environment, self maps to some object, which we think of as the “current object” — the object currently executing a method. To look up an instance variable $@x$, we use the object bound to self — each object has its own state and we use self’s state. To look up a class variable @@x, we just use the state of the object bound to self.class instead. To look up a method $m$ for a method calls is more sophisticated... In class-based object-oriented languages like Ruby, the rule for evaluating a method call like $e_0.m(e_1,...,e_n)$ is: - Evaluate $e_0$, $e_1$, ..., $e_n$ to values, i.e., objects $obj_0$, $obj_1$, ..., $obj_n$. - Get the class of $obj_0$. Every object “knows its class” at run-time. Think of the class as part of the state of $obj_0$. - Suppose $obj_0$ has class $A$. If $m$ is defined in $A$, call that method. Otherwise recur with the superclass of $A$ to see if it defines $m$. Raise a “method missing” error if neither $A$ nor any of its superclasses define $m$. (Actually, in Ruby the rule is actually to instead call a method called method_missing, which any class define, so we again start looking in $A$ and then its superclass. But most classes do not define method_missing and the definition of it in Object raises the error we expect.) - We have now found the method to call. If the method has formal arguments (i.e., argument names or parameters) $x_1$, $x_2$, ..., $x_n$, then the environment for evaluating the body will map $x_1$ to $obj_1$, $x_2$ to $obj_2$, etc. But there is one more thing that is the essence of object-oriented programming and has no real analogue in functional programming: We always have self in the environment. While evaluating the method body, self is bound to $obj_0$, the object that is the “receiver” of the message. The binding of self in the callee as described above is what is meant by the synonyms “late-binding,” “dynamic dispatch,” and “virtual method calls.” It is central to the semantics of Ruby and other OOP languages. It means that when the body of $m$ calls a method on self (e.g., self.someMethod 34 or just someMethod 34), we use the class of $obj_0$ to resolve someMethod, not necessarily the class of the method we are executing. This is why the PolarPoint class described above works as it does. There are several important comments to make about this semantics: - Ruby’s mixins complicate the lookup rules a bit more, so the rules above are actually simplified by ignoring mixins. When we study mixins, we will revise the method-lookup semantics accordingly. - This semantics is quite a bit more complicated than ML/Racket function calls. It may not seem that way if you learned it first, which is common because OOP and dynamic dispatch seem to be a focus in many introductory programming courses. But it is truly more complicated: we have to treat the notion of self differently from everything else in the language. Complicated does not necessarily mean it is inferior or superior; it just means the language definition has more details that need to be described. This semantics has clearly proved useful to many people. - Java and C# have significantly more complicated method-lookup rules. They do have dynamic dispatch as described here, so studying Ruby should help understand the semantics of method lookup in those languages. But they also have static overloading, in which classes can have multiple methods with the same name but taking different types (or numbers) of arguments. So we need to not just find some method with the right name, but we have to find one that matches the types of the arguments at the call. Moreover, multiple methods might match and the language specifications have a long list of complicated rules for finding the best match (or giving a type error if there is no best match). In these languages, one method overrides another only if its arguments have the same type and number. None of this comes up in Ruby where “same method name” always means overriding and we have no static type system. In C++, there are even more possibilities: we have static overloading and different forms of methods that either do or do not support dynamic dispatch. Dynamic Dispatch Versus Closures To understand how dynamic dispatch differs from the lexical scope we used for function calls, consider this simple ML code that defines two mutually recursive functions: ```ml fun even x = if x=0 then true else odd (x-1) and odd x = if x=0 then false else even (x-1) ``` This creates two closures that both have the other closure in their environment. If we later shadow the `even` closure with something else, e.g., ```ml fun even x = false ``` that will not change how `odd` behaves. When `odd` looks up `even` in the environment where `odd` was defined, it will get the function on the first line above. That is “good” for understanding how `odd` works just from looking where is defined. On the other hand, suppose we wrote a better version of `even` like: ```ml fun even x = (x mod 2) = 0 ``` Now our `odd` is not “benefiting from” this optimized implementation. In OOP, we can use (abuse?) subclassing, overriding, and dynamic dispatch to change the behavior of `odd` by overriding `even`: ```ruby class A def even x if x==0 then true else odd(x-1) end end def odd x if x==0 then false else even(x-1) end end end class B < A def even x # changes B’s odd too! x % 2 == 0 end ``` Now \((B.\texttt{new.odd 17})\) will execute faster because \texttt{odd}'s call to \texttt{even} will resolve to the method in \texttt{B} – all because of what \texttt{self} is bound to in the environment. While this is certainly convenient in the short example above, it has real drawbacks. We cannot look at one class \((A)\) and know how calls to the code there will behave. In a subclass, what if someone overrode \texttt{even} and did not know that it would change the behavior of \texttt{odd}? Basically, any calls to methods that might be overridden need to be thought about very carefully. It is likely often better to have private methods that cannot be overridden to avoid problems. Yet overriding and dynamic dispatch is the biggest thing that distinguishes object-oriented programming from functional programming. ### Implementing Dynamic Dispatch Manually in Racket Let’s now consider coding up objects and dynamic dispatch in Racket using nothing more than pairs and functions.\(^4\) This serves two purposes: - It demonstrates that one language’s semantics (how the primitives like message send work in the language) can typically be coded up as an idiom (simulating the same behavior via some helper functions) in another language. This can help you be a better programmer in different languages that may not have the features you are used to. - It gives a lower-level way to understand how dynamic dispatch “works” by seeing how we would do it manually in another language. An interpreter for an object-oriented language would have to do something similar for automatically evaluating programs in the language. Also notice that we did an analogous exercise to better understand closures earlier in the course: We showed how to get the effect of closures in Java using objects and interfaces or in C using function pointers and explicit environments. Our approach will be different from what Ruby (or Java for that matter) actually does in these ways: - Our objects will just contain a list of fields and a list of methods. This is not “class-based,” in which an object would have a list of fields and a class-name and then the class would have the list of methods. We could have done it that way instead. - Real implementations are more efficient. They use better data structures (based on arrays or hashtables) for the fields and methods rather than simple association lists. Nonetheless, the key ideas behind how you implement dynamic dispatch still come through. By the way, we are wise to do this in Racket rather than ML, where the types would get in our way. In ML, we would likely end up using “one big datatype” to give all objects and all their fields the same type, which is basically awkwardly programming in a Racket-like way in ML. (Conversely, typed OOP languages are often no friendlier to ML-style programming unless they add separate constructs for generic types and closures.) Our objects will just have fields and methods: \[ \text{(struct obj (fields methods))} \] \(^4\)Though we did not study it, Racket has classes and objects, so you would not actually want to do this in Racket. The point is to understand dynamic dispatch by manually coding up the same idea. We will have fields hold an immutable list of mutable pairs where each element pair is a symbol (the field name) and a value (the current field contents). With that, we can define helper functions get and set that given an object and a field-name, return or mutate the field appropriately. Notice these are just plain Racket functions, with no special features or language additions. We do need to define our own function, called assoc-m below, because Racket’s assoc expects an immutable list of immutable pairs. ```racket (define (assoc-m v xs) (cond [(null? xs) #f] [(equal? v (mcar (car xs))) (car xs)] [#t (assoc-m v (cdr xs))])) (define (get obj fld) (let ([pr (assoc-m fld (obj-fields obj))]) (if pr (mcdr pr) (error "field not found")))) (define (set obj fld v) (let ([pr (assoc-m fld (obj-fields obj))]) (if pr (set-mcdr! pr v) (error "field not found")))) ``` More interesting is calling a method. The methods field will also be an association list mapping method names to functions (no mutation needed since we will be less dynamic than Ruby). The key to getting dynamic dispatch to work is that these functions will all take an extra explicit argument that is implicit in languages with built-in support for dynamic dispatch. This argument will be “self” and our Racket helper function for sending a message will simply pass in the correct object: ```racket (define (send obj msg . args) (let ([pr (assoc msg (obj-methods obj))]) (if pr ((cdr pr) obj args) (error "method not found" msg))))) ``` Notice how the function we use for the method gets passed the “whole” object obj, which will be used for any sends to the object bound to self. (The code above uses Racket’s support for variable-argument functions because it is convenient — we could have avoided it if necessary. Here, send can take any number of arguments greater than or equal to 2. The first argument is bound to obj, the second to msg, and all others are put in a list (in order) that is bound to args. Hence we expect (cdr pr) to be a function that takes two arguments: we pass obj for the first argument and the list args for the second argument.) Now we can define make-point, which is just a Racket function that produces a point object: ```racket (define (make-point _x _y) (obj (list (mcons 'x _x) (mcons 'y _y)) (list (cons 'get-x (lambda (self args) (get self 'x))) (cons 'get-y (lambda (self args) (get self 'y))) (cons 'set-x (lambda (self args) (set self 'x (car args)))))) ``` 22 (cons 'set-y (lambda (self args) (set self 'y (car args)))) (cons 'distToOrigin (lambda (self args) (let ([a (send self 'get-x)] [b (send self 'get-y)]) (sqrt (+ (* a a) (* b b))))) ) Notice how each of the methods takes a first argument, which we just happen to call `self`, which has no special meaning here in Racket. We then use `self` as an argument to `get`, `set`, and `send`. If we had some other object we wanted to send a message to or access a field of, we would just pass that object to our helper functions by putting it in the `args` list. In general, the second argument to each function is a list of the “real arguments” in our object-oriented thinking. By using the `get`, `set`, and `send` functions we defined, making and using points “feels” just like OOP: (define p1 (make-point 4 0)) (send p1 'get-x) ; 4 (send p1 'get-y) ; 0 (send p1 'distToOrigin) ; 4 (send p1 'set-y 3) (send p1 'distToOrigin) ; 5 Now let’s simulate subclassing... Our encoding of objects does not use classes, but we can still create something that reuses the code used to define points. Here is code to create points with a color field and getter/setter methods for this field. The key idea is to have the constructor create a point object with `make-point` and then extend this object by creating a new object that has the extra field and methods: (define (make-color-point _x _y _c) (let ([pt (make-point _x _y)]) (obj (cons (mcons 'color _c) (obj-fields pt)) (append (list (cons 'get-color (lambda (self args) (get self 'color))) (cons 'set-color (lambda (self args) (set self 'color (car args)))))) (obj-methods pt)))) We can use “objects” returned from `make-color-point` just like we use “objects” returned from `make-point`, plus we can use the field `color` and the methods `get-color` and `set-color`. The essential distinguishing feature of OOP is dynamic dispatch. Our encoding of objects “gets dynamic dispatch right” but our examples do not yet demonstrate it. To do so, we need a “method” in a “superclass” to call a method that is defined/overridden by a “subclass.” As we did in Ruby, let’s define polar points by adding new fields and overriding the `get-x`, `get-y`, `set-x`, and `set-y` methods. A few details about the code below: - As with color-points, our “constructor” uses the “superclass” constructor. - As would happen in Java, our polar-point objects still have `x` and `y` fields, but we never use them. • For simplicity, we just override methods by putting the replacements earlier in the method list than the overridden methods. This works because assoc returns the first matching pair in the list. Most importantly, the distToOrigin “method” still works for a polar point because the method calls in its body will use the procedures listed with 'get-x and 'get-y in the definition of make-polar-point just like dynamic dispatch requires. The correct behavior results from our send function passing the whole object as the first argument. (define (make-polar-point _r _th) (let ([pt (make-point #f #f)]) (obj (append (list (mcons 'r _r) (mcons 'theta _th)) (obj-fields pt)) (append (list (cons 'set-r-theta (lambda (self args) (begin (set self 'r (car args)) (set self 'theta (cadr args)))))) (cons 'get-x (lambda (self args) (let ([r (get self 'r)] [theta (get self 'theta)]) (* r (cos theta)))))) (cons 'get-y (lambda (self args) (let ([r (get self 'r)] [theta (get self 'theta)]) (* r (sin theta)))))) (cons 'set-x (lambda (self args) (let* ([a (car args)] [b (send self 'get-y)] [theta (atan (/ b a))] [r (sqrt (+ (* a a) (* b b)))] (send self 'set-r-theta r theta)))) (cons 'set-y (lambda (self args) (let* ([b (car args)] [a (send self 'get-x)] [theta (atan (/ b a))] [r (sqrt (+ (* a a) (* b b)))] (send self 'set-r-theta r theta)))) (obj-methods pt))))) We can create a polar-point object and send it some messages like this: (define p3 (make-polar-point 4 3.1415926535)) (send p3 'get-x) ; 4 (send p3 'get-y) ; 0 (or a slight rounding error) (send p3 'distToOrigin) ; 4 (or a slight rounding error) (send p3 'set-y 3) (send p3 'distToOrigin) ; 5 (or a slight rounding error)
{"Source-Url": "http://courses.cs.washington.edu/courses/cse341/13wi/unit7notes.pdf", "len_cl100k_base": 16204, "olmocr-version": "0.1.46", "pdf-total-pages": 24, "total-fallback-pages": 0, "total-input-tokens": 63501, "total-output-tokens": 17589, "length": "2e13", "weborganizer": {"__label__adult": 0.0004220008850097656, "__label__art_design": 0.0003833770751953125, "__label__crime_law": 0.00021266937255859375, "__label__education_jobs": 0.003265380859375, "__label__entertainment": 8.362531661987305e-05, "__label__fashion_beauty": 0.00015497207641601562, "__label__finance_business": 0.00017595291137695312, "__label__food_dining": 0.0003902912139892578, "__label__games": 0.0005469322204589844, "__label__hardware": 0.0004215240478515625, "__label__health": 0.000274658203125, "__label__history": 0.00020754337310791016, "__label__home_hobbies": 0.00010287761688232422, "__label__industrial": 0.0003120899200439453, "__label__literature": 0.0003266334533691406, "__label__politics": 0.00019443035125732425, "__label__religion": 0.0005397796630859375, "__label__science_tech": 0.001651763916015625, "__label__social_life": 0.0001461505889892578, "__label__software": 0.004184722900390625, "__label__software_dev": 0.98486328125, "__label__sports_fitness": 0.0003261566162109375, "__label__transportation": 0.00047659873962402344, "__label__travel": 0.00023484230041503904}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 71326, 0.01412]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 71326, 0.69006]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 71326, 0.89711]], "google_gemma-3-12b-it_contains_pii": [[0, 4724, false], [4724, 8334, null], [8334, 10975, null], [10975, 14042, null], [14042, 17576, null], [17576, 20570, null], [20570, 23215, null], [23215, 26354, null], [26354, 29928, null], [29928, 33658, null], [33658, 36209, null], [36209, 38563, null], [38563, 41219, null], [41219, 44174, null], [44174, 46503, null], [46503, 49612, null], [49612, 51753, null], [51753, 54204, null], [54204, 58228, null], [58228, 60700, null], [60700, 63912, null], [63912, 66501, null], [66501, 69076, null], [69076, 71326, null]], "google_gemma-3-12b-it_is_public_document": [[0, 4724, true], [4724, 8334, null], [8334, 10975, null], [10975, 14042, null], [14042, 17576, null], [17576, 20570, null], [20570, 23215, null], [23215, 26354, null], [26354, 29928, null], [29928, 33658, null], [33658, 36209, null], [36209, 38563, null], [38563, 41219, null], [41219, 44174, null], [44174, 46503, null], [46503, 49612, null], [49612, 51753, null], [51753, 54204, null], [54204, 58228, null], [58228, 60700, null], [60700, 63912, null], [63912, 66501, null], [66501, 69076, null], [69076, 71326, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 71326, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, true], [5000, 71326, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 71326, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 71326, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, true], [5000, 71326, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 71326, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 71326, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 71326, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 71326, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 71326, null]], "pdf_page_numbers": [[0, 4724, 1], [4724, 8334, 2], [8334, 10975, 3], [10975, 14042, 4], [14042, 17576, 5], [17576, 20570, 6], [20570, 23215, 7], [23215, 26354, 8], [26354, 29928, 9], [29928, 33658, 10], [33658, 36209, 11], [36209, 38563, 12], [38563, 41219, 13], [41219, 44174, 14], [44174, 46503, 15], [46503, 49612, 16], [49612, 51753, 17], [51753, 54204, 18], [54204, 58228, 19], [58228, 60700, 20], [60700, 63912, 21], [63912, 66501, 22], [66501, 69076, 23], [69076, 71326, 24]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 71326, 0.0]]}
olmocr_science_pdfs
2024-11-23
2024-11-23
11f3cdfd2e613ad286ae0a9331d5df629eb3376c
5-2007 ATTESTATION-BASED REMOTE BIOMETRIC AUTHENTICATION Thomas Polon Clemson University, tpolon@alumni.clemson.edu Follow this and additional works at: https://tigerprints.clemson.edu/all_theses Part of the Electrical and Computer Engineering Commons Recommended Citation Polon, Thomas, "ATTESTATION-BASED REMOTE BIOMETRIC AUTHENTICATION" (2007). All Theses. 117. https://tigerprints.clemson.edu/all_theses/117 This Thesis is brought to you for free and open access by the Theses at TigerPrints. It has been accepted for inclusion in All Theses by an authorized administrator of TigerPrints. For more information, please contact kokeefe@clemson.edu. ATTESTATION-BASED REMOTE BIOMETRIC AUTHENTICATION A Thesis Presented to the Graduate School of Clemson University In Partial Fulfillment of the Requirements for the Degree Master of Science Computer Engineering by Thomas Polon May 2007 Accepted by: Samuel Sander, Committee Chair Walt Ligon Tarek Taha ABSTRACT Migration from password and token-based authentication in distributed systems requires fundamental changes to the authentication process. A person’s biometric data is not a secret, which presents a fundamental difference with other authentication methods. Matching a sample with a database template is secondary to establishing trust in the integrity of the sample. The process is similar to establishing a chain of custody for judicial evidence. In computer systems this is accomplished using attestation architectures. In this paper, a design for a secure remote biometric login system based on an attestation architecture is analyzed. The system uses a commercially available Trusted Platform Module (TPM) to authenticate the platform during the boot process and perform trusted private-key functions to participate in a challenge/response between the client and a remote biometric matcher. The result is a system that can provide higher assurance than current systems in an economically and administratively feasible system. # TABLE OF CONTENTS <table> <thead> <tr> <th>Chapter</th> <th>Page</th> </tr> </thead> <tbody> <tr> <td>TITLE PAGE</td> <td>i</td> </tr> <tr> <td>ABSTRACT</td> <td>iii</td> </tr> <tr> <td>TABLE OF CONTENTS</td> <td>v</td> </tr> <tr> <td>LIST OF FIGURES</td> <td>vii</td> </tr> <tr> <td>CHAPTER</td> <td></td> </tr> <tr> <td>1. INTRODUCTION</td> <td>1</td> </tr> <tr> <td>2. BACKGROUND</td> <td>7</td> </tr> <tr> <td>Related Work</td> <td>7</td> </tr> <tr> <td>Attestation Overview</td> <td>11</td> </tr> <tr> <td>BioAPI Overview</td> <td>13</td> </tr> <tr> <td>3. METHODOLOGY</td> <td>21</td> </tr> <tr> <td>Code Overview</td> <td>26</td> </tr> <tr> <td>Results</td> <td>27</td> </tr> <tr> <td>Threat Assessment</td> <td>31</td> </tr> <tr> <td>Conclusions</td> <td>33</td> </tr> <tr> <td>Future Work</td> <td>33</td> </tr> <tr> <td>APPENDIX</td> <td>35</td> </tr> <tr> <td>REFERENCES</td> <td>39</td> </tr> <tr> <td>Figure</td> <td>Page</td> </tr> <tr> <td>-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------</td> <td>------</td> </tr> <tr> <td>1. Attack Tree For Generic System</td> <td>3</td> </tr> <tr> <td>2. Block Diagram For Boot Sequence</td> <td>12</td> </tr> <tr> <td>3. Client/Server Implementation Using Primitive Functions</td> <td>16</td> </tr> <tr> <td>5. Client/Server Implementation Using Streaming Callback – Client Initiated Operation</td> <td>18</td> </tr> <tr> <td>6. Client/Server Overview</td> <td>21</td> </tr> <tr> <td>7. Example Seal</td> <td>24</td> </tr> <tr> <td>8. Sequence Diagram For Authentication Protocol</td> <td>25</td> </tr> <tr> <td>9. Successful Sample Program Initialization</td> <td>28</td> </tr> <tr> <td>10. Failed Startup By Slightly Modifying The Driver</td> <td>28</td> </tr> <tr> <td>11. Successful BioAPI Device Test</td> <td>29</td> </tr> <tr> <td>12. Failed Device Test</td> <td>30</td> </tr> <tr> <td>13. Attack Tree For The Proposed System</td> <td>31</td> </tr> </tbody> </table> CHAPTER ONE INTRODUCTION Using biometric authentication as a primary means for system authentication is a viable alternative to using password authentication. However, this technology is still in its relative infancy, and issues concerning secure implementation of biometrics remain. Aside from assessing and improving the performance of specific biometrics, most current and past research in biometric system security revolves around protection of the biometric template. In this research, an attestation architecture is used in conjunction with biometric middleware to establish authenticity in the biometric capture process, resulting in a trusted path for secure biometric authentication. In most current authentication systems, the primary means for authentication is by password. However, most passwords are simple enough that they can be easily guessed or broken through simple dictionary attacks [6]. Thus, the system is only as secure as the password used for authentication. Simple passwords are easy to crack and compromise security. However, complex passwords are difficult to remember and are expensive to maintain. Adding to the problem, most users use the same password for different authentications/applications and therefore, if a password is compromised, it gives an attacker the full privileges assigned to the user. Password limitations can be improved by incorporating other methods of user authentication. One such method is biometric authentication. Biometric authentication refers to verifying individuals based on their physiological or behavioral characteristics. This can include such things as fingerprints, hand geometry, retina, and voice. Biometric authentication is potentially more reliable than password-based authentication, since biometric characteristics cannot be lost or stolen, they are difficult to copy, and they require presence at the point of authentication. Consequently, biometric authentication has the potential to become the primary authentication method in computing systems, but technical advances are needed in the three areas listed below to improve security. - **Performance** – reliable, unique measurement of biometric for widest set of users - **Liveness testing** – detection of physical spoofing - **Sample authenticity** – establishment of sample collection process Performance and liveness testing involve modality-specific improvements, and these metrics are important to assess before considering the use a particular biometric. This paper focuses on the third issue: sample authenticity, which current remote authentication systems give little attention to. Matsumoto and others successfully used fake fingerprints to achieve a biometric match [5]. Improved liveness testing can prevent physical attacks like these that do not compromise the system, but signal injection attacks will continue to be possible because sensors do not bind the sample to the identity of the sensor or the time that the sample was taken. For instance, retina scanning, which would be very difficult to spoof through physical means, can still be recorded and replayed at the sensor level. The use of templates protects privacy and prevents reuse of biometric samples between systems [4, 16], but there is little to prevent a dishonest party from capturing a biometric in raw form to be used as a live sample in another system. As biometric identification becomes widespread, people will become accustomed to frequently providing biometric samples, and the possibility of a Trojan sample acquisition or a dishonest administrator is realistic. The result is similar to using the same password for multiple systems. When personal biometrics are no longer a secret, then how can an automated system be sure that a biometric sample is coming from a biometric device and not recorded data? Consequently, biometric samples must be treated more like evidence and less like a password. Consider the attack tree in Figure 1, which represents a standard remote biometric login without trusted hardware. The system can be attacked through software or hardware (locally), and there is little to prevent an attacker from inserting a biometric sample from anywhere in the network, perhaps from an untraceable location. The addition of a local private key provides minimal additional protection, because an --- **Figure 1: Attack Tree For Generic System.** attacker can use a virus or Trojan horse to retrieve keystores, capture biometric samples, and keystrokes from an authorized user’s workstation. From the example in Figure 1, it is clear that adding a biometric to an insecure system provides little benefit, and there is no distinction between a valid platform and an attacker’s platform that can provide the same credentials. The opportunity for an attacker to insert or capture a live sample starts with the end sensor and continues up the chain until a trusted entity can sign or encrypt the sample. Ideally this would occur in the sensor itself, but this would require key management at the device level. Providing tamper resistance, enrollment and revocation at the device level would be ideal, but it is not considered in this paper due to the large administrative burden. Instead, it is more reasonable to establish a chain of integrity within the platform and sign the sample by the local root of trust. The level of trust in the signature depends on the ability to protect the key and the ability to authenticate requests to use the key. If the key is protected by tamper resistant hardware, and if the authenticity of the software is verified prior to signing, then this establishes a trusted relationship between the platform and the live sample. This can be accomplished using a commercially available attestation architecture, where components vouch for the validity of information by signing with a private key. In this research, the Trusted Computing Group’s (TCG) Trusted Platform Module (TPM) [14] is used in the design of a secure remote biometric login system. The process involves a chain of several components, and each verifies the next component. The system remains independent of specific biometric technologies using the BioAPI specification [2]. A remote matching service is used to reduce the physical exposure of the final decision point, and the remote match is performed as a system independent step that can provide authentication credentials for multiple systems. In the following chapter, the background on which this research was built upon is presented. First, the related work will be covered. It can be noted that most work related to biometric security revolves around template security, as mentioned earlier. During this section, reasons why template protection alone is not enough for biometric security will be presented. Following this, an overview of bioAPI as well as an overview of our attestation device will be given. In relation to bioAPI, reasons why it is not secure in its current form will be presented. In the final chapter, the research methodology will be presented. First, an overview of the actual hardware and software used will be given. Second, an overview of the code used in this research is given. Next, the results are provided, which show how the work provides added security to a biometric system. Finally, conclusions are stated along with possible work in the future which can solidify a fully trusted path. CHAPTER TWO BACKGROUND Given the assumption that raw biometric data cannot be considered a secret as discussed in the previous section, approaches that create secret keys or unlock secret keys using biometric data are incomplete without integrity verification. This is still true if the algorithms used to achieve these ends remain a secret, since raw data can be injected to replace sensor data. Creation of keys from biometric data removes the need to trust the matching algorithm, but this is not useful if the biometric sample is not a secret or is not combined with other secrets. Using a local biometric match to unlock a key, which is used as the network login credential, can be even less secure than using a password. A biometric match is typically a Boolean value (after thresholding), providing no protection beyond code obfuscation, which is difficult to quantify. Password attacks at least have a measure of protection through repeated hashing to slow down a brute force attack. Even if sufficient protection is provided to enforce that a valid live sample is used to unlock the key, what mechanism prevents an attacker from using an electronic copy of a valid live sample to the matching algorithm? 2.1 Related Work Most work related to the protection of biometric data centers around template protection. This is quite important as biometric data spends most of its time in template form. However, if the biometric is not a secret, how important and how protected is the template if the raw data itself can in no way be legitimized? Sun et al. [10] proposed a template called KMT, or Key-Mixed Template. The idea is to use the template in conjunction with a secret key to create a new template. This mixture between the secret key and the original template is done on the user end and is matched on the server side with the database. By having a separate secret key per authentication system, having a template compromised does not necessarily mean the attacker can gain access to all systems that use that biometric template. This new template can help to prevent backend attacks, snooping, and tamper attacks without a performance hit. Sutcu et. al. [12] proposed a method for protecting minutiae-based fingerprint templates using a geometric transformation. The solution creates a two-dimensional vector from a set of minutiae points. A centroid point is calculated from this minutiae set and a circle is drawn around it. For every pair of minutiae points in the set that are greater than a pre-defined threshold, a line is drawn through them and the two points of intersection of the line and circle are determined. The intersection points are then organized into bins according to their position in the circle and the number of points in each bin are concatenated together to create the fingerprint code. This sounds fine in theory, but no rigorous security testing has been done as of yet, so the robustness of the code is not known. Furthermore, like other work which only deals with template protection, this work would not be able to protect against a raw biometric data compromise. Sutcu et. al. [11] also proposed a system to protect biometric templates by using secure sketch, an error-tolerant cryptographic primitive. They use feature vector extraction on biometric samples, apply user-specific random mapping on these vectors, and then secure them using the sketch. However, they note that the security measure in terms of entropy loss may not be sufficient since false accept rate and false reject rate should also be considered in practical systems. Uludag et. al. [16] proposed to generate a cryptographic key using biometric information. Their solution proposed to hide a cryptographic key in the user’s biometric template itself. It relies heavily on the robustness of the key hiding and retrieval algorithms, which could be placed within the biometric reader device, requiring controlled biometric devices. However, this does not really help to add security if the biometric itself is not a secret. Jain et. al. [4] constructed a list of possible biometric attacks which would leave biometrics vulnerable. From this list, they determined that it is of high importance to make sure the template is secure and cannot be compromised. Possible techniques to increase security within templates include watermarking and steganography. Also, by using smartcards to store biometric templates, the chance of an attacker stealing the template is reduced considerably. While all these systems help to protect the template, this still does not protect or authenticate the raw biometric capture data (before it is put into a template), and it also does not provide a trusted path from the capture device to the biometric server. While the biometric data does exist mostly in template form, and template protection is important, the raw data cannot be ignored. If an attacker were to steal the raw biometric data from one system and use it with a modified device in another to gain access, how could this be prevented? A protected template means nothing if it protects raw data that is easily stolen from another system and injected in the present one. For a system to fully trust that a user is who he or she says, the full path from the device to the authenticator needs to be trusted. Using a TPM to enhance the security of a biometric login is not a new idea, and there are multiple commercial solutions and research concepts using this widely available security tool [1, 3]. However, current systems only provide a wrapper around legacy password based systems (a successful biometric match unlocks a password cache). This places full trust in an end device that could be subjected to a rigorous offline attack. Current systems also do not provide sufficient authentication of the software on the platform used to collect the biometric sample. For instance, current systems do not detect if the device driver has been altered to send a pre-captured sample rather than read from the device. Ratha et. al. proposed a challenge/response system to alleviate the problem with resubmission attacks on biometric devices [7]. In their proposed method, the server would generate a random challenge and the sensor would compute a response to the challenge. Their research involves custom sensor devices, which use sensors that are able to integrate logic to participate in a challenge/response system. The research in this paper assumes no changes are made to the biometric sensor device. Chen and others proposed an attestation based system to provide for the integrity of the biometric sample [3]. Their work required a custom, trusted biometric reader device and a modified TPM capable of performing a biometric match, which may not be practical. The research in this paper assumes that an unaltered TPM and a standard biometric reader will be used, albeit at the cost of less assurance in the capture process. Additionally, rather than performing a local match and releasing a key that provides for a login credential, this paper uses a local key to attest that a live sample was collected from what appeared to be a valid device and then the signed sample is sent to a biometric matching server. A remote matching server provides additional security measures: it removes the capacity for offline attacks of the matching process, it provides increased integrity, and it provides better auditing and management of the authentication process. 2.2 Attestation Overview This system uses an attestation device to derive a trusted platform, which extends work by Safford [8] to include verification of the network client, BioAPI, and the biometric device driver. The research system uses the TCG Trusted Platform Module (TPM) Specification version 1.1b [14]. However, a newer version of this specification is currently available [15], which may be used in future development as resources permit. The TPM chip provides several security features to help make a system more secure [8]. The first is a boot-time authentication system. The TPM has the ability to measure the system as it is booted and as software is loaded. This creates a profile of the system’s operating software. This profile is based on a hash computed by the TPM from code as it is loaded. The TPM has sixteen Platform Configuration Registers (PCR) that can be used to store the hashes of the software boot chain. This checks the integrity of the BIOS, the MBR, trusted GRUB, Linux kernel, the initial Ramdisk image, the net client, BioAPI, and the biometric device driver. An example of this can be seen in Figure 2. In this system, each layer authenticates the next layer. This ensures integrity as the next layer is not loaded unless the previous layer has been approved. By doing this, we can provide evidence that all pertinent software components on the machine are unaltered. Figure 2: Block Diagram For Boot Sequence. The contents of the TPM’s Platform Configuration Registers can be compared to reference values at any time. This means that not only will all pertinent software be checked during the boot sequence, but if the software is reloaded at any time while the computer is on, the PCR will recheck the value with the reference value. If the values differ, an appropriate action (determined by the user) can be taken. Examples could be automatically denying access or prompting the user for a decision. The advantage to this is in situations when the intruder attempts to bypass the boot check by injecting a virus/worm after the computer has already booted. The TPM can also provide additional security by signing the hash value stored in the PCR. The signed value serves as proof of the state of the remote machine. For a server to only read the hash value of a remote machine does not provide assurance that the machine should in fact have access to the network. This is because stored, unsigned hash values can be stolen from one machine and used in another for an attack. Another possibility is an attacker changing the values during transmission. By signing the values using a trusted key inside the TPM, the remote party can be assured that the hash is legit. The TPM also provides hardware based public key management and authentication. The private keys for these services cannot be stolen by software attacks as they are generated and kept on-chip. Finally, it provides secure storage of data. This can include keys, which the TPM maintains over reboots. 2.3 BioAPI overview The purpose of BioAPI [2] was to provide an API that could serve the various biometric languages. The BioAPI Consortium was formed in April of 1998, with a multi-level API architecture developed later in that year. In December of 1998, I/O Software joined and the BAPI specification was integrated as the lower level of the BioAPI specification. In March 2000, Version 1.0 of the BioAPI Specification was released. BioAPI was originally developed to be a multi-level API. The “high level” would include basic calls such as enroll, verify, and identify. The lower level would address increasing control, detail, sophistication, and technology dependence. However, it was decided that the lower level proposals were not broad enough to justify inclusion into the API. Therefore, when Version 1.0 was published in 2000, it was done so as a single layer API. Features The API consists of three high-level abstraction functions: Enroll, Verify, and Identify. During Enroll, samples are captured from the biometric device, processed into a template, and then sent to the application. The Verify function captures one or more samples from the device, processes them into a template, and then matches the template against an input template. The results of this comparison are returned to the application. The Identify function is similar to the Verify in that a comparison takes place. However, instead of matching the captured sample template against a single input template that the user claims to be, the captured sample template is matched against a set of templates and a list is returned showing how close the sample compares against the top candidates in the set. The processing of biometric data from raw samples to template to matching against a template can be accomplished in many stages. However, this usually involves much CPU-intensive processing. The API has been defined to allow the developer as much freedom as needed in the placement of processing involved. It also allows the processing to be shared between the original client machine and possibly a server machine. Furthermore, it allows for devices that can do all the processing internally. There are other reasons as to why processing and matching are a good idea to do on a server. First, the algorithms will execute in a more secure and trusted environment. Second, the client PC may not have enough horsepower to run the algorithms as well, or not have the ability to support a large local database, both of which can be provided by a server. Third, the user database and resources may already be on the server, so this makes it more convenient. Finally, identification over large populations can only reasonably be done on a server. However, the developer needs to be very careful. Transmitting raw biometric data over a network between a client and a server could leave the data vulnerable to being captured by an attacker. This problem can be alleviated by creating the template on the client system, but again, this is up to the administrator as the client system might not be very powerful and take time to create the template. There are two methods provided by the API which support client/server processing. The first is the use of primitive functions. There are four primitive functions in the API which can accomplish the same result as high-level abstractions. They are Capture, Process, Match, and CreateTemplate. Capture is the process of capturing biometric data. This is always performed on the client machine. Doing so on a server (which would not have a biometric device attached) would return an error. The samples are acquired, done for the three basic functions mentioned earlier (Enroll, Verify, or Identify), and processing on the samples are then done. The Capture function is capable of performing all the processing on a sample and it is up to the developer as to how much is actually done on the client. The Process function is used to process samples necessary for verification and identification, but not enrollment. These algorithms must be available on the server; however, they can also be available on the client. On the server, processing will always be completed. On the client however, the application can defer processing to the server. Also, in an effort to save bandwidth or server horsepower, the client can opt to finish the processing itself. The Match function performs the actual comparison between the templates. It can be done between two templates (VerifyMatch) or a set of templates in a database. (IdentifyMatch). The match functions are always available on the server, and much like the process function, they may also be available on the client. The last function included in the primitive functions is the CreateTemplate function. It is provided to perform the processing of samples to form a template. Optionally, the function can also take an existing template and create a new template from it, using new samples acquired. Another option is the ability to allow the application to provide a “payload” to wrap inside the new template. An example of a primitive function implementation is shown in Figure 3. ![Diagram](image) **Figure 3: Client/Server Implementation Using Primitive Functions (Taken From The BioAPI Specification, Version 1.1 [2]).** The second method provided by the API to allow client/server processing support is called streaming callback. In this method, the application is responsible for providing a streaming interface to transfer the samples and return the results. Also, the application does not need to use the primitive functions described earlier. The Verify, Identify, and Enroll functions use the streaming interface to split the functions between client and server. If there are GUI callbacks set, the client will call them when needed to allow the application to control the look and feel of the UI. Streaming Callback leaves the decision making to the application. The client/server application decides whether authentication is driven by the client or the server. First, the driving component sets a Streaming Callback interface for the biometric service provider (BSP). Not only does this tell the BSP that it will operate in client/server mode, but also provides an interface for communication. The application then calls the appropriate high-level function, and the BSP calls the Streaming Callback to initiate the BSP-to-BSP protocol. The Streaming Callback is only used by the driving BSP. Whenever it is in control and has a message to deliver to its partner, it calls the interface to send the message, and receives an answer on return. A StreamInputOutput function is used by the non-driving application in order to deliver messages to the driving BSP. The driving application sends a return message by returning from the Streaming Callback. Figure 4 and Figure 5 show examples of a streaming callback implementation. Figure 4: Client/Server Implementation Using Streaming Callback - Server Initiated Operation (Taken From The BioAPI Specification, Version 1.1 [2]). Figure 5: Client/Server Implementation Using Streaming Callbacks - Client Initiated Operation (Taken From The BioAPI Specification, Version 1.1 [2]). Security Risks As discussed earlier, there are some possible security risks associated with having an open system using biometrics and BioAPI. The most common types of attacks might be in the form of signal injection, a Trojan horse, or software alteration. All of these attacks might give an intruder the ability to spoof an allowed user to gain access into the system. The first possible attack covered is a signal injection. Suppose an attacker was able to acquire a user’s biometric data from some other system. The way it was acquired is not really known but that is not important. The attacker has the raw data of an allowed user and can therefore possibly inject this data into the system. As long as the data is injected before the step where the raw data is converted into a template, the system will have no idea that the sample was injected and not captured from the biometric device. If this attack were to occur, the attacker would gain access and the system would be none the wiser. A second common attack would be a Trojan horse. This type of attack could be used in conjunction with the previous attack. For instance, the malicious script would extract the raw sample from the sequence chain (before it was converted to a template). This might happen on another system which is not as secure and therefore the attacker has access too. Or, it could be on the same system where the attacker has limited rights and is trying to gain access as a user with more rights on the system. An attacker can use a virus or Trojan horse to retrieve keystores, capture biometric samples, and keystrokes from an authorized user’s workstation. The third common attack discussed is software alteration. With an open system that has modifiable software and drivers, it is important that the software is not altered maliciously to allow attackers access. In the case of biometrics, some software might be altered to increase the false acceptance rate (FAR). Furthermore, BioAPI might be altered to pull templates or samples from locations other than the biometric sensor. It is important, therefore, to make sure that after the BioAPI software is installed, as well as the other pertinent biometric software, it is not being changed or altered. The system needs to be in the same working state that it was in when it was originally installed. CHAPTER THREE METHODOLOGY The research system uses platform authentication and remote matching to create a medium-grade authentication using a single-factor biometric authentication (which would be backed up by a password and token for users that are unable to reliably use the system). The hardware of the user workstation consists of a biometric device (any device with a Linux BioAPI device driver) and a complete commodity workstation equipped with an embedded TCG compliant TPM. The major software components of the user workstation consist of a trusted boot loader, operating system, network client, BioAPI, and a biometric device driver. By using a TPM in a bootstrap process [7], there is a measure of assurance that the platform has not been altered and that the proper driver is used to collect the sample. Figure 6: Client/Server Overview. A Biometric Authentication Server (BAS), shown in Figure 6, is used to evaluate the validity of a biometric sample using evidence provided by the user workstation as well as match the sample with a known template. Notice how the BAS is completely a completely separate entity from the login/remote service. To enable validation, a root of trust acknowledged by the BAS must enroll each user workstation. Given a successful validation and match, the BAS returns the requested login credentials – ideally in the form of signed challenges. The BAS is similar to the user workstation with the exception of the additional BAS service software and a reduced set of user applications. Like the user workstation, the BAS is designed to use BioAPI to be independent of biometric technologies. Additionally, the BAS enables independence from network services enabling a one-time login and removal of the requirement for network services to be biometric-aware. A remote biometric match also enables the following security features. - User revocation - Workstation revocation - Multiple attempt lockout - Convenient algorithm updates - Reliable auditing - Intrusion prevention possibilities These features prevent an attacker with physical access to an approved platform from physically spoofing a valid biometric. Our research platform is described in more detail as follows. The user workstation is an IBM ThinkPad z60t, outfitted with a TCG TPM (Version 1.1b) [9] and a built-in UPEK fingerprint reader device. The operating system is the Red Hat Fedora Core 5 with Linux kernel version 2.6.15. The Linux fingerprint driver provided by UPEK is invoked through BioAPI [2] to collect the fingerprint sample from the reader. Trousers, the open-source TCG Software Stack, is used to interact with the TPM [8]. Currently, a small program that requests a biometric sample through BioAPI is used to emulate the network client. A seal program needs to be used on the platform to seal all the data important to keeping the integrity of the system. When the system is in a known good state, the administrator will run a seal on all the data to be unsealed when the user attempts to log on at a later time. An example of the seal being run is shown in Figure 7. From the command line, the seal executable is run with three parameters. The first parameter is the TPM version, the second parameter is the PCR register to hold the system state for when the unseal is called. The last parameter is the file to be sealed. This command needs to be run for every file required to establish system integrity. In the figure below, the file being sealed is the biometric device driver. The protocol for the login sequence is shown in Figure 8. All communications between the local client and the remote service use 2-way authenticated SSL. Both the local machine and the remote service will contain private keys protected in hardware. When the local machine sends a login request to the remote service, the remote service will return an authentication challenge. The local client will then forward the challenge to the BioAPI, which will request a live sample from the biometric device. However, before the live sample is requested, the TPM will check the biometric driver during the BioAPI Init call. If the biometric driver has been compromised, the TPM will not allow BioAPI to finish initializing and the authentication will halt. If the biometric driver is unaltered, the TPM will allow the authentication to continue and the live sample to be requested. This and subsequent steps involving BioAPI interacting with the BAS and the TPM represent new functionality that is proposed as an enhancement to the current BioAPI or a new layer on top of the current BioAPI. Before taking the sample, and while BioAPI is initializing, the TPM will check the platform to make sure it has not been compromised. If the machine is in an approved state, the TPM will allow the authentication to continue. The TPM will then allow BioAPI to take the live sample, which it will forward to the BAS. The BAS will then check for a match. If a match is found the BAS will send a response for the authentication challenge back to the local client. The local client will send this response to the remote service, where it will be verified. A result is then sent back to the local client, either allowing or refusing a login. Figure 8: Sequence Diagram For Authentication Protocol. Below are example pseudo equations for the TPM functions used in this research. The name of the driver as well as the PCR used for this specific research are included in the equations for clarity. - **Seal Operation** - SealedDataBlob=Kroot(SHA1(libtfmessbsp.so),PCR8) - **Unseal Operation** - UnsealData=Kroot(SealedDataBlob,PCR8) - UnsealData?=SHA1(libtfmessbsp.so) - **Verify Operation** - CurrentConfig?=PCR8 The equations are explained as follows. For the seal function, the TPM root key (denoted by Kroot) is used to seal a SHA-1 hash of the driver, as well as store the current configuration at the time of seal in PCR-8. This sealed blob is then stored to a file. When the unseal is performed, the TPM will again use the root key to unseal this blob. At the time of unseal, the current value in PCR-8 will be checked against the value at the time of seal. If they do not match the unseal will fail. After the data is unsealed, the unsealed data will be checked against a SHA-1 hash of the current driver. If they differ by even one bit, the operation fails. Finally, during the verify phase of the login sequence, the current client configuration is compared against the reference value to make sure that no tampering has occurred while the biometric sample was being acquired. 3.1 Code Overview The code written consists of two main files, the seal function and the unseal function. The seal function receives a PCR number to use as well as the file to be sealed. Within the program, all the TPM handles are called and the file is sealed. However, before the seal function is called, a SHA-1 hash of the file is taken. This is done for two reasons: to make the file harder to infiltrate by attackers and to make the file sealable (the seal function has an upper file limit of 150 bytes). After the file is sealed, the data blob is outputted to a file. The unseal function, for the most part, looks very similar to the seal function. The same TPM handles are called and a file is passed in to compare with the unsealed data. Within the program, the blob is also passed in to be unsealed. After the unseal, the data, which will still be a SHA-1 hash, will be compared to a hash of the file being passed in. If both files match, the unseal function will return success and the initialize will continue. Otherwise it will return a failure and the initialize will stop and BioAPI will not start. The last written code was a modification to the BioAPI source code. The file modified was the manage_interface.c file. In this file, the unseal function mentioned earlier was added to the BioAPI initialization function. The unseal function is called and depending on the result, the initialization will continue or the API will completely stop loading. Finally, the original script used to install BioAPI and the driver was modified to copy over the unseal function, the hash function, and a new Makefile in the h_layer folder of the BioAPI source code that includes these functions. This Makefile has been modified to include the unseal function and the hash function as sources, creates object files from them, and adds them to the library. ### 3.2 Results The objective of the research system is to prevent most, if not all attacks that do not exploit the capture device. By using an attestation device as well as a challenge/response system between the authentication service and the biometric authentication service, we can assure that most attacks will be prevented. The result is a system that can prevent many more attacks than current systems, while using commodity hardware and not requiring proprietary components. Below are screenshots showing how the system works. When the BioAPI is initialized, it calls a TPM Unseal function which checks all the pertinent files to make sure they have not been modified. For testing purposes, we only used the biometric driver to seal and unseal. In Figure 9, a sample biometric program is run and started. without problems. When the biometric driver was modified by only one bit, the same sample biometric program did not start at all, as shown in Figure 10. ``` [root@riggs249dhcp39 bin]# ./upek-NonGUI_Sample Starting Sample Application Major=1 Minor=10 filesize: 937368 bytes SUCCESS, data returned from unseal matches! BSP Index= 0 BSP Name: libbioapi_dummy100.so Description: BioAPI v1.1 Dummy BSP Vendor: Example Vendor Module ID: {ffffffffffffffffffffffffffffffff} Device ID: 0x00000000 BSP Index= 1 BSP Name: libpwbasp.so Description: BioAPI Password BSP Vendor: BioAPI Consortium Module ID: {263a41e071eb11d49c34124037000000} Device ID: 0x00000000 BSP Index= 2 BSP Name: libtfmbsp.so Description: TouchChip TPM/ESS Fingerprint BSP Vendor: UPEK, Inc. Module ID: {5550454b2054464d2f45535320425350} Device ID: 0x00000000 e .. Enroll v .. Verify m .. Verify Match c .. Capture and Create Template q .. quit v Please enter your user id[] : tpolon ``` **Figure 9:** Successful Sample Program Initialization. ``` [root@riggs249dhcp39 bin]# ./upek-NonGUI_Sample Starting Sample Application Major=1 Minor=10 filesize: 937368 bytes ERROR data returned from unseal doesn't match! Access denied, TPM Unseal failed BioAPI_INIT failed, BioAPI Error Code: 1 (0x1) [root@riggs249dhcp39 bin]# ``` **Figure 10:** Failed Startup By Slightly Modifying The Driver. Below, in Figure 11 and Figure 12, a BioAPI test is run on the device to make sure that the device driver is operating and that it is communicating correctly. In the first example, the test is run successfully. However, in Figure 12, it can be observed that even a simple test will fail if the required files have been changed. Like stated earlier, this is because every time BioAPI is called at all, the TPM function will be called during the initialization function and check the known good data against the current data files. ``` [root@riggs249dhcp39 bin]# ./BioAPITest Starting BioAPI Test Application Major=1 Minor=10 filesize: 937368 bytes SUCCESS, data returned from unseal matches! 3SP Index= 0 3SP Name: libbioapi_dummy100.so Description: BioAPI v1.1 Dummy BSP Vendor: Example Vendor Module ID: {ffffffffffffffffffffffffffffffffffffffff} Device ID: 0x00000000 3SP Index= 1 3SP Name: libpwbsp.so Description: BioAPI Password BSP Vendor: BioAPI Consortium Module ID: {283a41e071eb11d49c34124037000000} Device ID: 0x00000000 3SP Index= 2 3SP Name: libbtfembsp.so Description: TouchChip TFM/ESS Fingerprint BSP Vendor: UPEK, Inc. Module ID: {5550454b2054464d2f45535320425350} Device ID: 0x00000000 Ending BioAPI Test Application [root@riggs249dhcp39 bin]# ``` Figure 11: Successful BioAPI Device Test. This added protection helps to make sure that there are no modified or corrupted files that would compromise the system. From the previous figures, we have proven that any type of change will be picked up before BioAPI even finishes initializing. By doing this so early in the authentication process, the system avoids any type of infiltration by the malicious code. ![Image](image.png) ``` [root@riggs249dhcp39 bin]# ./BioAPITest Starting BioAPI Test Application Major=1 Minor=10 filesize: 937368 bytes ERROR data returned from unseal doesn't match! Access denied, TPM Unseal failed BioAPI Error Code: 1 (0x1) [root@riggs249dhcp39 bin]# ``` **Figure 12: Failed Device Test.** However, this extra protection does come at a price. First, in order to use this system, a computer with a trusted platform module already installed would need to be used. While computers outfitted with a TPM are become more and more available, it is not yet a standard and therefore must be specified when purchasing. Cost is not the only hurdle. The time it takes for the TPM to initiate the seal and unseal commands is not instantaneous. In our tests, the unseal function only took a fraction of a second. But what if the administrator wanted to check the integrity of a dozen files, or even more? The unseal process might take several seconds. Ultimately, it is up to the stakeholders to decide whether the added protection is worth the several extra seconds it may take to authenticate the system. If the data is more important than an extra small period of time, then it should not be an issue. 3.3 Threat Assessment A new attack tree model for the proposed system is shown in Figure 13. The most obvious difference is the separation of machines into approved and rogue. The rogue machine side of the tree is fairly simple. The only way an outside machine can attack the system is through a PKI attack. This relies only on the strength of the cryptography. If a rogue machine is able to gain access, the cryptography will need to be strengthened. However, with a strong enough cryptography, the rogue machine has very little chance of access. Without a signature from the TPM, the BAS will not be able to verify and thus the authentication response will fail. Therefore, it is difficult for a host that is not approved to infiltrate the network. ![Attack Tree For The Proposed System.](image) Figure 13: Attack Tree For The Proposed System. An attack using an approved platform is more involved. While the platform itself can be approved, the device itself might become compromised at some point, as well as the software that is used for authentication (BioAPI, net client, or the device driver), but this would require finding vulnerabilities in these components while still maintaining the appearance of system integrity from the view of the preceding component. A man in the middle attack (MIM) would have to rely on a cryptographic attack or a protocol attack. As stated earlier, the system will use a 2-way authenticated SSL with private keys. Therefore, it is difficult for a MIM attack to occur with this system. In the event of software compromise, the attestation mechanism will prevent access in both cases. In one case, the software might be compromised before boot-up. In this case, the software boot chain will fail as the hash check will fail when the compromised software is checked. In the second case, post-boot compromise, the attestation mechanism will check the current state of the software with the hashes held in its registers. If any of the software fails, the attestation mechanism will not sign the live sample and the authentication will fail. The final case would be the event where nothing has been changed, but instead a physical attack on the device is made. The current system cannot prevent a physical attack on the biometric device. If an attacker was somehow able to physically spoof the biometric on an approved machine running approved software, he or she would be able to gain access. Also, if a device was somehow modified, such as the thermal reader on a fingerprint reader being modified or removed and replaced, there is nothing to prevent an attacker from injecting a signal into the system. However, methods such as additional authentication factors, liveness testing, multiple attempt lockout, passwords, tokens, monitoring, and the use of anti-tamper hardware can be used to prevent such attacks. 3.4 Conclusions In the beginning of this paper, we explained the potential weaknesses with using a biometric authentication system. We have proposed a solution that will alleviate problems created by a lack of secrets by adding verification to the sample collection process. The research system involves adding an attestation device, a Biometric Authentication Server, and biometric independent software. The system is independent of the biometric technology used and does not require single-source or proprietary products. 3.5 Future Work Currently, the system only works on a single independent platform. Since the TPM Unseal calls have been added to the source code, adding a BAS would be fairly simple as the source code is already written and just needs to be implemented. Also, the SSL sign on needs to be implemented as well. These additions should not take long to add and while important to the system, a remote biometric server and a secure login are not new research ideas and could possibly even be pulled from open source code elsewhere. In terms of where the future of a secure biometric login lies, this requires help from the OS developers as well as the biometric manufacturers. For instance, there is no type of real TPM integration within either Windows or Linux. Also, to a lesser extent, the modifications made to BioAPI to include TPM support have not been integrated. Even for this research, a software stack was needed in order to manipulate the TPM through Linux. From a hardware perspective, the next step would be to standardize the software and possibly integrate it within the actual device. By doing this, we can make the path even more secure as the sample can be checked for authenticity before it even leaves the device. When we start working towards all these solutions, and when developers and manufacturers begin to embrace the TPM in conjunction with a biometric device, we can finally produce a full trusted path. APPENDIX Software Dependencies Trousers: Automake > 1.4 Autoconf > 1.4 Pkgconfig Libtool Gtk2-devel Openssl >= 0.9.7 Openssl-devel >= 0.9.7 Pthreads library (glibc-devel) Tpm-tools: Automake Autoconf Libtool Gettext Gettext-devel Trousers Trousers-devel Installation Instructions As stated earlier, the platform used for this system is Fedora Core 5. If you are using a different Linux distro, the installation procedure might be different. Please visit http://fedora.redhat.com for more information on how to download a free version of this OS. To install the BioAPI software and driver for a UPEK fingerprint reader (which was used in this system), the full installation directions can be found at http://www.thinkwiki.org/wiki/How_to_enable_the_fingerprint_reader. To make things easier, if you are running a Fedora Core system, there is a script to completely install everything, including “bioapi_pam”, which adds fingerprint authentication to the Linux PAM (Pluggable Authentication Modules) framework. For this research, the script has been modified to include the TPM functions and the new Makefile described earlier in the code overview section. However, in doing so, the PAM installation will no longer work. This is not a problem though as the PAM framework is not required for the purpose of this research. This script can be downloaded at the site listed below. Again, this can only be used if you are using a Fedora Core distro. When installing the system on a new machine, the TPM code, modified BioAPI file, and modified Makefile must be placed in the directory used in the script in order for it to work properly. Alternatively, this code may be placed in another location so long as the script is modified to look for the files in said location. The installation of the TPM is a little trickier. When installing Fedora Core, I did not see an option to enable the TPM in Linux. Therefore, after the system was installed I downloaded the kernel. After extracting, “make menuconfig” must be run. Within the menu, module support for the TPM must be enabled. After doing so, the modules need to be copied by using “make modules_install” and the kernel needs to be compiled. When the new kernel is compiled with TPM support, Trousers can be installed. Trousers is used to interact with the TPM and is therefore required. Before installing Trousers, make sure all the dependencies are already installed on the system. The actual installation of Trousers is very straightforward and is included in a README file with the source code. The same goes for tpm-tools, an extension of Trousers, which also needs to be installed. When all these files are correctly installed, the computer is ready for TPM use. Software Fedora Core: http://fedora.redhat.com/download/mirrors.html BioAPI: http://www.bioapi.org/ Trousers: http://trousers.sourceforge.net/ Code Written Makefile: http://www.clemson.edu/~tpolon/Makefile Tspi_Data_Seal: http://www.clemson.edu/~tpolon/Tspi_Data_Seal.c Tspi_Data_Unseal: http://www.clemson.edu/~tpolon/Tspi_Data_Unseal.c Manage_Interface: http://www.clemson.edu/~tpolon/manage_interface.c Installation Script: http://www.clemson.edu/~tpolon/enable-fingerprint-reader.sh REFERENCES
{"Source-Url": "https://tigerprints.clemson.edu/cgi/viewcontent.cgi?referer=&httpsredir=1&article=1117&context=all_theses", "len_cl100k_base": 11278, "olmocr-version": "0.1.53", "pdf-total-pages": 48, "total-fallback-pages": 0, "total-input-tokens": 75113, "total-output-tokens": 13854, "length": "2e13", "weborganizer": {"__label__adult": 0.0004792213439941406, "__label__art_design": 0.0006775856018066406, "__label__crime_law": 0.00115203857421875, "__label__education_jobs": 0.0024509429931640625, "__label__entertainment": 0.00011420249938964844, "__label__fashion_beauty": 0.00024819374084472656, "__label__finance_business": 0.0005440711975097656, "__label__food_dining": 0.0003325939178466797, "__label__games": 0.0010061264038085938, "__label__hardware": 0.004863739013671875, "__label__health": 0.0010194778442382812, "__label__history": 0.00040793418884277344, "__label__home_hobbies": 0.0001531839370727539, "__label__industrial": 0.0007796287536621094, "__label__literature": 0.00033783912658691406, "__label__politics": 0.0003180503845214844, "__label__religion": 0.0004761219024658203, "__label__science_tech": 0.370849609375, "__label__social_life": 0.0001430511474609375, "__label__software": 0.02197265625, "__label__software_dev": 0.59033203125, "__label__sports_fitness": 0.0002899169921875, "__label__transportation": 0.0006117820739746094, "__label__travel": 0.0001615285873413086}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 57315, 0.04211]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 57315, 0.43605]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 57315, 0.91509]], "google_gemma-3-12b-it_contains_pii": [[0, 656, false], [656, 962, null], [962, 2001, null], [2001, 2001, null], [2001, 2884, null], [2884, 2884, null], [2884, 5815, null], [5815, 5815, null], [5815, 7498, null], [7498, 9311, null], [9311, 10207, null], [10207, 12101, null], [12101, 13238, null], [13238, 13238, null], [13238, 14790, null], [14790, 16601, null], [16601, 18450, null], [18450, 20271, null], [20271, 22118, null], [22118, 22811, null], [22811, 24596, null], [24596, 26416, null], [26416, 28262, null], [28262, 29377, null], [29377, 30637, null], [30637, 30937, null], [30937, 32583, null], [32583, 33279, null], [33279, 34132, null], [34132, 35437, null], [35437, 36792, null], [36792, 38242, null], [38242, 38994, null], [38994, 40798, null], [40798, 42545, null], [42545, 43897, null], [43897, 45209, null], [45209, 46791, null], [46791, 47640, null], [47640, 49473, null], [49473, 51124, null], [51124, 51602, null], [51602, 52542, null], [52542, 54387, null], [54387, 54875, null], [54875, 54875, null], [54875, 56564, null], [56564, 57315, null]], "google_gemma-3-12b-it_is_public_document": [[0, 656, true], [656, 962, null], [962, 2001, null], [2001, 2001, null], [2001, 2884, null], [2884, 2884, null], [2884, 5815, null], [5815, 5815, null], [5815, 7498, null], [7498, 9311, null], [9311, 10207, null], [10207, 12101, null], [12101, 13238, null], [13238, 13238, null], [13238, 14790, null], [14790, 16601, null], [16601, 18450, null], [18450, 20271, null], [20271, 22118, null], [22118, 22811, null], [22811, 24596, null], [24596, 26416, null], [26416, 28262, null], [28262, 29377, null], [29377, 30637, null], [30637, 30937, null], [30937, 32583, null], [32583, 33279, null], [33279, 34132, null], [34132, 35437, null], [35437, 36792, null], [36792, 38242, null], [38242, 38994, null], [38994, 40798, null], [40798, 42545, null], [42545, 43897, null], [43897, 45209, null], [45209, 46791, null], [46791, 47640, null], [47640, 49473, null], [49473, 51124, null], [51124, 51602, null], [51602, 52542, null], [52542, 54387, null], [54387, 54875, null], [54875, 54875, null], [54875, 56564, null], [56564, 57315, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 57315, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 57315, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 57315, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 57315, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 57315, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 57315, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 57315, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 57315, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 57315, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 57315, null]], "pdf_page_numbers": [[0, 656, 1], [656, 962, 2], [962, 2001, 3], [2001, 2001, 4], [2001, 2884, 5], [2884, 2884, 6], [2884, 5815, 7], [5815, 5815, 8], [5815, 7498, 9], [7498, 9311, 10], [9311, 10207, 11], [10207, 12101, 12], [12101, 13238, 13], [13238, 13238, 14], [13238, 14790, 15], [14790, 16601, 16], [16601, 18450, 17], [18450, 20271, 18], [20271, 22118, 19], [22118, 22811, 20], [22811, 24596, 21], [24596, 26416, 22], [26416, 28262, 23], [28262, 29377, 24], [29377, 30637, 25], [30637, 30937, 26], [30937, 32583, 27], [32583, 33279, 28], [33279, 34132, 29], [34132, 35437, 30], [35437, 36792, 31], [36792, 38242, 32], [38242, 38994, 33], [38994, 40798, 34], [40798, 42545, 35], [42545, 43897, 36], [43897, 45209, 37], [45209, 46791, 38], [46791, 47640, 39], [47640, 49473, 40], [49473, 51124, 41], [51124, 51602, 42], [51602, 52542, 43], [52542, 54387, 44], [54387, 54875, 45], [54875, 54875, 46], [54875, 56564, 47], [56564, 57315, 48]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 57315, 0.10029]]}
olmocr_science_pdfs
2024-12-07
2024-12-07
f68b96b5ef218f5823493e9eb26edd38aa69873f
[REMOVED]
{"Source-Url": "http://cgi.di.uoa.gr/~koubarak/publications/information-ecdl02.pdf", "len_cl100k_base": 9075, "olmocr-version": "0.1.49", "pdf-total-pages": 16, "total-fallback-pages": 0, "total-input-tokens": 50530, "total-output-tokens": 11818, "length": "2e13", "weborganizer": {"__label__adult": 0.00032067298889160156, "__label__art_design": 0.000579833984375, "__label__crime_law": 0.0004284381866455078, "__label__education_jobs": 0.0022983551025390625, "__label__entertainment": 0.0002036094665527344, "__label__fashion_beauty": 0.00021028518676757812, "__label__finance_business": 0.0006003379821777344, "__label__food_dining": 0.0003690719604492187, "__label__games": 0.0007309913635253906, "__label__hardware": 0.0009717941284179688, "__label__health": 0.0005846023559570312, "__label__history": 0.0004498958587646485, "__label__home_hobbies": 0.0001264810562133789, "__label__industrial": 0.0004191398620605469, "__label__literature": 0.0008931159973144531, "__label__politics": 0.0004072189331054687, "__label__religion": 0.0004723072052001953, "__label__science_tech": 0.1876220703125, "__label__social_life": 0.00018846988677978516, "__label__software": 0.044219970703125, "__label__software_dev": 0.7568359375, "__label__sports_fitness": 0.00020992755889892575, "__label__transportation": 0.0004944801330566406, "__label__travel": 0.00023925304412841797}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 43474, 0.02367]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 43474, 0.47717]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 43474, 0.84724]], "google_gemma-3-12b-it_contains_pii": [[0, 2234, false], [2234, 5289, null], [5289, 6961, null], [6961, 9958, null], [9958, 12812, null], [12812, 15376, null], [15376, 18286, null], [18286, 21278, null], [21278, 24522, null], [24522, 27490, null], [27490, 30316, null], [30316, 33565, null], [33565, 35031, null], [35031, 37907, null], [37907, 41166, null], [41166, 43474, null]], "google_gemma-3-12b-it_is_public_document": [[0, 2234, true], [2234, 5289, null], [5289, 6961, null], [6961, 9958, null], [9958, 12812, null], [12812, 15376, null], [15376, 18286, null], [18286, 21278, null], [21278, 24522, null], [24522, 27490, null], [27490, 30316, null], [30316, 33565, null], [33565, 35031, null], [35031, 37907, null], [37907, 41166, null], [41166, 43474, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 43474, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 43474, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 43474, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 43474, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 43474, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 43474, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 43474, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 43474, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 43474, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 43474, null]], "pdf_page_numbers": [[0, 2234, 1], [2234, 5289, 2], [5289, 6961, 3], [6961, 9958, 4], [9958, 12812, 5], [12812, 15376, 6], [15376, 18286, 7], [18286, 21278, 8], [21278, 24522, 9], [24522, 27490, 10], [27490, 30316, 11], [30316, 33565, 12], [33565, 35031, 13], [35031, 37907, 14], [37907, 41166, 15], [41166, 43474, 16]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 43474, 0.0]]}
olmocr_science_pdfs
2024-11-25
2024-11-25
ebbaa8f05bbb7e8d6e1cb8beff6ba1b0a6d9ccec
So today, we’re going to talk a bit more about parallelism and about how you get performance out of parallel codes. And also, we’re going to take a little bit of a tour underneath the Cilk++ runtime system so you can get an idea of what's going on underneath and why it is that when you code stuff, how it is that it gets mapped, scheduled on the processors. So when people talk about parallelism, one of the first things that often comes up is what’s called Amdahl's Law. Gene Amdahl was the architect of the IBM360 computers who then left IBM and formed his own company that made competing machines and he made the following observation about parallel computing, he said-- and I'm paraphrasing here-- half your application is parallel and half is serial. You can't get more than a factor of two speed up, no matter how many processors it runs on. So if you think about it, if it's half parallel and you managed to make that parallel part run in zero time, still the serial part will be half of the time and you only get a factor of two speedup. You can generalize that to say if some fraction alpha can be run in parallel and the rest must be run serially, the speedup is at most 1 over 1 minus alpha. OK, so this was used in the 1980s in particular to say why it was that parallel computing had no future, because you simply weren't going to be able to get very much speedups from parallel computing. You’re going to spend extra hardware on the parallel parts of the system and yet you might be limited in terms of how much parallelism there is in a particular application and you wouldn’t get very much speedup. You wouldn’t get the bang for the buck, if you will. So things have changed today that make that not quite the same story. The first thing is that with multicore computers, it is pretty much just as inexpensive to produce a p processor right now, like six processor machine as it is a one processor machine. so it's not like you're actually paying for those extra processing cores. They come for free. Because what else are you're going to use that silicon for? And the other thing is that we've had a large growth of understanding of problems for which there's ample parallelism, where that amount of time is, in fact, quite small. And the main place these things come from, it turns out, this analysis is kind of a throughput kind of analysis. OK, it says, gee, I only get 50% speedup for that application, but what most people care about in most interactive applications, at least for a client side programming, is response time. And for any problem that you have that has a response time that's too long and its compute intensive, using parallelism to make it so that the response is much zippier is definitely worthwhile. And so this is true, even for things like game programs. So in game programs, they don't have quite a response time problem, they have what's called a time box problem, where you have a certain amount of time-- 13 milliseconds typically-- because you need some slop to make sure that you can go from one frame to another, but about 13 milliseconds to do a rendering of whatever the frame is that the game player is going to see on his computer or her computer. And so in that time, you want to do as much as you possibly can, and so there's a big opportunity there to take advantage of parallelism in order to do more, have more quality graphics, have better AI, have better physics and all the other components that make up a game engine. But one of the issues with Amdahl's Law-- and this analysis is a cogent analysis that Amdahl made-- but one of the issues here is that it doesn't really say anything about how fast you can expect your application to run. In other words, this is a nice sort of thing, but who really can decompose their application into the serial part and the part that can be parallel? Well fortunately, there's been a lot of work in the theory of parallel systems to answer this question, and we're going to go over some of that really outstanding research that helps us understand what parallelism is. So we're going to talk a little bit about what parallelism is and come up with a very specific measure of parallelism, quantify parallelism, OK? We're also going to talk a little bit about scheduling theory and how the Cilk++ runtime system works. And then we're going to have a little chess lesson. So who here plays chess? Nobody plays chess anymore. Who plays Angry Birds? [LAUGHTER] OK. So you don't have to know anything about chess to learn this chess lesson, that's OK. So we'll start out with what is parallelism? So let's recall first the basics of Cilk++. So here's the example of the lousy Fibonacci that everybody parallelizes because it's good didactically. We have the Cilk spawn statement that says that the child can execute in parallel with the parent caller and the sync that says don't go past this point until all your spawn children have returned. And that's a local sync, that's just a sync for that function. It's not a sync across the whole machine. So some of you may have had experience with open MP barriers, for example, that's a sync across the whole machine. This is not, this is just a local sync for this function saying when I sync, make sure all my children have returned before going past this point. And just remember also that Cilk keywords grant permission for parallel execution. They don't command parallel execution. OK so we can always execute our code serially if we choose to. Yes? AUDIENCE: [UNINTELLIGIBLE] Can't this runtime figure that spawning an extra child would be more expensive? Can't it like look at this and be like-- PROFESSOR: We'll go into it. I'll show you how it works later in the lecture. I'll show you how it works and then we can talk about what knobs you have to tune, OK? So it's helpful to have an execution model for something like this. And so we're going to look at an abstract execution model, which is basically asking what does the instruction trace look like for this program? So normally when you execute a program, you can imagine one instruction executing after the other. And if it's a serial program, all those instructions essentially form a long chain. Well there's a similar thing for parallel computers, which is that instead of a chain as you'll see, it gets bushier and it's going to be a directed acyclic graph. So let's take a look at how we do this. So we'll the example of fib of four. So what we're going to do is start out here with a rectangle here that I want you think about as sort of a function call activation record. So it's a record on a stack. It's got variables associated with it. The only variable I'm going to keep track of is n, so that’s what the four is there. OK, so we’re going to do fib of four. So we’ve got in this activation frame, we have the variable four and now what I’ve done is I’ve color coded the fib function here and into the parts that are all serial. So there’s a serial part up to where it spawns, then there’s recursively calling the fib and then there’s returning. So there’s sort of three parts to this function, each of which is, in fact, a chain of serial instruction. I’m going to collapse those chains into a single circle here that I’m going to call a strand. OK, now what we do is we execute the strand, which corresponds to executing the instructions and advancing the program calendar up until the point we hit this fib of n minus 1. At that point, I basically call fib of n minus 1. So in this case, it’s now going to be fib of 3. So that means I create a child and start executing in the child, this prefix part of the function. However, unlike I were doing an ordinary function call, I would make this call and then this guy would just sit here and wait until this frame was done. But since it’s a spawn, what happens is I’m actually going to continue executing in the parent and execute, in fact, the green part. So in this case, evaluating the arguments, etc. Then it’s going to spawn here, but this guy, in fact, is going to what it does when it gets here is it evaluates n minus 2, it does a call of fib of n minus 2. So I’ve indicated that this was a called frame by showing it in a light color. So these are spawn, spawn, call, meanwhile this thing is going. So at this point, we now have one, two, three things that are operating in parallel at the same time. We keep going on, OK? So this guy that does a spawn and has a continuation, this one does a call, but while he’s doing a call, he’s waiting for the return so he doesn’t start executing the successor. He stalled at the Cilk sink here. And we keep executing and so as you can see, what’s happening is we’re actually creating a directed acyclic graph of these strands. So here basically, this guy was able to execute because both of the children, one that he had spawned and one that he had called, have returned. And so this fella, therefore, is able then to execute the return. OK, so the addition of x plus y in particular, and then the return to the parent. And so what we end up with is of all these serial chains of instructions that are represented by these strands, all these circles, they're embedded in the call tree like you would have in an ordinary serial execution. You have a call tree that you execute up and down, you walk it like a stack normally. Now, in fact, what we have is embedded in there is the parallel execution which form a DAG, directed acyclic graph. So when you start thinking in parallel, you have to start thinking about the DAG as your execution model, not a chain of instructions. And the nice thing about this particular execution model we're going to be looking at is nowhere did I say how many processors we were running on. This is a processor oblivious model. It doesn't know how many processors you're running on. We simply in the execution model, are thinking about abstractly what can run in parallel, not what actually does run in parallel in an execution. So any questions about this execution model? OK. So just so that we have some terminology, so the parallel instruction stream is a DAG with vertices and edges. Each vertex is a strand, OK? Which is a sequence of instructions not containing a call spawn sync, a return or thrown exception, if you're doing exceptions. We're not going to really talk about exceptions much. So they are supported in the software that we'll be using, but for most part, we're not going to have to worry about them. OK so there's an initial strand where you start, and a final strand where you end. Then each edge is a spawn or a call or return or what's called a continue edge or a continuation edge, which goes from the parent, when a parent spawns something to the next instruction after the spawn. So we can classify the edges in that fashion. And I've only explain this for spawn and sync, as you recall from last time, we also talked about Cilk four. It turns out Cilk four is converted to spawns and syncs using a recursive divide and conquer approach. We'll talk about that next time on Thursday. So we'll talk more about Cilk four and how it's implemented and the implications of how loop parallelism works. So at the fundamental level, the runtime system is only concerned about spawns and syncs. Now given that we have a DAG, so I've taken away the call tree and just left the strands of a computation. It's actually not the same as the computation we saw before. We would like to understand, is this a good parallel program or not? Based on if I understand the logical parallelism that I've exposed. So how much parallelism do you think is in here? Give me a number. How many processors does it make sense to run this on? Five? That's as parallel as it gets. Let's take a look. We're going to do an analysis. At the end of it, we'll know what the answer is. So for that, let $t_p$ be the execution time on $p$ processors for this particular program. It turns but there are two measures that are really important. The first is called the work. OK, so of course, we know that real machines have caches, etc. Let's forget all of that. Just very simple algorithmic model where every strand, let's say, costs us unit time as opposed to in practice, they may be many instructions and so forth. We can take that into account. Let's take that into account separately. So $T_1$ is the work. It's the time it if I had to execute it on one processor, I've got to do all the work that's in here. So what's the work of this particular computation? I think it's 18, right? Yeah, 18. So $T_1$ is the work. So even though I'm executing a parallel, I could it execute it serially and then $T_1$ is the amount of work it would take. The other measure is called the span, and sometimes called critical path length or computational depth. And it corresponds to the longest path of dependencies in the DAG. We call it $T$ infinity because even if you had an infinite number of processors, you still can't do this one until you finish that one. You can't do this one until you finish that one, can't do this one till you've finished that one and so forth. So even with an infinite number of processors, I still wouldn't go faster than the span. So that's why we denote by $T$ infinity. So these are the two important measures. Now what we're really interested in is $T_p$ for a given $p$. As you'll see, we actually can get some bounds on the performance on $p$ processors just by looking at the work, the span and the number of processors we're executing on. So the first bound is the following, it's called the Work Law. The Work Law says that the time on $p$ processors is at least the time on one processor divided by $p$. So why does that Work Law make sense? What's that saying? Sorry? AUDIENCE: Like work is conserved sort of? I mean, you have to do the same amount of work. PROFESSOR: You have to do the same amount of work, so on every time step, you can get $p$ pieces of work done. So if you're running for fewer than $T_1$ over $p$ steps, you've done less than $T_1$ work over and time $T_p$. So you won't have done all the work if you run for less than this. So the time must be at least $T_p$, time $T_p$ must be at least $T_1$ over $p$. You only get to do $p$ work on one step. Is that pretty clear? The second one should be even clearer, the Span Law. On $p$ processors, you're not going to go faster than if you had an infinite number of processors because the infinite processor could always use fewer processors if it's scheduled. Once again, this is a very simple model. We're not taking into account scheduling, we're not taking into account overheads or whatever, just a simple conceptual model for understanding parallelism. So any questions about these two laws? There's going to be a couple of formulas in this lecture today that you should write down and play with. So these two, they may seem simple, but these are hugely important formulas. So you should know that $T_p$ is at least $T_1$ over $p$, that's the Work Law and that $T_p$ is at least $T$ infinity. Those are bounds on how fast you could execute. Do I have a question in that back there? OK so let's see what happens to work in span in terms of how we can understand our programs and decompose them. So suppose that I have a computation $A$ followed by computation $B$ and I connect them in series. What happens to the work? How does the work of all this whole thing correspond to the work of $A$ and the work of $B$? What's that? AUDIENCE: [UNINTELLIGIBLE] PROFESSOR: Yeah, add them together. You get $T_1$ of $A$ plus $T_1$ of $B$. Take the work of this and the work of this. OK, that's pretty easy. What about the span? So the span is the longest path of dependencies. What happens to the span when I connect two things in a series? Yeah, it just sums as well because I take whatever the longest path is from here to here and then the longest one from here to here, it just adds. But now let's look at parallel composition. So now suppose that I can execute these two things in parallel. What happens to the work? It just adds, just as before. The work always adds. The work is easy because it's additive. What happens to the span? What's that? **AUDIENCE:** [UNINTELLIGIBLE] **PROFESSOR:** It's the max of the spans. Right, so whatever is the longest, whichever one of these ones has a longer span, that's going to be the span of the total. Does that give you some intuition? So we're going to see when we analyze the spans of things that in fact, we're going to see maxes occurring all over the place. So speedup is defined to be $T_1$ over $T_p$. So speedup is how much faster am I on $p$ processors than I am on one processor? Pretty easy. So if $T_1$ over $T_p$ is equal to $p$, we say we have perfect linear speedup, or linear speedup. That's good, right? Because if I put on use $p$ processors, I'd like to have things go $p$ times faster. OK, that would be the ideal world. If $T_1$ over $T_p$, which is the speedup, is greater than $p$, that says we have super linear speedup. And in our model, we don't get that because of the work law. Because the work law says $T_p$ is greater than or equal to $T_1$ over $p$ and just do a little algebra here, you get $T_1$ over $T_p$ must be less than or equal to $p$. So you can't get super linear speedup. In practice, there are situations where you can get super linear speedup due to caching effects and a variety of things. We'll talk about some of those things. But in this simple model, we don't get that kind of behavior. And of course, the case I left out is the common case, which is the $T_1$ over $T_p$ is less than $p$, and that's very common people write code which doesn't give them linear speedup. We're mostly interested in getting linear speedup here. That's our goal. So that we're getting the most bang for the buck out of the processors we're using. OK, parallelism. So we're finally to the point where I can talk about parallelism and give a quantitative definition of parallelism. So the Span Law says that $T_p$ is at least $T$ infinity, right? The time on $p$ processors is at least the time on an infinite number of processors. So the maximum possible speedup, that’s $T_1$ over $T_p$, given $T_1$ and $T_{\infty}$ is $T_1$ over $T_{\infty}$. And we call that the parallelism. It’s the maximum amount of speedup we could possibly attain. So we have the speedup and the speedup by the Span Law that says this is the maximum amount we can get, we could also view it as if I look along the critical path of the computation. It’s sort of what’s the average amount of work at every level. The work, the total amount of stuff here divided by that length there that sort of tells us the width, what’s the average amount of stuff that’s going on in every step. So for this example, what is the-- I forgot to put this on my slide-- what is the parallelism of this particular DAG here? Two, right? So the span has length nine-- this is assuming everything was unit time-- obviously in reality, when you have more instructions, you in fact would make it be whatever the length of this was in terms of number of instructions or what have you, of execution time of all these things. So this is length 9, there’s 18 things here, parallelism is 2. So we can quantify parallelism precisely. We’ll see why it’s important to quantify it. So that the maximum speedup we’re going to get when we run this application. Here’s another example we did before. Fib of four. So let’s assume again that each strand takes unit time to execute. So what is the work in this particular computation? Assume every strand takes unit time to execute, which of course it doesn’t, but-- anybody care to hazard a guess? 17, yeah, because there’s four nodes here that have 3 plus 5. So 3 times 4 plus 5 is 17. So the work is 17. OK, what’s the span? This one's tricky. Too bad it's not a little bit more focused. What the span? **AUDIENCE:** 8. **PROFESSOR:** 8, that’s correct. Who got 7? Yeah, so I got 7 when I did this and then I looked harder and it was 8. It’s 8, so here it is. Here’s the span. There is goes. Ooh that little sidestep there, that’s what makes it 8. OK so basically, it comes down here and I had gone down like that when I did it, but in fact, you've got to go over and back up. So it's actually 8. So that says that the parallelism is a little bit more than 2, 2 and 1/8. What that says is that if I use many more than two processors, I can't get linear speedup anymore. I'm only going to get marginal performance gains. If I use more than 2, because the maximum speedup I can get is like 2.125 if I had an infinite number of processors. So any questions about this? So this by the way deceptively simple and yet, if you don't play around with it a little bit, you can get confused very easily. Deceptively simple, very powerful to be able to do this. So here we have for the analysis of parallelism, one of the things that we have going for us in using the Cilk tool suite is a program called Cilkview, which has a scalability analyzer. And it is like the race detector that I talked to you about last time in that it uses dynamic instrumentation. So you run it under Cilkview, it's like running it under [? Valgrhen ?] for example, or what have you. So basically you run your program under it, and it analyzes your program for scalability. It computes the work and span of your program to derive some upper bounds on parallel performance and it also estimates a scheduling overhead to compute what's called a burden span for lower bounds. So let's take a look. So here's, for example, here's a quick sort program. So let's just see this is a c++ program. So here we're using a template so that the type of items that I'm sorting I can make be a variable. So tightening-- can we shut the back door there? One of the TAs? Somebody run up to-- thank you. So we have the variable T And we're going to quick sort from the beginning to the end of the array. And what we do is, just as you're familiar with quick sort, if there's actually something to be sorted, more than one thing, then we find the middle by partitioning the thing and this is a bit of a c++ magic to find the middle element. And then the important part from our point of view is after we've done this partition, we quick sort the first part of the array, from beginning to middle and then from the beginning plus 1 or the middle, whichever is greater to the end. And then we sync. So what we're doing is quick sort where we're spawning off the two sub problems to be solved in parallel recursively. So they're going to execute in parallel and they're going to execute in parallel and so forth. So a fairly natural thing to divide, to do divide and conquer on quick sort because the two some problems can be operated on independently. We just sort them recursively. But we can sort them in parallel. OK, so suppose that we are sorting 100,000 numbers. How much parallelism do you think is in this code? So remember that we're getting this recursive stuff done. How many people think-- well, it's not going to be more than 100,000, I promise you. So how many people think more than a million parallels? Raise your hand, more than a million? And how many people think more than 100,000? And how many people think more than 10,000? OK, between the two. More than 1,000? OK, how about more than 100? 100 to 1,000? How about 10 to 100? How about between 1 and 10? So a lot of people think between 1 and 10. Why do you think that there's so little parallels in this? You don't have to justify yourself, OK. Well let's see how much there is according to Cilkview. So here's the type of output that you'll get. You'll get a graphical curve. You'll also get a textual output. But this is sort of the graphical output. And this is basically showing what the running time here is. So the first thing it shows is it will actually run your program, benchmark your program, on in this case, up to 8 course. We ran it. So we ran up to 8 course and give you what your measured speedup is. So the second thing is it tells you the parallels. If you can't read that it's, 11.21. So we get about 11. Why do you think it's not higher? What's that? AUDIENCE: It's the log. PROFESSOR: What's the log? AUDIENCE: [UNINTELLIGIBLE] PROFESSOR: Yeah, but you're doing the two things in parallel, right? We'll actually analyze this. So it has to do with the fact that the partition routine is a serial piece of code and it's big. So the initial partitioning takes you 100,000-- sorry, 100 million steps of doing a partition-- before you get to do any parallelism at all. And we'll see that in just a minute. So it gives you the parallelism. It also plots this. So this is the parallelism. Notice that's the same number, 11.21 is plotted as this bound. So it tells you the span law and it tells you the work law. This is the linear speedup. If you were having linear speedup, this is what your program would give you. So it gives you these two bounds, the work law and span law on your speedup. And then it also computes what's called a burden parallelism, estimating scheduling overheads to sort of give you a lower bound. Now that's not to say that your numbers can't fall outside this range. But when they do, it will tell you essentially what the issues are with your program. And we'll discuss how you diagnose some of those issues. Actually that's in one of the handouts that we've provided. I think that's in one of the handouts. If not, we'll make sure it's among the handouts. So basically, this gives you a range for what you can expect. So the important thing here is to notice here for example, that we're losing performance, but it's not due to the parallelism, to the work law. Basically, in some sense, what's happening is we are losing it because the Span Law because we're starting to approach the point where the span is going to be the issue. So we'll talk more about this. So the main thing is you have a tool that can tell you the work and span and so that you can analyze your own programs to understand are you bounded by parallelism, for example, in particular, in the code that you've written. OK let's do a theoretical analysis of this to understand why that number is small. So the main thing here is that the expected work, as you recall, of quick sort is order n log n. You tend to do order n log n work, you partition and then you're solving two problems of the same size. If you actually draw out the recursion tree, it's log height with linear amount of work on every level for n log end total work. The expected span, however, is order n because the partition routine is a serial program that partitions up the thing of size n in order n time. So when you compute the parallelism, you get parallelism of order log n and log n is kind of puny parallelism, and that's our technical word for it. So puny parallelism is what we get out of quick sort. So it turns out there are lots of things that you can analyze. Here's just a selection of some of the interesting practical algorithms and the kinds of analyses that you can do showing that, for example, with merge sort you can do it with work $n \log n$. You can get a span of $\log qn$ and so then the parallelism is the ratio of the two. In fact, you can actually theoretically get $\log^2 n$ span, but that's not as practical an algorithm as the one that gives you $\log^3 n$. And you can go through and there are a whole bunch of algorithms for which you can get very good parallelism. So all of these, if you look at the ratio of these, the parallelism is quite high. So let's talk a little bit about what's going on underneath and why parallelism is important. So when you describe your program in Cilk, you express the potential parallelism of your application. You don't say exactly how it's going to be scheduled, that's done by the Cilk++ scheduler, which maps the strands dynamically onto the processors at run time. So it's going to do the load balancing and everything necessary to balance your computation off the number of processors. We want to understand how that process works, because that's going to help us to understand how it is that we can build codes that will map very effectively on to the number of processors. Now it turns out that the theory of the distributed schedulers such as is in Cilk++ is complicated. I'll wave my hands about it towards the end, but the analysis of it is advanced. You have to take a graduate course to get that stuff. So instead, we're going to explore the ideas with a centralized, much simpler, scheduler which serves as a surrogate for understanding what's going on. So the basic idea of almost all scheduling theory in this domain is greedy scheduling. And so this is-- by the way, we're coming to the second thing you have to understand really well in order to be able to generate good code, the second sort of theoretical thing-- so the idea of a greedy scheduler is you want to do as much work as possible on each step. So the idea here is let's take a look, for example, suppose that we've executed this part of the DAG already. Then there are certain number of strands that are ready to execute, meaning all their predecessors have exited. How many strands are ready to execute on this DAG? Five, right? These guys. So those five strands are ready to execute. So the idea is-- and let me illustrate for $p$ equals 3-- the idea is to understand the execution in terms of two types of steps. So in a greed schedule, you always do as much as possible. So is what would be called a complete step because I can schedule all three processors to have some work to do on that step. So which are the best three guys to be able to execute? Yes, so I'm not sure what the best three are, but for sure, you want to get this guy and this guy, right? Maybe that guy's not, but this guy, you definitely want to execute. And these guys, I guess, OK. So in a greedy schedule, no, you're not allowed to look to see which ones are the best execute. You don't know what the future is, the scheduler isn't going to know what the future is so it just executes any $p$ course. You just execute any $p$ course. In this case, I executed the $p$ strand. In this case, I executed these three guys even though they weren't necessarily the best. And in a greedy scheduler, it doesn't look to see what's the best one to execute, it just executes as many as it can this case. In this case, it's $p$. Now we have what's called an incomplete step. Notice nothing got enabled. That was sort of too bad. So there's only two guys that are ready to go. What do you think happens if I have an incomplete step, namely $p$ strands are ready, fewer than $p$ strands are ready? I just to execute all of them, as many as I can. Run all of them. So that's what a greedy scheduler does. Just at every step, it executes as many as it can and we can classify the steps as ones which are complete, meaning we used all our processors versus incomplete, meaning we only used a subset of our processors in scheduling it. So that's what a greedy scheduler does. Now the important thing, which is the analysis of this program. And this is, by the way, the single most important thing in scheduling theory but you're going to ever learn is this particular theory. It goes all the way back to 1968 and what it basically says it is any greedy scheduler achieves a bound of $T1$ over $p$ plus $T\infty$. So why is that an interesting upper bound? Yeah? AUDIENCE: That says that it's got the refinement of what you said before, even if you add as many processors as you can, basically you're bounded by T infinity. PROFESSOR: Yeah. AUDIENCE: It's compulsory. PROFESSOR: So basically, each of these, this term here is the term in the Work Law. This is the term in the Span Law, and we're saying you can always achieve the sum of those two lower bounds as an upper bound. So let's see how we do this and then we'll look at some of the implications. Question, do you have a question? No? So here's the proof that you meet this. So that the proof says-- and I'll illustrate for P equals 3-- how many complete steps could we have? So I'll argue that the number of complete steps is at most T1 over p. Why is that? Every complete step performs p work. So if I had more complete steps than T1 over p, I'd be doing more than T1 work. But I only have T1 work to do. OK, so the maximum number of complete steps I could have is at most T1 over p. Do people follow that? So the trickier part of the proof, which is not all that tricky but it's a little bit trickier, is the other side. How many incomplete steps could I have? So we execute those. So I claim that the number of incomplete steps is bounded by the critical path length, by the span. Why is that? Well let's take a look at the part of DAG that has yet to be executed. So that this gray part here. There's some span associated with that. In this case, it's this longest path. When I execute all of the ready threads that are ready to go, I guarantee to reduce the span of that unexecuted DAG by at least one. So as I do here, so I reduce it by one when I execute. So if I have a complete step, I don't guaranteed to reduce the span of the unexecuted DAG, because I may execute things as I showed you in this example, you don't actually advance anything. But I execute all the ready threads on an incomplete step, and that's going to reduce it by one. So the number of incomplete steps is at most infinity. So the total number of steps is at most the sum. So as I say, this proof you should understand in your sleep because it’s the most important scheduling theory proof that you’re going to probably see in your lifetime. It’s very old, and really, very, very simple and yet, there’s a huge amount of scheduling theory if you have a look at scheduling theory, that comes out of this just making this same problem more complicated and more real and more interesting and so forth. But this is really the crux of what’s going on. Any questions about this proof? So one corollary of the greedy scheduling algorithm is that any greedy scheduler achieves within a factor of two of optimal scheduling. So let's see why that is. So it's guaranteed as an upper bound to get within a factor of two of optimal. So here's the proof. So let's Tp star be the execution time produced by the optimal scheduler. This is the schedule that knows the whole DAG in advance and can schedule things exactly where they need to be scheduled to minimize the total amount of time. Now even though the optimal scheduler can schedule very officially, it's still bound by the Work Law and the Span Law. So therefore, Tp star has still got to be greater than T1 over p and greater than T infinity by the Work and Span Laws. Even though it's optimal, every scheduler must obey the Work Laws and Spam Law. So then we have, by the greedy scheduling theorem, Tp is at most T1 over p plus T infinity. Well that's at most twice the maximum of these two values, whichever is larger. I've just plugged in to get the maximum of those two and that's at most, by this equation, twice the optimal time. So this is a very simple corollary says oh, greedy scheduling is actually pretty good. It's not optimal, in fact, optimal scheduling is mP complete. Very hard problem to solve. But getting within a factor of two, you just do greedy scheduling, it works just fine. More importantly is the next corollary, which has to do is when do you get linear speedup? And this is, I think, the most important thing to get out of this. So any greedy scheduler achieves near perfect linear speedup whenever-- what's this thing on the left-hand side? What's the name we call that?-- the parallelism, right? That's the parallelism, is much bigger than the number of processors you're running on. So if the number of processors are running on is smaller than the parallelism of your code says you can expect near perfect linear speedup. OK, so what does that say you want to do in your program? You want to make sure you have ample parallelism and then the scheduler will be able to schedule it so that you get near perfect linear speedup. Let's see why that's true. So $T_1$ over $T_\infty$ is much bigger than $p$ is equivalent to saying that $T_\infty$ is much less than $T_1$ over $p$. That's just algebra. Well what does that mean? The greedy scheduling theorem says $T_p$ is at most $T_1$ over $p$ plus $T_\infty$. We just said that if we have this condition, then $T_\infty$ is very small compared to $T_1$ over $p$. So if this is negligible, then the whole thing is about $T_1$ over $p$. Well that just says that the speedup is about $p$. So the name of the game is to make sure that your span is relatively short compared to the amount of work per processor that you're doing. And in that case, you'll get linear speedup. And that happens when you've got enough parallelism compared to the number processors you're running on. Any questions about this? This is like the most important thing you're going to learn about parallel computing. Everything else we're going to do is going to be derivatives of this, so if you don't understand this, you have a hard time with the other stuff. So in some sense, it's deceptively simple, right? We just have a few variables, $T_1$, $T_p$, $T_\infty$, $p$, there's not much else going on. But there are these bounds and these elegant theorems that tell us something about how no matter what the shape of the DAG is or whatever, these two values, the work and the span, really characterize very closely where it is that you can expect to get linear speedup. Any questions? OK, good. So the quantity $T_1$ over $p$ $T_\infty$, so what is that? That's just the parallelism divided by $p$. That's called the parallel slackness. So this parallel slackness is 10, means you have 10 times more parallelism than processors. So if you have high slackness, you can expect to get linear speedup. If you have low slackness, don't expect to get linear speedup. OK. Now the scheduler we're using is not a greedy scheduler. It's better in many ways, because it's a distributed, what's called work stealing scheduler and I'll show you how it works in a little bit. But it's based on the same theory. Even though it's a more complicated scheduler from an analytical point of view, it's really based on the same theory as greedy scheduling. It guarantees that the time on p processors is at most T1 over p plus order T infinity. So there's a constant here. And it's a randomized scheduler, so it actually only guarantees this in expectation. It actually guarantees very close to this with high probability. OK so the difference is the big O, but if you look at any of the formulas that we did with the greedy scheduler, the fact that there's a constant there doesn't really matter. You get the same effect, it just means that the slackness that you need to get linear speedup has to not only overcome the T infinity, it's also got to overcome the constant there. And empirically, it actually turns out this is not bad as an estimate using the greedy bound. Not bad as an estimate, so this is sort of a model that we'll take as if we're doing things with a greedy scheduler. And that will be very close for what we're actually going to see in practice with the Cilk++ scheduler. So once again, it means near perfect linear speedup as long as p is much less than T1 over T infinity generally. And so Cilkview allows us to measure T1 and T infinity. So that's going to be good, because then we can figure out what our parallelism is and look to see how we're running on typically 12 cores, how much parallels do we have? If our parallelism is 12, we don't have a lot of slackness. We won't get very good speedup. But if we have a parallelism of say, 10 times more, say 120, we should get very, very good parallelism, very, very good speedup on 12 cores. We should get close to perfect speedup. So let's talk about the runtime system and how this work stealing scheduler works, because it different from the other one. And this will be helpful also for understanding when you program these things what you can expect. So the basic idea of the schedule is there's two strategies the people have explored for doing scheduling. One is called work sharing, which is not what Cilk++ does. But let me explain what work sharing is because it's helpful to contrast it with work stealing. So in works sharing, what you do is when you spawn off some work, you say let me go find some low utilized processor and put that worked there for it to operate on. The problem with work sharing is that you have to do some communication and synchronization every time you do a spawn. Every time you do a spawn, you're going to go out. This is kind of what Pthreads does, when you do Pthread create. It goes out and says OK, let me create all of the things it needs to do and get it schedule then on a processor. Work stealing, on the other hand, takes the opposite approach. Whenever it spawns work, it's just going to keep that work local to it, but make it available for stealing. A processor that runs out of work is going to go looking for work to steal, to bring back. The advantage of work stealing is that the processor doesn't do any synchronization except when it's actually load balancing. So if all of the processors have ample work to do, then what happens is there's no overhead for scheduling whatsoever. They all just crank away. And so you get very, very low overheads when there's ample work to do on each processor. So let's see how this works. So the particular way that it maintains it is that basically, each processor maintains a work deck. So a deck is a double-ended queue of the ready strands. It manipulates the bottom of the deck like a stack. So what that says is, for example, here, we had a spawn followed by two calls. And basically, it's operating just as it would have to operate in an ordinary stack, an ordinary call stack. So, for example, this guy says call, well it pushes a frame on the bottom of the call stack just like normal. It says spawn, it pushes a spawn frame on the bottom of the deck. In fact, of course, it's running in parallel, so you can have a bunch of guys that are both calling and spawning and they all push whatever their frames are. When somebody says return, you just pop it off. So in the common case, each of these guys is just executing the code serially the way that it would normally executing in C or C++. However, if somebody runs out of work, then it becomes a thief and it looks for a victim and the strategy that's used by Cilk++ is to look at random. It says let me just go to any other processor or any other workers-- I call these workers-- and grab away some of their work. But when it grabs it away, what it does is it steals it from the opposite end of the deck from where this particular victim is actually doing its work. So it steals the oldest stuff first. So it moves that over and now here what it's doing is it's stealing up to the point that it spawns. So it steals from the top of the deck down to where there's a spawn on top. Yes? AUDIENCE: Is there always a spawn on the top of every deck? PROFESSOR: Close, almost always. Yes, so I think that you could say that there are. So the initial deck does not have a spawn on top of it, but you could imagine that it did. And then when you steal, you're always stealing from the top down to a spawn. If there isn't something, if this is just a call here, this cannot any longer be stolen. There's no work there to be stolen because this is just a single execution, there's nothing that's been spawned off at this point. This is the result of having been spawned as opposed to that it's doing a spawn. So yes, basically you're right. There's a spawn on the top. So it basically steals that off and then it resumes execution afterwards and starts then operating just like an ordinary deck. So the theorem that you can prove for this type of scheduler is that if you have sufficient parallelism, so you all know what parallelism is at this point, you can prove that the workers steal infrequently. So in a typical execution, you might have a few hundred load balancing operations of this nature for something which is doing billions and billions of instructions. So you steal infrequently. If you're stealing infrequently and all the rest of the time you're just executing like the C or C++, hey, now you've got linear speedup because you've got all of these guys working all the time. And so as I say, the main thing to understand is that there's this work stealing scheduler running underneath. It's more complicated to analyze then the greedy scheduler, but it gives you pretty much the same qualitative kinds of results. And the idea then is that the stealing occurs infrequently so you get linear speedup. So the idea then is just as with greedy scheduling, make sure you have enough parallelism, because then the load balancing is a small fraction of the time these processors are spending executing the code. Because whenever it's doing things like work stealing, it's not working on your code executing, making it go fast. It's doing bookkeeping and overhead and stuff. So you want to make sure that stays low. So any questions about that? So specifically, we have these bounds. You have achieved this expected running time, which I mentioned before. Let me give you a pseudo-proof of this. So this is not a real proof because it ignores things like independence of probabilities. So when you do a probability analysis, you’re not allowed to multiply probabilities unless they’re independent. So anyway, here I’m multiplying probabilities that are independent. So the idea is you can view a processor as either working or stealing. So it goes into one of two modes. It’s going to be stealing if it’s run out of work, otherwise it’s working. So the total time all processors spend working is T1, hooray, that's at least a bound. Now it turns out that every steal has a 1 over p chance of reducing the span by one. So you can prove that of all of the work that’s in the top of all those decks that those are where any of the ready threads are going to be there are in a position of reducing the span if you execute them. And so whenever you steal, you have a 1 over p chance of hitting the guy that matters for the span of unexecuted DAG. So the same kind of thing as in theory. You have a 1 over p chance. So the expected cost of all steals is order PT infinity. So this is true, but not for this reason. But it's kind, the intuition is right. So therefore the cost of all steals is PT infinity and the cost of the work is T1, so that's the total amount of work and time spent stealing by all the p processors. So to get the time spent doing that, we divide by p, because they're p processors. And when I do that, I get T1 over p plus order T infinity. So that's kind of where that bound is coming from. So you can see what's important here is that the term, that order T infinity term, this the one where all the overhead of scheduling and synchronization is. There's no overhead for scheduling and synchronization in the T1 over p term. The only overhead there is to do things like mark the frames as being a steel frame or a spawn frame and do the bookkeeping of the deck as you’re executing so the spawn can be implemented very cheaply. Now in addition to the scheduling things, there are some other things to understand a little bit about the scheduler and that is that it supports the C, C++ rule for pointers. So remember in C and C++, you can pass a pointer to stack space down, but you can't pass a pointer to stack space back to your parent, right? Because it popped off. So if you think about a C or C++ execution, let's say we have this call structure here. A really cannot see any of the stack space of B, C, D or E. So this is what A gets to see. And B, meanwhile, can see A space, because that's down on the stack, but it can't see C, D or E. Particularly if you're executing this serially, it can't see C because C hasn't executed yet when B executes. However, C, it turns out, the same thing. I can't see any of the variables that might be allocated in the space for B when I'm executing here on a stack. You can see them in a heap, but not on the stack, because B has been popped off at that point and so forth. So this is basically the normal rule, the normal views of stack that you get in C or C++. In Cilk++, you get exactly the same behavior except that multiple ones of these views may exist at the same time. So if, for example, B and C are both executing at the same time, they each will see their own stack space and a stack space. And so the cactus stack maintains that fiction that you can sort of look at your ancestors and see your ancestors, but now it's maintained. It's called a cactus stack because it's kind of like a tree structure upside down, like a what's the name of that big cactus out West? Yes, saguaro. The saguaro cactus, yep. This kind of looks like that if you look at the stacks. This leads to a very powerful bound on how much space your program is using. So normally, if you do a greedy scheduler, you could end up using gobs more space then you would in a serial execution, gobs more stack space. In Cilk++ programs, you have a bound. It's p times s1 is the maximum amount of stack space you'll ever use where s1 is the stack space used by serial execution. So if you can keep your serial execution to use a reasonable amount of stack space-- and usually it does-- then in parallel, you don't use more than p times that amount of stack space. And the proof for that is sort of by induction, which basically says there's a property called the Busy Leaves Property that says that if you have a leaf that's being worked on but hasn't been completed-- so I've indicated those by the purple and pink ones- - then if it's a leaf, it has a worker executing on it. And so therefore, if you look at how much stack space you're using, each of these guys can trace up and they may double count the stack space, but it'll still be bounded by $p$ times the depth that they're at, or $p$ times $s_1$, which is the maximum amount. So it has good space bounds. That's not so crucial for you folks to know as a practical matter, but it would be if this didn't hold. If this didn't hold, then you would have more programming problems than you'll have. The implications of this work stealing scheduler is interesting from the linguistic point of view, because you can write a code like this, so for $i$ gets one to a billion, spawn some sub-routine $foo$ of $i$ and then sync. So one way of executing this, the way that the work sharing schedulers tend to do this, is they say oh, I've got a billion tasks to do. So let me create a billion tasks and now schedule them and the space just vrooms to store all those billion tasks, it gets to be huge. Now of course, they have some strategies they can use to reduce it by bunching tasks together and so forth. But in principle, you got a billion pieces of work to do even if you execute on one processor. Whereas in the work stealing type execution, what happens is you execute this in fact depth research. So basically, you're going to execute $foo$ of 1 and then you'll return. And then you'll increment $i$ and you'll execute $foo$ of 2, and you'll return. At no time are you using more than in this case two stack frames, one for this routine here and one for $foo$ because you basically keep going up. You're using your stack up on demand, rather than creating all the work up front to be scheduled. So the work stealing scheduler is very good from that point of view. The tricky thing for people to understand is that if executing on multiple processors, when you do Cilk spawn, the processor, the worker that you're running on, is going to execute $foo$ of 1. The next statement-- which would basically be incrementing the counter and so forth-- is executed by whatever processor comes in and steals that continuation. So if you had two processors, they're each going to basically be executing. The first processor isn't the one that excuse everything in this function. This function has its execution shared, the strands are going to be shared where the first part of it would be done by processor one and the latter part of it would be done by processor two. And then when processor one finishes this off, it might go back and steal back from processor two. So the important thing there is it's generating its stack needs sort of on demand rather than all up front, and that keeps the amount of stack space small as it executes. So the moral is it's better to steal your parents from their children than stealing children from their parents. So that's the advantage of doing this sort of parent stealing, because you're always doing the frame which is an ancestor of where that worker is working and that means resuming a function right in the middle on a different processor. That's kind of the magic of the technologies is how do you actually move a stack frame from one place to another and resume it in the middle? Let's finish up here with a chess lesson. I promised a chess lesson, so we might as well do some fun and games. We have a lot of experience at MIT with chess programs. We've had a lot of success, probably our closest one was Star Socrates 2.0, which took second place in the world computer chess championship running on an 1824 node Intel Paragon, so a big supercomputer running with a Cilk scheduler. We actually almost won that competition, and it's a sad story that maybe be sometime around dinner or something I will tell you the sad story behind it, but I'm not going to tell you why we didn't take first place. And we've had a bunch of other successes over the years. Right now our chess programming is dormant, we're not doing that in my group anymore, but in the past, we had some very strong chess playing programs. So what we did with Star Socrates, which is one of our programs, was we wanted to understand the Cilk scheduler. And so what we did is we ran a whole bunch of different positions on different numbers of processors which ran for different amounts of time. We wanted to plot them all on the same chart, and here's our strategy for doing it. What decided to do was do a standard speedup curve. So a standard speedup curve says let's plot the number of processors along this axis and the speed up along that axis. But in order to fit all these things on the same processor curve, what we did was we normalize the speedup. So what's the maximum pot? So here's the speedup. If you look the numerator here, this is the speedup, T1 over Tp. What we did is we normalized by the parallelism. So we said what fraction of perfect speedup can we get? So here one says that I got exactly a speedup, this is the maximum possible speed up that I can get because the maximum possible value of T1 over p is T1 over T infinity. So that's sort of the maximum. On this axis, we said how many processors are you running on it? Well, we looked at that relative to essentially the slackness. So notice by normalizing, we essentially have here the inverse of the slackness. So 1 here says that I'm running on exactly the same number of processors as my parallelism. A tenth here says I've got a slackness of 10, I'm running on 10 times fewer processors then parallelism. Out here, I'm saying I got way more processors than I have parallelism. So I plotted all the points. So it doesn't show up very well here, but all those green points, there are a lot of green points here, that's our performance, measured performance. You can sort of see they're green there, not the best color for this projector. So we plot on this essentially the Work Law and the Span Law. So this is the Work Law, it says linear speedup, and this is the Span Law. And you can see that we're getting very close to perfect linear speedup as long as our slackness is 10 or greater. See that? It's hugging that curve really tightly. As we approach a slackness of 1, you can see that it starts to go away from the linear speedup curve. So for this program, if you look, it says, gee, if we were running with 10 time, slackness of 10, 10 times more parallelism than processors, we're getting almost perfect linear speedup in the number of processors we're running on across a wide range of number of processors, wide range of benchmarks for this chess program. And in fact, this curve is the curve. This is not an interpolation here, but rather it is just the greedy scheduling curve, and you can see it does a pretty good job of going through all the points here. Greedy scheduling does a pretty good job of predicting the performance. The other thing you should notice is that although things are very tight down here, as you approach up here, they start getting more spread. And the reason is that as you start having more of the span mattering in the calculation, that's where all the synchronization, communication, all the overhead of actually doing the mechanics of moving a frame from one processor to another take into account, so you get a lot more spread as you go up here. So that's just the first part of the lesson. The first part was, oh, the theory works out in practice for real programs. You have like 10 times more parallelisms than processors, you're going to do a pretty good job of getting linear speedup. So that says you guys should be shooting for parallelisms on the order of 100 for running on 12 cores. Somewhere in that vicinity you should be doing pretty well if you've got parallelism of 100 when you measure it for your codes. So we normalize by the parallel there. Now the real lesson though was understanding how to use things like work and span to make decisions in the design of our program. So as it turned out, Socrates for this particular competition was to run on a 512 processor connection machine at the University of Illinois. So this was in the mid in the early 1990's. It was one of the most powerful machines in the world, and this thing is probably more powerful today. But in those days, it was a pretty powerful machine. I don't know whether this thing is, but this thing probably I'm pretty sure is more powerful. So this was a big machine. However here at MIT, we didn't have a great big machine like that. We only had a 32 processor CM5. So we were developing on a little machine expecting to run on a big machine. So one of the developers proposed to change the program that produced a speedup of over 20% on the MIT machine. So we said, oh that's pretty good, 25% improvement. But we did a back of the envelope calculation and rejected that improvement because we were able to use work and span to predict the behavior on the big machine. So let's see how that worked out, why that worked out. So I've fudged these numbers so that they're easy to do the math on and easy to understand. The real numbers actually though did sort out very, very similar to what I'm saying, just they weren't round numbers like I'm going to give you. So the original program ran for let's say 65 seconds on 32 cores. The proposed program ran for 40 seconds on 32 cores. Sounds like a good improvement to me. Let's go for the faster program. Well, let's hold your horses. Let's take a look at our performance model based on greedy scheduling. That $T_p$ is $T_1$ over $p$ plus infinity. What component we really need to understand the scale this, what component of each of these things is work and which is span? Because that's how we're going to be able to predict what's going to happen on the big machine. So indeed, this original program had a work of 2048 seconds and a span of one second. Now chess, it turns out, is a non-deterministic type of program where you use speculative parallelism, and so in order to get more parallelism, you can sacrifice and do more work versus less work. So this one over here that we improved it to had less work on the benchmark, but it had a longer span. So it had less work but a longer span. So when we actually were going to run this, well first of all, we did the calculation and it actually came out pretty close. I was kind of surprised how close the theory matched. We actually on 32 processors when you do the work spanned calculation, you get the 65 seconds on a 32 processor machine, here we had 40 seconds. But now what happens when we scale this to the big machine? Here we scaled it to 512 cores. So now we take the work divided by the number of processors, 512, plus 1, that's 5 seconds for this. Here we have the work but we now have a much larger span. So we have two seconds of work for processor, but now eight seconds of span for a total of 10 seconds. So had we made this quote "improvement," our code would have been half as fast. It would not have scaled. And so the point is that work and span typically will beat running times for predicting scalability of performance. So you can measure a particular thing, but what you really want to know is this thing this going to scale and how is it going to scale into the future. So people building multicore applications today want to know that they coded up. They don't want to be told in two years that they've got to recode it all because the number of cores doubled. They want to have some future-proof notion that hey, there's a lot of parallelism in this program. So work and span, work and span, eat it, drink it, sleep it. Work and span, work and span, work and span, work and span, work and span, work and span, OK? Work and span.
{"Source-Url": "https://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-172-performance-engineering-of-software-systems-fall-2010/video-lectures/lecture-13-parallelism-and-performance/UUKTIhxznF0.pdf", "len_cl100k_base": 14504, "olmocr-version": "0.1.53", "pdf-total-pages": 28, "total-fallback-pages": 0, "total-input-tokens": 54002, "total-output-tokens": 15657, "length": "2e13", "weborganizer": {"__label__adult": 0.0003731250762939453, "__label__art_design": 0.00045990943908691406, "__label__crime_law": 0.0004014968872070313, "__label__education_jobs": 0.0008840560913085938, "__label__entertainment": 0.00012421607971191406, "__label__fashion_beauty": 0.0001970529556274414, "__label__finance_business": 0.0003685951232910156, "__label__food_dining": 0.00040078163146972656, "__label__games": 0.0015735626220703125, "__label__hardware": 0.0031681060791015625, "__label__health": 0.00040268898010253906, "__label__history": 0.0003533363342285156, "__label__home_hobbies": 0.00015926361083984375, "__label__industrial": 0.0007987022399902344, "__label__literature": 0.0002675056457519531, "__label__politics": 0.00027370452880859375, "__label__religion": 0.0006337165832519531, "__label__science_tech": 0.069091796875, "__label__social_life": 7.176399230957031e-05, "__label__software": 0.0087432861328125, "__label__software_dev": 0.90966796875, "__label__sports_fitness": 0.00041794776916503906, "__label__transportation": 0.0007643699645996094, "__label__travel": 0.0002703666687011719}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 61719, 0.00258]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 61719, 0.2946]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 61719, 0.97311]], "google_gemma-3-12b-it_contains_pii": [[0, 2081, false], [2081, 4489, null], [4489, 6721, null], [6721, 9126, null], [9126, 11354, null], [11354, 13761, null], [13761, 15947, null], [15947, 18159, null], [18159, 20272, null], [20272, 22572, null], [22572, 24597, null], [24597, 26861, null], [26861, 29187, null], [29187, 31489, null], [31489, 33606, null], [33606, 36047, null], [36047, 38461, null], [38461, 40739, null], [40739, 43084, null], [43084, 45370, null], [45370, 47570, null], [47570, 50001, null], [50001, 52497, null], [52497, 54797, null], [54797, 57205, null], [57205, 59387, null], [59387, 61635, null], [61635, 61719, null]], "google_gemma-3-12b-it_is_public_document": [[0, 2081, true], [2081, 4489, null], [4489, 6721, null], [6721, 9126, null], [9126, 11354, null], [11354, 13761, null], [13761, 15947, null], [15947, 18159, null], [18159, 20272, null], [20272, 22572, null], [22572, 24597, null], [24597, 26861, null], [26861, 29187, null], [29187, 31489, null], [31489, 33606, null], [33606, 36047, null], [36047, 38461, null], [38461, 40739, null], [40739, 43084, null], [43084, 45370, null], [45370, 47570, null], [47570, 50001, null], [50001, 52497, null], [52497, 54797, null], [54797, 57205, null], [57205, 59387, null], [59387, 61635, null], [61635, 61719, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 61719, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 61719, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 61719, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 61719, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 61719, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 61719, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 61719, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 61719, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 61719, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 61719, null]], "pdf_page_numbers": [[0, 2081, 1], [2081, 4489, 2], [4489, 6721, 3], [6721, 9126, 4], [9126, 11354, 5], [11354, 13761, 6], [13761, 15947, 7], [15947, 18159, 8], [18159, 20272, 9], [20272, 22572, 10], [22572, 24597, 11], [24597, 26861, 12], [26861, 29187, 13], [29187, 31489, 14], [31489, 33606, 15], [33606, 36047, 16], [36047, 38461, 17], [38461, 40739, 18], [40739, 43084, 19], [43084, 45370, 20], [45370, 47570, 21], [47570, 50001, 22], [50001, 52497, 23], [52497, 54797, 24], [54797, 57205, 25], [57205, 59387, 26], [59387, 61635, 27], [61635, 61719, 28]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 61719, 0.0]]}
olmocr_science_pdfs
2024-12-10
2024-12-10
43b850065ebcd6bc1d68fd3bf0853f9f5f95f83e
## Contents - **Contents** .............................................................................................................. 2 - **Overview** .............................................................................................................. 4 - **About Indigo Renderer** .......................................................................................... 5 - **Licensing Indigo** .................................................................................................. 9 - **System Requirements** .......................................................................................... 11 - **About Installation** ............................................................................................... 13 - **Installation on Windows** ...................................................................................... 14 - **Installation on Macintosh** .................................................................................... 17 - **Installation on Linux** ........................................................................................... 18 - **Installing exporters for your modelling package** .............................................. 19 ## Working with the Indigo GUI - **Getting to know Indigo** ........................................................................................ 22 - **Resolution** ............................................................................................................ 27 - **Tone Mapping** ...................................................................................................... 28 - **White balance** ...................................................................................................... 33 - **Light Layers** .......................................................................................................... 34 - **Aperture Diffraction** ............................................................................................ 36 - **Network Rendering** ............................................................................................. 37 - **Render Log** ............................................................................................................ 38 - **Indigo File Types** ................................................................................................. 39 - **Rendering a Test Scene** ....................................................................................... 40 - **Saving and resuming a render using an IGI** ....................................................... 43 - **Network Rendering** ............................................................................................. 44 ## Working with the Indigo Material Editor - **The Material Editor** ............................................................................................. 47 Working with Scenes for Indigo Indigo Scenes ..............................................................................................................51 Materials .........................................................................................................................52 Texture maps ...................................................................................................................56 diffuse ...............................................................................................................................58 specular .............................................................................................................................59 phong .................................................................................................................................60 Glossy Transparent ...........................................................................................................62 diffuse_transmitter .........................................................................................................63 oren_nayar .........................................................................................................................64 blend ...................................................................................................................................65 Exit Portals .........................................................................................................................66 Null Material .......................................................................................................................67 Internal Medium ...............................................................................................................68 Indigo Shader Language ..................................................................................................70 Render Settings ................................................................................................................71 Environment Settings .......................................................................................................75 Camera ...............................................................................................................................77 Going further with Indigo .................................................................................................78 This manual covers the Indigo GUI interface, and Indigo scene attributes and functions. There are some package-specific details that are not included here, but rather in their respective plug-in manuals. There are two other Indigo manuals available, the Indigo Techniques Manual, which shows techniques on how to use Indigo to get beautiful renders, and the Indigo Technical Manual which gives all Indigo functions – useful reference for writing exporters. About Indigo Renderer Indigo Renderer is a stand-alone unbiased renderer. It takes 3D scenes generated in a modelling package and creates a photo-realistic visualization of the scene. About unbiased rendering: Indigo uses unbiased rendering technologies to create the most absolutely realistic visualization possible with current technology. Unbiased rendering means that Indigo uses the equations that model the behaviour of light, with no approximations or guesses taken. By accurately modelling all the interactions of light, Indigo can produce effects such as: - Depth of Field – the depth of field (DOF) is the portion of a scene that appears acceptably sharp in the image. - Spectral effects – as when a beam of light goes through a prism and a rainbow of colours is produced - Refraction – as when light enters a pool of water and the objects in the pool seem to be “bent” - Reflections – from subtle reflections on a polished concrete floor, to the pure reflection of a silvered mirror - Caustics – as in light that has been focussed through a magnifying glass and has made a pattern of brightness on the floor As the unbiased technique requires no approximations or user preferences to generate a realistic image, you can accurately discover what something will look like before it is built. If you are used to using older “global illumination” renderers, you will find that Indigo requires less set up and configuration to get good quality renders. Indigo is easy to set up, predictable and produces amazing quality renders. As with all things good – there is a downside, and with unbiased rendering techniques, the problem is that rendering is more computationally intensive. A high-quality render of a complex scene at 2 Megapixel resolution may take up to 5 hours on modern hardware. In the general case however, most renders can be completed in less than 30 minutes, and Indigo allows you to utilize network rendering to speed up the render. See the sections on 'system requirements' and 'network rendering' for more information about speeding up your renders. When you start your first render with Indigo, you will notice that the image will be produced quite rapidly - you will be able to see the outline of the scene within 20 seconds of starting the render – but it will be quite noisy. As time goes on, the image will become clearer and clearer. In this case, the render took 3 minutes to produce the following image: This is a characteristic of unbiased rendering. The first image is akin to the graininess you get when you take a photo of a dark room with an exposure that is too short. The problem is that not enough light has been simulated to create an accurate representation of the scene. On the plus side, you get to see instantly whether your render settings are correct, and if the render is looking good you can just leave Indigo to render for longer. **About Exporters:** Indigo is designed to be independent of the modelling package you use, and uses its own file format, called an Indigo Scene File (.igs extension). To create an .igs file, you need to use an *Exporter*, a plugin for your modelling package that can output .igs files. The exporters are complex pieces of software in their own right and it is recommended you read your exporter manual after you have finished looking through this document. At the time of printing, Indigo has exporters for the following software: - 3ds Max - Blender - Cinema 4D - Google Sketchup If your modelling package of choice is not listed, it is often possible to export your scene or 3D model into a format that can be loaded by one of the above packages and then exported to Indigo. Blender is often a popular choice for doing this – since it is a powerful and free modelling package. Licensing Indigo The development of Indigo began in 2004 and for the first five years of its life, Indigo was freely available via the internet. Beginning with Indigo 2.0, released in 2009, Indigo is a commercial software package and requires a licence if you want to use Indigo for commercial work – or remove the restrictions put on the free version. You are welcome to learn Indigo 2.0 and use it for non-commercial renders without paying for a licence. The following restrictions are present in the free version of Indigo: - Maximum resolution of 0.7 Megapixels – e.g. 1000 pixels by 700 pixels. - Indigo logo in the bottom right of the image - **May not be used for commercial work.** - No support (beyond that given in the forums at indigorenderer.com/forum/) If you need to create renders at higher resolutions or produce renders as part of your business, then you need to buy a commercial licence for Indigo. You can buy licences online at: http://store.glaretechnologies.com/ Once you have purchased a licence, you can instantly enable the full features of Indigo. Your licence will be locked to the hardware of your computer - but if you upgrade your computer in the future, you can ask to have your old licence invalidated, and you can generate a new licence for your new computer. The licence for your computer is based upon the CPU model of your processor and MAC address of your network card. You should avoid changing your network card regularly when using Indigo – for example avoid enabling and disabling your network card, as this may confuse the licensing software that Indigo uses. If you have any problem with your Indigo licence, you can always contact us at support@indigorenderer.com and we'll get you up and running as soon as possible! There are two different kinds of Indigo licences: - GUI Licence – for use on your desktop computer - Node Licence – for use on networked render slaves Having a GUI Licence does not mean that you can use unlicensed render slaves to generate a high resolution image, you will need a node licence for each computer that will be used to help you render your image. Indigo Licence activation Once you have purchased an Indigo Licence from the Glare Technologies Store you need to go through a few steps to activate it with Indigo. 1. Open Indigo and click on the **Licencing** button. 2. Press **Copy to Clipboard** to copy the hardware key. 3. Upon purchase on a licence, you will receive an email with a link to the store page with your details on it. Check they are correct. 4. Scroll down to the bottom section. Paste in your hardware key into the appropriate box, depending on the type of licence you own, and press **Generate Licence Key**. 5. A bunch of characters will be returned in a text box, copy it all. 6. Paste it back into the Indigo Licence dialog box at the bottom. And press **Verify licence key**. ![Indigo Licence dialog box](image) Success! 7. The Indigo background will also tell you if it is verified. ![Indigo Render background](image) **Indigo Render v2.2.5, Windows 64-bit Release build. Copyright (c) Glare Technologies Limited** Licence verified, licence type: Indigo 2.x Node, licensed to... System Requirements Indigo will run on most modern computers. **Minimum system requirements:** Windows: - Pentium class CPU with SSE2 – anything purchased in the last 5 years should satisfy this requirement. - 1GB of RAM - 100MB of Hard drive space - Windows 98 or above Mac: - Intel Macintosh – PowerPC based macs (G4/G5) are not supported - 1GB of RAM - 100MB of Hard drive space - OSX 10.5 Leopard Linux: - CPU with SSE2 - 1GB of RAM - 100MB of Hard drive space Recommended systems To get the best results from Indigo when rendering large scenes, you should look at getting a computer with multiple cores (e.g. the Intel Core 2 Quad or Core i7 CPU) and at least 2GB of RAM. If you are rendering exceptionally large scenes you may require 4GB or more of memory – in this case you should use a 64-bit build of Indigo and a 64-bit operating system so that Indigo can access all of your memory. See the notes on 32-bit versus 64-bit in the next section. About Installation To download Indigo, go to http://www.indigorenderer.com/download/ and select the appropriate version of Indigo for your platform (Windows, Macintosh or Linux). You should download the latest available version of Indigo which will be listed at the top of the page. 32 bit versus 64 bit Indigo is available for each platform in 32-bit and 64-bit versions. If you have a 32-bit CPU or 32-bit operating system you can only use the 32-bit version of Indigo. If you have a 64-bit CPU and operating system (e.g. Windows XP 64 bit, Windows Vista or OS X Leopard) then you can use the 64-bit version of Indigo. The 64-bit version of Indigo has the following benefits: - Ability to access more than 2GB of memory - Slight performance increase on 64-bit CPUs The 64-bit version of Indigo for your platform is available under the 64-bit builds section on the Indigo download page: http://indigorenderer.com/download/ It is free to upgrade to the 64-bit version of Indigo. Installation on Windows Download the newest version of Indigo for windows, then double click the installer file. Step 1 – Agree to the licence You will be presented with the Indigo End User Licence Agreement. You should read through it and click 'I Agree' if you agree with the terms. Step 2 – Choose Components We recommend you leave the checkboxes selected but you are able to disable each component if you have special needs on your system. Press Next to continue. Step 3 – Choose Install Location We recommend you use the default installation location, as most Indigo exporters will expect to find Indigo here – however you are able to change this path if you need. Indigo will write a registry key that exporters will use to find Indigo automatically if Indigo is installed in a non-standard location. Press Install to complete the installation. After Installation Once installation has completed, you can find Indigo in the start menu under the Indigo Renderer menu. This manual is available as *Indigo Manual*, you can start the Indigo Renderer GUI with the *Indigo Renderer* entry or start the *Indigo Renderer Network Slave* if this PC is to be used as a network rendering slave. See the relevant exporter manual to get started with your modelling package. Installation on Macintosh Step 1 Download the newest version of Indigo for Macintosh then double click the download file to unzip it. Step 2 Double click the file that is unzipped to mount the Indigo disk image. Step 3 Drag the Indigo icon to your applications directory to copy it to applications. Indigo is now ready to be used on your mac. Installation on Linux Step 1 Ensure you have correct prerequisites. Indigo on Linux requires that you have qt-4.5 installed for the GUI. This library is available for most modern distributions and can usually be installed with rpm or aptitude. Step 2 Download the latest indigo .tar.gz file from http://www.indigorenderer.com/download Step 3 Create a folder in your home directory and unzip the .tar.gz into that directory. Indigo is statically linked as far as possible and should be ready to be used. Run ./indigoconsole -h to see if Indigo installed correctly. You are now ready to run Indigo. As described in the *About Indigo* section, Indigo requires an 'exporter' to work with each modelling package. You can download these exporters at: In the *Download Exporters* section. Each exporter will come with its own installer and should automatically detect the location of Indigo. Notes about exporters: - You need to install Indigo before you install the exporter for your modelling package. - If are are getting strange errors with Indigo complaining about not being able to render your scene file, ensure that you have the same version of Indigo (e.g. 2.0.7) as your version of the exporter (e.g. Blendigo 2.0.7). Further information about using the Indigo exporters you should see the relevant *Exporter Manual*. Working with the Indigo Interface Getting to know Indigo Note: The screenshots in this section of the Indigo manual are taken from the Windows 7 version of Indigo – the GUI may look different on your system but should act identically. A first look at Indigo To get started, click Open Scene and browse to the testscenes directory in your Indigo Renderer directory. Open the scene \Caterpillar - Paha Shabanov\caterpillar_5.igs This will let you see all of the Indigo user interface elements. The Indigo window is divided into four sections: 1. Toolbar – Open and close scenes, start and pause rendering, save rendered image and more. 2. Rendering frame – This section will show the Indigo logo and your licensing information. Once rendering has started, the rendered image will be shown here. 4. Render settings – This section is only available when you have an open scene. You can use these settings to modify the scene settings and modify the image settings as the render progresses. 1. Toolbar Most functionality in Indigo can be accessed from the toolbar. Each option in the toolbar is also available from the Indigo menu bar. **Open Scene** Opens a new scene in the current window. Closes currently open scene (if any). **Close Scene** Closes the current scene, terminating the current render. Ensure you have saved your output image before closing the scene. **Render** Start rendering the current scene. Upon pressing this button, the scene will be processed and then rendering will start. The scene building process can take up to a minute on large scenes. **Pause Render** This will pause the current render and free up your computer's CPU. You can resume the render at any stage. You may need to do this if Indigo is causing your system to slow down while rendering. **Stop Render** This stops the current render and frees your computer's CPU and memory. You can still tone-map and save the rendered image after the render has been stopped – but you cannot easily restart the render (see more information about .igi files if you need to stop and start renders). **Network Rendering** Enables network rendering. This button must be pressed before *Render* is pressed to start a network rendering job. See the section on *Network Rendering* for more information. **Save Image** Once an Image is rendering, you can click Save Image to save the image that is currently being displayed in Indigo. **Update Image** Indigo only updates the image on the screen every minute (by default), to speed up your rendering time. If you want to see the progress that has been made since the screen was last updated, you can press Update Image to force a screen update. **Licensing** Use this button to open the licensing window. You can use this to instantly buy a licence for Indigo and remove the restrictions of the free version. ### 2. Rendering frame The render frame shows the progress of your rendering. It will resize to the size of the render you are rendering currently. To zoom in or out on the image, click on the rendering frame and press + to zoom in, - to zoom out and press 0 to reset to the 1:1 zoom level, you can also use the mouse scroll 3. Statusbar The statusbar shows render progress. It displays samples per pixel, time elapsed and the total number of samples. About samples per pixel Indigo measures its render progress as the number of samples that have been calculated. You can imagine these as being the number of “light particles” that have bounced around the scene and hit the sensor in your camera. Depending on the complexity of your scene, it may take up to 1000 samples per pixel before the image starts to become clear enough for your purpose. Many scenes will start to resolve at around 100 samples per pixel, and some scenes look good after 10 samples. How long do I render for? Unbiased renderers (like Indigo) are never truly “finished” rendering. You will get your first image from Indigo within 30 seconds of starting your render, but this image will be very noisy (lots of “grain” or “static” in the image). As the render progresses, the noise in the image will go down according to the following graph: So, at the start of the render, the amount of noise in the image will decrease very fast – if you watch the render you'll notice it gets visibly clearer in the first 5 minutes. However, over time - the quality of the render improves more slowly, until eventually you will not get any noticeable difference from rendering any further. In general, most people will just leave their scene rendering until it looks clear enough for their purposes. 4. Render settings The render settings are only visible when a scene is open. There are several pages of render settings – you can access the different pages via the drop down control: The pages of render settings are described in the following sections. Resolution The resolution page controls the size of the image you will create. You can specify the resolution from one of the presets, or enter it manually in the width and height controls. The resolution will be calculated and displayed in Megapixels (the same measurement used for digital cameras description). Higher resolutions will take longer to render to a good quality. Background Mode is an option that is only available on windows. It specifies how much of your CPU that Indigo is allowed to use. This will make your computer more responsive for normal usage, while Indigo will continue running (slightly slower) in the background. This is useful if you need to use your computer for other tasks while Indigo is running. If Super-Samples is greater than 1, then the image is rendered at a higher resolution internally, then downsampled using the downsize filter before the render is saved to disk. This can help to reduce aliasing around high contrast edges. Note that higher factors require more memory (RAM). Tone Mapping Tone mapping changes the brightness and contrast of your image. It can be done at any stage during the render process. Changes to tone mapping will be applied immediately to the rendered image. Tone mapping is non-destructive, so you can play around with the different tone mapping settings without permanently effecting the rendered image. You may want to tone map your image using different settings, and press Save Image to save out several different images. Some background: Indigo creates a high dynamic range (HDR) image as it renders, and this must be converted to a standard low dynamic range red, green and blue image that can be displayed on your computer monitor or saved as an image. Tone mapping can be a slow process on high resolution images (especially if aperture diffraction is turned on) and so tone mapping is only done periodically to ensure that Indigo can dedicate most of it’s time to tracing the light paths inside your scene. Indigo has three different tone mapping techniques that you can choose from: Reinhard, Linear and Camera. Reinhard is the simplest to use as it automatically scales to the brightness of your render. Once mastered however, camera tone mapping can give a nice artistic feel to the renders. Reinhard tone mapping Reinhard is a method based on a paper by Reinhard, Stark, Shirley and Ferwerda from the University of Utah. It is often the best tone mapping technique because it automatically adjusts to the amount of light in the scene. It can be tricky to get linear or camera tone mapping to work correctly in scenes where there is an extremely bright light source – the Reinhard method is a good choice for scenes like this. The parameters of Reinhard are hard to explain, as they represent parameters for this formula: \[ L_d(x, y) = \frac{L(x, y)}{1 + V_1(x, y, s_m(x, y))} \] Luckily, the default Reinhard settings of prescale=6, postscale=1, burn=2 will result in great results for all Renders. If you do want to adjust the Reinhard method – here is an approximate description of each parameter. **Prescale** Similar to a contrast control, works by increasing the amount of light in the HDR buffer. **Postscale** Works like a brightness control, increases the absolute brightness of the image after it has been tone mapped. **Burn** Specifies the brightness that will be mapped to full white in the final image. Can be thought of as gamma control. We recommend that most people use Reinhard with its default settings. **Linear tone mapping** ![Linear Settings](image) The simplest tone mapping method, linear depends on just a single number. Every pixel in the HDR image will be multiplied by this number. ![Images of linear tone mapping with different scales](image) Scale = 1.0 Scale = 0.1 Scale = 0.01 Linear is easy to understand, but doesn't give the best results – the Reinhard and Camera methods tend to give a nicer feel to the image. For example – linear will be hard to configure when there is a bright light source visible (such as the sun) while the rest of the scene is dimmer. Camera tone mapping simulates the working of a photographer's camera. You adjust the exposure and ISO settings as you would in a real camera to modify the tone mapping. The parameters you modify are: **ISO** The ISO number represents the speed of film that is used. The higher the ISO number, the more light will be collected in the HDR Image. In low light situations, a fast film should be used, such as ISO 1600, and in bright lighting situations, a slow film can be used, such as ISO 100. **EV** The exposure value can range from -20 to +20 and represents a correction factor that is applied to the collected light. The higher the EV, the brighter the final image will be. Increasing the EV by one will make the image twice as bright. The final parameter is the response function. This specifies the type of film or digital camera to emulate. Different films and cameras emphasise different colours. The response functions are taken from real cameras – for example the images below use Ektachrome 100CD film which is famous for being used by National Geographic in their older photos. A good default for sunny well-lit scenes is an ISO of 200 and an EV of -5.0. Camera tone mapping using Ektachrome 100CD film, and an EV of -6.0: Camera tone mapping using ISO 200, EV of -6.0 and different response functions: - Ektachrome 100CD - Advantix 100CD - DSCS315_6 White balance is used for the same reason as in traditional photography. The human eye and brain adjust to the light in a situation to make the whitest colours look true white. For example, a sheet of white paper will appear white outdoors, where there is a lot of blue light, as well as appear white indoors under incandescent bulb lighting, where there is a lot more orange and red light. When rendering, you can adjust the whitepoint so that the scene doesn't have a blue or yellow tinge. The white balance is specified using x and y chromaticity coordinates. These should be matched to the chromaticity of the scene lighting as closely as possible. You can also set the whitepoint coordinates indirectly, by selecting a whitepoint preset from the 'Preset' drop-down box. The list contains the whitepoint coordinates for various different standard illuminants. For example, if you are lighting your scene with a 'perfectly white' light (e.g. a flat spectral power distribution), you will want to select the 'E' preset. If your scene uses the sun+sky model, then the 'D65' preset is a good choice, as it corresponds to a noon daylight illuminant. Light layers allow you to separate contributions from different lights onto different 'layers'. Each layer can then be manipulated separately, even after the render has completed. You can change the brightness of each layer, or change the overall colour of each layer, or even turn each layer off completely. Enabling Light Layers By default, all lights in an Indigo scene are assigned to layer 0. This means that the HDR image will have only one layer – layer 0. However, in the exporter for your 3D modelling program, you can change the layer that a light is assigned to. All contributions from that light will then be rendered onto that layer. Each layer has a number of controls that you can manipulate in the Indigo GUI. These controls are described below: Master Gain Applies an overall scaling factor to the layer. Increasing this value past one makes the layer brighter than originally. X gain Scales the X component of the layer, which is similar to the red component of the layer. Y gain Scales the Y component of the layer, which is similar to the green component of the layer. Z gain Scales the Z component of the layer, which is similar to the blue component of the layer. Enable Layer This checkbox allows you to easily turn on and off all contributions from this layer to the final blended image. If it is disabled, this layer will not be added to the final image, and no lights assigned to this layer will be visible. Aperture Diffraction Aperture diffraction allows the simulation of light diffraction through the camera aperture. Such diffraction creates a distinct 'glare' effect around bright light sources in the image. In the following images, you can see the difference aperture diffraction makes: Render of the sky and sun, with aperture diffraction disabled Render of the sky and sun, with aperture diffraction enabled You can enable or disable aperture diffraction by checking or unchecking the 'Enable aperture diffraction' checkbox. Note: Aperture Diffraction increases dramatically the amount of RAM used. Network Rendering Indigo can be made to render much faster by using several computers at once. This tab shows the current 'render nodes' that are connected to your computer and are helping Indigo render the image faster. The 'Working master' button specifies whether or not this computer should use its own processor to render the scene – or if the computer should purely manage the render nodes that will do the rendering for you. See the section on 'Using Network Rendering with Indigo' for more information on this section. Render Log The render log shows you messages from the core rendering engine inside Indigo. You do not normally need to access the rendering log. You may want to refer to the log to get an idea of how many triangles in your scene or what Indigo is doing at each stage of the render to satisfy your curiosity. The render log can be valuable if you are using Indigo's advanced features or are experiencing strange errors with a pre-release version of Indigo. Indigo File Types Indigo has several of its own file types for use specifically with Indigo. **IGM**: Indigo Material. Contains material information, but nothing else. **PIGM**: Packed Indigo Material. Contains material information and anything else relevant to the material, such as textures. Can be upzipped with compression programs such as WinZip, WinRar, or 7Zip. Use to distribute materials. **IGI**: Indigo Image. Contains information saved from an Indigo render. Used to resume renders. **IGS**: Indigo Scene. Contains information on an Indigo scene. **PIGS**: Packed Indigo Scene. Contains everything needed to render a scene, such as models and textures. Can be upzipped with compression programs such as WinZip, WinRar, or 7Zip. Use to distribute or archive scenes. Rendering a Test Scene To get a feel for Indigo – click Open Scene and browse to the testscenes folder your Indigo Render install, likely C:\Program Files\Indigo Renderer\testscenes and open the \Caterpillar - Paha Shabanov\caterpillar_5.igs scene. This is a winner of a past Indigo competition by Paha Shabanov. Using the resolutions settings on the right hand side of the window, set the resolution to 800x800 and then press the Render button on the tool bar. Indigo will now 'build' the scene and prepare it for rendering. For a simple scene, building the scene will be nearly instantaneous, but for larger scenes (with many millions of polygons), building the scene can take up to a minute. You can tell if Indigo is building the scene because the status bar at the bottom will say 'Building Scene...'. Once the scene has started rendering, the status bar will update to say 'Rendering | Samples per pixel:...' . This means that Indigo is tracing light rays around your scene and you can start to see the results of your render. After a few seconds of rendering, press the Update Image button on the toolbar. You should see the render looking something like this: ![Caterpillar after a short period of rendering](image) The image will be noisy for the first few minutes of rendering, then will be much clearer. The image displayed will update automatically every so often – but you can force the image to update at any stage by pressing Update Image on the toolbar. Next you should use the render settings dropdown to change to Tone mapping. The default setting for this scene is Camera with FP900Z. Click on the ISO box and change the ISO value to 1500, you should see the scene instantly become brighter. Next – press pause on the render. The render is now paused, but you can still change the tone mapping settings – press the reset button on the tone mapping controls and the image will return to its normal brightness. Now click the ‘Camera’ dropdown and change to the ‘Reinhard’ method. Change the Prescale to 10 and the Postscale to 30. The image will now look like it has been captured with an auto-exposure. Change the tone mapping method back to Camera and set the ISO back to 800 then use the render settings dropdown to go to ‘white balance’. Using the white balance preset, change the preset to D75, notice that the scene becomes slightly yellow-tinged. Next, change the whitepoint x to 0.35 – notice that the scene becomes notably greener. Press reset to reset the scene to a default white balance. Now – press 'Save Image' on the toolbar. Save the image to your desktop as caterpillar.jpg – specify JPG as the file type in the dropdown menu at the bottom of the dialogue. A useful technique when rendering is to pause the render, try different tone mapping settings and use 'Save Image' to save multiple variations of the render. Saving and resuming a render using an IGI While Indigo is rendering a scene, you can save the HDR buffer into an *Indigo Image* (*IGI, extension*.igu) file. Along with the original scene file, the IGI file contains all the information needed to resume rendering the scene, from the point where the IGI was saved. You can resume rendering the scene even after closing Indigo and opening it again later. To resume rendering an image saved to an IGI, follow these steps: 1. Start rendering the scene. When you wish to save the IGI: 2. Click the 'Save Image' button. 3. Select the *Indigo Image file* type in the *Save File* dialog. 4. Choose a filename for your IGI file, for example 'test.igi', and click *Save*. 5. You can now close Indigo. 6. When you wish to resume your render, open Indigo, and select *Resume Render from IGI* from the *File* menu: 7. You will then be prompted to locate the scene file. This is because Indigo needs to know both the location of the scene file, plus that of the IGI, in order to resume the render. You must open the same scene that you were rendering when you saved the IGI. 8. After selected the scene file, you will be prompted to locate the IGI file. Navigate to where you saved the IGI file, and press the 'Open' button after selecting it. 9. You can confirm that the render resumed successfully by looking at the status bar – the *time elapsed* value should include all the time spent rendering, before the IGI was saved. Network Rendering Indigo has built-in support for network rendering, which allows all the computers on a network to work together to render a single Indigo scene more rapidly. You will need one master computer, that will coordinate the rendering process. You will also need one or more slave computers, that will be helping to render the scene. For the purposes of this tutorial, the slave computers must be on the same local area network (LAN), and able to communicate with each other. On the master computer: **Step 1:** Start Indigo Renderer (indigo.exe). **Step 2:** Open the scene that you want to render in the Indigo Renderer GUI using the "Open Scene" button. **Step 3:** Press the 'Network Rendering' button to enable network rendering mode. **Step 4:** Press the start render button On the slave computer(s): **Step 1:** Execute the "Indigo Network Render Slave" shortcut. Providing the network slave can find the master and connect to it on the network, it should then download the scene from the master and start rendering it. Viewing connected slaves on the master GUI You can view all network slaves that are helping with the current render by selecting "Network Rendering" from the combo box on the right hand edge of the Master GUI: <table> <thead> <tr> <th>Description</th> <th>Samples per second.</th> </tr> </thead> <tbody> <tr> <td>192.168.71.1:51105 hope; ...</td> <td>320k</td> </tr> </tbody> </table> Working with the Indigo Material Editor The Material Editor The Indigo Material Editor is a controlled environment to aid the process of creating materials for your scenes. While all the controls are available in your exporter, it is much quicker to make iterations of your materials and easier to see the results. This section covers the usage of the Indigo Material Editor’s interface only. See the Indigo Material section below for information on material attributes. The Indigo Material Editor 1. The **standard** Indigo toolbar with two extra options – Material database, and Upload to Material database. 2. The preview panel. Rendering progress is displayed here. After your first render, you can view your past renders by scrolling down here. 3. The materials panel here lists all material types used on this single material. 4. The medium panel lists mediums that the material is currently using. 5. The control panel. Here you can adjust the material type and its attributes depending on what is selected. Also displays the medium’s attributes when a medium is selected. 1. Toolbar See [Indigo Toolbar](#) for the full toolbar. ### Render/Restart Render This button differs slightly from the Indigo Renderer, in that it can either start a new render using any material changes you have made, or resume the current render. You must stop a render in order to start a new render with different settings. ### Material Database This new feature allows you to browse the Indigo Material Database hosted on the Indigo website through the Material Editor. All these materials are submitted by the community and all materials are [Creative Commons Licensed](#) and can be freely used in commercial work. Downloading the material instantly downloads it and places it in the material editor. Note: Downloading a material replaces the current material open. ### Upload to the Material Database This will take your current render, and current material settings and upload it to the online Indigo Material Database with a form for you to fill out describing it. The Material Database model must be used when uploading to the database and it is strongly suggested that the render of your material is clear and easy to see. 2. Rendering frame Rendering your material using the **Render/Restart Render** will draw your material applied to the default Material Database model here. Subsequent new renders will push old ones down below and start above. To view old material renderings, just scroll down here. Note: only the newest render will be saved using the **save image** button, and any old ones will be lost when the program is closed. 3. Materials List Here is a list of all the currently used material types. If blended materials are used, this also shows the hierarchy. **Add Material:** Adds a new default material to the current list. **Remove Material:** Deletes the selected material. 4. Medium This shows the medium being used. Using a material type (specular or glossy transparent) that has a medium automatically adds it down here. A material can only have one medium present. See **Medium**. 5. Control Panel Use this to describe the type of material you want. The drop-down is a selection of material types, which affects the attributes that are available below. See **Materials**. Working with Scenes for Indigo Indigo Scenes This section explains all the special features that Indigo offers to enhance the scenes you create within your 3D package. If you have been using an Indigo exporter, such as Cindigo, Blendigo, SkIndigo, or MaxIgo, and are unsure what some features do, you’ve come to the right place. There are 2 main sections that you will work with in order to get good renders with Indigo: Materials, and the Render Settings. Indigo materials allow you to add in all the extra details that most renderers are not able to simulate, and the Render Settings allow you to control how the scene is rendered. Indigo has 7 different material types. Each one represents a different physical material. When light strikes and object, it interacts with it in some way, reflecting or penetrating the material. Indigo material types define what the light does on the surface and inside it, giving you all the controls to tell the light what to do. This section will go through each material type and its attributes and will also include the several miscellaneous types such as Exit Portals and Nulls. Materials are rendered using the Material Editor with the default Material Database Model for clarity. Material Attributes Each material has attributes that control aspects of itself. There are a several common attributes, as listed here, and unique attributes, as listed under their respective Material Type. All attributes can be controlled by either a single number, a Texture, or a shader. Here is a list of the shared material attributes. Albedo Defines the color of the surface. See the Texture Maps section for information on texture attributes. Materials with attribute: Diffuse, Phong, Diffuse transmitter, Oren-Nayar **Bump** Gives the illusion of a bumped surface by creating highlighted and shadowed areas based on a texture map. It does not actually displace the surface at all. Good for small details and renders faster than displacement maps. The scale value (B) tells Indigo how far the distance is from full black to full white. Because bump maps do not actually change the surface, a low number is suggested in the range of several millimetres, otherwise smooth gradients can become harsh lines. See the [Texture Maps](#) section for information on texture attributes. **Materials with attribute:** Diffuse, Phong, Specular, Glossy Transparent, Oren-Nayar --- **Displacement** Creates 'real', or 'physical' bumps on a surface. Most commonly created by use of a texture map. Can be used for anything from small details such as a rough surface, through medium details such as brick, and even for mountain ranges. A constant setting displaces the entire mesh evenly by the defined amount. A texture map displaces the vertices based on values in a grey-scale image. See the [Texture Maps](#) section for information on texture attributes. **Materials with attribute:** Diffuse, Phong, Specular, Glossy Transparent, Diffuse transmitter, Oren-Nayar Base Emission Emits a specified brightness and color of light, use this to create lights. There are several modes to set this: **RGB:** Light based on color and brightness. **Uniform:** A white light with intensity based on value given. **Blackbody:** Light is based on the temperature. Measured in Kelvin. **Peak:** Define the limits of the wavelength. **Real Tabulated:** Allows nearly arbitrary spectra to be defined. The spectrum value is given at regular wavelength intervals, and linear interpolation is used to sample at intermediate wavelengths. **Materials with attribute:** Diffuse, Phong, Specular, Glossy Transparent, Diffuse transmitter, Oren-Nayar Emission Modifies the Base Emission value. The final emission is based on the Base Emission and Emission. Emissions are measured in Lumins **Emission Scale:** Scales the emissions from the material by given scale. Various photometric units are available. **IES profile** If an IES profile is selected, then the emitted light has a particular pattern based on the information in the IES profile. This is an easy way to get light as emitted from a realistic light fixture, without all the modelling. Only IES files with vertical angles below 90 degrees are supported. See the Texture Maps section for information on texture attributes. Also see the IES tutorial in the Techniques Manual. **Materials with attribute:** Diffuse, Phong, Specular, Glossy Transparent, Diffuse transmitter, Oren-Nayar --- **Layer** Choose the layer that the light reflected/transmitted from this material will be recorded onto. Used for creating several different lighting set-ups to render at once. See Light Layers, and Techniques Manual: Light layers **Materials with attribute:** Diffuse, Phong, Specular, Glossy Transparent, Diffuse transmitter, Oren-Nayar --- **Exponent** ![Image of a rough surface](image) Controls the 'roughness' of the surface. The smoother the surface (or higher the exponent), the sharper the reflection. Higher exponent means more 'perfect' reflection, lower exponent leads to more glossy and diffuse highlights. Can range from ~1 to up to 10000 or more. **Materials with attribute:** Phong, Glossy Transparent Texture maps Unadjusted texture Supported texture formats: JPEG (.jpg, .jpeg): greyscale, RGB supported. PNG (.png): greyscale (8 or 16 bits per pixel), RGB (24 or 48 bits per pixel) supported. Note that 16 bits per channel data will be internally converted to 8 bits per channel data. Truevision TGA (.tga): greyscale (8 bits per pixel) or RGB (24 bits per pixel) supported. RLE compression is not supported. Windows Bitmap (.bmp): greyscale (8 bits per pixel) or RGB (24 bits per pixel) supported. RLE compression is not supported. Open EXR (.exr) TIFF (.tif / .tiff): greyscale, RGB, RGBA supported. UV set: Name of the set of uv coordinates used for texture lookup. Usually generated by your 3D package plugin. Path: Path to the texture map on disk. Path must be absolute or relative to the scene working directory. Gamma (Exponent): Used for converting texture RGB values to display values. A typical value is thus 2.2. **A,B,C Values** The A, B, C values are modifiers for the texture map. This is the equation used (for those that have studied calculus this equation will be familiar): \[ x = ax^2 + bx + c \] The A, B, C, values are taken from here. Thus: **A value – Quadratic** Scales values by a quadratic, so low values stay low, and larger values become exponentially larger. You will not often need to use this, usually it easier to get expected results by modifying the texture map with an image editing program. **B value - Scale/Multiplier** Scales the texture map values. Can be associated with contrast. Maps the value range of 0-255 to 0-1 (for a usual LDR texture), which is then multiplied by this number. For example: a B value of 2 makes a pure red RGB 255,0,0 to 510,0,0. ![Texture Scale(B) of 2](image1) **C value – Base Value** Total RGB offset, generally making the texture brighter or darker. ![Texture base value(C) of 0.2](image2) Indigo Shader Language ISL stands for Indigo Shader Language. It's a functional language that allows you to write shaders for every channel in Indigo materials. With shaders you are not tied to the restrictions of textures any more: they are procedurally computed for every point on the surface. Diffuse materials are flat, matte surfaces that don't have shiny edges. Flat wall paint, or a piece of paper are good examples of a diffuse material. There will be no particular reflection from a diffuse material. **Common attributes:** [Albedo](#), [Bump](#), [Displacement](#), [Base Emission](#), [Emission](#), [Layer](#) Specular materials are quite powerful and can be made to act as perfect reflectors (like a mirror) or as a fully transparent glass and anything in between. If transparent, the medium defines how the light moves through the object, scattering and/or absorbing. **Transparent:** If enabled, it allows light to pass through the material. Otherwise only reflected light is simulated. **Common attributes:** Internal Medium, Bump, Displacement, Base Emission, Emission, Layer Phong Phong is a shiny material. Commonly used for shiny paints or any metals. In particular, phong will have a "specular highlight" where the light is completely reflected. Phong is useful for anything that has a lacquer applied to it - for example a shiny wood floor or a car paint. **IOR (Index Of Refraction):** of the dielectric coating or substance making up the material. Basically controls the amount of light reflected by the surface. The amount of light reflected. **Nk_data:** Indigo comes packaged with a set of Lab-measured metals. Use this attribute to set a metal to the material. If Nk_data is used, then the Diffuse and Specular attributes are ignored. Various Nk_data profiles **Specular Color:** Generally speaking, this changes the color of the reflections. If this is enabled, then IOR and Albedo are ignored. It is therefore only good for simulating metals. **Common attributes:** Albedo, Exponent, Bump, Displacement, Base Emission, Emission, Layer Glossy Transparent The glossy transparent is a material that simulates a rough surface of a transparent dielectric medium. It's good for simulating stuff like frosted glass, human skin etc. Common attributes: Internal Medium, Exponent, Bump, Displacement, Base Emission, Emission, Layer Diffuse Transmitter This material is a very simple BSDF that basically scatters incoming light into the opposite hemisphere, with a cosine-weighted distribution. Although it doesn't really have any exact physical basis, it could be thought of as the limit of many sub-surface scatters inside a thin, highly scattering material. As such it should be useful for simulating such materials as curtains, lampshades etc.. It's meant to be used on single-layer geometry, and it does not have an associated internal medium (it's not an interface material). It will probably be a good idea to blend this material with a diffuse or phong material, so that some backscattered light is visible, not just transmitted light. Common attributes: Albedo, Displacement, Base Emission, Emission, Layer Note: Image shows a blend of diffuse transmitter and Phong materials Oren-Nayar materials are very rough materials that scatter light in every direction. They are rougher than diffuse materials. Oren-Nayar is useful for creating surfaces that are like clay. They aren't shiny at all. **Sigma**: Controls the roughness of the material. A higher sigma gives a rougher material with more backscattering. *Diffuse Material; Oren-Nayar Material with Sigma: 0.0, 0.2, 0.5, 1.0* Notice with the increasing Sigma, the rim shadows disappear, and the overall brightness fades. **Common attributes**: [Albedo], [Bump], [Displacement], [Base Emission], [Emission], [Layer] The blend material allows two materials to be blended together, controlled by either a constant value, or an image/texture map. It is possible to blend more than two materials together by arranging them into a hierarchy. Only restrictions are that you cannot blend null & null, and specular & specular, and null & specular material types. **Blend:** Controls the amount of each material used. A value of 0 means only material \( a \) is used, a value of 1 means only material \( b \) is used. **Step Blend:** Applies a step to the blend amount. Values over 0.5 will become 1, values under 0.5 will become 0. Recommended for clip masks to reduce noise. Exit Portals Exit portals are useful for speeding up interior renderings, when the interior is lit by an environmental light source, such as the sun/sky model. Exit portals are placed over the openings between the interior and the exterior environment. These openings are the 'portals' in the scene. Exit portals make the rendering process more efficient, because paths passing through such openings can be more efficiently sampled when explicitly marked with an exit portal. Requirements for exit portal usage: • If exit portals are present in the scene, then all openings must be covered by exit portals. In other words, all possible paths that start on the camera, and then travel through space or a transparent object, and then escape out of the scene into the environment, must be blocked by one or more exit portals. • The geometric normal (defined by triangle winding order) of an exit portal mesh triangle, where reachable by some path from the camera, must point into the interior of the scene. (i.e. The front side of the mesh faces should be visible by the camera) Null Material The null material is a very simple material that doesn't scatter light at all. It's effectively invisible. It is often used to add transparency to materials by adding it to a blend material. The null material has no parameters. Internal Medium The medium attribute fills the interior of the mesh with a medium that diffracts, scatters and absorbs light, depending on the type set. A medium has a type (much like material have types). Media types include basic, epidermis, and dermis. **Precedence:** Precedence is used to determine which medium is considered to occupy a volume when two or more media occupy the volume. The medium with the highest precedence value is considered to occupy the medium, 'displacing' the other media. The predefined and default scene medium, 'air', has precedence 1. **Basic** **IOR:** Index of refraction. Should be >= 1. Glass has an IOR (index of refraction) of about 1.5, water about 1.33. The IOR of plastic varies, 1.5 would be a reasonable guess. **Cauchy B Coeff:** Sets the 'b' coefficient in Cauchy's equation, which is used in Indigo to govern dispersive refraction. Units are micrometers squared. Setting to 0 disables dispersion. Note: the render can be slower to converge when dispersion is enabled, because each ray refracted through a dispersive medium can represent just one wavelength. So only set cauchy_b_coeff to other than 0 if you really want to see dispersion. Typical values for glass and water lie in the range 0.003 – 0.01 (see [http://en.wikipedia.org/wiki/Cauchy%27s_equation](http://en.wikipedia.org/wiki/Cauchy%27s_equation) for some coefficients) **Absorption Coefficient Spectrum:** Controls the rate at which light is absorbed as it passes through the medium. **Subsurface Scattering:** Use this element to make the medium scatter light as it passes through it. **Scattering Coefficient Spectrum:** Chooses the phase function used for the scattering. **Phase Function** The phase function controls in what direction light is scattered, when a scattering event occurs. **Uniform**: Takes no parameters **Henyey Greenstein**: The Henyey-Greenstein phase function can be forwards or backwards scattering, depending on the 'g' parameter. **G Spectrum**: The g parameter may vary with wavelength, and is therefore specified using a spectrum element. Spectrum, Peak , Blackbody , Rgb, Regular Tabulated as defined above. **Epidermis** Medium for simulating the outer layer of skin. **Melanin Fraction**: Fraction of melanin present in tissue. Typical range: 0 – 0.5 **melanin Type Blend**: Controls the amount of eumelanin relative to pheomelanin in the tissue. Typical range: 0 – 1 **Dermis** **Hemoglobin Fraction**: Controls the amount of hemoglobin present. Typical range: 0.001 – 0.1 **Mesh Controls** **Subdivide:** Divides each triangle in the mesh into 4, with each level increasing it exponentially. Therefore a large mesh mesh of, say, 1 million becomes 4 million subdivided only once. Twice it becomes 16 million, and three times become 64 million. Render Settings These settings effect how Indigo renders. Logging: If true, a log from the console output is written to log.txt Save Untonemapped Exr: An untomemapped EXR image is saved in the renders directory. Save tonemapped Exr: A tonemapped EXR image is saved in the renders directory. Save igi: An untomemapped Indigo Image (.igi) file is saved in the renders directory. Image Save Period: The rendered image(s) will be saved to the renders directory this often. Halt Time: Indigo will stop rendering after this amount of time. Halt Samples Per Pixel: Indigo will stop rendering after after this amount of samples-per-pixel has been reached. See Samples Per Pixel Frame Upload Period: Period between uploads of the image buffer from slave to master when rendering in network mode. Auto Choose Num Threads: Automatically chooses all available CPU cores for rendering. Turn this off to specify number of threads to use for rendering. Num Threads: Define the number of threads for Indigo to render with. Super Sample Factor: If this factor is greater than 1, then the image is rendered at a higher resolution internally, then downsampled using the downsize filter before the render is saved to disk. This can help to reduce aliasing around high contrast edges. Note that higher factors require more memory (RAM). Display Period: The internal HDR buffer is tonemapped and displayed on screen this often. Watermark: An 'Indigo Renderer' logo is drawn on the bottom right hand corner of the output render. **Info Overlay:** If true, a line of text is drawn on the bottom of each render, containing some statistics about the current render process. **Cache Trees:** If true, kd-trees are cached to disk after construction, in the tree_cache directory. **Aperture Diffraction:** There are two options: Physical and Post-process. Physical is calculated during rendering and while it is slightly more accurate than the post-process aperture diffraction, it is slower. Post-process aperture diffraction is suggested. See [Aperture Diffraction](#). **Render Region:** Only a certain region of the image is rendered. **Render Foreground Alpha:** The output image is just a greyscale image, with the foreground as white, and the background (physical sky, env map, constant background, void background etc..) as black. Intended to be used as an alpha layer for compositing. **Splat Filter:** Controls the filter used for splatting contributions to the image buffer. A Gaussian filter with standard deviation of 0.35 pixels. or Mitchell-Netravali cubic filter which is a good all-round filter with little aliasing. Mitchell-Netravali has two variables: blur and ringing. Higher blur values cause more blurring of the image and higher ring values cause more 'ringing'. (alternating bands of black and white around high contrast edges). **Downsize filter:** Controls the filter used for downsizing super-sampled images. Only used when Super Sample Factor is greater than one. Takes exactly the same parameters as Splat Filter. **Lens Shift:** Shifts the lens to compensate for perspective. From [Wikipedia:](https://en.wikipedia.org/wiki/Lens_shift) (a) Keeping the camera level, with an ordinary lens, captures only the bottom portion of the building. (b) Tilting the camera upwards results in vertical perspective. (c) Shifting the lens upwards results in a picture of the entire subject. Render Mode Indigo is a Ray-tracer, which means that it captures scenes by firing out light rays and seeing where they go and what they hit. There are several ways that rays are calculated, with some being better than others in certain situations. The options are: - **BiDir pathtracing** - **Normal pathtracing** - **MLT with BiDir** - **Normal MLT** Generally, **BiDir pathtracing** should be used as it is the best all-round solution. Here is a diagram describing what they do. **Normal Pathtracing:** Rays are only fired outwards from the camera, recording what they hit on their way. **BiDirectional Pathtracing:** Rays are fired outward from both the camera and light sources. They are then joined together to give a result. **MLT (Metropolis Light Transport):** When a ray makes a successful path, another ray is fired off on a slightly similar direction. Gives good results for caustics. **Non-MLT (QMC- Quasi-Monte Carlo):** Rays are evenly distributed. Options available: <table> <thead> <tr> <th></th> <th>MLT on</th> <th>MLT off</th> </tr> </thead> <tbody> <tr> <td>Normal Pathtracing</td> <td>Good for debugging</td> <td></td> </tr> <tr> <td>BiDirectional</td> <td>Good for 'tricky' scenes</td> <td>Best default.</td> </tr> </tbody> </table> Environment Settings There are several options that allow you to fill the 'outside' of your scene. Background Illuminates scene with a uniform environment light. Sun and Sky Image by Radiance Indigo comes with a Sun and Sky model that realistically depicts the sky. Changing the sun's direction creates time-of-day effects: a low angle creates a sunrise/sunset with correctly colored sky and brightness. Turbidity: The turbidity defines the haziness/clearness of the sky. Lower turbidity means a clearer sky. Should be set to something between 2 and ~5. Extra Atmospheric: Removes the sky and renders only the sun. Good for renders in space. Environment Map Image by Fused Illuminates scene with an HDR environment map. Indigo can load two types of HDR environment maps, an `.exr`, and a `.float` maps in spherical format. `.float` is a simple format exported by the HDR Shop program. You can define the `.float` map's width, but it must be equal to its height. **Gain:** The map is scaled by this factor when it is loaded. The indigo camera controls how the scene is captured. It not only controls what is rendered, it also contains features found in a real SLR camera, such as the aperture radius and focal distance. These allow for effects such as depth-of-field. **Aperture Radius**: Defines the radius of the camera aperture. Larger radius means more depth of field. **Focus Distance**: The distance forward from the camera at which objects will appear 'sharp' in focus. **Aspect Ratio**: Influences the directions in which rays are traced. Should be set to the image width divided by the image height. **Sensor Width**: Width of the sensor element of the camera. A reasonable default is 0.036. (36mm). Determines the angle of view (FOV), together with the Lens sensor distance. **Lens sensor distance**: Distance from the camera sensor to the camera lens. A reasonable default is 0.02. (20mm) **White Balance**: Sets the white balance of the camera. See [White Balance](#). **Exposure Duration**: How long the exposure will be. The longer the exposure duration, the greater the light energy registered by the sensor. **Autofocus**: Sets the focal distance to the distance from the camera straight forward to the first object it hits. **Obstacle Map**: An obstacle map texture is used when calculating the diffraction though the camera aperture. Use to change the way the aperture diffraction appears. **Aperture Shape:** This allows a particular shape of camera aperture to be specified. The allowable shapes are image, generated, or circular. A preview of the final aperture shape will be saved in the working directory as `aperture_preview.png`. It must be a PNG file format and square with power-of-two dimensions of at least 512 x 512. The image is interpreted as a grey-scale image with the white portions being transparent and the black being solid. Going further with Indigo To learn more about Indigo, we recommend you view the following resources: • Indigo Renderer website: http://indigorenderer.com/ • Our forum for asking questions and learning from the community: http://indigorenderer.com/forums/ • The Indigo Technical Reference (a PDF file that comes with your Indigo install) contains an in-depth description of the Indigo file format if you need to edit the XML directly. • Our free materials database for finding great materials to use in your renders: http://indigorenderer.com/materials/ • Our online documentation: http://indigorenderer.com/documentation/ We hope you enjoy using Indigo Renderer and look forward to seeing the images that you create!
{"Source-Url": "https://www.indigorenderer.com/dist/manual/indigo-manual-2.2.12.pdf", "len_cl100k_base": 14002, "olmocr-version": "0.1.53", "pdf-total-pages": 83, "total-fallback-pages": 0, "total-input-tokens": 119576, "total-output-tokens": 17358, "length": "2e13", "weborganizer": {"__label__adult": 0.0007348060607910156, "__label__art_design": 0.047760009765625, "__label__crime_law": 0.00040841102600097656, "__label__education_jobs": 0.0020580291748046875, "__label__entertainment": 0.0015583038330078125, "__label__fashion_beauty": 0.0004973411560058594, "__label__finance_business": 0.0005826950073242188, "__label__food_dining": 0.0005626678466796875, "__label__games": 0.0035343170166015625, "__label__hardware": 0.0042724609375, "__label__health": 0.00041604042053222656, "__label__history": 0.0011425018310546875, "__label__home_hobbies": 0.0005674362182617188, "__label__industrial": 0.0009617805480957032, "__label__literature": 0.0010423660278320312, "__label__politics": 0.0003614425659179687, "__label__religion": 0.00116729736328125, "__label__science_tech": 0.1322021484375, "__label__social_life": 0.0002944469451904297, "__label__software": 0.289794921875, "__label__software_dev": 0.50830078125, "__label__sports_fitness": 0.00041413307189941406, "__label__transportation": 0.0005769729614257812, "__label__travel": 0.0006494522094726562}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 66333, 0.01327]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 66333, 0.32241]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 66333, 0.85159]], "google_gemma-3-12b-it_contains_pii": [[0, 0, null], [0, 2902, false], [2902, 5319, null], [5319, 5778, null], [5778, 7242, null], [7242, 8223, null], [8223, 9255, null], [9255, 9553, null], [9553, 11323, null], [11323, 11686, null], [11686, 12102, null], [12102, 12342, null], [12342, 12753, null], [12753, 13226, null], [13226, 13716, null], [13716, 14703, null], [14703, 15176, null], [15176, 15561, null], [15561, 15978, null], [15978, 16324, null], [16324, 16925, null], [16925, 17739, null], [17739, 17774, null], [17774, 18539, null], [18539, 19667, null], [19667, 20979, null], [20979, 22206, null], [22206, 22676, null], [22676, 23701, null], [23701, 24983, null], [24983, 26011, null], [26011, 26790, null], [26790, 28031, null], [28031, 28160, null], [28160, 29313, null], [29313, 29623, null], [29623, 30779, null], [30779, 31385, null], [31385, 31915, null], [31915, 32373, null], [32373, 33156, null], [33156, 34541, null], [34541, 35625, null], [35625, 36018, null], [36018, 37493, null], [37493, 38755, null], [38755, 38936, null], [38936, 38976, null], [38976, 40024, null], [40024, 41168, null], [41168, 42253, null], [42253, 42285, null], [42285, 42890, null], [42890, 44010, null], [44010, 45254, null], [45254, 46494, null], [46494, 47456, null], [47456, 48392, null], [48392, 49337, null], [49337, 49634, null], [49634, 49961, null], [49961, 50434, null], [50434, 51107, null], [51107, 51411, null], [51411, 51700, null], [51700, 52556, null], [52556, 53152, null], [53152, 53807, null], [53807, 54889, null], [54889, 55133, null], [55133, 56831, null], [56831, 57673, null], [57673, 57945, null], [57945, 59436, null], [59436, 60981, null], [60981, 61348, null], [61348, 61833, null], [61833, 62718, null], [62718, 63368, null], [63368, 63754, null], [63754, 65146, null], [65146, 65602, null], [65602, 66333, null]], "google_gemma-3-12b-it_is_public_document": [[0, 0, null], [0, 2902, true], [2902, 5319, null], [5319, 5778, null], [5778, 7242, null], [7242, 8223, null], [8223, 9255, null], [9255, 9553, null], [9553, 11323, null], [11323, 11686, null], [11686, 12102, null], [12102, 12342, null], [12342, 12753, null], [12753, 13226, null], [13226, 13716, null], [13716, 14703, null], [14703, 15176, null], [15176, 15561, null], [15561, 15978, null], [15978, 16324, null], [16324, 16925, null], [16925, 17739, null], [17739, 17774, null], [17774, 18539, null], [18539, 19667, null], [19667, 20979, null], [20979, 22206, null], [22206, 22676, null], [22676, 23701, null], [23701, 24983, null], [24983, 26011, null], [26011, 26790, null], [26790, 28031, null], [28031, 28160, null], [28160, 29313, null], [29313, 29623, null], [29623, 30779, null], [30779, 31385, null], [31385, 31915, null], [31915, 32373, null], [32373, 33156, null], [33156, 34541, null], [34541, 35625, null], [35625, 36018, null], [36018, 37493, null], [37493, 38755, null], [38755, 38936, null], [38936, 38976, null], [38976, 40024, null], [40024, 41168, null], [41168, 42253, null], [42253, 42285, null], [42285, 42890, null], [42890, 44010, null], [44010, 45254, null], [45254, 46494, null], [46494, 47456, null], [47456, 48392, null], [48392, 49337, null], [49337, 49634, null], [49634, 49961, null], [49961, 50434, null], [50434, 51107, null], [51107, 51411, null], [51411, 51700, null], [51700, 52556, null], [52556, 53152, null], [53152, 53807, null], [53807, 54889, null], [54889, 55133, null], [55133, 56831, null], [56831, 57673, null], [57673, 57945, null], [57945, 59436, null], [59436, 60981, null], [60981, 61348, null], [61348, 61833, null], [61833, 62718, null], [62718, 63368, null], [63368, 63754, null], [63754, 65146, null], [65146, 65602, null], [65602, 66333, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, false], [5000, 66333, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 66333, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 66333, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 66333, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 66333, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 66333, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 66333, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 66333, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 66333, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 66333, null]], "pdf_page_numbers": [[0, 0, 1], [0, 2902, 2], [2902, 5319, 3], [5319, 5778, 4], [5778, 7242, 5], [7242, 8223, 6], [8223, 9255, 7], [9255, 9553, 8], [9553, 11323, 9], [11323, 11686, 10], [11686, 12102, 11], [12102, 12342, 12], [12342, 12753, 13], [12753, 13226, 14], [13226, 13716, 15], [13716, 14703, 16], [14703, 15176, 17], [15176, 15561, 18], [15561, 15978, 19], [15978, 16324, 20], [16324, 16925, 21], [16925, 17739, 22], [17739, 17774, 23], [17774, 18539, 24], [18539, 19667, 25], [19667, 20979, 26], [20979, 22206, 27], [22206, 22676, 28], [22676, 23701, 29], [23701, 24983, 30], [24983, 26011, 31], [26011, 26790, 32], [26790, 28031, 33], [28031, 28160, 34], [28160, 29313, 35], [29313, 29623, 36], [29623, 30779, 37], [30779, 31385, 38], [31385, 31915, 39], [31915, 32373, 40], [32373, 33156, 41], [33156, 34541, 42], [34541, 35625, 43], [35625, 36018, 44], [36018, 37493, 45], [37493, 38755, 46], [38755, 38936, 47], [38936, 38976, 48], [38976, 40024, 49], [40024, 41168, 50], [41168, 42253, 51], [42253, 42285, 52], [42285, 42890, 53], [42890, 44010, 54], [44010, 45254, 55], [45254, 46494, 56], [46494, 47456, 57], [47456, 48392, 58], [48392, 49337, 59], [49337, 49634, 60], [49634, 49961, 61], [49961, 50434, 62], [50434, 51107, 63], [51107, 51411, 64], [51411, 51700, 65], [51700, 52556, 66], [52556, 53152, 67], [53152, 53807, 68], [53807, 54889, 69], [54889, 55133, 70], [55133, 56831, 71], [56831, 57673, 72], [57673, 57945, 73], [57945, 59436, 74], [59436, 60981, 75], [60981, 61348, 76], [61348, 61833, 77], [61833, 62718, 78], [62718, 63368, 79], [63368, 63754, 80], [63754, 65146, 81], [65146, 65602, 82], [65602, 66333, 83]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 66333, 0.01178]]}
olmocr_science_pdfs
2024-12-11
2024-12-11
6b320add379bd3c8525a2cad614e779501121d0e
[REMOVED]
{"Source-Url": "https://inria.hal.science/inria-00289549/file/proofs_dataflow_optimizations.pdf", "len_cl100k_base": 10057, "olmocr-version": "0.1.53", "pdf-total-pages": 17, "total-fallback-pages": 0, "total-input-tokens": 48828, "total-output-tokens": 11502, "length": "2e13", "weborganizer": {"__label__adult": 0.0003886222839355469, "__label__art_design": 0.0002646446228027344, "__label__crime_law": 0.0003254413604736328, "__label__education_jobs": 0.00032138824462890625, "__label__entertainment": 4.655122756958008e-05, "__label__fashion_beauty": 0.0001634359359741211, "__label__finance_business": 0.0002040863037109375, "__label__food_dining": 0.00042366981506347656, "__label__games": 0.0004963874816894531, "__label__hardware": 0.0012865066528320312, "__label__health": 0.0005216598510742188, "__label__history": 0.00020110607147216797, "__label__home_hobbies": 8.660554885864258e-05, "__label__industrial": 0.0004367828369140625, "__label__literature": 0.00020754337310791016, "__label__politics": 0.00028705596923828125, "__label__religion": 0.0005602836608886719, "__label__science_tech": 0.0110626220703125, "__label__social_life": 5.835294723510742e-05, "__label__software": 0.0032825469970703125, "__label__software_dev": 0.97802734375, "__label__sports_fitness": 0.0003559589385986328, "__label__transportation": 0.0006260871887207031, "__label__travel": 0.0002199411392211914}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 45821, 0.01793]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 45821, 0.59888]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 45821, 0.85447]], "google_gemma-3-12b-it_contains_pii": [[0, 1046, false], [1046, 3588, null], [3588, 5926, null], [5926, 8857, null], [8857, 10365, null], [10365, 13879, null], [13879, 17148, null], [17148, 19734, null], [19734, 22190, null], [22190, 25457, null], [25457, 28281, null], [28281, 31226, null], [31226, 34265, null], [34265, 37117, null], [37117, 40237, null], [40237, 43512, null], [43512, 45821, null]], "google_gemma-3-12b-it_is_public_document": [[0, 1046, true], [1046, 3588, null], [3588, 5926, null], [5926, 8857, null], [8857, 10365, null], [10365, 13879, null], [13879, 17148, null], [17148, 19734, null], [19734, 22190, null], [22190, 25457, null], [25457, 28281, null], [28281, 31226, null], [31226, 34265, null], [34265, 37117, null], [37117, 40237, null], [40237, 43512, null], [43512, 45821, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 45821, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 45821, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 45821, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 45821, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 45821, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 45821, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 45821, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 45821, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 45821, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 45821, null]], "pdf_page_numbers": [[0, 1046, 1], [1046, 3588, 2], [3588, 5926, 3], [5926, 8857, 4], [8857, 10365, 5], [10365, 13879, 6], [13879, 17148, 7], [17148, 19734, 8], [19734, 22190, 9], [22190, 25457, 10], [25457, 28281, 11], [28281, 31226, 12], [31226, 34265, 13], [34265, 37117, 14], [37117, 40237, 15], [40237, 43512, 16], [43512, 45821, 17]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 45821, 0.0]]}
olmocr_science_pdfs
2024-12-10
2024-12-10
1b543b3e5b6588e940a973eb208bc6d5397cea91
[REMOVED]
{"len_cl100k_base": 16369, "olmocr-version": "0.1.53", "pdf-total-pages": 25, "total-fallback-pages": 0, "total-input-tokens": 75620, "total-output-tokens": 20493, "length": "2e13", "weborganizer": {"__label__adult": 0.0004122257232666016, "__label__art_design": 0.00039267539978027344, "__label__crime_law": 0.0003478527069091797, "__label__education_jobs": 0.0006351470947265625, "__label__entertainment": 9.077787399291992e-05, "__label__fashion_beauty": 0.00018405914306640625, "__label__finance_business": 0.0001697540283203125, "__label__food_dining": 0.00045943260192871094, "__label__games": 0.0007252693176269531, "__label__hardware": 0.0007443428039550781, "__label__health": 0.0005679130554199219, "__label__history": 0.0002903938293457031, "__label__home_hobbies": 9.739398956298828e-05, "__label__industrial": 0.0003979206085205078, "__label__literature": 0.0004863739013671875, "__label__politics": 0.0003273487091064453, "__label__religion": 0.0006418228149414062, "__label__science_tech": 0.0225982666015625, "__label__social_life": 9.709596633911131e-05, "__label__software": 0.00423431396484375, "__label__software_dev": 0.96484375, "__label__sports_fitness": 0.0003542900085449219, "__label__transportation": 0.0006771087646484375, "__label__travel": 0.00020956993103027344}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 74772, 0.01515]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 74772, 0.3827]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 74772, 0.83017]], "google_gemma-3-12b-it_contains_pii": [[0, 2247, false], [2247, 6220, null], [6220, 9285, null], [9285, 13185, null], [13185, 17612, null], [17612, 19722, null], [19722, 23195, null], [23195, 26549, null], [26549, 30237, null], [30237, 32734, null], [32734, 36238, null], [36238, 38571, null], [38571, 42132, null], [42132, 44265, null], [44265, 47649, null], [47649, 49967, null], [49967, 52711, null], [52711, 54007, null], [54007, 57730, null], [57730, 61730, null], [61730, 65581, null], [65581, 67271, null], [67271, 69976, null], [69976, 74772, null], [74772, 74772, null]], "google_gemma-3-12b-it_is_public_document": [[0, 2247, true], [2247, 6220, null], [6220, 9285, null], [9285, 13185, null], [13185, 17612, null], [17612, 19722, null], [19722, 23195, null], [23195, 26549, null], [26549, 30237, null], [30237, 32734, null], [32734, 36238, null], [36238, 38571, null], [38571, 42132, null], [42132, 44265, null], [44265, 47649, null], [47649, 49967, null], [49967, 52711, null], [52711, 54007, null], [54007, 57730, null], [57730, 61730, null], [61730, 65581, null], [65581, 67271, null], [67271, 69976, null], [69976, 74772, null], [74772, 74772, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 74772, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 74772, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 74772, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 74772, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 74772, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 74772, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 74772, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 74772, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 74772, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 74772, null]], "pdf_page_numbers": [[0, 2247, 1], [2247, 6220, 2], [6220, 9285, 3], [9285, 13185, 4], [13185, 17612, 5], [17612, 19722, 6], [19722, 23195, 7], [23195, 26549, 8], [26549, 30237, 9], [30237, 32734, 10], [32734, 36238, 11], [36238, 38571, 12], [38571, 42132, 13], [42132, 44265, 14], [44265, 47649, 15], [47649, 49967, 16], [49967, 52711, 17], [52711, 54007, 18], [54007, 57730, 19], [57730, 61730, 20], [61730, 65581, 21], [65581, 67271, 22], [67271, 69976, 23], [69976, 74772, 24], [74772, 74772, 25]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 74772, 0.0]]}
olmocr_science_pdfs
2024-12-07
2024-12-07
d929a33b8fbaed7f06d4ec4a2189a8949b7def02
Fault-tolerant Scheduling of Fine-grained Tasks in Grid Environments Gosia Wrzesińska, Rob V. van Nieuwoort, Jason Maassen, Thilo Kielmann, Henri E. Bal Dept. of Computer Science, Vrije Universiteit, Amsterdam, The Netherlands {gosia, rob, jason, kielmann, bal}@cs.vu.nl http://www.cs.vu.nl/ibis Abstract Divide-and-conquer is a well-suited programming paradigm for parallel Grid applications. Our Satin system efficiently schedules the fine-grained tasks of a divide-and-conquer application across multiple clusters in a grid. To accommodate long-running applications, we present a fault-tolerance mechanism for Satin that has negligible overhead during normal execution, while minimizing the amount of redundant work done after a crash of one or more nodes. We study the impact of our fault-tolerance mechanism on application efficiency, both on the Dutch DAS-2 system and using the European testbed of the EC-funded project GridLab. 1 Introduction Parallel applications are being executed on increasingly large and complex systems like computational grids [1, 4, 24]. In large-scale grids, the probability of a failure is much greater than in traditional parallel systems [15]. Therefore, fault tolerance is becoming a crucial area in grid computing. In this paper, we propose a fault-tolerance mechanism for divide-and-conquer applications. Divide-and-conquer parallelism is a popular and effective paradigm for writing parallel grid applications [5, 24]. Exploiting the structure of the divide-and-conquer applications allowed us to create a mechanism that has smaller overhead and is simpler to implement than more general techniques such as checkpointing. Divide-and-conquer programs are a generalization of the popular master/worker paradigm. They operate by recursively dividing a problem into subproblems, until they become trivial to solve, and then combining their results. Such programs can be run efficiently in parallel [8]. Also, because of their hierarchical structure, they can be run efficiently on hierarchical grids [24]. An example of a divide-and-conquer system designed for grids is Satin [22], which we use as an experimental platform for our research. Satin is implemented on top of our Java-based grid programming platform Ibis [12, 23]. In Satin, each processor maintains a work queue containing jobs (i.e., subproblems) that still need to be executed. The system load is balanced by a special, grid-aware version of work stealing that overlaps local steals with remote ones [22]. Satin is implemented entirely in Java and can run efficiently in distributed, heterogeneous, wide-area environments [24], making it an excellent platform for parallel grid applications. The divide-and-conquer paradigm has several advantages when implementing fault tolerance. There is no notion of global state in a divide-and-conquer application: function execution does not have side-effects and the result of a function depends only on its input parameters. Function execution will always produce the same outputs if given the same inputs, a property known as referential transparency [11]. So, the work lost in a crash of a processor can be redone at any time during execution of the application. Therefore, it is possible to create a fault-tolerance mechanism based on redoing the work lost by processor crashes. Such a mechanism can have very low overhead, as no synchronization between processes is needed and no data needs to be stored on stable storage. Several such techniques have been proposed [5, 7, 14, 18]. However, the common problem of these techniques is redundant computation – work done by live (i.e., still working) processors that has to be discarded and redone as a result of crashes. The main contribution of this paper is a novel fault-tolerance mechanism for divide-and-conquer applications that avoids redundant computations by storing partial results in a global (replicated) table. These results can later be reused, thereby minimizing the amount of work lost as a result of a crash. The execution time overhead of our mechanism is close to zero. Our mechanism can handle crashes of multiple processors or entire clusters at the same time. It can also handle crashes of the root node that initially started the parallel computation. We have evaluated the performance of our mechanism on the Dutch wide-area Distributed ASCI Supercomputer 2 (DAS-2), and on the heterogeneous testbed of the European GridLab [2] project. In this experiment, we ran a fault-tolerant parallel application simultaneously on five different parallel machines distributed over Europe. The rest of this paper is organized as follows: in Section 2, we discuss related work. In Section 3, we present our fault-tolerance mechanism, discuss its correctness and describe its implementation. We present the results of the performance evaluation of our system in Section 4. We conclude in Section 5. 2 Related work The most popular fault-tolerance mechanism is rollback recovery, which comes in two flavours: checkpoint-based and log-based [13]. With checkpointing, the state of the application is periodically saved on stable storage, usually a hard disk. After a crash, the application is restarted from the last checkpoint rather than from the beginning [3]. Checkpointing is used in grid computing by systems such as Condor [19] and Cactus [1]. Log-based techniques combine checkpointing with logging of nondeterministic events [13]. Message logging is a special case of log-based recovery scheme in which all nondeterministic events are modeled as a message receipt. During recovery, the logged events are replayed to the recovering process in their original order. Log-based recovery enables the application to recover beyond its most recent checkpoint and therefore is especially attractive to applications frequently communicating with outside world which cannot be rolled back. One of the disadvantages of rollback recovery is its execution time overhead, even if there are no crashes. For checkpointing, the main source of this overhead is writing the state of the process to stable storage. This overhead might be reduced by using concurrent checkpointing [20] and incremental checkpointing [16]. With log-based techniques, copying messages increase communication latency. For systems that implement stable storage by a filesystem available through the network, communication bandwidth required for the application doubles, as each message has to be sent also to the stable storage. Another problem of most rollback-recovery schemes is the complexity of the crash recovery procedure, especially in dynamic and heterogeneous grid environments where rescheduling the job and retrieving and transferring the checkpoint data between nodes is non-trivial. The main advantage of checkpointing is that it is a very general technique which can be applied to any type of parallel applications. The approach we present in this paper is less general, it only applies to divide-and-conquer and master-worker applications, but it has zero overhead when no crashes occur. Several fault-tolerance mechanisms have been designed specifically for divide-and-conquer applications. One example is used in DIB [14], which, like Satin, uses divide-and-conquer parallelism and work stealing. In DIB, when a processor runs out of work, it issues a steal request, but in the mean time it starts redoing (unfin- ished) work that was stolen from it earlier. This approach is robust since crashes can be handled even without being detected. However, this strategy can lead to much redundant computation. One example is the ancestral-chain problem: if P1 gives work to P2, which in turn gives some of it to P3, and P3 crashes, both P1 and P2 will redo the stolen work, so the work stolen by P3 will be redone twice. Another problem concerns orphan jobs, which are stolen from a crashed processor. Such a job is computed, but its result cannot be returned to the job's owner since the owner has crashed. The result must therefore be discarded. The same job will be done again while redoing the work given to the crashed processor. Therefore, like in the case of ancestral chains, part of the work will be done twice by live processors. Satin's fault tolerance algorithm is designed to solve both aforementioned problems. Another approach based on redoing work was proposed by Lin and Keller [18]. When a crash of a processor is detected, the jobs stolen by it are redone by the owners of those jobs, i.e., the processors from whom the jobs were stolen. Orphan jobs are handled as follows. Each job contains not only the identifier of its parent processor (from which the job was stolen), but also the identifier of its grandparent processor (from which the parent processor stole the ancestor of our job). When the parent processor crashes, the orphan job is passed after completion to the grandparent processor which in turn passes it to the processor which is redoing the work lost in the crash. The result of an orphan job can thus be reused. However, if both parent and grandparent processor crash, the orphan job cannot be reused anymore. More levels could be used, but that requires storing more data (identifiers). Also, the result of an orphan job is passed to the grandparent processor only after the execution of this job is completed, which may occur a long time after the crash. By that time, some other processor may have already started or even completed redoing the same job. Our experiments show that such situations occur often. Therefore, although this mechanism tries to reuse orphan jobs, the amount of redundant work is still high. The algorithm we propose does not suffer from this problem, because it notifies the grandparent of the orphan job immediately after the crash of the parent. The likely best-known family of divide-and-conquer systems is the C-based Cilk [8] (for shared-memory machines), and its extensions CilkNOW [7] (for networks of workstations), and Atlas [5]. The latter has been designed with heterogeneity and fault tolerance in mind, but aims only at moderate performance. Its fault-tolerance mechanism is also based on redoing the work. The problem of orphan jobs is not addressed in Atlas. Fault-tolerance mechanisms have also been proposed for other, similar programming models, such as master-worker. In the master-worker paradigm, all jobs are spawned by a single process, called the master, and distributed among other processes, called workers. The master-worker model can be viewed as a special case of the divide-and-conquer programming style (it is thus less expressive than divide-and-conquer). Therefore, similarly to the divide-and-conquer model, fault tolerance in master-worker systems can be provided by redoing the work lost in a crash. Since only the master processor spawns work and collects results, there is no orphan jobs problem, as long as the master stays alive. Crashes of the master need to be handled separately. An example of a system that adopts this fault-tolerance approach is MW [17]. MW is a programming framework which provides an API for implementing grid-enabled master-worker applications. It also defines an Infrastructure Programming Interface (IPI) such that it can be ported to use various grid software toolkits. Charlotte [6] introduces a fault-tolerance mechanism called eager scheduling. It reschedules a task to idle processors as long as the task's result has not been returned. Crashes can be handled without the need of detecting them. Assigning a single task to multiple processors also guarantees that a slow processor will not slow down the progress of the whole application. Satin tries to avoid this duplicate work altogether. 0. if (the master crashed) elect a new master 1. forall (job stolen by a crashed processor) put job back in the work queue 2. forall (descendant of any job stolen from a crashed processor) if (descendant is finished) store the descendant’s result in the global result table else abort the descendant 3. if (the old master crashed and I am the new master) restart the application Figure 1: The crash recovery procedure for a live processor 3 Fault tolerance using a global result table Like other fault-tolerance algorithms for divide-and-conquer applications, our approach is based on redoing work lost in crashes. The novelty of our approach, however, is the elimination of a common problem of other solutions – redundant computation, that is, losing and redoing work done by a live processor as a result of a crash of another processor. This happens in case of or- phan jobs (jobs stolen from crashed processors). With the existing algorithms discussed in Sec- tion 2, the processor which has finished working on an orphan job must discard the result of this job, because it does not know where to return that result to. To eliminate the problem of orphan jobs, we use a global result table – a concept similar to a transposition table [10] used in game solving environments or the table used in tabled execution of logic programs [21]. It is a table accessible to all processors in which results of jobs can be stored. We use this table during the crash recovery procedure for storing the (partial) results of orphan jobs so that other processors can reuse those results. Jobs stored in the table are identi- fied by their parameters. The global result table is replicated on all pro- cessors. Lookups in the table are local opera- tions, and are therefore cheap. The replicas of the table do not have to be strongly consistent (if a processor does not find a job, it can always recompute it), so updates of the table are propa- gated to other processors asynchronously. Also, updates are infrequent, since we do not store all jobs in the global result table, but only orphan jobs in the system; these are less than 1% of all jobs. Finally, for many applications, the amount of data that needs to be broadcast for each job (the parameters and the result) is small – a few bytes. Therefore, the overhead by using the ta- ble is small. We will show this experimentally in Section 4.1. We assume a fail-stop failure model, that is, if a processor fails, it will no longer transmit any valid messages. If a processor comes back after a crash, it receives a new processor identifier and is treated as a new processor. We also assume reliable communication. The crashes of proces- sors are detected by the communication layer. The crashes do not have to be detected immedi- ately after they occur, but they must be detected eventually. 3.1 The algorithm To be able to redo jobs lost in crashes, each pro- cessor maintains a list of jobs stolen from it. For each job, the processor ID of the thief is stored along with all the information needed to restart the job. When a crash of one or more processors is detected, each live processor executes a crash recovery procedure summarized in Figure 1. In step 1 of this procedure, the list of stolen jobs is searched for jobs stolen by crashed proces- sors. Such jobs are put back in the work queues of their owners, so they will eventually be recom- puted. Each job reinserted into a work queue after a crash is marked as redone. The descen- dants of a redone job (i.e., children, grandchil- dren, etc.) are also marked as redone when they are spawned. Before a processor starts comput- ing a redone job, it first performs a lookup in the global result table, because the result of this job might already be stored there, as explained below. In step 2 of Figure 1, the results of orphan jobs are stored in the global result table, so that they can be found and reused by other processors redoing the jobs’ parents. To be more specific, instead of waiting until an orphan job is finished and then storing this job’s result, we store the results of those parts (subjobs) of the orphan jobs that are already finished at the moment of the crash. We adopted this approach, because computing the whole orphan subtree might take much time and in the meantime some other processor may start working on the same subtree. In that case, the result stored in the table will not be used and the orphan job will be computed twice. Our experiments have shown that this situation is very common. If the master crashes (i.e., the processor which spawned the job which is the root of the job tree), the remaining live processors elect a new master (step 0 in Figure 1). Afterwards, the crash recovery procedure proceeds normally. At the end of the procedure, the new master restarts the application (step 3 in Figure 1). The information needed to restart the application is replicated on all processors. The new run of the application will reuse the results stored in the global result table during the crash recovery procedure. As an example, consider the computation tree shown in Figure 2 (a). The regions delimited by plain lines show how the computation is divided among the processors. When processor 2 crashes all the jobs computed by it are lost (jobs 2, 5, 10, 11, 16, 17, 22, 23). When processor 1 detects the crash, it searches its list of stolen jobs and discovers that job 2 was stolen by a crashed processor. Processor 1 reinserts job 2 into its work queue. Job 4 is an orphan (its parent, job 2, was computed on a crashed machine), so the already completed jobs 9 and 15 are stored in the global result table. Next, the whole orphan subtree (jobs 4, 8, 9, 14, 15, 20 and 21 in Figure 2 (a)) is removed from the system (aborted). After the crash recovery procedure, the computation tree will look as in Figure 2 (b). We discuss the correctness of our algorithm in the appendix. It may seem that by aborting unfinished jobs, we lose much work. However, as we already explained above, computing the whole orphan subtree and only then storing it in the table would lead to much bigger loss of work, because in the meantime some other processor is likely to start working on the same subtree. In that case the result in the table will not be used and the whole subtree will be computed twice. Besides, the amount of work we actually lose by aborting is small. Most of the unfinished jobs in the system are those which are waiting for results of their subjobs (jobs 4, 8, 14 in Figure 2 (a)). Those jobs are internal nodes of the computation tree. The bulk of the computation, however, is typically done in the leaf nodes. Other aborted jobs are those which were spawned but no processor has started working on them yet (job 20 in Figure 2 (a)). In that case, only a small amount of work, for spawning jobs, is wasted within the runtime system. No application-level work is lost. Additionally, during normal execution, when a result of a stolen job is returned to the job’s owner, it is also stored in the global table. This approach prevents that a job done by one processor is lost in a crash of another processor. This can happen when the result of a job is sent back to a processor which will crash afterwards. Our approach adds only a small performance penalty, since the cost of storing a job in the replicated table is not much higher than the cost of sending it to another processor. The former needs sending one asynchronous broadcast message while the latter needs one asynchronous point-to-point message. Moreover, only a small fraction of the jobs in the system are stolen and sent to another processor. As shown in [22], with typical Satin applications, only one out of 1000–10000 jobs actually gets stolen. When a processor crashes, we do not lose any work done by any other, live processor, except for the jobs in progress, which need to be aborted. But, as explained above, this causes little work to be lost. In Section 4.2, we will also give an experimental evaluation of this claim. Note that the use of the global result table does not influence the correctness of the algo- algorithm. If the result of a job is not found in the table, the job can always be recomputed. The table only was introduced to improve the performance of the system. Therefore, broadcasting does not need to be reliable. Scalable broadcasting algorithms, such as gossiping, can be used. Also, if the size of the table is too large, part of the entries might be safely dropped. As future work, we plan to extend our algorithm with support for applications with large parameters and results. To avoid broadcasting large amounts of data, the results will be stored locally and only the location from which they can be retrieved is broadcast. Jobs with large parameters are then identified by their position in the job tree rather than their parameters. 3.2 Implementation We have incorporated our fault-tolerance mechanism in Satin, which is a Java-based divide-and-conquer system. Satin is implemented on top of the Ibis [23] communication library. The core of Ibis is implemented in pure Java, without using any native code. The Satin runtime system and our fault-tolerance extension also are written entirely in Java. The resulting system therefore is highly portable (due to Java’s “write once, run anywhere” property) allowing the software to run unmodified on a heterogeneous grid. The global result table is implemented as a replicated hash table. Keys in this table are records containing the parameters of the job. The hash of such a record is computed as a sum of hashes of all its fields. Hashes of array parameters are computed as sums of hashes of their elements. After an update, an asynchronous update message is broadcast to all replicas of the table. Lookup is a local operation. 4 Evaluation In this section, we will evaluate our mechanism. We show the following properties of our fault-tolerance mechanism and its implementation in the Satin system: 1. Our fault-tolerance mechanism adds very little overhead to Satin in the absence of crashes; 2. The overhead incurred by lookups in the global result table is very small; 3. With our scheme, little redundant computation is done after a crash; 4. Our scheme outperforms the traditional approach, which does not use a global result table; 5. The scheme is suitable for divide-and-conquer applications that run in a real grid environment. We show properties 1 and 2 by doing experiments on a single DAS-2 cluster (see Section 4.1). For properties 3 and 4, we do experiments on the wide-area DAS-2 system (see Section 4.2). The DAS-2 system consists of five clusters located at five Dutch universities. Each node contains a 1 GHz Pentium III processor and runs RedHat Linux 7.2. The nodes are connected both by 100 Mbit Ethernet and by Myrinet [9]. In our experiments we used Ethernet. For the experiments on the DAS-2 system, we used the IBM JIT 1.4. The DAS-2 system is used because its homogeneous structure makes it suitable for meaningful performance evaluations. For property 5, we use the testbed of the European GridLab [2] project (see Section 4.3). For the experiments on the GridLab testbed, we used whichever Java implementation was preinstalled on the sites. 4.1 Overhead on normal execution We first assess the impact of our fault-tolerance mechanism on application performance in the absence of crashes. Therefore, we ran five application kernels with three versions of the Satin runtime system each: (1) the plain Satin system, without our fault-tolerance mechanism, (2) fault-tolerant Satin, and (3) a modified version of fault-tolerant Satin in which lookups in the global result table are performed for all jobs. Comparing (1) and (2) indicates the bookkeeping overhead for the additional data structures of our fault-tolerance mechanism. As there are no crashes, version (2) will not perform any table lookups. Comparing (2) and (3) indicates the overhead of table lookups. The performance of (3) thus gives a lower bound on application performance caused by our fault-tolerance mechanism for those processors of a faulty system that remain alive during an application run. Figure 3 shows the speedups achieved by our application kernels on 48 processors in all three cases (plain Satin, fault-tolerant Satin, fault-tolerant Satin with lookups for all jobs). The speedups were calculated relative to the sequential Java applications that were run without Satin. For all applications we tested, there is no significant difference in speedup between plain Satin, fault-tolerant Satin and fault-tolerant Satin with lookups for all jobs. We conclude that, in the absence of crashes, our fault-tolerance mechanism incurs only negligible overhead on application performance. 4.2 Efficiency in case of crashes We will now assess the efficiency of our fault-tolerance mechanism by comparing settings with and without crashes, and with and without using a global result table. For these experiments we use four DAS-2 clusters (Amsterdam, Delft, Leiden, Utrecht), with 16 CPUs each. In preliminary experiments we found that crashes of individual nodes and of whole clusters show similar effects, proportional to the number of crashed nodes. In the following, we will only discuss results with crashes of all nodes in a cluster, as these are more pronounced. Such a crash of a whole cluster represents the situation in which the cluster becomes unreachable due to network problems. From our application kernels we have chosen the knapsack program as it is the most sensitive to crashes of all applications in our preliminary experiments. Figure 4 shows the results of our assessment. Part (a), on the left side, compares our fault-tolerance algorithm with the traditional ap- proach that does not use a global result table. Traditionally, orphan jobs are simply discarded; work lost in a crash (including discarded orphan jobs) has to be recomputed. This approach is adopted by most other fault-tolerant divide-and-conquer systems. We first ran the knapsack application on four DAS-2 clusters, without any crashes. The average run time was 125.2 seconds. The left pair of bars in Figure 4(a) shows the application runtimes when one of the four clusters will crash after 50% of the four-cluster runtime, i.e., after 62.6 seconds. Using our global result table, the application terminated after 159.4 seconds, while not using a result table took 217.9 seconds. Likewise, with two of the four clusters crashing (the right pair of bars), the application terminated after 214.6 seconds with, and after 350.7 seconds without a result table. Clearly, our global result table significantly improves the application runtime in case of crashes. Figure 4(b), on the right side, shows an assessment of the overhead while handling crashes, caused by redundant computations due to aborting and restarting unfinished parts of orphan jobs. For this experiment we modified slightly the Satin runtime system. With our modified runtime system, we assess the worst case of a processor crash, which is the situation in which none of the results computed by the crashed processor will be propagated to live processors. In our modified system, the to-be-crashed processors will be tagged during application startup. Our runtime system simply discards their results; these results are neither forwarded to other processors, nor written into the result table. The tagged processors are still allowed to steal jobs from other processors and to act as victims of steal requests by other processors. The latter case will generate orphan jobs when the crash occurs. As with Figure 4(a), we trigger a crash of all tagged processors after 62.6 seconds, which is 50% of a successful four-cluster run. The left pair of bars in Figure 4(b) compares the runtime of three clusters without crashes (no clusters were tagged as to-be-crashed) with the runtime of four clusters, where after 62.6 seconds one cluster will crash. In both cases, the three live clusters have to compute all jobs of the application. The runtime difference, however, quantifies the amount of additional work, mostly redundant computations, that has to be performed to recover from the crash. As the figure shows, this difference is marginal, e.g., less than 2 seconds. The right pair of bars similarly compares two clusters, with four clusters of which two clusters will crash after 62.6 seconds. Again, the runtime difference is marginal, e.g., less than 3 seconds. Comparing the bars between parts (a) and (b) of Figure 4 gives two additional insights to the behaviour of Satin in case of crashes. The first observation is that, in the beginning of a run, only few jobs actually get completed with all their children, such that their results can already be returned to other clusters where the jobs had been stolen from. Without crashes, three clusters terminate after 162.3 seconds while four clusters of which one cluster crashes terminate after 159.4 seconds. The marginal gain of 3 seconds is the contribution of the fourth cluster before it crashed. With two clusters crashing, the situation is similar. Two clusters, without crashes, terminate after 240.6 seconds; four clusters with two of them crashing terminate after 214.6 seconds. Here, the contribution of the two crashed clusters is 26 seconds. The second observation concerns the effectiveness of our global result table. We compare the case of two out of four clusters crashing, without using a result table, (350.7 seconds) with two clusters running without crashes (240.6 seconds). Obviously, without a global result table, handling the crash is more expensive than starting with fewer clusters. This is because orphan jobs are not aborted but computed until they complete, but the results must be discarded and recomputed. However, with our result table, starting with four clusters is beneficial, as the runtime improves from 240.6 seconds to 214.6 seconds. Comparing three clusters with four, out of which one cluster crashes, shows analogous results (comparing 217.9 with 162.3 and 159.4 seconds). 4.3 Grid experiment To evaluate our divide-and-conquer system in a real grid environment, we carried out an experiment on the testbed of the European GridLab project. We used 64 processors in total, using 5 machines located in 3 countries across Europe. Figure 5 shows a map of Europe, annotated with the machine locations. The machines happened to run different flavors of Linux; we used the JVMs installed on the individual sites. The machines are connected by the Internet. The links show typical wide-area behavior, as the physical distance between the sites is large. We used a real-world application for this test, a satisfiability solver (a classical DPLL SAT solver [26]) implemented with Satin, computing a FPGA design verification problem. On a single node of the Amsterdam DAS-2 cluster, the solver runs for 102,045 seconds, about 28 hours, Table 1: Machines on the GridLab testbed <table> <thead> <tr> <th>location</th> <th>architecture</th> <th>operating system</th> <th>JVM</th> <th>CPUs / node</th> <th>total CPUs</th> </tr> </thead> <tbody> <tr> <td>Vrije Universiteit</td> <td>Intel Pentium-III</td> <td>Red Hat</td> <td>IBM</td> <td>2</td> <td>18</td> </tr> <tr> <td>Amsterdam</td> <td>1 GHz</td> <td>Linux 7.2</td> <td>1.40</td> <td>2</td> <td></td> </tr> <tr> <td>The Netherlands</td> <td></td> <td>kernel 2.4.18</td> <td></td> <td></td> <td></td> </tr> <tr> <td>Konrad-Zuse-Zentrum für</td> <td>Intel XEON 2.4 GHz</td> <td>Red Hat</td> <td>SUN</td> <td>2</td> <td>2</td> </tr> <tr> <td>Informationstechnik Berlin,</td> <td>HyperThreading</td> <td>Linux 9</td> <td>1.42</td> <td>2</td> <td></td> </tr> <tr> <td>Germany</td> <td></td> <td>kernel 2.4.20</td> <td></td> <td></td> <td></td> </tr> <tr> <td>Masaryk University</td> <td>Intel XEON 2.4 GHz</td> <td>Debian</td> <td>SUN</td> <td>2</td> <td>4</td> </tr> <tr> <td>Brno</td> <td>HyperThreading</td> <td>Linux 3.0</td> <td>1.42</td> <td>2</td> <td></td> </tr> <tr> <td>Czech Republic</td> <td></td> <td>kernel 2.4.27</td> <td></td> <td></td> <td></td> </tr> <tr> <td>Technische Universität Delft</td> <td>Intel Pentium-III</td> <td>Red Hat</td> <td>IBM</td> <td>2</td> <td>16</td> </tr> <tr> <td>The Netherlands</td> <td>1 GHz</td> <td>Linux 7.2</td> <td>1.40</td> <td>2</td> <td></td> </tr> <tr> <td>PC</td> <td>Intel Pentium-III</td> <td>Red Hat</td> <td>IBM</td> <td>2</td> <td></td> </tr> <tr> <td>University of Paderborn</td> <td>850 MHz</td> <td>Linux 7.2</td> <td>1.4.1</td> <td>2</td> <td>24</td> </tr> <tr> <td>Paderborn, Germany</td> <td></td> <td>kernel 2.4.7</td> <td></td> <td></td> <td></td> </tr> </tbody> </table> in total spawning about one billion jobs. Figure 6 summarizes the results of our experiment. Using all 5 clusters together, the SAT solver completed after 2494 seconds; using only four clusters (without the Delft cluster), the runtime was 3229 seconds. Then, we deployed our fault-tolerance mechanism: after 50% of the runtime with five clusters (1247 seconds), we crashed the nodes of the Delft cluster. In this case, the SAT solver terminated after 3082 seconds which is consistent with our tests presented in Section 4.2. Finally, we used our system to dynamically increase the number of processors at runtime, namely by starting with four clusters, and adding the Delft cluster in the middle of the run, again after 1247 seconds. In this constellation, the SAT solver terminated after 2940 seconds. In both cases, with the crash and with the added cluster, the total processing power is the same. Still, with the added cluster the runtime is 5% lower than the runtime after the crash. This difference can be attributed to the amount of redundant work performed while recovering from the crash. We can conclude that Satin and its fault-tolerance mechanism can efficiently execute realistic applications in Grid environments while handling changing numbers of available processors. 5 Conclusions In this paper, we have presented a fault-tolerance mechanism for divide-and-conquer systems. Because our mechanism exploits the properties of the divide-and-conquer paradigm, its overhead during the normal (i.e., crash-free) execution is very small. For all applications we have tested, there is no significant difference in speedup between the application run on the plain Satin system and its fault-tolerant version. We propose a novel approach to salvaging orphan jobs – a global result table. Using this approach we minimized the amount of redundant computation which is a problem of many other fault-tolerance mechanisms for divide-and-conquer systems. To evaluate our approach, we carried out tests on the Dutch wide-area DAS-2 system and on the GridLab testbed. Our fault-tolerant Satin system has the potential to become a viable platform for Grid applications. To approach this goal, we are currently working on two extensions. One is an alternative result table mechanism for jobs with large pa- rameter or result variables. The other extension will allow us to use our mechanism for supporting malleability and migration of long-running Satin applications [25]. Acknowledgments This work was carried out in the context of the Virtual Laboratory for e-Science project (www.vl-e.nl). This project is supported by a BSIK grant from the Dutch Ministry of Education, Culture and Science (OC&W) and is part of the ICT innovation program of the Ministry of Economic Affairs (EZ). Further support came from the European Commission, grant IST-2001-32133 (GridLab), and the Netherlands Organization for Scientific Research (NWO) grant 612.060.214 (Ibis: a Java-based grid programming environment). We would also like to thank Rutger Hofman, Ceriel Jacobs and Kees Verstoep for their useful comments on this paper. Kees van Reeuwijk wrote the SAT solver and Matthias Hovestadt helped a lot with accessing the machines at Paderborn University. References ence on Parallel Processing, pages 405–412, University Park, PA, USA, August 1986. ence on Automated Deduction, pages 295–313, Copenhagen, July 2002. ACM. Appendix: Correctness of the algorithm A crash recovery algorithm is correct if it brings the system back to an error-free state from which the system can continue to execute. In general, finding such a state is difficult, because the local states of each of the processors must be consistent. In a divide-and-conquer application, however, achieving such a state is easier since the computations performed by each of the processors are to a great extent independent of each other. Jobs can be evaluated independently of each other (due to referential transparency), except that a child must return the result to its parent before the parent can be completed. Therefore, dependencies between processors appear only when one processor steals a job from another processor – the result must be returned before the stolen job's parent can be finished. A crash of a processor thus has a direct impact only on the processors from which the crashed processor stole a job or which stole a job from the crashed processor. To analyze this impact let us assume that processor T (the thief) steals a job from processor V (the victim). A state transition diagram of this process is shown in Figure 7. Let us analyze all possible cases, assuming that neither of the processors is the master. 1. In states 1 and 8 a crash of one processor obviously does not have any influence on the other processor; 2. If V crashes while the job is being stolen from it (states 2 and 3), T cancels the steal request as soon as it detects the crash of V and sends a steal request to another processor; 3. If T crashes while stealing the job, the behavior of V depends on when it detects the crash. If V detects the crash before sending the reply (state 2 or 3), it discards the steal Figure 7: The state transition diagram for stealing, computing and returning the result of a job request. If V detects the crash after it sent the reply (state 4), it treats the job as stolen and acts as in case 4; 4. If T crashes while working on the stolen job (states 5 and 6), V will not receive the result and will not be able to finish the stolen job’s parent. Consequently, all other ancestors of the job (including the root) will not be completed. To solve this problem, V redoes the stolen job (and all its subjobs) after detecting the crash; 5. If V crashes after T stole the job from it (states 4, 5 and 6), the job becomes an orphan. T aborts the job and all its descendants to avoid unnecessary work. The job will be redone while redoing jobs stored on the crashed V (by processors from which V was stealing). The finished parts of the job are stored in the global result table; 6. If T crashes before the result is received (state 7), V acts as in case 4 and redoes the job. However, since the result is sent over the network, it was put in the global result table by T. The result can thus be reused while recomputing the job; 7. If V crashes before it receives the result (state 7), T ignores it. As in case 6, the result will be stored in the global result table and used while redoing the job (by the processor from which an ancestor of this job was stolen by V). In all cases, live processors will be able to continue their work. Their jobs that have become orphans will be aborted. All other jobs will be completed and their results will eventually be returned to the nodes from which the jobs had been stolen. In particular, the master will be able to successfully compute all its jobs including the root job which marks a successful end of the computation. A special case is the crash of the master. The new master will restart the whole computation.
{"Source-Url": "http://www.cs.vu.nl/~kielmann/papers/ijhpca.pdf", "len_cl100k_base": 8744, "olmocr-version": "0.1.53", "pdf-total-pages": 14, "total-fallback-pages": 0, "total-input-tokens": 91272, "total-output-tokens": 10923, "length": "2e13", "weborganizer": {"__label__adult": 0.00034689903259277344, "__label__art_design": 0.00036787986755371094, "__label__crime_law": 0.0003962516784667969, "__label__education_jobs": 0.0009603500366210938, "__label__entertainment": 0.00013184547424316406, "__label__fashion_beauty": 0.00018513202667236328, "__label__finance_business": 0.0003902912139892578, "__label__food_dining": 0.00037932395935058594, "__label__games": 0.0010528564453125, "__label__hardware": 0.00213623046875, "__label__health": 0.0005908012390136719, "__label__history": 0.00045180320739746094, "__label__home_hobbies": 0.00013184547424316406, "__label__industrial": 0.000759124755859375, "__label__literature": 0.00031757354736328125, "__label__politics": 0.0003600120544433594, "__label__religion": 0.0006046295166015625, "__label__science_tech": 0.1923828125, "__label__social_life": 0.00010472536087036131, "__label__software": 0.0146026611328125, "__label__software_dev": 0.78173828125, "__label__sports_fitness": 0.0003292560577392578, "__label__transportation": 0.0008401870727539062, "__label__travel": 0.0002428293228149414}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 44908, 0.02102]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 44908, 0.21944]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 44908, 0.91757]], "google_gemma-3-12b-it_contains_pii": [[0, 3220, false], [3220, 7417, null], [7417, 11730, null], [11730, 15560, null], [15560, 19910, null], [19910, 21878, null], [21878, 25580, null], [25580, 28285, null], [28285, 30773, null], [30773, 34885, null], [34885, 36494, null], [36494, 39575, null], [39575, 43031, null], [43031, 44908, null]], "google_gemma-3-12b-it_is_public_document": [[0, 3220, true], [3220, 7417, null], [7417, 11730, null], [11730, 15560, null], [15560, 19910, null], [19910, 21878, null], [21878, 25580, null], [25580, 28285, null], [28285, 30773, null], [30773, 34885, null], [34885, 36494, null], [36494, 39575, null], [39575, 43031, null], [43031, 44908, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 44908, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 44908, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 44908, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 44908, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 44908, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 44908, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 44908, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 44908, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 44908, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 44908, null]], "pdf_page_numbers": [[0, 3220, 1], [3220, 7417, 2], [7417, 11730, 3], [11730, 15560, 4], [15560, 19910, 5], [19910, 21878, 6], [21878, 25580, 7], [25580, 28285, 8], [28285, 30773, 9], [30773, 34885, 10], [34885, 36494, 11], [36494, 39575, 12], [39575, 43031, 13], [43031, 44908, 14]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 44908, 0.07843]]}
olmocr_science_pdfs
2024-12-07
2024-12-07
edf17a9c512b6eb41f81f876fa22b33d9c168f3a
Building an Ontology for the Metamodel ISO/IEC24744 using MDA Process Mehdi Mohamed Hamri EEIDIS Laboratory, Computer science department, Djillali Liabes University, Algeria Email: hamri.m.m@gmail.com Sidi Mohamed Benslimane Ecole Superieure en Informatique de Sidi Bel Abbes, Algeria Email: s.benslimane@esi-sba.dz Abstract—The idea of using ontologies in the field of software engineering is not new. For more than 10 years, the Software Engineering community arouse great interest for this tool of semantic web, so to improve; their performance in production time and realisation complexity on the one hand, and software reliability and quality on the other hand. The standard ISO / IEC 24744, also known as the SEMDM (Software Engineering – Meta-model for Development Methodologies), provides in a global perspective, a conceptual framework to define any method of software development, through the integration of all methodological aspects related to the followed procedures, as well as, products, people and tools involved in the conception of a software product. The purpose of this article is to create domain ontology for ISO / IEC 24744 using an MDA process. This ontology will serve as semantic reference in order to assist for a better interoperability between the different users of the standard (human, software or machine). Index Terms—ISO/IEC 24744, Ontology, MDA, OWL, Software Process, Metamodel, UML. I. INTRODUCTION The development of means of transportation, telecommunication and other technological means, relies on the use of more and more complex software, which has to respect very demanding requirements furthermore, according to Rida Noor, “The success of software industry lies in developing a defect free and quality product within reasonable time and budget.”[1]. Software Engineering had to meet these requirements while increasing the level of abstraction of the methods, which has, for example, led to the emergence of Model Driven Engineering (MDE). Software engineering gives response to problems involving information share and exchange between great numbers of entities. The representation of such information has to be consensual, not only in order to facilitate exchange and communication (and so permit those entities to collaborate), but also to avoid issues of both integration and interoperability provoked by the use of heterogeneously represented structures in which every entity has a specific meaning. The MDE approach is presented as a solution to interoperability problems. It tries to give a conceptual meaning to software artefacts. However, due to often reached complexity levels, it is difficult to obtain a thorough conceptualisation of the artefacts. Accordingly, Jin and Cordy [2] proposed an ontological approach to represent Software Engineering knowledge. As Uschold has asserted in [3], ontologies consist of three main categories of use: Communication, Interoperability and Systems engineering, this latter, is used to assist conception processes, and to maintain software systems, either the systems are based on knowledge or not. Ontologies are interesting while facing exchange and interoperability problems, they proved to be a solution for conception and modelling of complex systems. Ontology is a philosophical branch that studies what exists [4]. Aristotle employed it to describe the existence of beings. In another context, the domain of artificial intelligence broaches models of the world and so, it seized the term ontology to describe all what can be represented from the real world in a program, and thus facilitate knowledge share and reuse. In addition to the artificial intelligence research community, ontologies interest numerous domains relative to knowledge. Therefore, a high interest towards ontologies is found in Information Systems (IS) and Knowledge Based Systems (KBS). KBS and IS are concerned by the mastery of the domains and the resolution of knowledge problems, for both, ontologies are means of analysis, modelling and knowledge domains implementation [5][6]. The consensual aspect of an ontology is central. Every ontology has to be the result of a process in which all the operators of the domain cooperate and understand each other regarding the meaning given to every concept relative to the domain, so that ontology can be adopted by everyone and used as a common basis for the mastery of the domain. According to Isotani [S. Isotani] ontologies are applied to address three major challenges in software engineering, namely, difficulty in communicating and sharing information at first, secondly, effective management of software development phases and finally, development of techniques and environments in order to support the production of semantic software through an interdisciplinary approach. In the domain of Software Engineering, the norm ISO/IEC 24744 [8][9] has been strongly inspired by the works of Henderson-Sellers on OPF meta-model (OPEN Process Framework) [10]. These works have emerged as result to strong critique of the first versions of OMG’s Software Process Engineering Meta-model (SPM) [11], especially shifting mechanisms from a modelling level to another, for example from M2 to M1to M0 [12][13]. To reach the limits of SPM, the normalised meta-model ISO/IEC 24744, presents a new modelling approach, based on three aspects that are Process, Products and work Producers, which implies two kinds of users, developers and method engineers. Though this norm presents several advantages, it may seem intimidating because of the adoption of new concepts that constitute a paradigm change, which implies a new way of thinking and perceiving meta-modelling processes. The idea of using ontologies as semantic references for the norm ISO/IEC 24744, can be a good solution for helping users to surpass the important learning curve of this new paradigm. It permits better comprehension and communication between different users of the norm. In this article, we will propose an MDA-based approach[14] that will permit the elaboration of a domain ontology for the standard ISO/IEC 24744. The rest of the present article is organized as follows: the next section presents a brief review of the literature that is most related to our work. The third section gives a global view of the norm ISO/IEC 24744 and details the most important concepts of our work. The fourth section introduces our construction architecture of the norm ISO/IEC 2744. In section five, we present the profiles construction steps and transformations in OWL. Section six illustrates the experimentations realised to demonstrate the feasibility of our approach, it is followed, in section seven, by a comparison with a related work. Finally, we conclude and mention perspectives for this work. II. RELATED WORKS Using ontologies in Software Engineering is not a new idea. During the last decade, several works have been undertaken. We will mention the most relative ones to our work. [15] Defined a generic ontology for process domain considering, it resulted in a contribution of the recently built process ontology to the semantic enrichment of the terms for measurement and evaluation domain ontology by means of stereotypes. Gazel et al [16] presented an ontology-based tool for software process evaluation, this tool was developed in order to support the phase of collecting data of the evaluation process and to assess software processes, in conformity with CMMI [17]. Rungratri and Usanavasin [18] proposed «CMMI-GAAF v.1.2» a framework for an automatic analysis of the gaps relative to the lack of conformity with CMMI, using the work of Soydan et.al. [19] Soydan and Kokar. In this context, Project Assets Ontology was developed, to so merge CMMI process and project assets. Lee et al[20] have proposed an ontology-based multi-agent system for the evaluation of CMMI, this system permits the establishment of evaluation links on both processes and product quality in conformity with CMMI. Liao et al [21] aimed to create a generic Software Process Ontology (SPO), with the objective to make it meet the requirement of both CMMI and ISO/IEC 15504, SPO represented by atomic practices, was used in order to represent models of process. Liška and Návrat [22] brought an approach that facilitates the use of Software Process Meta-Model in order to convey improvements by means of knowledge engineering approaches, they developed an SPM ontology in order to demonstrate its technical application on the semantic web. In[23] Falbo presented an SPO aiming to establish a common vocabulary for software process, in order to support organisations working on improving software process . Falbo et al [24] they also developed an ontology model for software process, according to the authors, this ontology is sufficiently expressive to be used as a common base for mapping software process fragments of norms such as IEC 12207-ISO 9001:2000-ISO/IEC 15504, CMMI, RUP and SPEM. Wongthongtham et al. [25] presented an ontology model for software engineering, to represent software engineering knowledge, thus helping to define utilised information during communication in semantic projects, it is also used as a communication frame. Guizzardi et al. [26] presented the last development relative to Unified Foundational Ontology (UFO), this latter is useful for improving the quality languages and models of conceptual modelling. Mendes and Abran [27] proposed an ontology prototype based on the SWEBOK[28] guide that is able to represent Software Engineering data, an extraction from the guide resulted in almost six thousand (6000) Software Engineering concepts, and about four hundred (400) types of relations between the concepts have been identified. Sicilia et al [29] have also proposed an ontology based on the SWEBOK guide, it contains: a descriptive part that identifies artefacts and activities and a prescriptive part containing approaches for commonly accepted concrete activities. Hilera et al [30] proposed OntoGLOSE, another ontology that conceptualises the domain of software engineering, based on the Software Engineering Terminology Glossary and published by IEEE, It includes more than 1500 concepts corresponding to 1300 glossary term, each one with its different meanings. Henderson-Sellers et al [31][32] proposed initiatives aiming to standardize the different ISO norms, such as the project intended by the SC7 ISO study group. Initiatives from both parts often resort to other ontologies in order to deal with the problem of semantic interoperability. As a result, we need high quality ontologies as bases for integration. Standardization is consolidated as a source of knowledge. that reflects a common conceptualisation. However, most of the standards have not been designed to be ontologies. Ruy et al [33] presented an ontological analysis of a part of the meta-model ISO/IEC 24744, this analysis is accomplished in the light of UFO [34], the authors have identified some problems and underlined some solutions. Suggestions and general recommendations were presented in order to transform SEMDM into an ontology of quality in accordance with the needs of ISO standardization. [35] Souleymane Koussoube ET AL proposed an ontology-based contribution to Agent Oriented Software Engineering called OBAMAS (Ontology-Based Approach for Multi-Agents Systems engineering). It starts with an analysis phase that consists of the construction of three formal ontologies (a domain ontology, an ontology of functionalities, and an ontology of multi-agents systems) and their alignment to merge in a single one. Secondly, a design phase consists of the operationalization of the single ontology in order to infer the agents of the system in a more formal way. In this section we have mentioned a range of works aiming to use ontologies in the domain of Software Engineering, nevertheless, Liska’s work [22] is the closest to the present approach, and we will compare both approaches in the seventh section. III. THE NORM ISO/IEC 24744:2010 The norm ISO / IEC 24744, commonly called SEMDM (Software Engineering - Meta-model for Development Methodologies) defines a meta-model for development methodologies. In this context, a meta-model indicates a semi-formal language able to describe methods. These methods are themselves models, which are similar to other meta-models such as SPEM of OMG. The norm is strongly inspired from Henderson-Sellers’ works on the OPF meta-model [10]. The standard ISO/IEC 24744 has emerged after proposing a solution to duality problems caused by OMG’s four layers, which occur when an element defined in a layer is at the same time; object (the element is the result of the instantiation of the elements of the higher layer) and class (the element is subject to an instantiation). The standard ISO/IEC 4744 permits the possibility to bypass this problem through the use of two concepts, namely Power type and Clabject [36]. The elements of the norm are organized by the communities involved in their creation and use (Fig 1). Methodologies are created by method engineers; they will be used by software developers to create software products. Both communities intervene in three different domains i.e. metamodeling, methodology and Endeavour. Every domain is a representation of the domain “below”, which means that, methods represent Endeavour and meta-models represent methodologies. ![Fig.1. The Three Utilization Domains of the Norm ISO/IEC 24744](image) SEMDM sorts the elements of a methodology in three categories; Endeavour elements, that represent the elements to be created by the developers in a project, Template elements, representing all the elements created by method engineers during the construction of an ontology, Resource elements, representing the elements of a methodology directly used at the level of project without instantiation (Fig 2). The elements Endeavour, Template and Resource provide all the necessary classes to proceed with the three aspects of methodologies; Process, Product and Producers. Fig 3 gives a partial view of the meta-model Endeavour Element with the different links that exist between the three elements (Process, Product and producers). ![Fig.2. Partial Class Diagram of ISO/IEC 24744 Meta-Model.](image) The Endeavour element contains five main classes, which are, Work Unit class; that processes works that are realised or intended to be realised, Stages class; that concerns the management of time limits, Producers class; it concerns agents in charge of executing Work Units, Work Producers class; that refers to utilised artefacts and Model Units class that treat utilised models. IV. CONSTRUCTION ARCHITECTURE OF THE ISO/IEC 24744 ONTOLOGY Though the advantages presented by the meta-model SEMDM are undeniable [37], its use is sometimes intimidating. The divergence of conventional approaches and the adoption of new concepts constitute a paradigm change, which implies a new manner of thinking and perceiving meta-modelling process, and so the learning curve is likely to be important. In addition to that, the fact that SEMDM is specified in terms of purely abstract concepts, without offering a specialised notation that permits a simplified manner of modelling methods, makes the conception and the validation processes of the method more difficult. Using ontologies as a semantic reference can be a good solution that helps users to overcome such problems. Although the norm ISO/IEC 24744 has various advantages comparing to OMG approaches such as SPEM in the domain of Software Engineering, it is not to deny that MDA has savoir-faire and experience in model-based ontological engineering domain, furthermore, the duality problem of the MDA approach is irrelevant in this situation, since our objective is the creation of a domain ontology that allows the definition of the concepts of the norm and their relations. In addition, the norm uses UML[38] class diagrams to define its meta-models, which facilitating the use of both the MDA approach and its widely available tools. A. Ontologies modelling architecture in an MDA process For the creation of our MDA-based ontology, our approach is inspired from the work of Djurić et al [39] in its transformation stages. Before beginning the transformation, we first extract, three separated meta-models, each one respectively corresponding to the concepts Endeavour, Template and Resource. The extraction is based on the specification of the meta-model. Secondly, we create a UML profile for the norm, it gathers three packages, each one corresponding to each of the three extracted meta-models. This profile will be used as starting point for our MDA-based transformation process. As for the validation of the domain OWL ontology, there exist numerous validation tools in the related literature. In our work we use the Protégé ontological tool. In this work, we propose an MDA-based architecture for ontology engineering that contains (see Fig 4): - A UML profile for the norm ISO/IEC 24744 (UPISO). - An ontology UML profile for ISO (OUPISO) - An Ontology Definition Meta-model (ODM) [40]. - Semantic web languages (OWL, RDFs, etc.). Ontology Definition Meta-model stands as a link between MDA on the one hand and both semantic web and Software Engineering on the other hand, which makes of ODM the core of this architecture. Therefore, our architecture is an MDA-based ontological architecture that includes a UML profile for the norm ISO/IEC 24744 (UPISO). To build this UML profile, we first choose the package containing all the stereotypes that allow us to export the profile towards the target meta-model PSM which can be OWL. Afterwards, we exploit ontologies to model the semantic aspects of the norm in order to define an ontology UML profile that will be translated in an ODM. This meta-model gathers all the ontological concepts, it is defined according to Meta-Object Facility (MOF) [41] and its construction is based on OWL. Once ODM built, it is translated towards OWL meta-model, for example to generate an OWL description. Consequently, the gateway between MDA and semantic web is created via the use of ODM. This offers numerous advantages such as flexibility and opening. Focusing only on the OWL meta-model, we will propose our approach to construct a domain ontology in the next section. B. MDA based approach for the construction of a domain ontology Fig 4 depicts a global view of the steps to be followed during the construction of our ontology. The base of our architecture is the construction of UML profiles of ISO/IEC 24744, namely a UML profile for Endeavour, Template and Resource. These UML profiles are presented as follows: C. UML profile of the norm (UPISO) The profile is the cornerstone of our work, because it permits passage to MDA space. It is a central part of our approach, because all the following steps of the work rely on it. This UML profile is used to model the semantic aspects of the norm. A group of UML extensions constitutes a UML profile. UML offers three extension mechanisms to extend the elements of UML’s base meta-model; Stereotypes which are classes of the profile define how an existing meta-class can be extended within the frame of a profile, while respecting base elements, tagged values that introduce properties and finally constraints that act as restrictions upon the new element. We use a UML profile in order to mark the model that is independent from the platform, called PIM (Platform Independent Model), and to facilitate the profile’s transformation into the target meta-model PSM (Platform Specific Model) which is in our case the OWL meta-model. During the following steps, we will need this PSM to generate our domain ontology in OWL. The creation of these profiles is not source to problems, because the meta-model of the norm ISO/IEC 24744 is defined in diagrams of UML OMG class. The results of this phase are the three profiles; Endeavour, Template and Resource. Endeavour profile is the most important; it will be composed of three main elements which are Product, Producer and Process. However to generate an OWL ontology of ISO/IEC 24744, we have adopted a methodology composed of numerous steps, these steps are described in the following section. D. Generation methodology of a domain ontology For an automatic generation of our ontology, we first extract information relative to the concepts (Endeavour, Template and Resource) from the description of the meta-model of the norm. In the extraction process, we use the UML plug-in tools under the platform Eclipse (Eclipse, 2015) [42] in order to create the profiles Endeavour, Template and Resource that will respectively have as sources, the norm’s meta-models Endeavour, Template and resource. Once the profiles created, they will be stereotyped with the concepts of the norm. The profiles will be called UPISO which stands for UML Profile of the norm ISO, they are in fact three UML profiles. In order to generate an OWL domain ontology, we have used mappings between the concepts UPISO, OUPISO, ODM, OWL. For the validation of the generated ontology, we have used the Protége tool (Ref). Fig 6 depicts the generation process of the ontology ISO/IEC 24744. This process includes the following steps: Step 1: Meta-model fragmentation This step permits the extraction of the information relative to the concepts Endeavour, Template and Resource of the norm’s description. This step is not quite complicated since it selects the different part of the meta-model that are relative to the three domains described in the norm which are; Endeavour, Template and Resource. Step 2: UPISO construction (UML profiles for the norm) After fragmentation, we use the UML tool (Eclipse Modelling Tools and its Plug-in Papyrus) in order to create three UML profiles with stereotypes that include constructors of the norm. In this step, we obtain three profiles; Endeavour, Template and Resource. Step 3: Transformations of UPISO into OUPISO In this step, we transform these three UPISO profiles in their corresponding OUPISO profiles: an ontology UML profile for Endeavour profile (Endeavour Ontology UML Profile), an ontology UML profile for Templates profile (Templates Ontology UML Profile) and an ontology UML profile for Resource profile (Resource Ontology UML Profile). Step 4: Transformations of OUPISO into ODM At this level, the three OUPISO profiles are transformed into their corresponding ODM. Since all the meta-models are in accordance with MOF (Meta-Object Facility) of MDA architecture, we first generate XMI documents (XML Metadata Interchange) for these meta-models; XMI formats for UML, OUPISO for ODM. After that, we use ATL (Atlas Transformation Language) [43] to transform the source representations into their corresponding target representations. In the implementation section, we will mention the transformation rules that have been applied in this part. Once these rules executed, we will obtain three XML representations of the ODM meta-models. Step 5: Mapping ODM meta-model in OWL description The purpose of this step is to generate an OWL description of the norm. This stage is not quite difficult since the ODM concepts are almost identical to the OWL concepts. The utilised transformation rules are defined in Table 1. An example of transformation rule is defined in the implementation section. Step 6: OWL descriptions fusion The sixth step consists of gathering the three OWL documents respectively corresponding to the profiles Endeavour, Template and Resource in order to create a complete OWL file corresponding to ISO/IEC 24744 domain ontology. Step 7: Creation of the relation “Kind” This step consists of establishing a link between the concepts « element » and « element Kind » for the creation of a Kind non-taxonomic relation. The creation of this relation has been implemented using Jena, a Java API (Atlas Transformation) that permits ontologies creation and manipulation under OWL. In this stage, we browse the ontology and we create for every concept of the sub-ontology Endeavour a Kind relation with the corresponding concept of the sub-ontology Template, for example, the concept Workunit will be linked to WorkunitKind. Step 8: Ontology validation The ontology validation stage allows the detection of syntax errors, or possible incoherencies in the final description of the OWL ontology. The XMI documents are exported in the Proté gé tool for validation. V. PROFILE CONSTRUCTION AND TRANSFORMATION IN OWL A. UML profile construction for Endeavour UPISO The first thing to do during this step is the construction of a package that gathers all the stereotypes of ISO/IEC 24744. These stereotypes correspond to the concepts of the norm. Fig 7 depicts a screenshot of the package of the stereotypes Endeavour elements. Once the package built, we construct three UML profiles (UPISO) corresponding to the modular specification of the norm concerning the three parts. In order to construct these UML profiles, we first have to select the stereotypes corresponding to each part Endeavour, Template and Resource starting from the package. Once elaborated, every UML profile is saved in its corresponding package. Since the number of transformations is important, we restrict our representation to certain construction and transformation steps of these profiles. Fig 8 depicts the profile UPISO Endeavour. B. Transformation and validation To realise models transformations, and to stay relevant to the MDA-based standardization context, we have used ATL, a language that meets the specification MOF 2.0 and QVT (Query/Views/Transformations), defined by OMG as a meta-model for models transformation (OMG, 2011b)[44]. The Meta-models UPISO, OUPISO, ODM and OWL are first translated into XMI representations, after that we realise the transformations via ATL. These transformations concern the mappings from UPISO to OUPISO then from OUPISO to ODM and finally from ODM to OWL, at last, The Protégé ontological tool is used for the validation of OWL generated descriptions. a. Transformation of UPISO into OUPISO The translation of UPISO into OUPISO is performed by transformation tools that are defined in Table 1. UPISO elements indicate ontological concepts in OUPISO. Consequently, UPISO extends UML with new constructors to support our specific ontological concepts. such as stereotypes classes <<Ontology>> and <<OntClass>>. We convert stereotypes classes to ontological classes with the stereotype <<OntClass>>. Tagged values corresponding to properties or attributes are transformed to ontological data with the stereotype <<DatatypeProperty>>. Finally, the stereotype <<Package>> becomes <<Ontology >> and the stereotypes association are translated to the concept <<ObjectProperty>>. Table 1. Mapping UPISO and OUPISO <table> <thead> <tr> <th>UPISO Concepts (Stereotypes or tags)</th> <th>OUPISO Concepts (Ontological concepts)</th> </tr> </thead> <tbody> <tr> <td>« Package »</td> <td>« Ontology »</td> </tr> <tr> <td>« Class »</td> <td>« OntClass »</td> </tr> <tr> <td>«Association»</td> <td>« ObjectProperty »</td> </tr> <tr> <td>« Attribute »</td> <td>« DatatypeProperty »</td> </tr> </tbody> </table> b. Transformation of OUPISO into ODM and OWL The construction of Ontology Definition Meta-model (ODM) is based on OWL with ontological concepts. Fig 9 presents a partial view of the ODM meta-model. ![Partial view of ODM](image) The transformation rules from OUPISO to ODM and from OMD to OWL meta-model are quite simple and direct since ODM concepts are used as stereotypes within OUPISO on the one hand, and ODM is defined according to OWL concepts on the other hand. The use of stereotyped classes <<Ontology>> and <<OntClass>> in OUPISO serves to identify respectively a domain and a concept. Therefore, they will be represented as classes in ODM. The stereotype <<ObjectProperty>> is a representation of the classes <<ObjectProperty>> in ODM and only with individuals from its domain and range. Lastly, the stereotype <<DatatypeProperty>> is considered as a class ‘DatatypeProperty’ in ODM. Table 2 depicts the mappings between the concepts OUPISO, ODM and OWL. Table 2. Mappings between the concepts OUPISO, ODM and OWL. <table> <thead> <tr> <th>OUPISO Concepts (Ontological concepts such as stereotypes or tag values)</th> <th>ODM Concepts (ontological concepts)</th> <th>OWL Concepts</th> </tr> </thead> <tbody> <tr> <td>«Ontology »</td> <td>Class Ontology</td> <td>OWL : Ontology</td> </tr> <tr> <td>«OntClass»</td> <td>Class Class</td> <td>OWL : Class</td> </tr> <tr> <td>«ObjectProperty»</td> <td>ObjectProperty</td> <td>OWL : objectProperty</td> </tr> <tr> <td>«DatatypeProperty»</td> <td>Class DatatypeProperty</td> <td>OWL : datatypeProperty</td> </tr> </tbody> </table> VI. IMPLEMENTATION The objective of our experimentation is to verify the feasibility of the process on which relies our approach. Our implementation and transformations are based on the Framework Eclipse and the plugin Papyrus. Our choice has been motivated by the fact that EMF[45] is at present the reference environment for Model Driven Engineering, because it proposes the implementation of the Meta layers for most of the tools derived from MDE. For model transformation, we have chosen a project among the most adopted by the Eclipse community, which is the transformation engine ATL. This engine provides an implementation similar to OMG’s standard Query View Transform (QVT) that supports both declarative and imperative enunciation of transformation rules, in our case, we have developed all UML profiles with the UML tool, which relies itself on the platform Eclipse. It will be noticed that models manipulations have been realised through MDE technologies and a part of their code has been generated by means of models. We have implemented our profiles as Ecore format EMF meta-model, in order to use them at the beginning of the serialisation phase and in model transformation, their edition was completely realised in UML with the tool Papyrus. However, since Papyrus is a UML editor the meta-classes that it instantiates and serialises in these models are Meta-classes of the UML meta-model but not Meta-classes of the MOF meta-model. We had to convert UML models in into Ecore models; this format is the implementation of the MOF provided by EMF. To illustrate our MDA process of generation, which we have described previously, we will only present screenshots related to the elaboration of the UML profiles for OWL, their transformations and then the validation of the domain Ontology. A. UPISO transformations to OUPISO These transformations concern mappings of UPISO concepts to OUPISO concepts. OUPISO is a UML ontology profile for ISO/IEC 24744 and its concepts are ontological. Before undertaking any transformations, we first construct a package containing all the stereotypes that can support ontological concepts such as “Ontology”, “OntClass”, “ObjectProperty” and “DatatypeProperty”. After that, the stereotypes that we create should support ODM in order to facilitate mapping between OUPISO and ODM. Once the stereotypes created, the user is able to perform his transformations. Fig 10 depicts a screenshot of the stereotypes OUPISO package. Once the stereotypes OUPISO created, we translate the UML profile (UPISO) constructed before, to its corresponding OUPISO. In order to do it, we execute transformation rules defined in Table 2. We mention Rule 1 as an example that permits transformation of a class into an Ontoclass. **Rule 1:** transformation of a UPISO class into an OUPISO class 1: rule Class2Class 2: 3: from 4: a: UPISO!Class 5: to 6: p: OUPISO!Class() 7: name<a.getDefNameSet(), 8: generalization<a.generalization 9: on: OUPSWS!OntClass(base_Class<p) 10: Fig 10 depicts a screenshot of the stereotypes OUPISO package. Once the stereotypes OUPISO created, we translate the UML profile (UPISO) constructed before, to its corresponding OUPISO. In order to do it, we execute transformation rules defined in Table 2. We mention Rule 1 as an example that permits transformation of a class into an Ontoclass. Fig 11 depicts a screenshot after the complete execution of the transformation rules that permitted the generation of the Ontology UML Profile OUPISO. Fig 11. OUPISO Part Generated for Endeavour. B. Transformations from OUPISO to ODM The transformations of the UML Ontology profile (OUPISO) to ODM are simple because ODM concepts are used as stereotypes in OUPISO. After the execution of the rules corresponding to this part, we obtain the ODM generated Endeavour part (Fig 12). We mention as an example rule 2 that permits the transformation of an OUPISO class to an ODM class. ``` 1: rule Class2Class 2: { 3: from a : OUPISO!Class 4: to p: ODM!Class(name<'Class', 5: ownedAttribute<pr,generalization<- 6: a.generalization), 7: pr:ODM!Property(name<a.name) 8: } ``` Fig. 12. The ODM Part Generated for Endeavour. C. Transformations from ODM to OWL Once the three ODM parts generated, we execute the transformation rules corresponding to this phase, in order to generate corresponding OWL parts. These transformation rules are already defined in table 2. After executing ATL rules, we obtain an OWL description that we present in Fig 13. We mention as an example rule 3 that permits the transformation of all ODM classes in OWL classes. <table> <thead> <tr> <th>Rule 3: ODM classes transformation in OWL classes.</th> </tr> </thead> <tbody> <tr> <td>helper context</td> </tr> <tr> <td>Class ! package def:</td> </tr> <tr> <td>GetCodeOwl</td> </tr> <tr> <td>(!</td> </tr> </tbody> </table> Fig.13. The OWL Part Generated for Endeavour. D. Fusion of the generated OWL descriptions In this final step, we fuse the three OWL descriptions generated in the preceding steps in a single OWL file. We use API JENA to generate links between the elements Endeavour and Template with the relation Kind. The OWL file obtained will be exported to the tool Protégé for validation. VII. COMPARISON We have compared our work with Liska’s work [22], this latter aims at creating an ontology for the method SPEM 2.0. We did not intend to compete with his works for the simple reason that we treat different methods, but we intended to reuse his contributions in order to improve our approach. From an architectural perception, our work is quite similar to Liska’s work, since both approaches have used Djuric’s architecture for ontologies creation. Both articles propose the transformation of an MDA norm into Semantic Web with a mapping between an ontology UML profile and an arbitrary UML profile. The existence of similarities between the models « SPEM and ISO/IEC 24744 » motivates us for this choice. Our approach permitted the creation of a UML profile for the norm, while Liska’s work had the advantage of having SPEM UML profile with formal OMG specification. Though Liska’s work had this advantage since SPEM originates from MDA with an XMI specification, which permits him to use directly modelling tools such as Eclipse, ATL and Ecore, the author preferred writing mapping tools in Adhoc. However, in our approach we use passage rules with ATL in order to generate mappings automatically. Furthermore, we have preferred modularity by using the profiles Endeavour, Template and Resource, in order to facilitate maintenance and evaluation, which has not been done in the other works. Liska’s work has been a reference for us and a great source of inspiration though the objectives are not specifically the same, but the main purpose was to create a domain ontology for Software Engineering. VIII. CONCLUSION The main purpose of this work consists of developing a domain ontology of the norm ISO/IEC 24744, this ontology has the objective of defining the concepts relative to the norm. The use of the MDA approach for the construction of ISO/IEC 24744 ontology proved to be audacious since ISO/IEC 24744 with its three layers has been created to fill the lacks of the MDA approach. An intermediary objective can be considered as another contribution is the creation of a UML profile for ISO/IEC 24744, this profile will serve as reference to other works relative to the domain. Other experimentations will be necessary in order to confirm that the proposed ontology is able to meet the user’s needs. Unfortunately, it was difficult to find industrial partners that are familiar with the norm ISO/IEC 24744 and ready to experiment our Ontology. We must recognise that our research has to continue in order to check and validate the approach in real use situations. As a perspective we will work on OCL constraints that contain semantic[46] (OMG, 2014b), which allows us to reason on the obtained OWL description. REFERENCES Copyright © 2015 MECS I.J. Modern Education and Computer Science, 2015, 8, 48-60 [38] OMG. "UML2.4.1." http://www.omg.org/spec/UML/2.4.1/, 2011. Authors’ Profiles Mohamed Mehdi Hamri: is a PhD student at Djillali Liabes University. He received his M.S. degree in computer science from Sidi Bel Abbes University in 2009. Since 2009, he is an Assistant Professor at the Computer Science Department of Sidi bel abbes University. Currently, he is member of the EEDIS Laboratory. His research interests include semantic web, ontology engineering, information and knowledge management, and software process modeling. Sidi Mohamed Benslimane: is a Full professor at Ecole Superieure en informatique de Sidi Bel Abbes. He received his PhD degree in computer science from Sidi Bel Abbes University in 2007. He also received a M.S. and a technical engineer degree in computer science in 2001 and 1994 respectively from the Computer Science Department of Sidi Bel Abbes University, Algeria. He is currently Head of Research Team ‘Service Oriented Computing’ at the Evolutionary Engineering and Distributed Information Systems Laboratory, EEDIS. His research interests include, semantic web, service oriented computing, ontology engineering, information and knowledge management, distributed and heterogeneous information systems and context-aware computing.
{"Source-Url": "https://www.mecs-press.org/ijmecs/ijmecs-v7-n8/IJMECS-V7-N8-6.pdf", "len_cl100k_base": 8296, "olmocr-version": "0.1.48", "pdf-total-pages": 13, "total-fallback-pages": 0, "total-input-tokens": 42975, "total-output-tokens": 11394, "length": "2e13", "weborganizer": {"__label__adult": 0.0002994537353515625, "__label__art_design": 0.00043582916259765625, "__label__crime_law": 0.00037217140197753906, "__label__education_jobs": 0.0016832351684570312, "__label__entertainment": 5.996227264404297e-05, "__label__fashion_beauty": 0.00015592575073242188, "__label__finance_business": 0.0002605915069580078, "__label__food_dining": 0.0002758502960205078, "__label__games": 0.0004925727844238281, "__label__hardware": 0.0005598068237304688, "__label__health": 0.0003864765167236328, "__label__history": 0.0002818107604980469, "__label__home_hobbies": 8.624792098999023e-05, "__label__industrial": 0.0004210472106933594, "__label__literature": 0.0003132820129394531, "__label__politics": 0.0002484321594238281, "__label__religion": 0.00047516822814941406, "__label__science_tech": 0.032470703125, "__label__social_life": 0.00010991096496582033, "__label__software": 0.010711669921875, "__label__software_dev": 0.94921875, "__label__sports_fitness": 0.0002455711364746094, "__label__transportation": 0.0004453659057617187, "__label__travel": 0.00020003318786621096}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 45535, 0.0408]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 45535, 0.33938]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 45535, 0.87215]], "google_gemma-3-12b-it_contains_pii": [[0, 4621, false], [4621, 10705, null], [10705, 14308, null], [14308, 18011, null], [18011, 22004, null], [22004, 25465, null], [25465, 26432, null], [26432, 31481, null], [31481, 32761, null], [32761, 33394, null], [33394, 35985, null], [35985, 42134, null], [42134, 45535, null]], "google_gemma-3-12b-it_is_public_document": [[0, 4621, true], [4621, 10705, null], [10705, 14308, null], [14308, 18011, null], [18011, 22004, null], [22004, 25465, null], [25465, 26432, null], [26432, 31481, null], [31481, 32761, null], [32761, 33394, null], [33394, 35985, null], [35985, 42134, null], [42134, 45535, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 45535, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 45535, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 45535, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 45535, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 45535, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 45535, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 45535, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 45535, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 45535, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 45535, null]], "pdf_page_numbers": [[0, 4621, 1], [4621, 10705, 2], [10705, 14308, 3], [14308, 18011, 4], [18011, 22004, 5], [22004, 25465, 6], [25465, 26432, 7], [26432, 31481, 8], [31481, 32761, 9], [32761, 33394, 10], [33394, 35985, 11], [35985, 42134, 12], [42134, 45535, 13]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 45535, 0.08531]]}
olmocr_science_pdfs
2024-11-24
2024-11-24
e99f5dd5015cc9d6eb43310cd58f8cd46bfec1d8
PowerInfer: Fast Large Language Model Serving with a Consumer-grade GPU Yixin Song, Zeyu Mi,† Haotong Xie and Haibo Chen Institute of Parallel and Distributed Systems (IPADS), Shanghai Jiao Tong University Abstract This paper introduces PowerInfer, a high-speed Large Language Model (LLM) inference engine on a personal computer (PC) equipped with a single consumer-grade GPU. The key underlying the design of PowerInfer is exploiting the high locality inherent in LLM inference, characterized by a power-law distribution in neuron activation. This distribution indicates that a small subset of neurons, termed hot neurons, are consistently activated across inputs, while the majority, cold neurons, vary based on specific inputs. PowerInfer exploits such an insight to design a GPU-CPU hybrid inference engine: hot-activated neurons are preloaded onto the GPU for fast access, while cold-activated neurons are computed on the CPU, thus significantly reducing GPU memory demands and CPU-GPU data transfers. PowerInfer further integrates adaptive predictors and neuron-aware sparse operators, optimizing the efficiency of neuron activation and computational sparsity. Evaluation shows that PowerInfer attains an average token generation rate of 13.20 tokens/s, with a peak of 29.08 tokens/s, across various LLMs (including OPT-175B) on a single NVIDIA RTX 4090 GPU, only 18% lower than that achieved by a top-tier server-grade A100 GPU. This significantly outperforms llama.cpp by up to 11.69× while retaining model accuracy. 1 Introduction Generative large language models (LLMs) have garnered attention for their remarkable capabilities in creative writing, advanced code generation, and sophisticated natural language processing tasks [5, 42, 49]. These models, widely deployed in data centers equipped with high-end and expensive server-grade GPUs, have significantly influenced our daily lives and work practices. Meanwhile, there is an emerging trend of running LLMs on more accessible local platforms, particularly personal computers (PCs) with consumer-grade GPUs. This evolution is driven by the need for enhanced data privacy [25], model customization [22], and reduced inference costs [42]. In contrast to data-center deployments, which prioritize high throughput [18, 37, 47], local deployments focus on low latency in processing small batches. Nonetheless, deploying LLMs on consumer-grade GPUs presents significant challenges due to their substantial memory requirements. LLMs, typically functioning as autoregressive Transformers, sequentially generate text token-by-token, each needing to access the entire model consisting of hundreds of billions of parameters. Therefore, the inference process is fundamentally constrained by the GPU’s memory capacity. This limitation is particularly acute in local deployments where the processing of individual requests (often just one at a time) [6] leaves minimal opportunity for parallel processing. Existing approaches to such memory issues include model compression and offloading. Compression techniques like quantization [12, 46], distillation [48], and pruning [23] reduce the model size. However, even deeply compressed models remain too large for consumer-grade GPUs. For instance, an OPT-66B model with 4-bit precision demands approximately 40GB of memory just to load its parameters [20], exceeding the capacity of even high-end GPUs like the NVIDIA RTX 4090. Model offloading, which partitions the model between GPU and CPU at the Transformer layer level [3, 14, 37]. State-of-the-art systems like llama.cpp [14] distribute layers between CPU and GPU memories, leveraging both for inference, thus reducing the GPU resources required. However, this method is hindered by the slow PCIe interconnect and the CPUs’ limited computational capabilities, resulting in high inference latency. In this paper, we argue that the key reason for memory issues in LLM inference is the locality mismatch between hardware architecture and the characteristics of LLM inference. Current hardware architectures are designed with a memory hierarchy optimized for data locality. Ideally, a small, frequently accessed working set should be stored in the GPU, which offers higher memory bandwidth but limited capacity. In contrast, larger, less frequently accessed data are better suited for CPUs, which provide more extensive memory capacity but lower bandwidth. Nevertheless, the vast volume of parameters required for each LLM inference iteration leads to a working set that is too large for a single GPU, thus impeding efficient locality exploitation. We have observed that LLM inference inherently exhibits high locality. Specifically, during each inference iteration, a limited number of neurons\(^1\) are activated, significantly influencing the outcome of token inference. These activations, which are input-specific, can be accurately predicted during runtime. For example, in the OPT model, less than 10% of the elements in the activation map are non-zero, and these can be predicted with more than 93% accuracy at runtime [21]. Notably, neuron activation in an LLM follows a skewed power-law distribution: a small subset of neurons consistently contributes to the majority of activations (over 80%) across various inputs (hot-activated), while the majority are involved in the remaining activations, which are determined based on the inputs at runtime (cold-activated). Building on the locality insights, we introduce PowerInfer, an efficient LLM inference system optimized for local deployments using a single consumer-grade GPU. The key idea of PowerInfer is to exploit the locality in LLM inference by assigning the minor hot neurons to the GPU, while cold neurons, which constitute the majority, are managed by the CPU. PowerInfer preselects and preloads hot-activated neurons onto the GPU offline and leverages online predictors during runtime to identify activated neurons. This approach allows the GPU and CPU to independently process their respective sets of neurons, thereby minimizing the need for costly PCIe data transfers. However, there are significant challenges that complicate the design of PowerInfer. First, the online predictors, which are essential for identifying active neurons in LLM layers and are typically situated on the GPU, occupy a considerable amount of GPU memory. This memory could otherwise be used for the LLM. To address this, PowerInfer introduces an adaptive method for constructing smaller predictors for layers with higher activation sparsity and skewness. This iterative process reduces the size of the predictors while maintaining their accuracy, thus freeing up GPU memory for LLM inferences. Second, leveraging LLM sparsity requires the use of sparse operators. Conventional libraries like cuSPARSE [30] are not optimal due to their general-purpose design, which includes tracking each non-zero element and converting dense matrices into sparse formats [45, 51]. In contrast, PowerInfer designs neuron-aware sparse operators that directly interact with individual neurons, thereby bypassing operations on entire matrices. This approach enables efficient matrix-vector multiplication at the neuron level and removes the need for specific sparse format conversions. Lastly, the optimal placement of activated neurons between the GPU and CPU in PowerInfer is a complex task. It involves evaluating each neuron’s activation rate, intra-layer communication, and available hardware resources like GPU memory sizes. To effectively manage this, PowerInfer utilizes an offline phase to generate a neuron placement policy. This policy uses a metric that measures each neuron’s impact on LLM inference outcomes and is framed as an integer linear programming problem. The policy formulation considers factors such as neuron activation frequencies and the bandwidth hierarchy of CPU and GPU architectures. The online inference engine of PowerInfer was implemented by extending llama.cpp with an additional 4,200 lines of C++ and CUDA code. Its offline component, comprising a profiler and a solver, builds upon the transformers framework [44] with approximately 400 lines of Python code. PowerInfer is compatible with various popular LLM families, including OPT (7B-175B), LLaMA (7B-70B), and Falcon-40B, and supports consumer-grade GPUs like the NVIDIA RTX 4090 and NVIDIA RTX 2080 Ti. Performance evaluation reveals that PowerInfer, when deployed on a PC equipped with a single NVIDIA RTX 4090 GPU, delivers an average generation speed of 13.20 tokens/s for quantized models and 8.32 tokens/s for non-quantized models, maintaining model accuracy. These results significantly surpass llama.cpp’s performance, exhibiting up to 8.00x and 11.69x improvements for quantized and non-quantized models, respectively. Significantly, the inference speed achieved on an NVIDIA RTX 4090 GPU (priced at approximately $2,000) is only 18% slower compared to the performance on a top-tier A100 GPU (costing around $20,000) that can fully accommodate the model. PowerInfer’s source code is publicly available at https://github.com/SJTU-IPADS/PowerInfer. 2 Background and Motivation 2.1 LLM Inference & Architecture LLM inference, an autoregressive model, generates each token based on previous ones. The process, illustrated in Figure 1, starts with a prompt (e.g., “I love reading”) and unfolds in two phases: first, the prompt phase outputs an initial token (“OSDI”), then the generation phase sequentially produces tokens until a maximum limit or an end-of-sequence (<EOS>) token is reached. Each token generation, an inference iteration, requires running the full LLM model. The LLM architecture includes multiple Transformer layers, each comprising a self-attention and an MLP (Multi-Layer Perceptron) block (see Figure 2, left). The self-attention block generates embedding vectors by capturing the relationships among input tokens. In this process, different heads focus on extracting distinct feature information. The computation results from these different heads are aggregated and then utilized as the input for the MLP block. The MLP block applies non-linear transformations via fully connected layers and activation functions to refine the input sequence representation. The output either advances to subsequent layers or forms the LLM’s final output. In Figure 2 (right), the MLP block’s layers, FC1 and FC2, generate vectors through matrix multiplication. Each output element comes from the dot product of an input vector and a neuron (a row/column in a weight matrix). Activation functions like ReLU [1] act as gates to selectively retain or discard values in a vector, influencing neuron activations in FC1 and FC2. For example, ReLU in this figure filters out negative values, allowing only positively valued neurons in FC1 to influence the output. These neurons, which contribute to the output, are considered activated in this paper. Similarly, these values also affect which neurons in FC2 are activated and involved in the computation of its output vector. **Activation Sparsity.** Recent studies have revealed that LLM inference shows a notable sparsity in neuron activations [19, 21, 50]. For example, we observe that approximately 80% of neurons in the OPT-30B model remain inactivated during the inference. This phenomenon of activation sparsity exists in both self-attention and MLP blocks. In self-attention blocks, nearly half of the attention heads (neurons) make minimal contributions, leading to their high sparsity. The sparsity observed within the MLP blocks is primarily attributed to the characteristics of the activation functions. Crucially, the activation sparsity is input-specific, meaning that the activation of specific neurons is directly influenced by the current input and cannot be predetermined before the model’s inference iteration begins. While it is not feasible to know which neurons will be activated before the entire model runs, it is possible to predict neuron activations a few layers in advance within the ongoing model iteration. DejaVu [21], for instance, utilizes MLP-based predictors during inference, achieving a remarkable accuracy rate of at least 93% in predicting neuron activation. ### 2.2 Offloading-based LLM Serving Current model compression techniques are inadequate for fitting large language models (LLMs) within resource-limited consumer-grade GPUs. In contrast, the offloading technique, which leverages the CPU’s additional computational and memory resources, presents a more viable solution for accommodating LLMs on such hardware. Figure 3 illustrates two main offloading approaches: **GPU-centric offloading** utilizes CPU memory to store portions of the model parameters that exceed the GPU’s capacity. During each iteration, as depicted in Figure 3a), it processes the parameters located in the GPU memory, transferring more from the CPU as needed. This strategy enables the inference of LLMs of varying sizes, provided that sufficient combined CPU memory and hard disk storage are available. FlexGen [37] is a typical example that adopts a zig-zag scheduling approach to prioritize throughput over latency, processing batches sequentially for each layer. Nonetheless, this method leads to substantial per-token latency in latency-sensitive scenarios (Figure 4a), mainly due to frequent data transfers between GPU and CPU, especially with batch sizes of one. Over 99.5% of processing time is consumed by transferring LLM weights from CPU to GPU, significantly impacting overall latency, as illustrated in Figure 4b. DejaVu [21] accelerates LLM inference by using activation sparsity. It selectively processes only those neurons that are predicted to be activated (called predicted neurons for brevity), while bypassing the inactivated ones. However, this approach, initially designed for data center inference, struggles on consumer-grade GPUs that cannot accommodate full-scale LLMs. The key challenge with DejaVu in such contexts stems from the need to frequently transfer activated neurons from the CPU to the GPU during runtime. For LLMs like OPT-30B that exceed GPU memory limits, DejaVu\(^2\), albeit reducing the computational load on the GPU, is constrained by the data transfer procedure (Figure 4a). Consequently, as shown in Figure 4a, DejaVu experiences significant inference latency, comparable to that of FlexGen. **Hybrid offloading** distributes model parameters between GPU and CPU, splitting them at the Transformer layer level as shown in llama.cpp [14] (Figure 3b). The CPU processes its layers first, then sends intermediate results to the GPU for token generation. This offloading method reduces inference latency to around 600ms (Figure 4a) by minimizing data transfer and mitigating slow PCIe bandwidth. However, hybrid offloading still faces the locality mismatch issue, leading to suboptimal latency. Each inference iteration accesses the entire model, resulting in poor locality for hierarchical GPU-CPU memory structures. GPUs, while computationally powerful, are constrained by memory capacity. For instance, a 30B-parameter model on a 24GB NVIDIA RTX 4090 GPU means only 37% of the model is on the GPU, shifting most computational tasks to the CPU. The CPU, with higher memory but lower computational power, ends up handling 98% of the total computational load (Figure 4b). ### 3 Insights into Locality in LLM Inference This section introduces our insights into locality in the LLM inference procedure, highlighting two distinctive features. #### 3.1 Insight-1: Power-law Activation LLM inference exhibits a high degree of locality, indicating that a consistent group of neurons is frequently activated. Notwithstanding the input dependence of LLM activation sparsity, a power-law distribution is evident among activated neurons. Figure 5a reveals that in the MLP layers of OPT-30B and LLama (ReGLU)-70B, 26% and 43% of neurons respectively are responsible for 80% of total activations. These are termed *hot-activated* neurons. Conversely, the activation of the remaining 74% and 57% of neurons is input-dependent, classifying them as *cold-activated* neurons. This high locality is not confined to a single layer but extends throughout the model. As illustrated in Figure 5b, approximately 17% of neurons in OPT-30B and 26% in LLama (ReGLU)-70B are responsible for 80% of the total activations across all layers. #### 3.2 Insight-2: Fast In-CPU Computation If activated neurons reside in CPU memory, computing them on the CPU is faster than transferring them to the GPU, especially with the small number of activated neurons and the small batch sizes typical in local deployments. Modern CPUs with vector extensions can efficiently handle such smaller matrix computations. We compared the time to load and compute 10%\(^3\) of the MLP layer and 60% of attention layer’s CPU-side neurons on the GPU versus direct CPU execution in OPT-30B. Results in Figure 6 indicate that for batch sizes under 32, the time taken to transfer the weights of these neurons and compute them on the GPU (NVIDIA RTX 4090) exceeds the time required for calculation directly on the CPU using the AVX2 vector extension. ### 4 PowerInfer Overview This paper introduces PowerInfer, a low-latency LLM inference system deployed in a PC equipped with a single consumer-grade GPU. PowerInfer proposes a neuron-aware offloading strategy and an inference engine by fully leveraging the high locality insights described in §3. It utilizes both GPU and CPU for weight storage, accommodating LLMs of various sizes. This offloading approach, based on **Insight-1**, effectively exploits the power-law distribution of LLM inference. Specifically, PowerInfer preloads the GPU with weights --- \(^3\)While Insight-1 indicates that 43% of neurons account for 80% of the total activations in a single MLP layer, it is typically found that only about 10% of its neurons are activated during an individual inference iteration. for neurons that activate frequently, while less active neurons’ weights are kept on the CPU. To reduce inference latency, the inference engine computes only neurons predicted as active by online predictors, skipping most inactive ones. Moreover, the preloading strategy enables PowerInfer to allocate the bulk of inference tasks to the GPU, given that hot-activated neurons that have been loaded on the GPU constitute a major fraction of activations. For cold-activated neurons not in GPU memory, PowerInfer executes their computations on the CPU, eliminating the need for weight transfers to the GPU (Insight-2). 4.1 Architecture and Workflow Figure 7 presents a detailed introduction to the neuron-aware inference engine in PowerInfer, comprising both offline and online components. Due to the variation in locality properties among different LLMs, the offline component should profile LLMs’ activation sparsity, differentiating between hot and cold neurons. In the online phase, the inference engine loads two types of neurons into both GPU and CPU, serving LLM requests with low latency during runtime. **LLM Profiler and Policy Solver (Offline):** This component includes an LLM profiler that collects activation data from inference processes using requests derived from general datasets (e.g., C4 [32]). It monitors neuron activation across all layers (Step 1), followed by a policy solver categorizing neurons as hot or cold. The solver aims to activate frequently activated neurons to the GPU and others to the CPU. It uses a neuron impact metric and hardware specifications to balance the workload, using integer linear programming to maximize the GPU’s impact metric for neurons (Step 2). **Neuron-aware LLM Inference Engine (Online):** Before processing user requests, the online engine assigns the two types of neurons to their respective processing units (Step 3), as per the offline solver’s output. During runtime, the engine creates GPU and CPU executors, which are threads running on the CPU side, to manage concurrent CPU-GPU computations (Step 4). The engine also predicts neuron activation and skips non-activated ones. Activated neurons preloaded in GPU memory are processed there, while the CPU calculates and transfers results for its neurons to the GPU for integration. The engine uses sparse-neuron-aware operators on both CPU and GPU, focusing on individual neuron rows/columns within matrices. 4.2 Single Layer Example Figure 8 illustrates how PowerInfer coordinates GPU and CPU in processing a layer’s neurons. It classifies neurons based on offline data, assigning hot-activated ones (e.g., indices 3, 5, 7) to GPU memory and others to CPU memory. Upon receiving an input, a predictor identifies which neurons in the current layer are likely to be activated. For instance, it predicts activation for neurons 3, 4, and 5. It is crucial to note that hot-activated neurons, identified through offline statistical analysis, may not consistently match the runtime activation behaviors. For example, neuron 7, though labeled as hot-activated, is forecasted to be inactive in this case. Both CPU and GPU then process predicted active neurons, ignoring inactive ones. The GPU computes neurons 3 and 5, while the CPU handles neuron 4. Once neuron 4’s computation is complete, its output is sent to the GPU for result integration. 5 Neuron-aware Inference Engine This section presents a detailed introduction to the neuron-aware inference engine in PowerInfer. We first elaborate on the design of activation predictors leveraged by PowerInfer in §5.1. Then, we elucidate the process of dividing and managing neurons between the CPU and GPU in §5.2. Following this, the design of the hybrid execution model within PowerInfer is described in §5.3. Lastly, we explain the details of neuron-aware operators used in PowerInfer in §5.4. 5.1 Adaptive Sparsity Predictors The online inference engine in PowerInfer reduces computational loads by only processing those neurons that are predicted to be activated. This method was also used in DejaVu [21], which advocates for training a set of fixed-size MLP predictors. Within each Transformer layer, DejaVu utilizes two separate predictors to forecast the activation of neurons in the self-attention and MLP blocks. Consequently, the Inference computation is confined to neurons anticipated to be active. However, designing effective predictors for local deployments with limited resources is challenging, balancing prediction accuracy and model size. These predictors, frequently invoked for neuron activation prediction, should be stored in GPU memory for fast access. Yet, the considerable memory requirements of numerous fixed-size predictors can encroach upon the space needed for storing LLM parameters. For example, predictors for the OPT-175B model require around 27GB of GPU memory, surpassing an NVIDIA RTX 4090 GPU’s capacity. On the other hand, naively reducing predictor size may impair accuracy; a decrease from 480MB to 320MB in predictor size dropped its accuracy from 92% to 84%, further adversely affecting the overall LLM accuracy (e.g., winogrande [35] task accuracy from 72.77% to 67.96%). We have observed that the size of predictors is influenced by two main factors: the sparsity of LLM layers and their internal skewness. As shown in Figure 9, layers with higher activation sparsity simplify the task of identifying activated neurons, allowing for smaller predictor models. In contrast, layers with lower activation sparsity necessitate larger models with more parameters, as accurately pinpointing activated neurons becomes increasingly challenging. Additionally, in cases of high skewness, where activations are heavily concentrated in a few neurons, even a compact predictor can achieve high accuracy. To optimize for these factors, PowerInfer designs an iterative training method for non-fixed-size predictors for each Transformer layer. The process begins by establishing a baseline model size based on the layer’s sparsity profile (Figure 9). Subsequently, the model size is iteratively adjusted, taking into account the internal activation skewness to maintain accuracy. An MLP predictor typically comprises input, hidden, and output layers. Since the dimensions of the input and output layers are determined by the Transformer layer’s structure, modifications primarily target the hidden layer. During the iterative adjustments, the hidden layer’s dimension is modified according to the observed skewness. For layers exhibiting significant skewness, the hidden layer size is reduced progressively until accuracy falls below 95%. Conversely, for layers with minimal skewness, the dimension is increased to improve accuracy. Through this approach, PowerInfer effectively limits predictor parameters to a mere 10% of the total LLM parameters. 5.2 Neuron Placement and Management When the offline solver determines a neuron placement policy, the online inference engine of PowerInfer loads the model into the CPU and GPU memory as per the policy. For each layer, which may consist of multiple weight matrices, PowerInfer assigns each neuron to either the GPU or CPU based on whether the neuron is hot-activated. Ensuring the accurate computation of these segmented neurons in their proper sequence is vital for precise results. To this end, PowerInfer creates two neuron tables, one located in the CPU and the other in the GPU memory. These tables correlate each neuron to its original position in the matrix. During the process of multiplying with an input tensor, each neuron interacts with its corresponding tensor value, guided by the mappings in the neuron tables. The additional memory required for these neuron tables is relatively insignificant, totaling only about 9MB for an LLM like OPT-175B, which needs 350GB of storage. 5.3 GPU-CPU Hybrid Execution Given that PowerInfer processes only a limited number of neurons predicted to be active, such as less than 10% in an MLP layer, a potential method for GPU and CPU collaboration involves transferring cold-activated neuron weights from the CPU to the GPU for computation. However, as per Insight-2, the time spent transferring activated neurons to the GPU surpasses the time needed for direct computation on the CPU. Therefore, PowerInfer implements a GPU-CPU hybrid execution model, wherein both units independently compute their respective activated neurons and then combine the results on the GPU. This method effectively balances the computational workload, leveraging the strengths of each unit while reducing transfer time inefficiencies. Before inference, PowerInfer constructs a computationally directed acyclic graph (DAG) with each node representing a computational LLM inference operator and stores it in a global queue in the CPU memory. Each operator in the queue is tagged with its prerequisite operators. During inference, two types of executors, pthreads created by the host OS, manage calculations on both CPU and GPU. They pull operators from the global queue, check dependencies, and assign them to the appropriate processing unit. The GPU and CPU use their neuron-aware operators, with the GPU executor launching GPU operators using APIs like cudaLaunchKernel, and the CPU executor coordinating unoccupied CPU cores for calculations. Before executing an operator, the CPU executor also determines the necessary thread count for parallel comp- utput. To manage operator dependencies, especially when a parent node of a CPU operator is processed on the GPU, a barrier ensures GPU computations are complete before the CPU starts its operator. In scenarios where activated neurons are split between GPU and CPU, synchronization between these processing units also becomes crucial. After one unit finishes its neuron calculations, it waits for the other to merge results. As GPU neurons are activated more frequently, PowerInfer assigns merging operations to the GPU. To optimize synchronization overhead, a selective synchronization strategy is used, bypassing result synchronization when the CPU executor has no activated neurons, allowing it to proceed to subsequent blocks, thereby enhancing overall efficiency. 5.4 Neuron-aware Operator Considering the activation sparsity in LLMs, matrix multiplication operations can bypass inactive neurons and their weights, necessitating the use of sparse operators. However, current sparse matrix multiplication tools, including state-of-the-art sparse-aware compilers like SparTa [52] and Flash-LLM [45], as well as libraries like cuSPARSE [30] and Spunik [33], fall short in this regard. They either support only static compilation of sparse-aware kernels or require dynamic conversion of sparse matrices into dense formats, leading to significant performance overhead, especially with the dynamic sparsity in our scenario. Additionally, the dynamic JIT compiler PIT [51], though efficient for general sparse matrix multiplication on GPUs, is not suited for CPU-GPU hybrid execution where CPU computational capabilities are limited. To overcome these limitations, PowerInfer introduces neuron-aware operators that directly compute activated neurons and their weights, necessitating the use of sparse operators. However, current sparse matrix multiplication tools, including state-of-the-art sparse-aware compilers like SparTa [52] and Flash-LLM [45], as well as libraries like cuSPARSE [30] and Spunik [33], fall short in this regard. They either support only static compilation of sparse-aware kernels or require dynamic conversion of sparse matrices into dense formats, leading to significant performance overhead, especially with the dynamic sparsity in our scenario. Additionally, the dynamic JIT compiler PIT [51], though efficient for general sparse matrix multiplication on GPUs, is not suited for CPU-GPU hybrid execution where CPU computational capabilities are limited. Neuron-aware Operators for GPU: Despite vector-vector calculations being less efficient than matrix-vector calculations on GPUs, neuron-aware operators based on vector-vector computation are advantageous when the batch size is small. They avoid unnecessary computations and memory operations associated with inactive neurons and do not need costly matrix conversions. Furthermore, these operators allow all thread blocks to concurrently check neuron activations and compute corresponding vectors if activated. Neuron-aware Operators for CPU: Neuron-aware operators are particularly beneficial for CPUs, which generally have lower parallelism and matrix computation efficiency. The CPU executor assigns a neuron-aware operator to multiple cores, dividing neurons into smaller batches for concurrent activation checking. Each core processes only the activated neurons in its batch, optimizing vector-vector calculations with hardware vector extensions like AVX2, widely supported in modern CPUs. 6 Neuron Placement Policy To fully unleash the computational capability of the GPU and CPU, PowerInfer’s offline component provides a placement policy to guide the allocation of each neuron to either the GPU or CPU. This policy, output by a solver, controls neuron placement within each layer, thereby defining the runtime computational workload for the respective processing units. The solver considers a range of factors, including each neuron’s activation frequency, communication overhead, and the computational capacities of the processing units, such as their memory sizes and bandwidths. The solver defines an impact metric for each neuron to model its activation information. By integrating the neuron impacts with the capabilities of different computing units, the solver constructs an integer linear programming model to generate the optimal neuron placement. 6.1 Offline Profiling Before determining the placement of each neuron, the offline profiler of PowerInfer needs to gather runtime inference data for each neuron. To achieve this, it deploys the LLM to handle requests generated from multiple general datasets, such as C4 [32] and Wikipedia [10]. To accurately measure activation information, the profiler inserts a monitoring kernel after each block within a Transformer layer. Additionally, it builds a neuron information table on the GPU, designed to track the activation count of each neuron. This kernel checks whether each neuron in the layer gets activated during the inference process and, if so, increments the corresponding count in the neuron table. Once all requests have been processed, the profiler retrieves the activation data from this table and passes it to the solver. 6.2 Neuron Impact Metric The neuron impact metric measures each neuron’s contribution to the LLM’s overall inference outcome, crucial for GPU neuron allocation. We calculate this metric effectively by leveraging the fact that profiled activation frequency mirrors runtime behavior accurately, provided the profiling involves a substantial amount of input data. As Equation 1 shows, this metric for a neuron is defined by its activation frequency obtained during profiling. \[ v_i = f_i \quad \forall i \in \mathbb{N} \] (1) 6.3 Modeling of Neuron Placement Based on the neuron impact metric, PowerInfer utilizes a solver to optimize the total impacts of all neurons in the GPU. This cumulative impact is formulated as the objective function, as defined in Equation 2. This function is then input into an The number of neurons preloaded onto the GPU is limited by memory bandwidth. Therefore, the computation time for a neuron approximately equals the time needed to communicate overhead for a single instance of intra-layer communication. Subsequently, the solver utilizes Integer Linear Programming (ILP) to optimize the objective function, conforming to all the constraints from Equation/Inequality 3 to 8. Given that ILP problems are inherently NP-complete, directly solving them for an LLM with hundreds of billions of parameters poses a considerable computational challenge. To expedite the process and achieve an approximate solution, the primary strategy involves aggregating neurons within each layer into batches for collective placement analysis. Specifically, the solver groups 64 neurons with similar impacts from a layer into a single batch. This batching strategy dramatically reduces the total neuron count, N, from several millions to roughly tens of thousands, thereby significantly decreasing the time to solve the ILP problem to approximately 10 seconds. <table> <thead> <tr> <th>Symbol</th> <th>Type</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td>L</td> <td>Par</td> <td>All layers</td> </tr> <tr> <td>N</td> <td>Par</td> <td>All neurons</td> </tr> <tr> <td>U</td> <td>Par</td> <td>CPU and GPU</td> </tr> <tr> <td>f_i</td> <td>Par</td> <td>Activation frequency of neuron i</td> </tr> <tr> <td>N_i</td> <td>Par</td> <td>Neuron in layer i</td> </tr> <tr> <td>t_e</td> <td>Par</td> <td>Neuron impact for neuron i</td> </tr> <tr> <td>C_i</td> <td>Par</td> <td>The memory size for neuron i</td> </tr> <tr> <td>MCap_j</td> <td>Par</td> <td>The memory size for processing unit j</td> </tr> <tr> <td>Bandwidth_j</td> <td>Par</td> <td>The memory bandwidth for processing unit j</td> </tr> <tr> <td>T sync</td> <td>Par</td> <td>The time required for one synchronization between the CPU and GPU</td> </tr> <tr> <td>K</td> <td>Par</td> <td>A large positive number</td> </tr> <tr> <td>a_{in}</td> <td>Var</td> <td>Whether neuron n is placed on processing unit U</td> </tr> <tr> <td>T_{in}</td> <td>Var</td> <td>The time for computing one neuron in layer l on processing</td> </tr> <tr> <td>C_{in}</td> <td>Var</td> <td>The minimum number of neurons required to be allocated on the GPU when the solver opts to split neurons in layer l</td> </tr> <tr> <td>y_i</td> <td>Var</td> <td>Binary auxiliary variable for layer l to facilitate the modeling of conditional constraints</td> </tr> </tbody> </table> **Table 1: Terminology for ILP formulation.** The Par represents the parameters gathered from the profiler or the expressions used to define constraints, none of which need to be solved by the solver. The Var refers to the constraint and objective variables that emerge from the modeling process, which need to be solved by the solver. When maximizing the objective function, the solver also needs to consider two sets of constraints associated with the communication overhead between processing units and their hardware capabilities. ### 6.3.1 Communication Constraint The number of neurons preloaded onto the GPU is limited by the communication overhead within a layer, a constraint dictated by hardware PCIe bandwidth limitations. If too few neurons are preloaded, this overhead negates the computational benefits offered by the GPU. As a result, the solver must identify a minimum number of neurons to allocate to the GPU for processing. This ensures that neuron processing on the GPU, including synchronization time, is more efficient than CPU processing, as specified in Inequality 4. In this inequality, C_i is the minimum count of neurons that must be assigned to the GPU for layer l. When solving Inequality 4, it is essential to define both the computation time for an individual neuron in layer l and the intra-layer communication overhead, T sync. In LLM inference, especially with smaller batch sizes, the process is primarily limited by memory bandwidth. Therefore, the computation time for a neuron approximately equals the time needed to access all of its weights once, as indicated in Equation 5. With smaller batch sizes, the extent of intra-layer data transfer tends to be consistent across layers, leading to a uniform synchronization cost. Consequently, we describe T sync as the profiled overhead for a single instance of intra-layer communication. \[ C_i \cdot T_{in}^{GPU} + T_{sync} \leq C_i \cdot T_{in}^{CPU} \quad \forall i \in L \] \[ T_{in}^l = M \cdot \text{Bandwidth}_j \quad \forall j \in D, \forall i \in L \] 7 Implementation The online inference engine of PowerInfer has been implemented by incorporating an additional 4,200 lines of C++ and CUDA code into llama.cpp [14], a state-of-the-art open-source LLM inference framework designed for PCs. The extensions made by PowerInfer include modifications to the model loader for distributing an LLM across GPU and CPU, following the guidance from the offline solver’s outputs. We have also optimized the inference engine for GPU-CPU hybrid execution and introduced 10 neuron-aware operators for both processing units. All other components and functionalities of llama.cpp remain unchanged. For instance, the KV cache continues to reside in CPU memory, allowing more GPU memory for hot-activated neurons, as its access has minimal impact on inference latency, particularly in small batch sizes. Furthermore, around 400 lines of Python code were added to the transformers framework [44], enabling it to function as an offline profiler and solver for PowerInfer. The current implementation of PowerInfer supports a range of mainstream LLM families with varying parameter sizes, including the OPT [49] family (from 7B to 175B parameters), the LLaMA [42] family (7B to 70B), and Falcon-40B [2]. For these models, PowerInfer utilizes DejaVu [21] to train online activation predictors, which has been enhanced with an adaptive training method. While training an LLM is a lengthy process, often taking several hours, it is a one-time task. The duration of this process can be significantly reduced by utilizing multiple high-end GPUs. 8 Evaluation 8.1 Experimental Setup Hardware. To demonstrate the generalization of PowerInfer across various hardware setups, experiments were conducted on two distinct PC configurations, representing both high-end and low-end hardware scenarios: - **PC-High**: Equipped with an Intel i9-13900K processor (eight physical cores at 5.4GHz) and 192GB host memory (memory bandwidth of 67.2 GB/s). This configuration includes an NVIDIA RTX 4090 GPU (24G) with a memory bandwidth of 1TB/s and operates with a PCIe 4.0 interface (64GB/s bandwidth). - **PC-Low**: Features an Intel i7-12700K processor (eight physical cores at 4.9GHz), coupled with 64GB of host memory (memory bandwidth at 38.4 GB/s). It also includes an NVIDIA RTX 2080Ti GPU (11G) with a memory bandwidth of 616GB/s and utilizes PCIe 3.0 interface (32GB/s bandwidth). Models. We use a range of OPT [49] models with parameters from 6.7B to 175B, as well as Falcon(ReLU)-40B [38] and LLaMA(ReLU)-70B [39] models. Notably, the 175B parameter model is comparable in size to the GPT-3 model [5]. For our experiments, all models in our experiments use FP16 and INT4 quantized parameters, with intermediate activations in FP32, consistent with recent LLM research practices [12,47]. Workloads. The workloads for our experiments are derived from ChatGPT prompts [28] and Alpaca [41] datasets, covering a wide spectrum of language model uses. These datasets consist of input and output texts typical of real LLM services. ChatGPT prompts include user interactions with ChatGPT [31], and Alpaca features instruction sets generated by GPT3.5 through self-instruction. Baseline System. We compare PowerInfer with llama.cpp [14], a state-of-the-art local LLM inference framework. To facilitate this comparison, we extended llama.cpp to support the OPT model, as it lacks native compatibility. While other alternatives like FlexGen [37] and DejaVu [21] exist, they exhibit higher latency in the latency-sensitive scenarios discussed in this paper, as analyzed in §2.2. Therefore, llama.cpp serves as the more relevant benchmark for our evaluation. Key Metrics. As we focus on low latency setting, our primary evaluation metric is *end-to-end generation speed*, quantified as the average number of tokens generated per second (tokens/s). It is calculated by dividing the total count of generated tokens by the end-to-end response time, offering a precise measure of the response generation process’s efficiency. 8.2 End-to-End Performance Figure 10: Speedup of various models on PC-High in FP16 format. The X axis indicates the output length. The Y axis represents the speedup compared with llama.cpp. The number above each bar indicates the end-to-end generation speed (tokens/s). The first row of the figure is configured with an input length of around 64, and the second row with an input length of approximately 128. We first compare the end-to-end inference performance of PowerInfer and llama.cpp with a batch size of one, the typical setting for local deployments [6]. Given real-world dialog input/output length variability [18], we sample prompts from Alpaca and ChatGPT datasets, ranging from 8 to 128 characters. Both PowerInfer and llama.cpp generated 8, 128, and 512 tokens in response to each prompt. Figure 10 illustrates the generation speeds for various models and input-output configurations on a PC-High equipped with an NVIDIA RTX 4090. On average, PowerInfer achieves a generation speed of 8.32 tokens/s, reaching up to 16.06 to- Optimizing Large Language Models with PowerInfer **Inference with Quantization.** Figure 13 illustrates that PowerInfer effectively supports LLMs that are compressed using INT4 quantization. On a high-end PC (PC-High), PowerInfer delivers responses at an average speed of 13.20 tokens/s, reaching a peak of 29.08 tokens/s. The average speedup achieved compared with llama.cpp is 2.89×, with a maximum of 4.28×. On a lower-end setup (PC-Low), the average speedup is 5.01×, peaking at 8.00×. The reduction in memory requirements due to quantization enables PowerInfer to more efficiently manage larger models. For instance, in our experiment with the OPT-175B model on PC-High, PowerInfer nearly reaches two tokens per second, surpassing llama.cpp by a factor of 2.66×. **Batching Inference.** We also evaluate the end-to-end inference performance of PowerInfer with different batch sizes, as shown in Figure 14. PowerInfer demonstrates a significant advantage when the batch size is smaller than 32, achieving an average 6.08× improvement in performance compared with llama.cpp. As the batch size increases, the speed-up ratio offered by PowerInfer decreases. This reduction is attributed to the diminished sparsity of model joint activations. However, even with the batch size set to 32, PowerInfer still maintains a considerable speedup, achieving a 4.38× speedup. **8.3 Ablation Studies** **8.3.1 Performance Breakdown** Figure 15 breaks down the contributions of each PowerInfer component to the overall performance speedup. Using a step-by-step integration method, we progressively incorporate PowerInfer features into llama.cpp. First, we add PowerInfer’s predictors and neuron-aware operators into llama.cpp (labeled "+PO"), enabling computation of only activated neurons on both GPU and CPU. Yet, +PO still adheres to layer-wise computation, where each layer is processed entirely by either GPU or CPU. Building on +PO, we introduce PowerInfer’s hybrid infer- ence engine (denoted "+Engine"), which allows neuron-aware operators to process neurons within the same layer simultaneously on both GPU and CPU. +Engine uses a naive neuron partitioning policy that assigns frequently activated neurons to the GPU. The final step involves optimizing our integrated policy (+Policy), formulated by the offline solver as described in §6, into the +Engine setup, showcasing the full capabilities of PowerInfer. The initial integration of +PO into llama.cpp yields performance boosts of 1.98× and 2.00× for OPT-30B and OPT-66B, respectively, primarily by reducing unnecessary inactive neurons. +Engine further escalates these gains to 9.97× and 3.43×, thanks to precise neuron placement and intra-layer calculations that significantly increase the GPU’s computational share. Finally, incorporating +Policy results in improvements of 10.47× and 3.67×. The enhancement achieved by our policy lies in its ability to finely balance the intra-layer communication overhead. The naive partitioning policy in +Engine overlooks the GPU-CPU intra-layer communication, often offsetting the benefits of assigning high-frequency activation neurons to the GPU. Conversely, our policy in PowerInfer more adeptly balances processing loads and communication costs between the CPU and GPU. 8.3.2 Neuron-aware Operator Performance This section evaluates the performance of PowerInfer’s sparse operators on both CPU and GPU across various sparsity levels. We benchmark PowerInfer against leading sparse libraries: for CPU benchmarks, we use PyTorch sparse, the state-of-the-art sparse kernels within PyTorch, as our baseline. In GPU, PowerInfer is compared with PIT [51]. Given that the sparsity in LLMs is typically based on neuron granularity, our experiments are specifically designed to evaluate sparse matrices of this nature. We focus on sparse matrix-vector multiplication using a [4096, 4096] × [4096, 1] configuration, a common setup in local LLM inference [6]. To adjust sparsity, we introduce zero values to matrix rows. Figure 16 shows that PowerInfer’s operator achieves nearly linear acceleration with increasing sparsity levels, a stark contrast to dense matrix computations. On the GPU, traditional sparse operators do not outperform dense computation until sparsity surpasses 87%. However, PowerInfer’s CPU operator outperforms dense matrix multiplication even at sparsity levels below 10%. For the GPU, PowerInfer matches PIT in performance. Its primary advantage, however, is its unified CPU-GPU framework. This design allows for flexible execution of sparse operators on both processing units, unlike PIT, which is optimized solely for GPU-based sparse matrix multiplication and does not support hybrid CPU-GPU environments. 8.3.3 Predictor Overhead The execution time of the online predictors for different models is also measured, as depicted in Figure 17. On average, the execution of predictors constitutes less than 10% of the total inference time in PowerInfer. This efficiency is primarily due to the adaptive methods used in constructing sparsity predictors, which minimizes computational load. Moreover, these dense-model predictors are incorporated into PowerInfer’s solver for neuron placement decisions, with a preference for allocating them to the GPU. This strategy effectively 8.3.4 Performance Comparison with A100 In our study, we analyze the extent to which PowerInfer reduces the performance gap between a consumer-grade GPU and its top-tier server-grade counterpart. Therefore, we evaluate the generation speed of PowerInfer, deployed on PC-High, in comparison to the performance of llama.cpp and vLLM [18] executed on a single 80GB NVIDIA A100 GPU. We chose the OPT-30B and Falcon-40B models for comparison, considering their exact memory requirements matching precisely with the capacity of the A100 GPU. Our evaluation used input lengths of 1 and 64 to measure pure generation speed and conversational interactions, respectively. Figure 18a demonstrates that PowerInfer significantly narrows the performance gap between the NVIDIA 4090 and A100 in generation tasks with input length 1. On PC-High, llama.cpp lags behind vLLM on the A100 by 93% and 92% for OPT-30B and Falcon-40B, respectively, but PowerInfer reduces this to 18% and 23%. Figure 18b shows that despite reduced cumulative sparsity in the prompt phase, PowerInfer still reduces the performance gap to 28% and 29%. The remaining disparity mainly stems from the CPU’s considerable computational load, which has become a bottleneck. 8.4 LLM Accuracy Since PowerInfer selectively omits neurons predicted to be inactive, we investigated whether this approach affects the inference accuracy of LLMs. Table 2 compares the accuracy of models from the OPT, Falcon (ReLU), and LLaMA (ReGLU) families, both with and without differentiating activated/inactivated neurons, across a variety of downstream tasks. The results show that PowerInfer causes negligible loss in inference accuracy, regardless of the model size or type of task, consistent with previous research findings [21]. Although the predictors in each Transformer layer maintain an accuracy rate above 95%, they may occasionally miss some active neurons. As a result, there are minor fluctuations in LLM accuracy, leading to slight decreases or sometimes even increases in performance on specific downstream tasks. 9 Related Work **LLM Activation Sparsity:** Recent advancements like DejaVu [21], PIT [51], and brainstorm [8] are crucial to optimizing LLM inference, akin to PowerInfer. DejaVu [21] proposes enhancing inference speed through activation sparsity prediction, while PowerInfer leverages a power-law distribution in neuron activations, focusing on GPU computation of frequently activated neurons. PIT [51] accelerates GPU tasks by converting sparse to dense matrices. However, these methods, primarily exploiting GPU sparsity, face limitations in resource-constrained local environments. **LLM Weight Sparsity:** Model pruning [16, 17, 24], reducing parameter count by setting some weights to zero, is exemplified by SparseGPT [11] and Wanda [40], achieving nearly 50% unstructured sparsity. SparTA [52] leverages both sparse tensor and SIMT cores by dividing sparse matrices. Flash-LLM [45] introduces a "Load-as-Sparse and Compute-as-Dense" approach for tensor core SpMM. However, these methods, orthogonal to LLMs’ intrinsic sparse activations, usually incur accuracy losses and wall-clock model acceleration challenges [27]. This is in contrast to the natural sparse activations utilized by PowerInfer, which maintain perfor- Speculative LLM Inference: speculative inference [6, 13, 43] can also be leveraged to serve models exceeding GPU memory. Speculative decoding [7] uses a smaller, faster model to pre-decode tokens, later validated by the main model in a batch, reducing steps and CPU-GPU communication. SpecInfer [26], as another example, effectively reduces the number of LLM decoding steps and the overall communication between CPU DRAM and GPU HBM. While separate from our focus, integrating speculative inference into PowerInfer could further boost LLM inference speed. LLM-Specific Serving Optimizations: The prominence of Transformers has led to specialized serving systems [9, 36, 53]. Orca [47] introduces iteration-level scheduling. vLLM [18] implements Paged Attention for token storage. PowerInfer is a fast inference system optimized for LLMs that exploits the locality property in LLM inference. It utilizes continuous storage limit. While vLLM effectively mitigates the issue of severe GPU memory fragmentation, it does not address the challenge of deploying models on PCs where the entire model cannot fit within the available GPU memory. 10 Conclusion PowerInfer is a fast inference system optimized for LLMs that exploits the locality property in LLM inference. It utilizes adaptive predictors and neuron-aware operators for neuron activation and computational sparsity. PowerInfer achieves up to 11.69× faster LLM inference compared to systems like llama.cpp, without compromising accuracy. 11 Acknowledgments We express our sincere gratitude to to Rong Chen and Yubin Xia for their comprehensive and constructive feedback, which greatly enhanced the quality of this paper. We also thank Yifan Tan and Shuyi Lin for their valuable contributions to the experimental setups. References
{"Source-Url": "https://ipads.se.sjtu.edu.cn/_media/publications/powerinfer-20231219.pdf", "len_cl100k_base": 11049, "olmocr-version": "0.1.53", "pdf-total-pages": 15, "total-fallback-pages": 0, "total-input-tokens": 54052, "total-output-tokens": 13810, "length": "2e13", "weborganizer": {"__label__adult": 0.0006237030029296875, "__label__art_design": 0.0008463859558105469, "__label__crime_law": 0.0004737377166748047, "__label__education_jobs": 0.0008172988891601562, "__label__entertainment": 0.0002892017364501953, "__label__fashion_beauty": 0.0003292560577392578, "__label__finance_business": 0.0003323554992675781, "__label__food_dining": 0.0004589557647705078, "__label__games": 0.001361846923828125, "__label__hardware": 0.004886627197265625, "__label__health": 0.000911712646484375, "__label__history": 0.0005054473876953125, "__label__home_hobbies": 0.00013828277587890625, "__label__industrial": 0.0008349418640136719, "__label__literature": 0.0006337165832519531, "__label__politics": 0.00045180320739746094, "__label__religion": 0.0009984970092773438, "__label__science_tech": 0.411376953125, "__label__social_life": 0.0001341104507446289, "__label__software": 0.0162353515625, "__label__software_dev": 0.5556640625, "__label__sports_fitness": 0.00036787986755371094, "__label__transportation": 0.0007448196411132812, "__label__travel": 0.0002582073211669922}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 59573, 0.02914]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 59573, 0.39761]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 59573, 0.87584]], "google_gemma-3-12b-it_contains_pii": [[0, 4728, false], [4728, 9844, null], [9844, 13713, null], [13713, 18009, null], [18009, 22316, null], [22316, 27444, null], [27444, 33442, null], [33442, 37895, null], [37895, 42974, null], [42974, 44947, null], [44947, 48274, null], [48274, 51571, null], [51571, 57091, null], [57091, 57091, null], [57091, 59573, null]], "google_gemma-3-12b-it_is_public_document": [[0, 4728, true], [4728, 9844, null], [9844, 13713, null], [13713, 18009, null], [18009, 22316, null], [22316, 27444, null], [27444, 33442, null], [33442, 37895, null], [37895, 42974, null], [42974, 44947, null], [44947, 48274, null], [48274, 51571, null], [51571, 57091, null], [57091, 57091, null], [57091, 59573, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 59573, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 59573, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 59573, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 59573, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 59573, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 59573, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 59573, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 59573, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 59573, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 59573, null]], "pdf_page_numbers": [[0, 4728, 1], [4728, 9844, 2], [9844, 13713, 3], [13713, 18009, 4], [18009, 22316, 5], [22316, 27444, 6], [27444, 33442, 7], [33442, 37895, 8], [37895, 42974, 9], [42974, 44947, 10], [44947, 48274, 11], [48274, 51571, 12], [51571, 57091, 13], [57091, 57091, 14], [57091, 59573, 15]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 59573, 0.09091]]}
olmocr_science_pdfs
2024-12-08
2024-12-08
69d9da872c00b43f5cbc92ea57a9019bd8f6b3e5
The previous homework focused on 2D graphics (which is already quite important!). In this homework, we're going 3D. We will define shapes in 3D, project them onto the screen space, and render them. The projection is going to simulate how a camera (or our eyes) works. In particular, we will implement a pinhole camera. The light coming from an object goes through a very small hole and projects on a film (Fig. 1). To facilitate the projection, we will focus on representing 3D surfaces, instead of the full volume. Instead of supporting multiple shapes (circles, squares, etc) like last time, we will focus on a single primitive: triangle. A main reason is that triangle has a very cool property: after perspective projection to 2D, it’s still a triangle! (See Fig. 2.) Many other shapes do not have this nice property – a sphere projecting on to 2D can be an ellipse, a square projecting to the screen can become a general quadliteral. Figure 1: In this homework, we will implement 3D rendering by projecting 3D objects onto images. This is similar to a real-world camera. In particular, we will implement an ideal pinhole camera. Figure taken from Wikipedia. Figure 2: The perspective projection of a triangle. 1 Rendering a single 3D triangle (20 pts) Let’s start simple and render just a single 3D triangle. Our plan is to first project the triangle to a 2D image plane, then we can directly use the code from our previous homework to render the projected triangle. Let’s assume in the camera space, x-axis is pointing right, y-axis is pointing up, and z-axis is pointing away from the direction the camera is looking at (the z is specified this way so that we are following a right-handed coordinate system). We also assume that the image plane is located at $z = -1$ – this is where we are going to project our triangle onto. Fig. 3 shows that the perspective projection of a point $(x, y, z)$ boils down to computing the intersection between the line formed by the point and the camera origin with the image plane. The projected point $(x', y')$ is $$\begin{bmatrix} x' \\ y' \end{bmatrix} = \begin{bmatrix} -x/z \\ -y/z \end{bmatrix}.$$ (1) Furthermore, we need to define the extent of the image plane (we can’t have an image with infinite size!). Note that our image can be a rectangle (instead of a square). We define the extent of the image plane to be $[-sa, -s, -1] \times [sa, s, -1]$: $s$ is a scaling factor that controls the size of the image (it’s half of the sensor size), and $a$ is the aspect ratio ($\text{image width}$/$\text{image height}$). $s$ is related to the vertical field of view $\alpha$ of a camera: $$s = \tan\left(\frac{\alpha}{2}\right).$$ (2) Any point that lands outside of the extent of the image plane is discarded and not going to show up in our image. We call the set of points that are going to land on the image planes the view frustrum. Fig. 3 also visualizes the view frustrum. Therefore, given a triangle with 3 vertices, we will project all three of them onto the view frustrum (Eq. 1). This generates a 2D triangle which we can then render using our previous homework’s code. There are a few other complications though. Firstly, the point $(x', y')$ is in the (projected) camera space after the projection. We will need to transform it into the screen space. Recall that our screen space has x-axis pointing right with y-axis pointing down, and the extent is $[0, 0] \times [\text{width}, \text{height}]$. See Fig. 4. So we need to further convert the point $(x', y')$ from the projected camera space to image space. Looking at Fig. 4, we can see that we need to translate the origin, scale the axes, and flip the $y$ axis. We will give you the formula for the $x$-axis, and you should figure out the $y$-axis formula yourself: $$x'' = w \frac{x' + sa}{2sa},$$ where $w$ is the width of the image. The second complication is that a triangle vertex can be behind the camera i.e., $-z < 0$. In fact, even if $z$ is very close to zero, it can be still problematic: recall that in Eq. (1), we need to divide by $-z$ for the projection. When $z$ is very close to zero, the division can be unstable due to limited floating point precision. Hence, we consider all points such that $-z < z_{\text{near}}$ to be behind the camera. $z_{\text{near}}$ is usually called the near clipping plane. Dealing with triangles with only one or two vertices behind the camera, and the other in front of the camera is tricky: we will need to implement clipping (described below as a bonus). Instead, in this homework, we only require you only render the triangles where all three vertices are in front of the near plane. If even one of the vertices of a triangle is behind the near clipping plane, you should reject the triangle and not render it. We’ll use the same antialiasing scheme we used in Homework 1, i.e., a $4 \times 4$ supersampling. Implement your triangle rendering in `hw_2_1()` in `hw2.cpp`. To test your rendering, use the following commands: ```bash ./balboa -hw 2_1 -s 1 -p0 -1 -1 -3 -p1 1 1 -3 -p2 1 -1 -3 -color 0.7 0.3 0.4 -znear 1e-6 ./balboa -hw 2_1 -s 1 -p0 -1 0 -2 -p1 0 2 -4 -p2 1 -2 -5 -color 0.7 0.3 0.8 -znear 1e-6 ./balboa -hw 2_1 -s 1 -p0 2 2 -1 -p1 -1 -1 -2 -p2 2 0 -3 -color 0.3 0.8 0.2 -znear 1e-6 ./balboa -hw 2_1 -s 1 -p0 200 200 -100 -p1 1 1 -3 -p2 -2 -2 -2 -color 0.8 0.1 0.3 -znear 1e-6 ``` We provide our rendering of the first command in Fig. 6. In your submission, save the images generated by the second to fourth commands as outputs/hw_2_1_1.png outputs/hw_2_1_2.png outputs/hw_2_1_3.png We’ll compare your output with our rendering for grading. **Bonus: triangle clipping (15 pts).** In practice, instead of rejecting a triangle if one or two vertices are behind the near clipping plane, graphics pipelines would implement triangle clipping (Fig. 5). As a bonus, you will implement the clipping of the triangles and render them correctly even when some vertices are behind the near clipping plane. To speed up the computation, clipping is also often done with the entire 3D view frustum, discarding any triangles that are outside of the screen or too far away from the camera. We don’t do it in this homework. 2 Rendering a triangle mesh (20 pts) Next, we’ll extend our previous code to handle more than one triangle. In computer graphics, we often store these triangles in a data structure called “triangle mesh” (Fig. 7). Triangle mesh is a more efficient data structure than simply storing a list of triangles since many of the triangles would share vertices in graphics (really? when will it be better and when will it not be better?). To render triangle meshes, you need to go through the face array and loop through all the triangles. An important difference, compared to the list of triangles we have in Homework 1, is to determine the depth order between all these triangles. That is, for a point inside a pixel, we need to decide which triangle is the one we actually see. The tricky part is, unlike Homework 1, it is impossible to globally sort the triangles to determine a depth order (Fig. 8). Therefore, we need to know the depth value of all the triangles overlapping with the point in the pixel. That is, given a image space point inside a projected triangle, we need to interpolate from the depth values of the three vertices. This turns out to be slightly involved mathematically (code-wise it’s actually not that much though, my implementation of the depth interpolation takes around 70 lines including lots of comments). To explain how to find the desired depth value, we need to explain what are barycentric coordinates. Any point \( p \) inside a triangle with three vertices \( p_0, p_1, p_2 \) can be expressed using linear combination of the three vertices: \[ p = b_0 p_0 + b_1 p_1 + b_2 p_2, \tag{4} \] where \( b_0 + b_1 + b_2 = 1, b_0 \geq 0, b_1 \geq 0, \) and \( b_2 \geq 0 \). Given a point \( p \), we can compute the unique coefficients... using Cramer’s rule: \[ \begin{align*} \frac{b_0}{\text{area} (p_0, p_1, p_2)} &= \frac{\text{area} (p, p_1, p_2)}{\text{area} (p_0, p_1, p_2)}, \\ \frac{b_1}{\text{area} (p_0, p_1, p_2)} &= \frac{\text{area} (p_0, p, p_2)}{\text{area} (p_0, p_1, p_2)}, \\ \frac{b_2}{\text{area} (p_0, p_1, p_2)} &= \frac{\text{area} (p_0, p_1, p)}{\text{area} (p_0, p_1, p_2)}. \end{align*} \] (5) To get the area of a triangle, you can use the length of the cross product between two of the edge vectors, which will give you the area of the parallelogram, you can then divide the parallelogram area by two. This works also for 2D triangles, you only need to pretend the 2D triangle is on a 3D plane (e.g., \(z = 0\)). As illustrated in Fig. 9, our goal is, given an image plane point \(p’\) and a triangle with three vertices \(p_0\), \(p_1\), and \(p_2\), figure out the \(z\) coordinate of the corresponding point \(p\). We want to use barycentric coordinates to help us. So we need to figure out what \(b_0\), \(b_1\), and \(b_2\) are, so that we can interpolate the \(z\) coordinates from \(p_0\), \(p_1\), and \(p_2\). Unfortunately, we cannot directly use Eq. (5), since we don’t know \(p\) (otherwise we would have known the answer already!). What we do know are the original vertices \(p_0\), \(p_1\), and \(p_2\), projected vertices \(p_0’\), \(p_1’\), and \(p_2’\), and our image plane point \(p’\). Furthermore, we know that \(p\) projects to \(p’\) and \(p_i\) projects to \(p_i’\). Given the projected vertices and the image plane point, we can compute the projected barycentric coordinates \(b_0’\), \(b_1’\), \(b_2’\) using Eq. (5). We want to relate the projected barycentric coordinates with the original ones. Since \(p\) projects to \(p’\), we know that \[ p’ = \left( \frac{p.x}{p.z}, \frac{p.y}{p.z}, -1 \right) = -\frac{p}{p.z}. \] (6) Plugging in \(p = b_0p_0 + b_1p_1 + b_2p_2\) and \(p.z = b_0p_{0.z} + b_1p_{1.z} + b_2p_{2.z}\): \[ p’ = -\frac{b_0p_0 + b_1p_1 + b_2p_2}{b_0p_{0.z} + b_1p_{1.z} + b_2p_{2.z}}. \] (7) Next, we know that \(p_0\) projects to \(p_0’\), \(p_1\) projects to \(p_1’\), and \(p_2\) projects to \(p_2’\): \[ \begin{align*} -(p_0.z)(p_0’) &= p_0 \\ -(p_1.z)(p_1’) &= p_1 \\ -(p_2.z)(p_2’) &= p_2. \end{align*} \] (8) Plugging in, we get \[ p’ = \frac{b_0(p_{0.z})p_0’ + b_1(p_{1.z})p_1’ + b_2(p_{2.z})p_2’}{b_0p_{0.z} + b_1p_{1.z} + b_2p_{2.z}}. \] (9) Figure 7: A triangle mesh contains a list of vertices (3D positions) and a list of faces (3 integers pointing towards the index of the vertices). The figure shows a case of a triangle mesh with 4 vertices and 4 faces/triangles. The first face represents the triangle on the right side, the second face represents the triangle at the back, the third face represents the triangle on the left, and the last face represents the triangle at the bottom. Compare the above with: \[ \mathbf{p}' = b'_0 \mathbf{p}_0 + b'_1 \mathbf{p}_1 + b'_2 \mathbf{p}_2. \] (10) using the uniqueness of barycentric coordinates, we have: \[ \begin{align*} b'_0 &= \frac{b_0 \mathbf{p}_0 \cdot \mathbf{z}}{b_0 \mathbf{p}_0 \cdot \mathbf{z} + b_1 \mathbf{p}_1 \cdot \mathbf{z} + b_2 \mathbf{p}_2 \cdot \mathbf{z}} \\ b'_1 &= \frac{b_1 \mathbf{p}_1 \cdot \mathbf{z}}{b_0 \mathbf{p}_0 \cdot \mathbf{z} + b_1 \mathbf{p}_1 \cdot \mathbf{z} + b_2 \mathbf{p}_2 \cdot \mathbf{z}} \\ b'_2 &= \frac{b_2 \mathbf{p}_2 \cdot \mathbf{z}}{b_0 \mathbf{p}_0 \cdot \mathbf{z} + b_1 \mathbf{p}_1 \cdot \mathbf{z} + b_2 \mathbf{p}_2 \cdot \mathbf{z}}. \end{align*} \] (11) We are almost there: we now want to express \( b_0, b_1, \) and \( b_2 \) using \( b'_0, b'_1, \) and \( b'_2. \) Let \( B = b_0 \mathbf{p}_0 \cdot \mathbf{z} + b_1 \mathbf{p}_1 \cdot \mathbf{z} + b_2 \mathbf{p}_2 \cdot \mathbf{z}, \) we have: \[ \begin{align*} b_0 &= \frac{b'_0 B}{\mathbf{p}_0 \cdot \mathbf{z}} \\ b_1 &= \frac{b'_1 B}{\mathbf{p}_1 \cdot \mathbf{z}} \\ b_2 &= \frac{b'_2 B}{\mathbf{p}_2 \cdot \mathbf{z}}. \end{align*} \] (12) Furthermore, we know that \( b_0 + b_1 + b_2 = 1, \) so: \[ B = \frac{1}{\frac{b'_0}{\mathbf{p}_0 \cdot \mathbf{z}} + \frac{b'_1}{\mathbf{p}_1 \cdot \mathbf{z}} + \frac{b'_2}{\mathbf{p}_2 \cdot \mathbf{z}}}. \] (13) Rewriting Eq. (11) using the equation above, we have: \[ \begin{align*} \frac{b_1}{p_{0.z}} + \frac{b_2}{p_{1.z}} + \frac{b_2}{p_{2.z}} &= b_0 \\ \frac{b_1}{p_{0.z}} + \frac{b_1}{p_{1.z}} &= b_1. \\ \frac{b_1}{p_{0.z}} + \frac{b_1}{p_{1.z}} &= b_2. \end{align*} \] (14) The equation above has an intuitive meaning: the original barycentric coordinates can be obtained by the projected barycentric coordinate weighted by inverse depth. We will use these equations again later in the homework. Having the barycentric coordinates, we can finally get the desired depth: \[ p.z = b_0p_{0.z} + b_1p_{1.z} + b_2p_{2.z}. \] (15) To recap: given an image plane point and a triangle, we first convert it from screen space to camera space (using the inverse of Eq. (3), recall Fig. 4). Then, we compute the projected barycentric coordinates for each triangle using Eq. (5). Using the projected barycentric coordinates and the depth at the three vertices, we convert them to the original barycentric coordinates using Eq. (14). Finally, we obtain the depth using Eq. (15) and use the depth to pick the triangle that is the closest to the pixel sample, but in front of the clipping plane. One final detail, remember we discussed two variants for rendering multiple objects in a scene? The depth testing makes the two variants differ more. For the ray tracing style (i.e., for each pixel, check all triangles), you need to maintain a minimal \( z \) value when traversing all the triangles. For the rasterization style (i.e., for each triangle, check all pixels), you need to maintain a whole image of \( z \) values, and this is usually called the Z-buffer. # For each pixel, check all triangles for each pixel: \( z_{\text{min}} = \infty \) for each triangle: # check if the pixel center hits the triangle # overwrite color and \( z_{\text{min}} \) if the triangle is closer Figure 9: Given a point on image plane $p'$, and a triangle with three vertices $p_0$, $p_1$, $p_2$, we want to know the depth, i.e., the $z$ coordinate at the corresponding point $p$. ```cpp # For each triangle, check all pixels Z_buffer = Image(w, h) for each triangle: # project the triangle for each pixel: # check if the pixel center hits the triangle # overwrite color and Z_buffer[pixel] if the triangle is closer ``` We will discuss the pros and cons of the two approaches in depth in the lectures. Now you should be ready to implement the rendering of a triangle mesh! In this part, to specify the color of the triangles, in our triangle mesh, we further store a color per triangle. Our `TriangleMesh` data structure looks like this: ```cpp struct TriangleMesh { std::vector<Vector3> vertices; // 3D positions of the vertices std::vector<Vector3i> faces; // indices of the triangles std::vector<Vector3> face_colors; // per-face color of the mesh, only used in HW 2.2 std::vector<Vector3> vertex_colors; // per-vertex color of the mesh, used in HW 2.3 and later Matrix4x4 model_matrix; // used in HW 2.4 }; ``` `faces` and `face_colors` will always be the same length. Go implement your triangle mesh rendering code in `hw_2_2`. To test your implementation, use the command ``` ./balboa -hw 2_2 -s 1 -znear 1e-6 -scene_id 0 ./balboa -hw 2_2 -s 1.5 -znear 1e-6 -scene_id 1 ./balboa -hw 2_2 -s 0.4 -znear 1e-6 -scene_id 2 ./balboa -hw 2_2 -s 0.5 -znear 1e-6 -scene_id 3 ``` where `[scene_id]` is the scene you want to render (0-3). Our rendering for `scene_id 0` is in Fig. 10. In your submission, save your rendering of `scene_id=1-3` as - outputs/hw_2_2_1.png - outputs/hw_2_2_2.png - outputs/hw_2_2_3.png We’ll compare your output with our rendering for grading. **Bonus: occlusion culling (20 pts).** During rasterization-style rendering, if we can prove that a triangle is completely blocked by some other triangles (using the current Z buffer), we can completely skip the rendering of the triangle to speed up our rendering. This is called occlusion culling or Z-culling. Read the paper *Hierarchical Z-Buffer Visibility* from Greene et al. and implement occlusion culling using a hierarchical Z buffer. Our test scenes do not have heavy occlusion, so you will need to design your own scenes to show the speedup. ### 3 Perspective-corrected interpolation (20 pts) So far, we have been rendering constant color triangles. It’s time to make things more colorful. Instead of specifying *face colors*, we’ll specify *vertex colors*, and interpolate them using barycentric coordinates. It might be tempting to use the projected barycentric coordinates \((b'_0, b'_1, \text{ and } b'_2)\) to interpolate the vertex colors, but this is incorrect: our triangle would be changing color based on the vertex depth if we do this (try it!). Instead, we want to interpolate using the original barycentric coordinates \(b_0, b_1, \text{ and } b_2\). Fortunately, we already know how to get them using Eq. (14)! After computing the original barycentric coordinates, we’ll just interpolate the vertex colors \(C_0, C_1, C_2\) defined at the triangle vertices: \[ C = b_0 C_0 + b_1 C_1 + b_2 C_2. \] This is what people mean if they say they are doing *perspective-corrected interpolation* in a renderer. That’s all you need to know to implement vertex color rendering! (I hope it’s easier than the previous two.) Go and implement it in `hw_2_3`. Test it using - `./balboa -hw 2_3 -s 1 -znear 1e-6 -scene_id 0` - `./balboa -hw 2_3 -s 1.5 -znear 1e-6 -scene_id 1` - `./balboa -hw 2_3 -s 0.4 -znear 1e-6 -scene_id 2` - `./balboa -hw 2_3 -s 0.5 -znear 1e-6 -scene_id 3` As usual, our rendering for *scene_id 0* is in Fig. 11. 4 3D transformation (20 pts) So far we have assumed that everything is in the camera space and camera is always located at (0, 0, 0) facing negative z with up vector y. Let’s add some transformations so that things are less restricted. Remember that in the 2D case in Homework 1, we use a 3 × 3 matrix to represent affine transformations. Here, we will use a 4 × 4 matrix. Like in 2D, we will support scaling, translation, and rotation (shearing is also possible, but we want to save you some typing). Furthermore, we will support two kinds of new transformations: lookAt transform and perspective transform that we will talk about soon. The perspective transform implementation is optional, but implementing it might help understand parts of the next homework. Before we explain the 3D transformations, we need to explain our spaces in 3D. Previously in 2D, we only had object space and screen space. The existence of the camera makes things slightly more complicated: the camera lives in the camera space (the coordinate system in the previous parts), and the matrices now transform the objects into world space. As a convention, we usually call the object-to-world transformation the model matrix M, the world-to-camera transformation the view matrix V, the camera-to-screen transformation the projection matrix P (yes, we can express the projection as a matrix! more on this later). Given a vertex v on a 3D triangle mesh, we can chain the transformations to project it onto the screen space: v′ = PVMv (unfortunately, the combined matrix PVM is usually called the “MVP” matrix). Fig. 12 illustrates this. **Scaling and translation.** Scaling and translations are basically the same as in 2D: \[ \begin{bmatrix} x' \\ y' \\ z' \\ 1 \end{bmatrix} = \begin{bmatrix} s_x & 0 & 0 & 0 \\ 0 & s_y & 0 & 0 \\ 0 & 0 & s_z & 0 \\ 0 & 0 & 0 & 1 \end{bmatrix} \begin{bmatrix} x \\ y \\ z \\ 1 \end{bmatrix} \] (17) \[ \begin{bmatrix} x' \\ y' \\ z' \\ 1 \end{bmatrix} = \begin{bmatrix} 1 & 0 & 0 & t_x \\ 0 & 1 & 0 & t_y \\ 0 & 0 & 1 & t_z \\ 0 & 0 & 0 & 1 \end{bmatrix} \begin{bmatrix} x \\ y \\ z \\ 1 \end{bmatrix} \] (18) **Rotation.** Rotation in 3D is a lot more complicated. Unlike 2D, which we pretty much only have two ways to rotate (clockwise or counterclockwise), in 3D there are infinitely many ways to rotate. We will talk about a lot of them in the lectures, but for this homework we will focus on rotating over a given axis \(\mathbf{a}\) by \(\theta\) degree. This is usually called an Axis/Angle representation of rotation. The following derivation is taken from the book Physically-based Rendering: From Theory to Implementation, which is based on the famous Rodrigues’ rotation formula. Also see this excellent article from Max Slater if you want to read more. ![Figure 13: To rotate a vector \(\mathbf{v}\) about an axis \(\mathbf{a}\), we construct a plane with normal \(\mathbf{a}\) with coordinate basis \(\mathbf{v}_1\) and \(\mathbf{v}_2\). The rotation can then be expressed as \(\mathbf{v}' = \mathbf{v}_c + \cos \theta \mathbf{v}_1 + \sin \theta \mathbf{v}_2\).](image) Our idea is to construct a coordinate system around the axis \(\mathbf{a}\), then apply trigonometric identities in the 2D rotation plane. Instead of directly constructing the rotation matrix, it’s easier to first derive what happens after we rotate a vector \(\mathbf{v}\). Fig. 13 illustrates the geometry: we first project the vector \(\mathbf{v}\) to axis \(\mathbf{a}\): \[ \mathbf{v}_c = (\mathbf{v} \cdot \mathbf{a}) \mathbf{a}. \] (19) Next, we want to construct a coordinate system at \(\mathbf{v}_c\). We choose the first axis to be: \[ \mathbf{v}_1 = \mathbf{v} - \mathbf{v}_c. \] (20) The next axis \(\mathbf{v}_2\) needs to be perpendicular to \(\mathbf{v}_1\), so: \[ \mathbf{v}_2 = \mathbf{a} \times \mathbf{v}_1. \] (21) With some trigonometry, we can then derive the rotated vector \(\mathbf{v}'\): \[ \mathbf{v}' = \mathbf{v}_c + \cos \theta \mathbf{v}_1 + \sin \theta \mathbf{v}_2. \] (22) (Note that our formulas are slightly different from the textbook above, since we use a right-handed coordinate system instead of a left-handed one.) We can do a quick sanity test: let \(\mathbf{a}\) be the \(z\) axis. We have \(\mathbf{v}_c = (0, 0, \mathbf{v}.z)\), \(\mathbf{v}_1 = (\mathbf{v}.x, \mathbf{v}.y, 0)\), and \(\mathbf{v}_2 = (-\mathbf{v}.y, \mathbf{v}.x, 0)\). Thus \(\mathbf{v}' = (\cos \theta \mathbf{v}.x - \sin \theta \mathbf{v}.y, \cos \theta \mathbf{v}.x + \sin \theta \mathbf{v}.y, \mathbf{v}.z)\). We’ve recovered the standard 2D rotation. 11 To obtain the rotation matrix, we can plug in $v = (1, 0, 0)$ to get the first column of the matrix, $v = (0, 1, 0)$ to get the second column, and $v = (0, 0, 1)$ to get the third column. Specifically, the first column of the $4 \times 4$ rotation matrix $R$ is given by: $$ \begin{bmatrix} a.xa.x + (1 - a.xa.x) \cos \theta \\ a.xa.y(1 - \cos \theta) + a.z \sin \theta \\ a.xa.z(1 - \cos \theta) - a.y \sin \theta \\ 0 \end{bmatrix}. $$ (23) The second column is $$ \begin{bmatrix} a.ya.x(1 - \cos \theta) - a.z \sin \theta \\ a.ya.y + (1 - a.ya.y) \cos \theta \\ a.ya.z(1 - \cos \theta) + a.x \sin \theta \\ 0 \end{bmatrix}. $$ (24) The third column is $$ \begin{bmatrix} a.za.a.x(1 - \cos \theta) + a.y \sin \theta \\ a.za.a.y(1 - \cos \theta) - a.x \sin \theta \\ a.za.a.z + (1 - a.za.a.z) \cos \theta \\ 0 \end{bmatrix}. $$ (25) \begin{figure}[h] \centering \includegraphics[width=\textwidth]{lookat-diagram.png} \caption{The LookAt transform maps a coordinate frame based on the parameters position, target, and up. $-z$ axis is mapped to the direction of target - position, $x$ axis is mapped to the cross product of direction and up, and $y$ axis is mapped to the cross product of right and direction.} \end{figure} **LookAt.** The LookAt transform is useful for positioning cameras. The LookAt transform takes 2 3D points and a 3D vector as parameters: the position of the object $p$, the target the object is looking at $t$, and the up vector $u$ that describe the orientation of the object. Fig. 14 illustrates the geometry. Given the input, we first compute where the camera should be facing using $p$ and $t$: $$d = \text{normalize}(t - p).$$ (26) Given the direction $d$, we can then compute the right vector $r$ using cross product with the given up vector $u$: $$r = \text{normalize}(d \times u).$$ (27) We are not done yet though. Since the up vector $u$ is not necessarily perpendicular to the camera direction $d$, we do not have an orthonormal basis yet. Thus we recompute the up vector using the cross product between the right vector and the camera direction: $$u' = r \times d.$$ (28) Given these information, we can build our transformation matrix: $$L = \begin{bmatrix} r.x & u'.x & -d.x & p.x \\ r.y & u'.y & -d.y & p.y \\ r.z & u'.z & -d.z & p.z \\ 0 & 0 & 0 & 1 \end{bmatrix}.$$ (29) The first column sends $x$ axis ($(1,0,0)$) to $\mathbf{r}$, the second column sends $y$ axis ($(0,1,0)$) to $\mathbf{u}'$, the third column sends $z$ axis to $\mathbf{d}$, and the last column translates the coordinate systems by $\mathbf{p}$. Note that when applied to cameras, the matrix $L$ is designed to transform from camera space to world space. When constructing the view matrix (Fig. 12), we need to go from world space to the camera space. **Perspective projection.** Now we are at the coolest part. It turns out that with some math tricks, we can turn the perspective projection we did in the first part (Fig. 3) into a matrix multiplication as well! The trick is to introduce something called the homogeneous coordinates. The idea is to make use of the 4th component of the vector. So far, we always assumed that the 4th component to be either 1 or 0 (when it's 0, it's a vector instead of a point). From now on, our vectors can have arbitrary 4th component: $$\begin{bmatrix} x \\ y \\ z \\ w \end{bmatrix}.$$ (30) The clever part is how we obtain the 3D vector from the 4D vector above: we define everything to be equivalent up to an arbitrary non-zero scaling: $$\begin{bmatrix} x \\ y \\ z \\ w \end{bmatrix} \equiv \begin{bmatrix} x/w \\ y/w \\ z/w \\ 1 \end{bmatrix}. \quad (31)$$ Following this definition, we can implement Eq. (1) using the following matrix multiplication: $$\begin{bmatrix} x' \\ y' \\ z' \\ w' \end{bmatrix} = \begin{bmatrix} 1 & 0 & 0 & 0 \\ 0 & 1 & 0 & 0 \\ 0 & 0 & 0 & 1 \\ 0 & 0 & -1 & 0 \end{bmatrix} \begin{bmatrix} x \\ y \\ z \\ w \end{bmatrix}. \quad (32)$$ Notice that $$\begin{bmatrix} x' \\ y' \\ z' \\ w' \end{bmatrix} = \begin{bmatrix} x \\ y \\ z \\ -1/z \end{bmatrix} = \begin{bmatrix} -x \\ y \\ -z \\ 1 \end{bmatrix}. \quad (33)$$ A bonus we get is that the new $z'$ component becomes the reciprocal of $-z$: we can directly use it for getting the barycentric coordinates (Eq. (14))! Remember that the projection above only projects within the camera space. We need to further convert to screen space (Eq. (3)). I’ll let you figure out how the matrix should look like! Now you should have everything you need to complete this homework. Like Homework 1, we will describe the camera transformation and the meshes in a JSON scene file. A scene file would look like this: ```json { "camera": { "resolution": [640, 480], "transform": [ { "lookat": { "position": [0,1,0], "target": [0,0,-5], "up": [0,1,0] } } ] } } ``` Instead of directly specifying the vertices/faces in the JSON file, we can also use the Stanford PLY format: ```json { "camera": { "resolution": [640, 480], "transform": [ { "lookat": { "rotate": [45, 1, 1, 1] } ] } } ``` The PLY file is human readable (when in the “ascii” mode) and looks like this: ``` ply format ascii 1.0 comment Created by Blender 3.4.1 - www.blender.org element vertex 4 property float x property float y property float z property float red property float green property float blue element face 4 property list uchar uint vertex_indices element face 4 ``` The scene will be parsed into the following scene data structure: ```c struct Camera { Matrix4x4 cam_to_world; Vector2i resolution; Real s; Real z_near; }; struct Scene { ``` Camera camera; Vector3 background; std::vector<TriangleMesh> meshes; }; Like in Homework 1, your first task is to implement the transformations in parse_transformation in hw2_scenes.cpp. Next, you’ll render the parsed scene in hw_2_4 in hw2.cpp. **Important**: the transform in the camera describes the transformation from camera to world, and that’s what we store in Camera::cam_to_world. The “view matrix” in Fig. 12 is the inverse of cam_to_world. To test your rendering, use the following commands: ``` ./balboa -hw 2_4 ../scenes/two_shapes.json ./balboa -hw 2_4 ../scenes/tetrahedron.json ./balboa -hw 2_4 ../scenes/cube.json ./balboa -hw 2_4 ../scenes/prism.json ./balboa -hw 2_4 ../scenes/teapot.json ``` Our renderings of the two_shapes and tetrahedron scenes are shown in Fig. 15. ![Image](image1.png) Figure 15: Reference renderings for homework 2.4. Save your outputs for the scenes above as following. ``` outputs/hw_2_4_cube.png outputs/hw_2_4_prism.png outputs/hw_2_4_teapot.png ``` Note that the last teapot scene contains 1570 triangles, so it might take a bit of time to render it (it took 30 seconds in my implementation). By the way, the teapot is the famous Utah teapot made by Martin Newell when doing his Ph.D. at Utah in the early days of computer graphics. **Bonus (15 pts)**. Like Homework 1, generate an animation by interpolating between transformations. To interpolate between rotations, read the article from Max Slater. Feel free to modify any part of the code in balboa. You can use ffmpeg to convert a sequence of images into a video file. 5 Design your own scenes (20 pts) As usual, design a scene yourself and submit the scene and your rendering to us. We will give extra credits to people who impress us. Feel free to download 3D model files on the internet (please credit the authors and let us know where you downloaded it). Note that our
{"Source-Url": "https://cseweb.ucsd.edu/~tzli/cse167/fa2023/homework2.pdf", "len_cl100k_base": 9269, "olmocr-version": "0.1.53", "pdf-total-pages": 16, "total-fallback-pages": 0, "total-input-tokens": 47713, "total-output-tokens": 10422, "length": "2e13", "weborganizer": {"__label__adult": 0.0006422996520996094, "__label__art_design": 0.0087890625, "__label__crime_law": 0.0004870891571044922, "__label__education_jobs": 0.0097503662109375, "__label__entertainment": 0.000270843505859375, "__label__fashion_beauty": 0.0003724098205566406, "__label__finance_business": 0.0002789497375488281, "__label__food_dining": 0.00070953369140625, "__label__games": 0.00165557861328125, "__label__hardware": 0.004642486572265625, "__label__health": 0.0007042884826660156, "__label__history": 0.0011186599731445312, "__label__home_hobbies": 0.0004429817199707031, "__label__industrial": 0.00147247314453125, "__label__literature": 0.0006089210510253906, "__label__politics": 0.0003886222839355469, "__label__religion": 0.00124359130859375, "__label__science_tech": 0.240234375, "__label__social_life": 0.00020182132720947263, "__label__software": 0.017547607421875, "__label__software_dev": 0.7060546875, "__label__sports_fitness": 0.0004813671112060547, "__label__transportation": 0.0012083053588867188, "__label__travel": 0.0005178451538085938}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 30246, 0.06948]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 30246, 0.43972]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 30246, 0.79929]], "google_gemma-3-12b-it_contains_pii": [[0, 1217, false], [1217, 3599, null], [3599, 6072, null], [6072, 7978, null], [7978, 10385, null], [10385, 12183, null], [12183, 14079, null], [14079, 15718, null], [15718, 17864, null], [17864, 19476, null], [19476, 22463, null], [22463, 24861, null], [24861, 27545, null], [27545, 27805, null], [27805, 28357, null], [28357, 30246, null]], "google_gemma-3-12b-it_is_public_document": [[0, 1217, true], [1217, 3599, null], [3599, 6072, null], [6072, 7978, null], [7978, 10385, null], [10385, 12183, null], [12183, 14079, null], [14079, 15718, null], [15718, 17864, null], [17864, 19476, null], [19476, 22463, null], [22463, 24861, null], [24861, 27545, null], [27545, 27805, null], [27805, 28357, null], [28357, 30246, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, false], [5000, 30246, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 30246, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 30246, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 30246, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, true], [5000, 30246, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 30246, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 30246, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 30246, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 30246, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 30246, null]], "pdf_page_numbers": [[0, 1217, 1], [1217, 3599, 2], [3599, 6072, 3], [6072, 7978, 4], [7978, 10385, 5], [10385, 12183, 6], [12183, 14079, 7], [14079, 15718, 8], [15718, 17864, 9], [17864, 19476, 10], [19476, 22463, 11], [22463, 24861, 12], [24861, 27545, 13], [27545, 27805, 14], [27805, 28357, 15], [28357, 30246, 16]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 30246, 0.0]]}
olmocr_science_pdfs
2024-12-11
2024-12-11
925b9860ced8ddf684608017616f0ace2e07fd5e
On the Semantics of tpf-qs towards Publishing and Querying RDF Streams at Web-scale Ruben Taelman\textsuperscript{a}, Riccardo Tommasini\textsuperscript{b}, Joachim Van Herwegen\textsuperscript{a}, Miel Vander Sande\textsuperscript{a}, Emanuele Della Valle\textsuperscript{b}, Ruben Verborgh\textsuperscript{a} \textsuperscript{a}Ghent University – imec – IDLab, Belgium \textsuperscript{b}Dipartimento di Elettronica, Informazione e Bioingegneria, Politecnico of Milano, Italy Abstract RDF Stream Processing (\textit{rsp}) is a rapidly evolving area of research that focuses on extensions of the Semantic Web in order to model and process Web data streams. While state-of-the-art approaches concentrate on server-side processing of RDF streams, we investigate the Triple Pattern Fragments Query Streamer (tpf-qs) method for server-side publishing of RDF streams, which moves the workload of continuous querying to clients. We formalize tpf-qs in terms of the rsp-ql reference model in order to formally compare it with existing rsp query languages. We experimentally validate that, compared to the state of the art, the server load of tpf-qs scales better with increasing numbers of concurrent clients in case of simple queries, at the cost of increased bandwidth consumption. This shows that tpf-qs is an important first step towards a viable solution for Web-scale publication and continuous processing of RDF streams. © 2018 The Authors. Published by Elsevier B.V. This is an open access article under the CC BY-NC-ND license (https://creativecommons.org/licenses/by-nc-nd/4.0/) Peer-review under responsibility of the scientific committee of the SEMANTiCS 2018 – 14th International Conference on Semantic Systems. Keywords: Linked Data; RDF stream processing; continuous querying; tpf-qs; rsp-ql; sparql 1. Introduction The problem of processing streams received a lot of attention by the Semantic Web community in the last 10 years [12]. Under the label of Stream Reasoning [10], several approaches were proposed, spanning from query answering to temporal and incremental reasoning. Among these solutions, RDF Stream Processing (\textit{rsp}) engines [6, 18, 9, 2] process unbounded sequences of non-decreasing timestamped RDF data on-the-fly. \textit{RSP} engines are designed to handle large volumes of heterogeneous data in a short time, whereas \textit{sparql} engines [17] allow querying over datasets which change never or very slowly. There exists however a range of use-cases inbetween these two extremes, where neither highly volatile streams or nearly static datasets apply. An example of such a use-case can be found in the CityBench \textit{rsp} benchmark [1]. In this case, the average number of cars that enter and exit a parking area in a given time interval is monitored. Data are produced by a sensor network deployed over the parking area where new observations are streamed out every 5 minutes. \textit{E-mail address:} ruben.taelman@ugent.be 1877-0509 © 2018 The Authors. Published by Elsevier B.V. This is an open access article under the CC BY-NC-ND license (https://creativecommons.org/licenses/by-nc-nd/4.0/) Peer-review under responsibility of the scientific committee of the SEMANTiCS 2018 – 14th International Conference on Semantic Systems. With the current state of the art, we have to either keep the server always active with an RSP engine for this slow stream, or we have to use a traditional SPARQL solution that lacks the temporal dimension. Clearly, these solutions are both sub-optimal and they suffer from scalability problems for a large number of clients that need to query the stream. This is because RSP engines have to maintain open connections with each client to push new results, whereas the high complexity of SPARQL queries can lead to low availability in SPARQL endpoints [8]. In previous work, which we further elaborate on in the next section and Section 3, we introduced Triple Pattern Fragments Query Streamer (TPF-QS) [23] to provide a different trade-off between server and client load for Web-scale querying of RDF streams. Instead of evaluating continuous queries server-side and pushing results to clients, which is the case with most of the RSP engines today, TPF-QS evaluates these queries client-side, using a low-cost data interface on the server. Now, we support this contribution by formalizing the operational semantics of TPF-QS using RSP-QL [11] (Section 4). This enables us to formally compare its evaluation with other RSP engines (Section 5). After that, we extensively evaluate TPF-QS using CityBench [1] (Section 6), an RSP benchmark with real-world data. Finally, we discuss these results and its conclusions in Section 7. 2. Related Work In this section, we first present the related work on querying and publishing Linked Data, which is required for formalizing our approach. After which we present approaches for querying and publishing within the context of RDF streams that we will compare our approach to in this work. 2.1. Linked Data Querying and Publishing RDF is a data model used to represent Linked Data on the Web. The SPARQL protocol [14] enables query execution on this data using the SPARQL syntax [17]. $U$, $B$, $L$, and $V$ respectively refer to the sets of all URIs, blank nodes, literals, and variables. The basis of the RDF model is the RDF statement or RDF triple $\tau$, which is defined as $\tau \in (U \cup B) \times (U \cup V) \times (U \cup L \cup V)$. RDF triples are the basis of the RDF model; a set of RDF statements is called an RDF graph. A triple pattern $\rho$ enables pattern matching over triples, and is defined as $\rho \in (U \cup V) \times (U \cup V) \times (U \cup L \cup V)$. A set of triple patterns is called a Basic Graph Pattern (BGP), which is the basis of a SPARQL query. A SPARQL query is always targeted at a certain RDF dataset, which is defined by one default graph and zero or more named graphs. The default graph is the default active graph for pattern matching, which can be changed to any of the named graphs. The result of a SPARQL query is called a solution mapping, which is a partial function $\mu : V \mapsto U \cup B \cup L$. Research has shown that the average public SPARQL endpoint is down for more than 1.5 days each month [8]. The Triple Pattern Fragments (TPF) interface [24] was introduced as a possible solution to this availability problem, moving part of the query evaluation complexity from the server to the client. The server exposes a low-cost interface that only accepts triple pattern queries, which are simpler for the server to evaluate than full SPARQL queries. Since caching of such coarse fragments is more effective, server load can be further reduced when multiple clients execute queries. A TPF client is a client-side SPARQL engine that is able to evaluate SPARQL queries at the client by consuming data from one or more TPF interfaces. Results show that this technique significantly reduces server load, at the cost of increased query execution times and bandwidth usage [24]. The TPF-QS approach has been built on top of the TPF approach, with the aim of reducing server load in the context of RDF streams. 2.2. RDF stream Querying and Publishing RDF Stream Processing (RSP) engines are used to query RDF streams, which are unbounded sequences of data encoded in RDF. Data Stream Management Systems (DSMS) [4] and Complex Event Processing (CEP) [19] are stream processing paradigms that can categorize RSP engines. The c-sparql [6] engine (which we will refer to as c-sparql), cqels [18] and Morphstream (implementing the SPARQL-stream language [9]) are examples of DSMS systems that focus on the continuous evaluation of queries over RDF streams. Continuous querying in those systems is possible by the means of SPARQL 1.1 extensions for continuous semantics [3]. Differences in the window operator implementation, and query evaluation strategies, distinguish the operational semantics of CQELS and C-SPARQL [11]. ETALIS [2] is an RSP engine that implements the ep-sparql language and combines RDF streams processing with CEP operators. In contrast to CQELS or C-SPARQL, it has no concept of windowing, but RDF statements are annotated with two timestamps that indicate their interval of validity. By means of an extended version of SPARQL 1.0, patterns can be detected over RDF streams and more complex events can be constructed. CQELS, MorphStream, and etalIS do not address the problem of publishing RDF streams, but instead delegate it to the user. Barbieri et al. [5] use c sparql to publish streams as RDF streams by the means of a RESTful API that controls the window. TripleWave [20] is a framework for publishing RDF streams on Web. It tackles common use cases for RDF stream publishing: Conversion uses the rml mappings language [13], to annotate existing raw streams into RDF streams; Replay streams historical streams that are stored as RDF datasets. Both approaches [5, 20] describe a stream using two types of named graphs referenced using URIs according to the Linked Data Principles: (iGraphs) Instantaneous Graphs represent a content unit in the RDF stream. (sGraph) the Stream Graph contains metadata about iGraphs. 3. Background In this section, we present those background concepts required for the rest of the work. For brevity, we omit or simplify some definitions. We invite the reader to refer to the original papers for more precise and complete references. 3.1. Client-side RDF Stream Processing with TPF-QS In previous work, we introduced TPF-QS [23], which is based on the TPF framework. Within TPF-QS, RDF streams are exposed, together with static background knowledge, through the TPF interface, which enables continuous client-side processing. TPF-QS aims to close the gap between the processing of high-velocity streams and static datasets by considering slowly evolving streams with a predictable rate or historical streams. Assuming storage is cheap, these RDF streams are stored instead of streamed, so that clients can retrieve the data in a pull-based manner, which reduces publication costs since the server is not responsible for pushing data to all registered clients. All RDF statements within the stream are annotated with a time interval, which indicates for how long these statements remain valid, which must be known at insertion time. An example of such a stream can be found in Listing 1. The client-side TPF-QS engine\(^1\) accepts query registrations using regular SPARQL 1.1 syntax [17], continuously evaluates them, and streams back the results. As a first step, the engine splits the incoming query into two separate queries. Based on the stream’s metadata, one is targeted at an RDF stream and one targeted at the static background knowledge. Thereby, it can cache parts of the background knowledge that are assumed not to change over the course of the query evaluation. For example, assuming the stream from Listing 1, the query Listing 2 is split into the queries from Listings 3 and 4. Next, TPF-QS starts by evaluating the static background knowledge query, which in our example is results in the binding ex:sensor1 for ?sensor. After that, the query targeted against the stream is materialized using these bindings. For example, the query from Listing 4 would be materialized to the query from Listing 5. TPF-QS now evaluates this materialized query, and retrieves the result that has a time interval that applies to the current time. The expiration times of these time intervals determine the time at which the materialized query should be re-evaluated. The stream from Listing 1 will therefore lead to an evaluation frequency of one minute. In previous work, we have demonstrated that this technique can be used as part of a low-cost continuous sensor observation publication pipeline [21], and previous results show that this approach is able to achieve a lower server load compared to server-side RSP engines (C-SPARQL and CQELS) for an increasing number of concurrent clients for simple queries over a small dataset [23]. \(^1\) The open source engine is available under a public license: https://github.com/LinkedDataFragments/QueryStreamer.js SELECT ?temperature WHERE { ?sensor a ex:Thermometer. ?sensor sao:hasValue ?temperature. } Listing 2: Query for retrieving thermometer measurements SELECT ?temperature ?initial ?final ?sensor WHERE { _:g { ?sensor sao:hasValue ?temperature. } _:g tmp:initial ?initial; } Listing 4: Query for retrieving time-annotated sensor measurements from the stream. SELECT ?sensor WHERE { ?sensor a ex:Thermometer. } Listing 3: Query for retrieving thermometers from the static background knowledge SELECT ?temperature ?initial ?final WHERE { _:g { ex:sensor1 sao:hasValue ?temperature. } _:g tmp:initial ?initial; } Listing 5: Materialized query for retrieving time-annotated sensor measurements. 3.2. The rsp-ql rdf Stream Processing Query Model As listed in Section 2.2, several rsp engines were developed independently in the past [18, 6, 2, 9], resulting in a high variety in stream handling and query evaluation. rsp-ql [11] is a unifying model that captures the differences between dsms systems [4] such as cqels, c-sparql and sparql-stream. Rsp-ql extends rdf and sparql, adding the time semantics as initially proposed in cql [3]. A time unit is the constant difference between two consecutive time instants ($t_{i+1} - t_i$), which belong to an infinite, discrete, and ordered sequence $T$. An rdf stream $S_{rsp-ql}$ is an unbounded sequence of pairs $(\tau, t)$ where $\tau$ is an rdf statement and $t \in T$ is a time instant. $t$ denotes a partial ordering because it is non-decreasing. Querying rdf streams requires extending the concept of an rdf dataset against which a query is evaluated. An rsp-ql dataset comprises an optional default graph, zero or more named graphs, and zero or more (named) time-varying graphs, i.e., a function that maps time instants $t \in T$ to instantaneous rdf graphs. The infinite nature of streams calls for specialized operators like time-based windows, that use opening ($o$) and closing ($c$) time instants to select subset of a stream $S_{rsp-ql}$, with a window defined by the interval $(o, c)$. A time-based sliding window is defined as $W(\alpha, \beta, t^0)$, where $\alpha$ is the width of the window in time units, $\beta$ is the slide parameter that defines how often the selection happens, and $t^0$ is the time instant at which $W$ starts to operate. The present window $W_p$ is defined as the window that is present in relation to the current moment in time. A time-based sliding window $W$ takes as an input a stream $S_{rsp-ql}$ and produces a time-varying graph $G_W$. The query evaluation repeats continuously upon a potentially infinite and stream-dependent sequence of time instants $ET$. These are determined by a policy $P$ that can be a combination of one or more boolean conditions, called strategies. Content Change (CC): the window reports if the content changes; Window Close (WC): the window reports if the active window closes, i.e., when the current timestamp falls outside of the active window; Non-empty Content (NC): the window reports if the active window is not empty, i.e., if the active window contains at least one statement; Periodic (P): the window reports at regular intervals. Finally, in order to report a stream of consecutive rsp-ql query results in a certain format, three streaming operators exist. They introduce a temporal dimension in the data by timestamping the solution mappings. RStream annotates an input sequence of solution mappings with the evaluation time; IStream streams the difference between the answer of the current evaluation and the one of the previous iteration; DStream streams the part of the answer at the previous iteration that is not in the current one. 4. Semantics of tpf-qs Querying The client-side tpf-qs engine is an extension of the tpf client. Whereas tpf clients can only query static datasets, tpf-qs clients are able to use tpf interfaces to consume the rdf streams and background knowledge. In this section, we formalize its operational semantics using rsp-ql. We start by formalizing the stream publishing mechanism, followed by the client-side windowing operation. Finally, we discuss an operational example. 4.1. Stream Publication Client-side TPF-qs engines can consume RDF streams exposed through a TPF interface to (continuously) evaluate queries. Similar to a rsp-ql stream, we represent a TPF-qs stream $S_{tpf-qs}$ as an unbounded sequence of pairs $(\tau, [t_1, t_2])$: where $\tau$ is an RDF statement and $[t_1, t_2]$ a time interval [16], with time points $t_1, t_2 \in T$ and $t_1 \leq t_2$, which denotes the closed interval from $t_1$ to $t_2$. Several triple-level time-annotation strategies exist to serialize this TPF-qs stream to RDF, as described in previous work [23]. As a special case of time intervals, expiration times are defined as the last time point at which a statement is valid [23]. An RDF statement $\tau$ with expiration time $e$ is equivalent to that same statement $\tau$ with as time interval $[0, e]$. These expiration times can be used when only the last version of certain observations needs to be stored. In order to conform with the definition of an RDF stream within the RSP-QL model, we can implicitly transform any time interval $[a, b]$ to a consecutive sequence of time instants $a \ldots b$ [7]. We therefore introduce the TpfqsToRspql function to transform a TPF-qs stream to a RSP-QL stream. **Definition 1.** TpfqsToRspql$(S_{tpf-qs}) = \{ (\tau, t) \mid \exists r_1, t_2 : (\tau, [t_1, t_2]) \in S_{tpf-qs} \land t \in [t_1, t_2] \}$, with $S_{tpf-qs}$ a TPF-qs stream. Additionally, the resulting set is ordered by $\preceq$ with $(\tau_1, t_1) \prec (\tau_2, t_2)$ if $t_1 < t_2$. 4.2. Client-side Windowing Within the TPF-qs approach, streams are stored server-side, while windowing and query evaluation happens client-side. Therefore, we introduce the following definitions. **Window Start** TPF-qs allows users to optionally pick a starting time instant $i^0$ different from the current time. This aspect is unique among state-of-the-art RSP engines and enables TPF-qs to query historical streams. **Tumbling Time-based Window** The TPF-qs engine applies a time-based tumbling window with a width $\alpha$ of one time unit, such that for an opening time $o_p$ and closing time $c_p$ we always have $c_p - o_p = 1$. A window opening at $o_p$ will always be defined by the interval $(o_p, c_p]$. In this case, the resulting time-varying graph $G_{\tau}$ will therefore contain exactly one instantaneous RDF graph $G_W$, which simplifies query evaluation using a non-continuous SPARQL engine, as processing can happen atemporally. **Windowing Strategy** TPF-qs has two configurable windowing strategies that characterize its operational semantics: Periodic or Mapping Expire (ME). The latter is the default policy for the TPF-qs engine. As explained in Section 3, when working with the Periodic strategy a window reports regularly over time. In this case, TPF-qs requires its user to specify a time period $p$ that is used as the time difference between two evaluation times. The Mapping Expire strategy is specific to TPF-qs: the window reports when the validity of an RDF statement that was used in the last solution mapping expires. This new strategy is possible because of the additional validity duration metadata on RDF streams that are represented by time intervals in TPF-qs streams. In the following, we provide the formal definition of this strategy w.r.t the RSP-QL model, i.e., how it characterizes the sequence of evaluation time instants ET. To this extent, we first formalize the notions of window on a TPF-qs stream; valid time intervals of a statement; active time interval for a statement and, finally, window expiration. **Definition 2.** The window $W_t$ on stream $S_{tpf-qs}$ is the set of triples valid at time $t$: $W_t = \{ \tau \mid \exists r_1, t_2 : (\tau, [t_1, t_2]) \in S_{tpf-qs} \land t \in [t_1, t_2] \}$ **Definition 3.** The set of all time intervals of an RDF statement $\tau$ in a TPF-qs stream $S_{tpf-qs}$ is validTimeIntervals$(\tau, S_{tpf-qs}) = \{ [t_1, t_2] \mid (\tau, [t_1, t_2]) \in S_{tpf-qs} \}$. **Definition 4.** The set of all time intervals of an RDF statement $\tau$ in a TPF-qs stream $S_{tpf-qs}$ valid at time $t$ is activeTimeIntervals$(\tau, S_{tpf-qs}, t) = \{ [t_1, t_2] \mid t \in [t_1, t_2] \land [t_1, t_2] \in \text{validTimeIntervals} (\tau, S_{tpf-qs}) \}$. We can now define the expiration of a statement in a stream given a time instant. Definition 5. For \( \tau \) an \( \text{RDF} \) statement, \( S_{\text{TPF-QS}} \), a \( \text{TPF-QS} \) stream and \( t \) a timestamp, let \( A = \text{activeTimeInterval}(\tau, S_{\text{TPF-QS}}, t) \). We then define \[ \text{nextExpiration}(\tau, S_{\text{TPF-QS}}, t) = \begin{cases} \max\{t_2 \mid [t_1, t_2] \in A, \text{with the smallest possible} \ t_1 \} & \text{if} \ A \neq \emptyset \\ \bot & \text{else} \end{cases} \] This means we take the interval with the largest \( t_2 \) and smallest \( t_1 \) if there are multiple. Using these definitions we can now define the expiration time of a Basic Graph Pattern as the earliest one of the relevant triples in a window expires. Definition 6. The expiration of a Basic Graph Pattern \( \text{bgp} \) with respect to a window \( W_i \) is defined as \[ \text{windowExpiration}(W_i, \text{bgp}) = \min(\{ t_2 \mid \exists \rho, \mu, t_1 : \rho \in \text{bgp} \land \mu[\text{bgp}] \subset W_i \land \text{nextExpiration}(\mu[\rho], t, S_{\text{TPF-QS}}) = t_1 \}) \] with \( \text{bgp} \) a basic graph pattern, \( \mu \) a solution mapping for \( \text{bgp} \), \( \mu[\text{bgp}] \) and \( \mu[\rho] \) the applications of \( \mu \) to \( \text{bgp} \) and \( \rho \) respectively, and \( S_{\text{TPF-QS}} \) the stream this window is applied to. Finally, we define the set \( \text{ET} \) under the Mapping Expire strategy as the set of time instants at which time a new window will be requested by the client. Definition 7. \( \text{ET}_{\text{ME}}(\text{bgp}) = \bigcup_{t=0}^{\infty} \{ t_{i+1} \mid t_i = \text{windowExpiration}(W_i, \text{bgp}) \} \), with \( \text{bgp} \) a Basic Graph Pattern, \( t \) a timestamp and \( W_i \) the window at time \( t_i \). This set contains the timestamps at which there will be a data expiration to the given \( \text{bgp} \), that causes a new evaluation to only be done when the data of a previous window expired. Additionally, we add the initial timestamp \( t_0 \) to \( \text{ET}_{\text{ME}} \). Mapping Expire Fallback In case of the Mapping Expire strategy, when no time intervals were found for a possibly empty solution mapping, a fallback mechanism is required to determine the next reporting time. The \( \text{TPF-QS} \) engine will consider the last evaluation time, and add twice its query evaluation duration to calculate a new evaluation time. 4.3. Evaluation Time Instants Example We assume the use case where a single sensor emits observations at a fixed rate of one observation every two time units. Fig. 1a illustrates this use case: since each value is guaranteed to not change within two discrete time units after an observation, we indicate this time interval as a horizontal line with a length of one time unit on the timeline for each observation. If a query is issued for the (current) observation with the default Mapping Expire policy, the evaluation times will be every two time instants. This is because the client will be able to detect the time interval for each observation, and it will slide the next window to the expiration time of that time interval. Furthermore, the same evaluation times can be achieved by using the Periodic policy with a period of 2. If we modify our use case where observations arrive more irregularly, but each one still remains unchanged for two time instants, the evaluation times of Fig. 1b will be reached with the Mapping Expire policy. Here we can observe the fallback strategy that is used when the engine calculates an empty result set for an evaluation time as explained in Section 4.2. In this example, we assume that all query evaluations take one time unit, except for the evaluation at time 6, which takes two time units. This means that the fallback expiration time will occur after two time units, except for the expiration time applied after time 6, which will be four time units. Because of this heuristic fallback strategy, the evaluation times results in a missing observation of \( c \). 5. Comparison of Operational Semantics In this section, we compare the operational semantics of \( \text{TPF-QS} \) with \( \text{c-sparql} \), \( \text{cqels} \) and Morphstream, as they appear in \( \text{rsp-ql} \) [11]. Differences and similarities between these three approaches are discussed in the following and summarized in Table 1. As explained in Section 3, \( \text{TPF-QS} \) proposes a client-side approach for \( \text{RDF} \) stream processing that relies on \( \text{tpf} \). On the other hand, state-of-the-art \( \text{RSP} \) engines like \( \text{c-sparql} \) and \( \text{cqels} \) work server-side only, exposing APIs for continuous ### Table 1: Summary of the main differences between TPF-QS, C-SPARQL and CQELS. <table> <thead> <tr> <th>Feature</th> <th>TPF-QS</th> <th>C-SPARQL</th> <th>CQELS</th> <th>Morphstream</th> </tr> </thead> <tbody> <tr> <td>volatile rdf stream</td> <td>no</td> <td>yes</td> <td>yes</td> <td>yes</td> </tr> <tr> <td>data retrieval</td> <td>pull</td> <td>push</td> <td>push</td> <td>push</td> </tr> <tr> <td>time annotation</td> <td>time interval</td> <td>timestamp</td> <td>timestamp</td> <td>timestamp</td> </tr> <tr> <td>window parameters</td> <td>( t^0 ) or ( \overline{t^0}, \overline{\alpha}, \overline{\beta} )</td> <td>( \overline{t^0}, \alpha ) and ( \beta )</td> <td>( \overline{t^0}, \alpha ) and ( \beta )</td> <td>( \overline{t^0}, \alpha ) and ( \beta )</td> </tr> <tr> <td>rsp-ql dataset</td> <td>( G^W ) in ( G_0 )</td> <td>( G^W ) in ( G_0 )</td> <td>named ( G^W )</td> <td>( G^W ) in ( G_0 )</td> </tr> <tr> <td>window policy</td> <td>ME or P</td> <td>RStream</td> <td>IStream</td> <td>RStream, IStream and DStream</td> </tr> <tr> <td>streaming operators</td> <td>RStream</td> <td>RStream</td> <td>IStream</td> <td>RStream, IStream and DStream</td> </tr> </tbody> </table> \( \alpha \) and \( \beta \) are fixed to one time unit; \( t^0 \) is an internally defined \( t^0 \). WC=Window Close; NC=Non-empty Content; CC=Content Change. querying. C-SPARQL, CQELS and Morphstream push the results to a required client. TPF-QS instead evaluates the query directly at the client side, pulling stream portions from the server. This paradigm shift influences how RDF streams are represented: C-SPARQL, CQELS and Morphstream handle an incoming volatile RDF stream on the fly using windows; TPF-QS accesses the RDF stream – that is (possibly temporally) stored with a TPF interface – using time annotations. The user of C-SPARQL, CQELS and Morphstream can control the time dimension specifying window width \( \alpha \) and slide \( \beta \) through SPARQL 1.1 extensions with time semantics (see Section 2). TPF-QS hides the time dimension behind the TPF interface, fixing the window width \( \alpha \) and \( \beta \) to one time unit. This decision simplifies the query expression, allowing the user to write traditional SPARQL 1.1 queries. While C-SPARQL, CQELS and Morphstream internally define the start time \( t^0 \) of a window, TPF-QS optionally allows this to be set to any moment in time. Similar to C-SPARQL and Morphstream, TPF-QS adds the time-varying graph to the default graph, while CQELS enables query-level access using a named time-varying graph. The TPF-QS window policy to determine evaluation times works in two alternative modes: (a) Mapping Expire (default), where evaluation times are based on data expiration time; (b) Periodic, where the periodicity can be configured to any amount of time units. TPF-QS uses the RStream operator to report results. C-SPARQL reports on “Window Close” with RStream operator too, but it does not show empty results; CQELS uses the IStream operator and reports results on “Content Change”. Morphstream reports on “Window Close” without empty results, and allows RStream, IStream or DStream for reporting. Finally, it is worth mentioning that ETLIS/EP-SPARQL is the only RSP engine with an interval-based time semantics like TPF-QS (see Section 2). Besides this similarity, the operational semantics of the two systems are not comparable under the rsp-ql model: EP-SPARQL does not provide any windowing approach, but CEP operators; TPF-QS has no notion of events at this stage of development. 6. Evaluation In order to evaluate the performance of tpf-qs compared to other rsp engines for equivalent queries, we extended\(^2\) the rsp benchmark CityBench [1] with tpf-qs support. This allows a performance comparison of our solution with c-sparql and cqels. However, we did not compare with Morph\(^3\), as it is not supported by CityBench. We measure server load, client load, query result latency, and query completeness with an increasing number of concurrent queries. In this section, we describe the CityBench benchmark, after which we present our experimental setup, results and a discussion. 6.1. CityBench CityBench is a benchmarking suite for evaluating rsp engines based on sensor data from the city of Aarhus, Denmark. This benchmark is a good candidate, since it evaluates elements of rsp engines that are of importance in realistic real-time scenarios, like result completeness, scalability and query result latency, and it provides queries over slow streams. Result completeness is measured internally as a fraction by comparing result streams with the expected output stream for each query. Latency is measured as the difference in time between inserting an element in the stream and it appearing as a result. The original CityBench framework supports the c-sparql and cqels engines. Since these are pure server-side engines, the benchmark can run on a single server machine. In order to evaluate tpf-qs, we made three significant changes to the framework. Given that CityBench provides queries in the c-sparql and cqels query syntax, and tpf-qs only accepts sparql 1.1 queries, we created a set of sparql queries to semantically equivalent results using on the rsp-ql-based formalization from Section 4 and operational engine comparisons from Section 5, so that they result in an evaluation frequency of 10 seconds. This frequency was chosen because earlier experiments have shown that tpf-qs works best with this order of frequencies or slower. Additional details on how these queries were semantically transformed can be found in the appendix\(^3\). We selected 6 of the 12 queries as the others used sparql filter operators that are currently unsupported by the tpf-qs engine. In order to ensure the server and client load were measured independently, tpf-qs clients ran on different machines, separate from the server. All clients connected to the server through a cache, which was flushed when data changed in the dataset. We limited the amount of clients running on a single machine to the number of cores machine cores. During experiment initialization, CityBench sent queries to each client machine and monitored its results. As with the server, the load of these machines was measured for the duration of the experiment. 6.2. Experimental Setup Our experimental setup consisted of one server machine and eight client machines. The client machines were only used to run tpf-qs clients, while c-sparql and cqels only ran on the server. Our experiment was executed on compute-optimized c3.2xlarge Amazon EC2 machines, with eight High Frequency Intel Xeon E5-2680 v2 (Ivy Bridge) Processor cores and 15 GiB of memory. All experimental results together with instructions to repeat them can be found at https://github.com/LinkedDataFragments/CityBench-Amazon. We ran the experiments with the following full-factorial setup: - **Engine**: tpf-qs, c-sparql, cqels - **Query**: Q1, Q2, Q3, Q6, Q9, Q11\(^2\) - **Number of concurrent clients**: 1, 16, 32, 64 The experiments were run with a minimum duration of 15 minutes. Every five seconds, we measured server cpu, query result latency and result completeness. For tpf-qs, we also measured bandwidth and client cpu usage in order to see the effects of moving load to the client. We implemented an extension of the tpf server with quad support\(^4\) in order to expose our rdf streams using graph-based annotation with expiration times [23]. For each query, we consider three null hypotheses stating that server cpu, query result latencies and result completeness are equal across the three query engines. We tested these hypotheses for equality using the Kruskal-Wallis test, and \(^2\) Modified version of CityBench and queries: https://github.com/LinkedDataFragments/CityBench \(^3\) Appendix describing the used queries: https://zenodo.org/record/200844#.WFEMB8MrKHp \(^4\) Implementation of the extended tpf server: https://github.com/LinkedDataFragments/Server.js/tree/feature-querystreamer-support performed post-hoc analysis with the Nemenyi test for pairwise comparisons. These results of these tests are summarized in Table 2 and will be further discussed hereafter. 6.3. Concurrency Fig. 2 shows the evolution of server CPU usage for the three evaluated engines. The load in the case of TPF-QS is significantly lower or equal for 3 of the 6 queries when compared to CQELS, and for 5 of the 6 queries when compared to C-SPARQL, as validated by comparison of their means in Table 2. For the other queries, the load with TPF-QS is higher. For each query, we can therefore reject the null hypothesis that server load is equal for the three query engines. In Fig. 3 we can see the average client CPU usage for TPF-QS for all queries, which illustrates the new trade-off in server and client load with the TPF-QS approach. For most queries, we see an initial peak in client load, after which this drops to a significantly lower CPU usage for all queries except for Q2 and Q9. This initial peak corresponds to the initial query rewriting phase, which was discussed in previous work [23]. Fig. 4 shows the corresponding query result latencies for an increasing amount of concurrent queries. Table 2 confirms that these latencies are significantly lower or equal for 3 of the 6 of the queries when compared to CQELS, and for 4 of the 6 queries when compared to C-SPARQL. For each query, we reject the null hypothesis for equal latencies across the three query engines. The queries with a lower latency for TPF-QS also have a relatively low server CPU usage. For almost all queries, we can see that in the case of TPF-QS, the latencies decrease until a certain number of concurrent clients is reached, after which the latencies increase. This effect is very clear for Q6, where the latency eventually becomes higher than that of C-SPARQL. For Q9 we see a different story, where eventually C-SPARQL’s initially lower latency goes above that of the TPF-QS, which suggests that C-SPARQL does not scale well for this query. It is clear that none of the engines performs better than the others for all queries. TPF-QS outperforms C-SPARQL and CQELS for simple queries Q1 and Q3, CQELS outperforms the others for the more complex queries Q6, Q9 and Q11, and C-SPARQL is faster for the simple query Q2. Figure 2: Average server CPU usage (%) for the TPF-QS, C-SPARQL and CQELS is higher for increasing amounts of concurrent queries. Figure 3: Average client CPU usage of the TPF-QS initially peaks, and then converges to a lower value for most queries (except Q2 and Q9). Competeness Fig. 5 shows the evolution of completeness for the different queries in terms of an increasing number of concurrent clients for the three evaluated engines. When we compare our solution with CQELS, we see that for Q1, TPF-QS has a Figure 4: Average latencies (ms) for the tpf-qs, c-sparql and cqels is typically higher for an increasing amount of concurrent queries. <table> <thead> <tr> <th></th> <th>tpf-qs</th> <th>c-sparql</th> <th>cqels</th> </tr> </thead> <tbody> <tr> <td>Q1</td> <td>-28.28</td> <td>-54.57</td> <td>0.0000</td> </tr> <tr> <td>Q2</td> <td>-32.55</td> <td>-49.08</td> <td>0.0000</td> </tr> <tr> <td>Q3</td> <td>-16.60</td> <td>-41.56</td> <td>0.0000</td> </tr> <tr> <td>Q6</td> <td>60.41</td> <td>0.0000</td> <td>0.0000</td> </tr> </tbody> </table> Table 2: Difference in means for server cpu (%), latency (ms) and result completeness (fraction) for the tpf-qs with cqels and c-sparql at a frequency of 10 seconds. The *p*-value indicates the significance of his equality; values annotated with a star indicate equality with a confidence level of 95%, Combinations for which the tpf-qs performs equal or better are marked in bold. Figure 5: Completeness (fraction) for the tpf-qs, c-sparql and cqels mostly decreases for an increasing amount of concurrent queries. higher completeness due to the simplicity of the query. This is confirmed by the comparison of their means in Table 2. Compared to c-sparql, the completeness level for Q1 is equal, while for Q11 tpf-qs performs much better. For all other queries, tpf-qs has a lower completeness. For each query, we can reject the null hypothesis saying that completeness is the same across the three query engines. We observe that for all engines, the completeness decreases for an increasing number of concurrent clients, which is caused by the increase in server load. We do however see a different trend for Q2 and Q9 with tpf-qs: it appears that its initially low completeness improves with a higher number of clients. This is because of the server-side cache that is able to improve request throughput, which enables the client to download and process a larger fraction of the required data in time before it expires again. 6.5. Bandwidth Fig. 6 shows the tpf-qs bandwidth usage for all queries, in which the synchronization behaviour of the query engine with the dynamic data can be seen. Verborgh et al. [24] have shown that data transfer is the main bottleneck in the tpf approach. From this figure we can see that for all queries, our server experiences a peak in data transfer at the start of the experiment. This is caused by the initial preprocessing step that needs to be done by the client at the start of each query evaluation. We also observe a highly rhythmic pattern for all queries; the reason for this is that the client re-evaluates the query at the moment the results expire. This expiration time is data-driven, and is defined by the time-annotations on the server, which are fixed at a length of 10 seconds. The shape of each phase is highly dependent on the type of query. For example, Q1 is a smaller query than Q9 in terms triple pattern count. The amount of triple patterns has an influence on the required data transfer for the tpf client’s query evaluation due to its iterative algorithm [24]. The larger query Q9 therefore leads to a higher evaluation time. Fig. 6 also shows a period of high bandwidth usage right after the initial peak for each query. The length of these periods varies strongly with each query. This period is the time that it takes for tpf-qs to synchronize in phase with the server. It exists because the query engine requires a non-negligible amount of query evaluation time. When certain statements expire during this time, solution mappings become invalid, what will cause the fallback slide parameter to be used for the Mapping Expire strategy. Eventually, most query evaluations get into the correct phase and are synchronized with the data-driven frequency. Q2 and Q9 periodically skip phases because their query evaluation time is too high with respect to this frequency. 6.6. Discussion We assessed how the query load redistribution to clients affects our solution, and how these effects compare to alternative solutions. We observed that, for simple query types, the server load and query result latency for tpf-qs are both lower than for the alternatives, while for more complex query types the opposite is true. For one simple query, our approach achieved a higher query result completeness. For the others, the completeness was equal or lower, which is caused by the longer query evaluation times. In both cases, there is a significant bandwidth usage. On the other hand, if observations in data streams arrive at an unpredictable rate, tpf-qs is not the appropriate solution. This has been illustrated in Section 4.3 where (unexpected) time gaps between subsequent observations, cause the tpf-qs client to not be able to properly derive the next evaluation time. Results also show an increase in result latencies when a higher number of concurrent clients is reached. This is caused by the cache that is cleared every time new data is inserted into the server. Caching makes tpf requests efficient for static data, but it is more difficult to manage with data streams, which is a point of improvement for future work. These caching issues will not arise when (static) historical streams are exposed. In fact, tpf-qs is the first engine that combines the worlds of rsp and rdf archiving [15], by allowing a custom \( t^0 \) to be chosen, instead of always querying for the current time. 7. Conclusions In this paper, we formalized the operational semantics of tpf-qs, a technique that combines both server-side rdf stream publication and client-side querying, using the rsp-ql model and we formally and experimentally compared it with c-sparql and cqels. The results of our evaluation paint an interesting and nuanced story, revealing that there is a potential for lightweight streaming interfaces, even though they do not exhibit optimal behavior in all cases. TPF-QS is effective for simple queries over streams at a low and predictable frequency. Furthermore, this new trade-off in bandwidth and server load is beneficial when bandwidth is cheaper than CPU, such as low-power sensors. We can compare the trade-off in server and client effort for RSP engines by checking the distribution of their different phases in RDF stream processing [11]: stream handling, windowing of streams, and query evaluation. Typical RSP engines handle everything server-side. TripleWave on the other hand only publishes streams server-side, and requires a separate client-side engine like c-sparql to consume their streams. The TPF-QS approach, in contrast, is an all-in-one solution: it requires the server to expose the stream, while the client performs the tasks of windowing and query evaluation. This gives the client more freedom in how to evaluate queries, without being purely dependent on internal query algorithms of server-side engines. Even though our results show that TPF-QS is not able to solve all of the current RSP scalability problems, for simple queries over slow streams, our approach scales better than others for an increasing number of clients. TPF-QS is therefore a next step towards the publication and consumption for low-velocity continuous Linked Data at Web scale. In future work, we plan improvements to our query algorithm, caching strategies and fragmented data publication. Furthermore, we intend to generalize the TPF-QS approach by integrating it within the modular Comunica query platform [22]. References
{"Source-Url": "https://www.rubensworks.net/raw/publications/2018/on_the_semantics_of_tpf-qs_towards_publishing_and_querying_rdf_streams_at_web-scale.pdf", "len_cl100k_base": 10634, "olmocr-version": "0.1.42", "pdf-total-pages": 12, "total-fallback-pages": 0, "total-input-tokens": 45499, "total-output-tokens": 12657, "length": "2e13", "weborganizer": {"__label__adult": 0.0003867149353027344, "__label__art_design": 0.0006542205810546875, "__label__crime_law": 0.0005102157592773438, "__label__education_jobs": 0.0011796951293945312, "__label__entertainment": 0.00024235248565673828, "__label__fashion_beauty": 0.00024020671844482425, "__label__finance_business": 0.0006418228149414062, "__label__food_dining": 0.0004642009735107422, "__label__games": 0.0008649826049804688, "__label__hardware": 0.000912189483642578, "__label__health": 0.0007290840148925781, "__label__history": 0.0005545616149902344, "__label__home_hobbies": 0.00011718273162841796, "__label__industrial": 0.0005621910095214844, "__label__literature": 0.0007677078247070312, "__label__politics": 0.0004508495330810547, "__label__religion": 0.0006003379821777344, "__label__science_tech": 0.267822265625, "__label__social_life": 0.0001863241195678711, "__label__software": 0.04205322265625, "__label__software_dev": 0.6787109375, "__label__sports_fitness": 0.00030541419982910156, "__label__transportation": 0.0007472038269042969, "__label__travel": 0.0002961158752441406}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 47785, 0.02742]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 47785, 0.363]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 47785, 0.86594]], "google_gemma-3-12b-it_contains_pii": [[0, 3287, false], [3287, 8234, null], [8234, 12210, null], [12210, 16422, null], [16422, 20789, null], [20789, 25435, null], [25435, 28859, null], [28859, 33349, null], [33349, 36162, null], [36162, 38026, null], [38026, 41727, null], [41727, 47785, null]], "google_gemma-3-12b-it_is_public_document": [[0, 3287, true], [3287, 8234, null], [8234, 12210, null], [12210, 16422, null], [16422, 20789, null], [20789, 25435, null], [25435, 28859, null], [28859, 33349, null], [33349, 36162, null], [36162, 38026, null], [38026, 41727, null], [41727, 47785, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 47785, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 47785, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 47785, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 47785, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 47785, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 47785, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 47785, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 47785, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 47785, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 47785, null]], "pdf_page_numbers": [[0, 3287, 1], [3287, 8234, 2], [8234, 12210, 3], [12210, 16422, 4], [16422, 20789, 5], [20789, 25435, 6], [25435, 28859, 7], [28859, 33349, 8], [33349, 36162, 9], [36162, 38026, 10], [38026, 41727, 11], [41727, 47785, 12]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 47785, 0.07282]]}
olmocr_science_pdfs
2024-11-22
2024-11-22
68a087659adee06982ec1273e60f9e25b06689f1
[REMOVED]
{"Source-Url": "http://www.galaxyng.com/adrian_atanasiu/articole/trellis.pdf", "len_cl100k_base": 9631, "olmocr-version": "0.1.53", "pdf-total-pages": 10, "total-fallback-pages": 0, "total-input-tokens": 52801, "total-output-tokens": 10656, "length": "2e13", "weborganizer": {"__label__adult": 0.0005311965942382812, "__label__art_design": 0.0009684562683105468, "__label__crime_law": 0.0005908012390136719, "__label__education_jobs": 0.0016937255859375, "__label__entertainment": 0.00032258033752441406, "__label__fashion_beauty": 0.00027751922607421875, "__label__finance_business": 0.0004117488861083984, "__label__food_dining": 0.0006465911865234375, "__label__games": 0.001262664794921875, "__label__hardware": 0.0026340484619140625, "__label__health": 0.0010766983032226562, "__label__history": 0.0005292892456054688, "__label__home_hobbies": 0.00023996829986572263, "__label__industrial": 0.0011014938354492188, "__label__literature": 0.0019855499267578125, "__label__politics": 0.00045943260192871094, "__label__religion": 0.0010652542114257812, "__label__science_tech": 0.423828125, "__label__social_life": 0.00014579296112060547, "__label__software": 0.00836944580078125, "__label__software_dev": 0.55029296875, "__label__sports_fitness": 0.0003657341003417969, "__label__transportation": 0.0008563995361328125, "__label__travel": 0.00023281574249267575}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 26256, 0.03307]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 26256, 0.93312]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 26256, 0.66104]], "google_gemma-3-12b-it_contains_pii": [[0, 2109, false], [2109, 4732, null], [4732, 7591, null], [7591, 10399, null], [10399, 13208, null], [13208, 16294, null], [16294, 18679, null], [18679, 21777, null], [21777, 24514, null], [24514, 26256, null]], "google_gemma-3-12b-it_is_public_document": [[0, 2109, true], [2109, 4732, null], [4732, 7591, null], [7591, 10399, null], [10399, 13208, null], [13208, 16294, null], [16294, 18679, null], [18679, 21777, null], [21777, 24514, null], [24514, 26256, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 26256, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 26256, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 26256, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 26256, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 26256, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 26256, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 26256, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 26256, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 26256, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 26256, null]], "pdf_page_numbers": [[0, 2109, 1], [2109, 4732, 2], [4732, 7591, 3], [7591, 10399, 4], [10399, 13208, 5], [13208, 16294, 6], [16294, 18679, 7], [18679, 21777, 8], [21777, 24514, 9], [24514, 26256, 10]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 26256, 0.0]]}
olmocr_science_pdfs
2024-12-10
2024-12-10
9a641d9609c08662165b4f44ae2a68cf9dca3f38
Title Automatic translation of MPI source into a latency-tolerant, data-driven form Permalink https://escholarship.org/uc/item/8fh786n4 Journal Journal of Parallel and Distributed Computing, 106 ISSN 0743-7315 Authors Nguyen, T Cicotti, P Bylaska, E et al. Publication Date 2017-08-01 DOI 10.1016/j.jpdc.2017.02.009 Peer reviewed Automatic translation of MPI source into a latency-tolerant, data-driven form Tan Nguyen, Pietro Cicotti, Eric Bylaska, Dan Quinlan, Scott Baden Department of Computer Science and Engineering, University of California, San Diego, La Jolla, CA 92093, USA Environmental Molecular Sciences Laboratory, Pacific Northwest National Laboratory, Richland, WA 99354, USA Center for Advanced Scientific Computing, Lawrence Livermore National Laboratory, Livermore, CA 94550, USA HIGHLIGHTS - Bamboo is a translator that can reformulate MPI source into a task graph form. - Bamboo supports both point-to-point and collective communication. - Bamboo supports GPUs, hiding communication among GPUs and between hosts and GPUs. - Bamboo speeds up applications containing elaborate data and control structures. ABSTRACT Hiding communication behind useful computation is an important performance programming technique but remains an inscrutable programming exercise even for the expert. We present Bamboo, a code transformation framework that can realize communication overlap in applications written in MPI without the need to intrusively modify the source code. We reformulate MPI source into a task dependency graph representation, which partially orders the tasks, enabling the program to execute in a data-driven fashion under the control of an external runtime system. Experimental results demonstrate that Bamboo significantly reduces communication delays while requiring only modest amounts of programmer annotation for a variety of applications and platforms, including those employing co-processors and accelerators. Moreover, Bamboo’s performance meets or exceeds that of labor-intensive hand coding. The translator is more than a means of hiding communication costs automatically; it demonstrates the utility of semantic level optimization against a well-known library. 1. Introduction At present, distributed-memory systems have evolved to a sophisticated level that requires applications to be heavily optimized to harness all resources provided by the hardware. An important consideration is how to minimize communication overheads in tandem with improvements in computational rates. There are two approaches to reducing communication overheads: tolerate them [55,29,57,4,61,60,32,22,20,33,58,40,21,38,46] or avoid them [56,5,42]. It is also possible to use both approaches in the same application. In this paper, we discuss an automated translation strategy that implements the first approach. We describe a domain-specific solution that applies to MPI applications. Since MPI is the de facto standard for distributed-memory programming, our approach has a broad application space. Although MPI enables one to write communication tolerant code, it does not support the activity. For example, MPI provides immediate mode communication to express split phase algorithms [65,37,17], a common technique for masking communication overheads under computations. However, it does not assist the programmer in pipelining and scheduling computation and communication, nor how to manage a sufficiently large pool for work needed to realize overlap (e.g. processor virtualization or overdecomposition in Charm++ [34]). As a result, policy decisions affecting performance become entangled with the application, greatly affecting code development time and performance robustness. Such requirements impose a significant burden on the domain-science focused programmer who will usually defer to the expert. To address obstacles to realizing communication overlap on high-end systems, we have developed a source-to-source translation framework, called Bamboo [46,44,45]. Bamboo transforms applications written in subset of MPI into a data-driven form that overlaps communication with computation automatically. Unlike other approaches [40,15] that offer an explicit data-driven model, we use information about communication operations embedded in an MPI program to reason about the data dependencies among processes in order to improve performance. Armed with such knowledge, Bamboo can reformulate MPI source that does not overlap communication with computation into a task dependency graph representation that realizes overlap. The graph maintains a partial ordering over the execution of tasks of the graph, and the program executes in a dataflow-like fashion under the control of an external scheduler, which can overlap communication with computation automatically. The Bamboo translation framework includes a programming model and a source-to-source translator. The programmer annotates the application with program directives, which inform Bamboo’s transformations. Compared to the conventional split phase technique, these transformations not only realize overlap but also prevent policy decisions from becoming intertwined with the application. The effect is to insulate application logic from technological change, allowing the original code to continue to run correctly and to retain its familiar code structure. The Bamboo software stack comprises 2 layers: core message passing and utility layers. The core layer transforms a minimal subset of MPI point-to-point routines (Bamboo does not support MPI’s one sided communication), whereas the second translates a subset of higher level MPI functionality into equivalent point-to-point encodings, which will be then translated by the core layer. This multi-layer design allows one to customize MPI collectives, which may benefit from a specialized interconnect topology or be tailored to the application [13]. Though Bamboo supports only a subset of MPI, we have found that it can improve the performance of a wide range of applications taken from well-known application motifs on diverse platforms. We ran at scale on Edison (Cray XC30) and Hopper (Cray XE6) systems at the National Energy Research Scientific Computing Center (NERSC) and on the Stampede system at the Texas Advanced Computing Center (TACC), which has advanced node architectures based on NVIDIA’s Kepler and the Intel’s Phi. We evaluated Bamboo against basic MPI and hand optimized code variants written by an expert to overlap communication with computation. Bamboo consistently realized a significant reduction in communication delays of the basic MPI variant. We observed that performance of applications translated with Bamboo met or exceeded that of the hand optimized code variants requiring only modest amounts of user annotation. The remainder of the paper is organized as follows. Section 2 presents the Bamboo source-to-source translation framework. Section 3 discusses the design and implementation of the Bamboo source-to-source translator. Next, Section 4 presents experimental validation for various applications. Section 5 presents Bamboo support on advanced node technologies. Section 6 reviews related work. Section 7 concludes the paper and presents future work. 2. Bamboo 2.1. Motivation Scalable applications are generally written under the SPMD (Same Program Multiple Data) model, and message passing has been the preferred vehicle for over two decades. The Message Passing Interface (MPI) [43] accounts for the lion’s share of scalable application software, which may employ the two tier MPI+X programming model to unfold node level parallelism via OpenMP, CUDA or OpenCL. MPI enables the application programmer to cater optimizations that benefit performance using heuristics, in particular, involving data motion and locality. Such domain specific knowledge is difficult to capture via general-purpose language constructs and associated compilation strategies that are unaware of application and library semantics and this helps explain the persistence of MPI. The MPI software community has been prolific, building a large body of knowledge and experience for writing high quality application software and tools. This knowledge and experience holds important clues for optimizing high performance applications. This observation motivates the design of Bamboo: a custom translator tailored to the MPI interface that effectively treats the API’s members as primitives in an embedded domain specific language. Bamboo extracts data and control dependencies from the pattern of MPI call sites and constructs a task precedence graph corresponding to the partial ordering of tasks. These tasks execute according to dataflow semantics [3,23]. A dataflow model has two appealing attributes. First, it can automatically mask data motion costs and hence improve performance without programmer intervention [6,20,33,58,19,21]. Second, it simplifies code development and maintenance by separating concerns surrounding policy decisions (e.g., scheduling) from program correctness. Since static analysis is not sufficient to infer matching sends and receives in a running program [47], Bamboo requires some modest amounts of programmer annotation of the original MPI program. 2.2. The bamboo programming model To illuminate our discussions about translation under Bamboo, we will use a simple example: an iterative finite difference solver for Laplace’s equation in two dimensions (Fig. 1). The MPI implementation partitions the solution meshes across processors, introducing data dependencies among adjacent mesh elements that straddle the boundaries between subproblems assigned to different processors. To treat these data dependencies, the solver stores copies of off-processor boundary values in ghost cells. Since a conventional compiler will ignore the annotations, the code in Fig. 1 is also a legal MPI program. We next describe Bamboo’s underlying programming model and its annotations. A Bamboo program is a legal MPI program, augmented with one or more code regions called olap-regions as shown in Fig. 1. An olap-region is a section of code containing communication to be overlapped with computation. The entry into an olap-region is called an evaluation point, where a task either continues or it yields control to another task because the required input data is not yet available. Receive operations residing within an olap-region will be included in the input window corresponding to the evaluation point of the olap-region. Bamboo preserves the execution order of olap-regions, which a task runs sequentially, one after the other. However, there is no implicit barrier at the exit of an olap-region. This allows a task to exit an olap-region and continue executing until it reaches the next olap-region, which it can enter if all the inputs defined by the corresponding evaluation point and input window are ready. Within an olap-region, send and receive calls are grouped within enclosing communication blocks. All code appearing within an overlap region must be properly enclosed in a communication block, of which there are two kinds: send and receive. A send block contains Sends (MPI_Send and MPI_Isend) only. In most cases, a receive block contains Recvs (MPI_Recv and MPI_Irecv) only, except for the following situation. If a Send consumes data obtained from a prior Recv (read after write dependence), then it has to reside within an appropriate receive block, either the same block as the Recv, or a later one. Communication blocks specify a partial ordering of communication operations at the granularity of a block, including associated statements that set up arguments for the communication routines, e.g., establish a destination process. While the statements within each block are executed in order, the totality of the statements contained within all the send blocks are independent of the totality of statements contained within all the receive blocks. This partial order enables Bamboo to reorder send and receive blocks. For example, Bamboo can move all send blocks up front and outside of the \textit{olap-region}, enabling all outputs to be sent out to fulfill inputs from the current olap-region onwards. Bamboo does not reorder blocks of the same type. However, because a Bamboo program executes asynchronously, inputs can arrive in any order, as they can be buffered upon arrival and then injected into tasks in the order specified by the programmer. 3. Implementation For the sake of portability, we split the Bamboo translator into 2 software layers as shown in Fig. 2(a). The lower level layer consists of a minimal set of MPI point-to-point primitives, hence the name \textit{core message passing}. An implementation of this layer highly depends on a runtime system that executes the generated task graph program. We will present the execution model and the implementation of the runtime system in Section 3.2. On top of the core message passing layer, we implement a utility layer, which supports a substantially richer set of MPI routines, including communicator splitting and collective operations. 3.1. MPI subset Bamboo supports an important subset of MPI used in a wide range of applications: point-to-point operations (Send/Isend/Recv/Irecv/Wait/WaitAll); a variety of collectives (see Table 2); communicator splitting, MPI status, derived datatypes (\textit{struct, contiguous} and \textit{vector}). Bamboo does not support one-sided communication currently. Since Bamboo’s runtime requires that task graphs be run time static structures (Section 3.2), Bamboo does not support MPI dynamic process creation. It can, however, support dynamic adaptive meshes, which are treated successfully with dynamic process creation. However, Bamboo would not be applicable to graph algorithms, for example, that employed fine grained communication, dynamic process creation, or both. 3.2. Runtime system A Bamboo program runs as a set of tasks coupled by data dependencies. The program can over-decompose the problem, creating more tasks than the number of processing cores. The task scheduling and communication handling jobs are handled by Bamboo’s runtime system called Tarragon [20,19]. 3.2.1. Task scheduling Tasks have state, and this state is used to manage task execution. A typical Bamboo task spends most of its time circulating among the following 3 states: eXecution (X), Waiting (W) or Runnable (R) as shown in Fig. 3. A waiting task will become runnable when all inputs are ready. The collection of all inputs of a task is represented by task’s firing rule, which is visible to the runtime. Tasks are executed by workers. A runnable task will start executing when the runtime identifies an available worker. Since a task cannot execute unless it has first become runnable, there is no explicit message waiting within a task; this activity is factored out of task execution and handled via a callback made by the runtime. Additional task state variables can be defined by Bamboo. For example, we use task state to control iterative methods, folding the iteration inside the tasks. Tasks and Task Graphs are run time static entities. Thus, once instantiated, their structure, including tasks dependencies, cannot change at run time. Currently Tarragon uses Pthreads to implement workers. The runtime can be configured to have either a shared task queue among all workers or multiple private queues. The former configuration allows the workload to be easily balanced but also incurs some overhead for memory protection. 3.2.2. Communication handler As a task is running, it produces data. Tasks can register certain data with the runtime as outputs, which enable other tasks to become runnable (R) and ultimately execute (X). Tasks will not block when producing outputs. Instead, outputs will be buffered and processed by the communication handler. Data sent out from a task will not become visible at the destination until the recipient has entered the W state. When a task is in the R or X state, incoming messages are hidden by the runtime system, in the order they were received, and only be made visible when the task enters the W state again. Currently, Tarragon uses MPI to implement the communication handler. It uses non-blocking routines (MPI_Isend, MPI_Irecv, Fig. 2. The Bamboo design and implementation. Fig. 3. Except for the initial state (I) and the final state (D), a task circulates among 3 states W, R, and X. Tasks never wait for inputs and hold computing resource at the same time. In addition, tasks only receive new inputs at the W state. Table 1 An intermediate code transformation that reorders blocks of code. Left: a typical MPI input program that requires code reordering. Sends within the send block of a process match with receives within the receive block of another process in the same iteration. Right: The same code with send reordered. Note that the replicated MPI_Send calls will not pose a deadlock issue. Bamboo will reinterpret MPI calls later, allowing the generated code to work correctly. <table> <thead> <tr> <th>Before reordering</th> <th>After reordering</th> </tr> </thead> <tbody> <tr> <td></td> <td></td> </tr> <tr> <td>1 #pragma bamboo olap</td> <td></td> </tr> <tr> <td>2 for (i=1;i&lt;niters;i++)</td> <td></td> </tr> <tr> <td>3 #pragma bamboo receive</td> <td></td> </tr> <tr> <td>4 (MPI_Irecv(rbuf0 ...));</td> <td></td> </tr> <tr> <td>5 MPI_Irecv(rbuf1 ...);</td> <td></td> </tr> <tr> <td>6 #pragma bamboo send</td> <td></td> </tr> <tr> <td>7 (MPI_Send(rbuf0 ...);</td> <td></td> </tr> <tr> <td>8 MPI_Send(rbuf1 ...);</td> <td></td> </tr> <tr> <td>9 MPI_Waitall(...);</td> <td></td> </tr> <tr> <td>10 Compute block</td> <td></td> </tr> <tr> <td>11 }</td> <td></td> </tr> <tr> <td>1 1=1</td> <td></td> </tr> <tr> <td>2 if(i&lt;niters){</td> <td></td> </tr> <tr> <td>3 MPI_Send(rbuf0 ...);</td> <td></td> </tr> <tr> <td>4 MPI_Send(rbuf1 ...);</td> <td></td> </tr> <tr> <td>5 }</td> <td></td> </tr> <tr> <td>6 #pragma bamboo olap</td> <td></td> </tr> <tr> <td>7 for (i&lt;niters){</td> <td></td> </tr> <tr> <td>8 #pragma bamboo receive</td> <td></td> </tr> <tr> <td>9 (MPI_Irecv(rbuf0 ...));</td> <td></td> </tr> <tr> <td>10 MPI_Irecv(rbuf1 ...);</td> <td></td> </tr> <tr> <td>11 MPI_Waitall(...);</td> <td></td> </tr> <tr> <td>12 Compute block</td> <td></td> </tr> <tr> <td>13 i=1</td> <td></td> </tr> <tr> <td>14 if(i&lt;niters){</td> <td></td> </tr> <tr> <td>15 MPI_Send(rbuf0 ...);</td> <td></td> </tr> <tr> <td>16 MPI_Send(rbuf1 ...);</td> <td></td> </tr> <tr> <td>17 }</td> <td></td> </tr> </tbody> </table> and MPI_Test) to handle inter-process communication requests. For intra-process communication requests, outputs of a task are injected directly to the recipient. To keep the communication handler responsive to requests, the runtime can dedicate a processor core to run the handler. 3.3. Translation: core message passing layer 3.3.1. Block reordering To use Bamboo, the MPI source is annotated with olap-regions, each consisting of communication blocks, send and receive blocks, which further contain MPI function calls. Due to the way in which the generated code executes, Bamboo performs an intermediate code transformation called block reordering. Bamboo will reorder certain communication blocks in certain situations. For example, the left side of Table 1 shows a common communication pattern used in MPI applications that will be restructured by Bamboo. Specifically, Sends (in the send block) issued by a process match up with Recvs (in the receive block) of the other process encoded in the same iteration. Bamboo has to reorder the send block due to the following reason. A task is runnable only when all necessary data is available. If we place the corresponding send within the same iteration as the corresponding receive, data sent in one iteration will not be received until the next. But, the algorithm needs to receive data within the same iteration. To cope with this timing problem, Bamboo reorders the send block, advancing it in time so that the sending and receiving activities reside in different iterations. Bamboo will set up a pipeline, replicating the send block to the front of, and outside, the iteration loop. It also modifies the call to the end of the loop body, adding an appropriate guard derived from the loop iteration control logic. After reordering, the transformed code appears as shown in the right side of Table 1. The matching send and receive blocks now reside in different iterations. We next present how Bamboo reinterprets all MPI calls produced in this phase as task’s inputs and outputs. 3.3.2. MPI reinterpretation Bamboo translates MPI calls into task methods. For MPI_Comm_rank and MPI_Comm_size, Bamboo simply rewrites these routines to corresponding method invocations that return the task ID and number of tasks in the graph, since over-decomposition does not change the communication pattern. For MPI_Send and MPI_Isend, Bamboo creates a message and copies communicated data from the outgoing buffer into the data buffer of the message. Bamboo then generates a signal code notifying the communication handler of the runtime system that the output data is ready to be sent out. MPI_Recv and MPI_Irecv, however, are handled in a different way since tasks do not explicitly invoke any method to receive data from other tasks. Instead, the runtime receives and buffers incoming messages. When a task is scheduled to execute, it can pull these messages from the runtime. Bamboo uses all Recv calls within an olap-region, together with any conditional statements connected with them, to generate firing rule which decides when a task becomes executable. Details of this implementation will be discussed in Section 3.3.3. Besides using MPI_Recv and MPI_Irecv to generate firing rules, Bamboo also uses the information encoded in these routines to generate code that pulls messages from the runtime system. Specifically, messages are sorted by source, destination, and tag. Bamboo transforms this information into queries to the runtime system. Finally, for MPI_Wait and MPI_Waitall Bamboo simply removes these calls since each olap-region requires all inputs to be available before it can execute. ### 3.3.3. Firing rule and yielding rule As previously mentioned, the task state often changes from $X$ into $W$ and from $W$ to $R$. The condition that determines when the runtime can enable a transition from $W$ to $R$ is called the firing rule. Upon scheduled to execute, the task state changes from $R$ to $X$. The formula that the runtime uses to reverse the state transition from $X$ into $W$ is called the yielding rule. Bamboo extracts information from MPI receive calls and associated conditional statements to generate firing and yielding rules. Let $m$ and $C$ be, respectively, a message possibly received by an MPI process in an olap-region and the associated conditional statements. Whether a particular process should wait for message $m$ or not is subject to the evaluation of the condition $C$. Thus, the firing rule for an olap-region can be written in the conjunctive normal form. $$\bigwedge (\neg C_i \lor m_i).$$ (1) On the contrary, we express the yielding rule in disjunctive normal form, where $i$ ranges from 1 to the number of messages possibly received by a process in an olap-region and $m_i$ is true means that message $i$ has arrived. $$\bigvee (C_i \land \neg m_i).$$ (2) ### 3.3.4. Inter-procedural translation The code transformation and analysis modules of Bamboo may need to span procedure boundaries. For instance, Fig. 4 gives an example where the source codes of an olap-region and its communication blocks (i.e. send block and receive block) reside in different procedures. To generate firing and yielding rules for the olap-region, the translator needs information in the receive block. Inlining is a technique that exposes the calling context to the procedure’s body and the procedure’s side effect on the caller. Bamboo performs inlining, and the process is as follows. If a procedure directly or indirectly invokes MPI calls, Bamboo registers it as an MPI-invoking procedure. Bamboo will subsequently inline all MPI-invoking procedures from the lowest to the highest calling levels. The inlining process is transparent to the programmer and does not require any annotation. However, due to the static nature of the strategy Bamboo currently does not support recursive procedures. This requires a redesign of the graph library and run time system. ![Fig. 4. A multigrid solver with call chains containing MPI invocations.](image) **Fig. 4.** A multigrid solver with call chains containing MPI invocations. Bamboo registers procedures that directly or indirectly invoke MPI calls as an MPI-invoking procedure. It then inlines all MPI-invoking procedures from the lowest to the highest calling levels. Pulls messages from the runtime system. Specifically, messages are sorted by source, destination, and tag. Bamboo transforms this information into queries to the runtime system. Finally, for MPI_Wait and MPI_Waitall Bamboo simply removes these calls since each olap-region requires all inputs to be available before it can execute. ### 3.3.3. Firing rule and yielding rule As previously mentioned, the task state often changes from $X$ into $W$ and from $W$ to $R$. The condition that determines when the runtime can enable a transition from $W$ to $R$ is called the firing rule. Upon scheduled to execute, the task state changes from $R$ to $X$. The formula that the runtime uses to reverse the state transition from $X$ into $W$ is called the yielding rule. Bamboo extracts information from MPI receive calls and associated conditional statements to generate firing and yielding rules. Let $m$ and $C$ be, respectively, a message possibly received by an MPI process in an olap-region and the associated conditional statements. Whether a particular process should wait for message $m$ or not is subject to the evaluation of the condition $C$. Thus, the firing rule for an olap-region can be written in the conjunctive normal form. $$\bigwedge (\neg C_i \lor m_i).$$ (1) On the contrary, we express the yielding rule in disjunctive normal form, where $i$ ranges from 1 to the number of messages possibly received by a process in an olap-region and $m_i$ is true means that message $i$ has arrived. $$\bigvee (C_i \land \neg m_i).$$ (2) ### 3.3.4. Inter-procedural translation The code transformation and analysis modules of Bamboo may need to span procedure boundaries. For instance, Fig. 4 gives an example where the source codes of an olap-region and its communication blocks (i.e. send block and receive block) reside in different procedures. To generate firing and yielding rules for the olap-region, the translator needs information in the receive block. Inlining is a technique that exposes the calling context to the procedure’s body and the procedure’s side effect on the caller. Bamboo performs inlining, and the process is as follows. If a procedure directly or indirectly invokes MPI calls, Bamboo registers it as an MPI-invoking procedure. Bamboo will subsequently inline all MPI-invoking procedures from the lowest to the highest calling levels. The inlining process is transparent to the programmer and does not require any annotation. However, due to the static nature of the strategy Bamboo currently does not support recursive procedures. This requires a redesign of the graph library and run time system. MPI point-to-point primitives as follows. All MPI processes in the existing communicator exchange information of color, key, and the corresponding rank in MPI_COMM_WORLD. Eventually each process holds information of the other processes. Based on the information retrieved from others, each process filters out processes with the same color. Such processes will be sorted on key before being assigned a new rank in the new communicator. Once the new communicator has been created, a communicator name and a process rank within the communicator will be sufficient to locate the corresponding rank in MPI_COMM_WORLD. 4. Results In this section, we describe computational results with 4 applications on various platforms: NERSC’s Hopper and Edison platforms, and TACC’s Stampede platform, using nodes that include NVIDIA Kepler K20 GPUs. In order to assess the performance benefits of Bamboo, we built a set of variants for each application. The first variant, MPI-basic, is the simplest implementation that does not overlap communication with computation. All remaining variants are obtained from MPI-basic. The Bamboo variant was obtained by translating MPI-Basic with Bamboo. MPI-Olap was obtained by restructuring the application to overlap communication with computation via split phase coding. The third variant, MPI-Olap, has been manually restructured to employ split phase coding to overlap communication with computation. The fourth variant, MPI-nocomm was obtained by suppressing communication in the code, and is a loose upper bound on the potential performance benefit of overlapping communication with computation. In some applications running on CPUs, we found it advantageous to use a mixed mode model MPI+OpenMP rather than “flat” MPI. To express variants based on this approach, we use an intuitive notation e.g. MPI+OMP-nocomm is an MPI+OMP code variant in which communication has been suppressed. 4.1. Dense linear algebra Dense linear algebra is a class of computations on matrices where all elements are stored explicitly. Typically, this class of applications delivers a high fraction of peak processor performance. Thus, the overall performance will become much more sensitive to communication overheads as computing capability is expected to be substantially increasing in years to come. In this section, we evaluate Bamboo using matrix multiplication and matrix factorization, two operations commonly used as building blocks in dense linear algebra problems. 4.1.1. 2.5D Cannon’s algorithm 2.5D Cannon (AKA communication avoiding, or CA) matrix multiplication algorithm [56] targets small matrices. Small matrix products arise, for example, in electronic structure calculations (e.g. ab-initio molecular dynamics using planewave bases [41,13]). At a high level, the 2.5D algorithm generalizes the traditional 2D Cannon algorithm [49] by employing an additional process dimension to replicate the 2D process grid. The degree of replication is controlled by a replication factor called c. When c = 1, we regress to 2D Cannon. When c = cmx = nprocs/2, we elide the shifting communication pattern and employ only broadcast and reduction. This algorithm is referred to as the 3D algorithm. The sweet spot for c falls somewhere between 1 and cmx, hence the name 2.5D algorithm. As in the 2D algorithm, the 2.5D algorithm shifts data in the X and Y directions. In addition, the 2.5D algorithm performs a broadcast and a reduction along the Z dimension. Through experimentation, we observed that, for the small matrices targeted by the 2.5D algorithm, the hybrid execution model MPI+OMP yields higher performance than a pure MPI implementation, which spawns only one MPI process per core. Therefore, we used the following 3 variants: MPI+OMP, MPI+OMP-olap, and Bamboo+OMP. All variants perform communication at the node level, using the OpenMP interface of the ACML math library to multiply the submatrices (dgemm). MPI+OMP is the basic MPI implementation without any overlap. MPI+OMP-olap is the optimized variant of MPI+OMP that pipelines computations of a step of the algorithm with communication for the next step. Bamboo+OMP is the result of passing the annotated MPI+OMP variant through Bamboo. As with the previous two applications, we also present results with communication shut off in the basic variant, i.e. MPI+OMP-nocomm, which uses the same code as MPI+OMP. We conducted a weak scaling study on 4K, 8K, 16K and 32K cores on Hopper. We chose problem sizes that enabled us to demonstrate the algorithmic benefit of data replication. Fig. 5 shows the results with the different variants. Both Bamboo+OMP and MPI+OMP-olap deliver the same speedup over the MPI+OMP variant on up to 8K cores. With 16K cores or more, Bamboo+OMP overtakes MPI+OMP-olap. Although Bamboo+OMP is still faster than the other variants on 32K cores, the speedup provided by Bamboo+OMP has dropped. We believe this behavior is the result of an interaction between the allowable replication factor c, and the degree of virtualization v. To understand the interaction, we first look at Table 3, which shows the values of c that maximize performance for the different variants. Note that the 2.5D algorithm requires that the first two dimensions of the processor core geometry must be equal. For the two MPI variants, the available values for the replication factor c are limited while Bamboo+OMP has more options due to the flexibility offered by virtualization. For example, on 8K cores MPI+OMP and MPI+OMP-olap can set c = 2 or c = 8, i.e. other values are illegal. On 16K cores, c can be 1, 4 or 16 while on 32K cores c can take on values of 2 or 8. For Bamboo+OMP, performance depends not only on our choice of c but also on the degree of virtualization v. Thus, we choose a combination of replication and virtualization that is optimal and cannot choose these parameters independently. As a result, performance is not stable as we grow the number of cores. The benefit of the 2.5D algorithm is that the communication volume shrinks with c and p. The cost is $O(n^2/\sqrt{p})$, where n is the number of cores. However, the effect of increasing v does not benefit from this cost function, since communication among virtualized tasks must be performed serially (hence p is not effectively change in that formula.) The effect is to improve pipelining as in the other applications. However, the number of messages is $O((2/(c^2) + \log(c)))$. It will grow as we increase v, because the message starts are serialized. The effect is to damp c as v increases, and this is evident from the data in Table 3. 4.1.2. High Performance Linpack The High Performance Linpack benchmark (HPL or Linpack for short) [26,25,24] is a well-known benchmark that solves a dense system of linear equations using LU factorization, and is often used to measure the performance of supercomputers. HPL uses a blocked cyclic data decomposition scheme. The HPL benchmark comprises 2 code variants. \textit{pdgesv0} does not make any attempt to overlap communication with computation, whereas \textit{pdgesvk2} applies an overlapping technique called \textit{lookahead}. We applied Bamboo annotations to \textit{pdgesv0}. Details of the 3 code variants are as follows. The \textit{pdgesv0} code consists of 3 key operations: panel factorization \textit{pFact}, panel broadcast \textit{pBcast}, and the trailing submatrix update \textit{pUpdate}. \textit{pFact} finds the pivots in column panel \textit{c}. This step is costly since we have to factorize a skinny matrix over a subset of the processes that own the panel, including a sequence of row swap-broadcasts, one for each \textit{pivot} within a single columns of the panel. HPL provides various panel factorization implementations, classified into recursive and non-recursive variants. We evaluated both variants and observed no difference in performance. Thus, we used the non-recursive variants. Once the panel has been factorized it must be broadcast to column processes within the same row (\textit{pBcast}). This is an efficient implementation that uses a ring broadcast algorithm, shifting data to the right along column processes. The \textit{pUpdate} operation swap-broadcasts \textit{U} among row processes and then performs a rank-1 update. It accounts for the lion’s share of LU’s computational work, performing \(O(N^3)\) multiply-adds. The \textit{pdgesvk2} variant applies \textit{lookahead} [26], a technique for overlapping communication with computation that fills idle gaps in the execution of LU. \textit{Lookahead} utilizes the dependence structure of the blocked algorithm to orchestrate computation and data motion. It uses split-phase coding [85], and may compute multiple iterations in advance. The underlying communication structure for this synchronization is complicated and difficult to implement and follow because the application must poll for arriving data in several places in the program. These complications have prevented lookahead from being used in practice. For example, lookahead is not employed in the widely-used ScalAPACK [7] library. This predicament has motivated new algorithmic reformulations [14] or data-driven implementations [33,8,14,39] to realize overlap. We annotated the \textit{pdgesv0} module and translated it with Bamboo. We also added scheduling policies via task prioritization using a bamboo priority pragma\(^1\) so that communication could be overlapped with communication more efficiently. The common wisdom in scheduling a non-preemptive task graph is that tasks should hold the core as long as they are still executable and only yield control when they need input from other tasks. This greedy strategy is intended to maintain the high hit rates of caches and TLB. However, LU factorization is an exception. Specifically, many tasks are waiting for data from the root task so that they can begin executing. Moreover, if for some reason the task that will become the next root is not scheduled soon, the next panel broadcast will be delayed. If this happens, performance could be significantly penalized since no overlap can be realized. Bamboo’s \textit{olap-regions} generally reside within an outer iteration, and HPL is no exception. Bamboo handles overlap regions as follows. When control reaches the end of an overlap region, if the priority is negative, the task yields processor/core, even if inputs are ready for the next iteration. To this end, we used 3 different values (0, −1, and 1) to represent for the priority of scheduling a task to run next. Among runnable tasks, those with higher priorities will be inserted at the top of the priority scheduling queue. Tasks with priority of 0 or 1 will execute until they cannot continue, since they await data from other tasks that have not yet completed. However, tasks with priority −1, must yield the core at the end of the olap region, even if they have the data needed to continue executing. Note that this scheme is not preemptive. Neither the runtime system nor task can force another task to yield control. Depending on the availability of the input and the current priority, a task decides whether it should continue or yield processor/core to another task. For more information about how we prioritize the LU task graph, see [45]. We performed experiments on Stampede [59], located at the Texas Advanced Computing Center (TACC), using the Sandy Bridge processors only. We ran on up to 128 nodes (4096 cores). The results appear in Fig. 6. We chose small problems sizes to ensure that communication overhead is significant and thus we can see the benefit of overlapping communication with computation. Fig. 6 shows that Bamboo was able to meet, and sometimes slightly exceed, the performance of the painstakingly coded \textit{lookahead} variant, so long as prioritization was employed. The vital role of task prioritization is inevitable. Theoretically, if we use a random scheduling algorithm and we run the unprioritized Task Graph variant for a large number of times, there is possibility that we observe the performance of the prioritized Task Graph variant. However, the required number of experiments could grow exponentially in \(k \times N\), where \(N\) is the number of panel columns of the input matrix and \(k\) is the number of communication events occurring for a particular \(N\). We repeated each experiment more than 10 times and took the best performance, but results without task prioritization were always far below the performance of \textit{lookahead}. Compared to the no-\textit{lookahead} variant, the performance of the unprioritized task graph was at best comparable and in some cases it was even lower. 4.2. Structured grid-multigrid solver Multigrid [10,66,12,27] is a family of methods to accelerate the convergence rate of conventional iterative methods such as Gauss–Seidel Red–Black and SOR. A multigrid solver consists of multiple cycles which solve an equation via a hierarchy of meshes. At each cycle, multigrid recursively solves an error equation on a coarser grid, which it uses to correct the solution. The recursion ends at some specified bottom-most level, where a bottom solver solves the error equation on the coarsest grid. The solution from this grid is then projected (via interpolation) up through the hierarchy of finer meshes until reaching the finest level. At this point the cycle completes. The cycle can have a V or W shape, or may be truncated at a certain level where the bottom solver can perform more efficiently. \(^1\) We did not present this pragma earlier since Bamboo simply translates the pragma into a method that sets task priority. <table> <thead> <tr> <th>#Cores</th> <th>4K</th> <th>8K</th> <th>16K</th> <th>32K</th> </tr> </thead> <tbody> <tr> <td>MPI+OMP</td> <td>(c = {1, 4})</td> <td>(c = {2, 8})</td> <td>(c = {1, 4, 16})</td> <td>(c = {2, 8})</td> </tr> <tr> <td>MPI+OMP-olap</td> <td>(c = {1, 4})</td> <td>(c = {2, 8})</td> <td>(c = {1, 4, 16})</td> <td>(c = {2, 8})</td> </tr> <tr> <td>Bamboo+OMP</td> <td>(c = 2, VF = 8)</td> <td>(c = 2, VF = 4)</td> <td>(c = 2, VF = 2)</td> <td>(c = 4, VF = 2)</td> </tr> </tbody> </table> We translated MiniGMG, a multigrid solver developed at Lawrence Berkeley National Laboratory [67]. This is an MPI+OpenMP code consisting of 4000 lines, 1000 of which are MPI code that need to be translated. It does not overlap communication with computation. Owing to the complexity of restructuring this third-party code by hand, we do not provide an MPI-Olap variant. This solver employs truncated V-cycles. On the way down of each cycle, smooths are applied to reduce the error before restrictions are used to determine the right-hand side of the coarser grids. Each smooth is a Gauss–Seidel Red–Black relaxation (GSRB). The V-cycle is truncated when the mesh reaches the minimal size threshold of $4^3$, and the bottom solver consists of a significant number of GSRB sweeps. Finally, the solution is interpolated and smoothed upward to the next finer mesh. The GSRB kernel is optimized further with a DRAM avoiding technique, which changes the communication pattern significantly. In particular, in addition to nearest neighbor communication, adjacent processes along the diagonals also communicate. The effect of this optimization is to increase the number of neighbors that a process communicates from 6 to 26. We conducted a weak scaling study on Edison, fixing the problem size at $8 \times 128^3$ boxes per core. The left part of Table 4 shows the execution time of modules of the MPI variant. Communication (comm) accounts for about 20% of the total execution time, and thus we have enough available computation to hide communication. While the communication cost grows slightly as the number of cores increases, the execution time for the other activities is stable, i.e. time to update data elements (compute), serialize and deserialize messages (pack/unpack), and copy ghost cells among boxes of the same MPI process (box copy). The right part of Table 4 shows the relative overhead of communication at each grid level. It can be seen that communication overhead increases by a factor of 2 from the finest grid L0 to L1, slowly increases (L1 to L2 and L2 to L3), or saturates from L3 to the coarsest level grids, L4. Fig. 7 compares the performance between MPI and Bamboo code variants in a weak scaling study. We can see that both MPI and Bamboo are highly scalable (in a weak sense) and that Bamboo improves the performance by up to 14%. These results are promising, given that overlap strategies for multigrid present three challenges. First, communication is effective at finest grids only as the message size on these grid levels is still significant. At coarser levels, the message size gets smaller and smaller, increasing the overhead of virtualization. In addition, when moving from a fine to a coarser grid, computation shrinks by a factor of 8 whereas communication reduces by only a factor of 4, reducing the efficiency of the overlapping technique. Furthermore, the number of messages that each processor has to communicate messages with its 26 neighbors is significant. This increases the processing overhead of the runtime system that manages overlap. 5. Advanced node technologies At present, it appears that further improvements to HPC systems will mainly come from enhancements at the node level [52,9,51]. Node architectures are changing rapidly, and systems will mainly come from enhancements at the node (i.e. coprocessors or accelerators) to amplify node performance is gaining traction. Bamboos supports state-of-the-art computing platforms employing advanced technologies such as Graphical Processing Units (GPUs) and Many Integrated Core (MIC). In this paper we present the results on the former. Results on MIC can be found in our previous work [44]. 5.1. Graphical processing units GPUs are a powerful means of accelerating compute-intensive and bandwidth-intensive applications and for lowering the power/performance ratio. CUDA (Compute Unified Device Architecture) is a well-known parallel programming model for GPUs developed by NVIDIA. Under this model, each GPU works as a device attached to a CPU called host. The host offloads compute kernels and dependent data to its device(s) each running thousands of CUDA threads to parallelize the workloads. The results are then collected back to the host. The host–device communication is routed over a PCIe bus, which can easily become a performance bottleneck due to its limited bandwidth. As the demand for compute and memory increases, applications require a cluster of many GPUs. MPI+CUDA is a hybrid programming model commonly used to parallelize the application workloads across multiple GPUs. This model spawns an MPI process per GPU to work as the host. The communication between MPI processes is called host–host communication. We extend Bamboos to hide the host–host and host–device communication overheads in MPI+CUDA applications. 5.2. A GPU-aware interface Because MPI is not aware of device memory, Bamboos can realize overlap among hosts only. It cannot overlap data motion between host and device. We defined and implemented a GPU-aware MPI interface, which allows MPI communication routines to specify device memory as the buffer for sending and receiving message data. Since distinguishing device and host buffers is challenging at static time and costly at dynamic time, we also have the programmer specify a different MPI_COMM_WORLD processes is called host–host communication. We extend Bamboos to hide the host–host and host–device communication overheads in MPI+CUDA applications. 5.3. Performance evaluation We evaluated our GPU-aware programming model on the 3D Jacobi solver running on a portion of Stampede containing hybrid CPU/GPU nodes. Only 32 such nodes were available at a time, so experimentation was limited to this configuration. A GPU node has a single K20 “Kepler” GPU with 5GB of fast device memory. Our applications ran out of this memory rather than on the more generous 32GB host memory, which is connected two 8-core Intel Xeon E5 “Sandy Bridge” processors. Nodes communicate via a Mellanox FDR InfiniBand interconnect. We use the Intel compiler to compile code running on the host and CUDA 5.5 to compile GPU kernel code. Mvapich handled communication among GPU nodes. We compared 5 code variants. The first and second variants, MPI-basic and MPI-olap, employ the traditional MPI+CUDA programming model. The third variant, Bamboo, is the task graph program obtained by translating MPI-basic. The fourth variant, Bamboo-GPU, is generated by the Bamboo translator from a basic MPI+CUDA code written under the GPU-aware programming model, i.e. MPI-basic except with MPI data motion calls replaced by the equivalent CUDA-aware MPI and CUDA calls that transfer data between the host and device disabled. The fifth variant, MPI-nocomm, was obtained by removing all host–host and host–device communication calls in MPI-basic. We conducted a weak scaling study on Stampede. During normal production time, this platform supports jobs with at most 32 K20 GPU nodes, so we limited ourselves to 32 nodes. Due to this small scale, 1D decomposition scheme was sufficient to meet the needs of the application (though not scalable for larger configurations). We evaluated all code variants with a base problem size of 510 × 512 × 128 per GPU, which consumes 0.765 GB of device memory per node. This problem size is intended to mimic a more realistic application scenario, in which Jacobi would comprise one step of a multiphase algorithm. Though Jacobi uses 3 variables per mesh zone, a more realistic application would use many variables — a factor of 5 or more. Thus, a production application would consume 3/4 or more of the node’s available memory and in some cases the mesh size per node would have to be reduced to avoid exceeding available memory capacity. The problem scaling size we use thus stresses communication at a level appropriate for production applications. Fig. 8 shows the performance in GFLOP/s of all code variants. It can be seen that Bamboo-GPU and MPI-olap significantly outperform Bamboo and MPI-basic. We attribute the performance improvements of Bamboo-GPU compared to Bamboo and MPI-basic to the following optimizations. First, the knowledge of host–device transfer enables Bamboo-GPU to take advantage of locality, such as tasks computing on the same GPU only exchange the header information of messages. This optimization can save significant bandwidth of the PCI Express bus connecting host and device. We found that this optimization is very significant at small scales, where the bandwidth between host and device is more critical than between hosts. Second, we modified the runtime to use pinned memory to buffer messages. Using pinned memory can significantly increase the bandwidth between host and device [63,16]. Third, we used asynchronous memory copies to avoid implicit synchronization on the GPU. 5.4. Future implementation for performance portability With the current implementation of our runtime system, messages among GPUs are always routed through their hosts. This policy is not optimal when all or some pairs of GPUs can communicate on a direct path. NVIDIA refers to this capability as GPUDirect, which can be enabled when either (1) GPUs of the same compute node share a common PCIe bus or (2) the interconnection network allows the communication among GPUs on different compute nodes to bypass their hosts. Although Stampede provides neither of these, Bamboo’s users may have access to GPUs clusters that have GPUDirect (e.g. the Comet system at San Diego Supercomputer Center). As a result, we plan to modify our implementation to support GPUDirect as follows. Our runtime system employs a single MPI process per compute node to handle the communication. Thus, for inter-node communication, we plan to use MPI implementations that support GPUDirect as the communication backend (e.g. MPI-ACC and MVAPICH2-GPU). For intra-node communication, we will need to provide our own implementation of GPUDirect. Specifically, once the runtime detects that the sender and receiver tasks locate on the same compute node, it sends the message descriptor instead of the raw data. The receiver opens the descriptor and pulls data directly from the sender using CUDA memory copy. In order to hide the communication cost, data dependency is only considered satisfied when this memory copy operation completes. We plan to use the asynchronous memory copy version so that we will not block the communication handler at the receiver side. It is worth noting that these two extensions will not require any modification on the Bamboo’s programming API. 6. Related work Danalis et al. [22] implemented transformations of MPI that realize communication overlap in collective operations. Strout et al. presented a framework for inter-procedural analysis of message-passing SPMD programs; generating MPI inter-procedural control-flow graphs that help reduce storage requirements [31]. Shires et al. [53] presented a program flow representation of an MPI program, which is useful in code optimization. β-MPI [54] generates the runtime dataflow graph of an MPI program, in order to assess communication volume. It overloads the MPI calls using macros, but does not perform source code analysis or code restructuring. Latency tolerant applications and infrastructure for expressing them have been previously reported in the literature including Charm++ [35], KeLP2 [4,28], Adaptive MPI [32] (built on top of Charm++, Tarragon [20,19], Thyme [58], and others [55,57,61,60, 50,18,29]. Charm++ supports virtualization and latency tolerance. KeLP2 is a C++ framework that supports an explicit hierarchical execution model, and masks latency. Adaptive MPI virtualizes MPI processes to support communication overlap and task scheduling. When a thread blocks on an MPI call, it yields to another thread. There is no explicit dataflow graph and the MPI source is not manipulated. Bamboo transforms MPI source into an explicit graph, which can be used to guide scheduling. Thyme is a C++ library with goals similar to Tarragon. Husbands and Yelick [33] have implemented thread-scheduling techniques for tolerating latency in dense LU factorization and use a dataflow interpretation of the algorithm that exposes the latent parallelism. PLASMA [38] is a library for dense linear algebra and it represents applications with a dataflow graph. To conserve memory, it allocates only a portion of the graph at a time, inhibiting global optimizations. Bamboo can avoid graph expansion by controlling the outer iteration within task state. We used the Rose source-to-source translator [48] to develop Bamboo. Rose is a member of the family of language processors that support semantic-level optimizations including Teleco 7. Conclusions This paper presented a novel interpretation of Message Passing Interface to execute MPI applications under a data-driven model that can overlap communication with computation automatically. This interpretation factors scheduling issues and communication decisions out of program execution. Specifically, by reformulating MPI source into the form of a task dependency graph, which maintains the data dependency among tasks of the graph, we can rely on a runtime system to schedule tasks based on the availability of data and computing resources. To implement our approach we developed Bamboo, a custom source-to-source translator that transforms MPI code into the task dependency graph representation. Bamboo treats the MPI API as an embedded domain specific language, and it requires only a modest amount of programmer annotation. The implementation of Bamboo comprises 2 software layers: core message passing and utility layers. The core message passing layer transforms a minimal subset of MPI point-to-point primitives, whereas the utility layer implements high-level routines by breaking them into their point-to-point components, which will be then translated by the core message passing layer. Such a multi-layer design allows one to customize the implementation of MPI high-level routines such as collectives, which may take advantage of special purpose hardware provided on some platforms. In addition, this design can reduce the amount of programming effort needed to port the core message passing layer to a different runtime system. We demonstrated that Bamboo improved performance by hiding communication. We showed that by using Bamboo, we can avoid the complications of the lookahead algorithm implemented in the High Performance Linpack (HPL) benchmark, while realizing... the benefits. For structured grid, we translated an iterative solver for Poisson’s equation and a geometric multigrid solver for Helmholtz’s equation. For all applications, we have validated our claim that, by interpreting an MPI program in terms of data flow execution, we can overlap communication with computation and thereby improving the performance significantly. Moreover, Bamboo performance meets or exceeds that of labor-intensive hand coding, at scale. Bamboo also improves performance of communication avoiding matrix multiplication (2.5D Cannon’s algorithm). The result on this application demonstrates that the translated code not only avoids communication, but tolerates what it cannot avoid. We believe that this dual strategy will become more widespread as data motion costs continue to grow. We also validated Bamboo on advanced node architectures, which accelerate node performance by offloading compute-intensive kernels to devices such as GPUs. Bamboo not only improves performance of a program written under the MPI+CUDA programming model, but also offers a simpler interface that allows communication between GPUs to be transparent to the programmer. Lastly, Bamboo enables the programmer to specify scheduling hints as task priorities in order to optimize the scheduler. A task with higher priority will have a higher chance to be scheduled quickly. Such task prioritization support is important in applications that consist of irregular workloads. While Bamboo’s scheduler employs a non-preemptive task scheduling rule, it allows tasks to voluntarily yield the processor, enabling tasks of the graph to work in a more cooperative manner. This dual scheduling scheme allows hardware resources to be efficiently shared among tasks. We evaluated the task prioritization support using the High Performance Linpack benchmark. Experimental results demonstrated that we gained significant performance benefits by employing simple prioritization schemes. In the future we can extend Bamboo to support complicated, heterogeneous computing. A compute node may contain multiple types of multicore and manycore processors. Thus, processor cores may run at different speeds with the result that data partitioning and mapping are non-trivial programming tasks. Bamboo alleviates these challenges by supporting process virtualization. However, in the future Bamboo needs to provide an analytical model and/or auto-tuning support for finding optimal or near-optimal virtualization factors and task mapping schemes. For irregular applications, hints from the programmer may be useful to effective task migration. Acknowledgments This research was supported by the Advanced Scientific Computing Research (ASCR), the U.S. Department of Energy, Office of Science, contracts No. DE-ER08-191010356-46564-95715, DE-FC02-12ER26118, and DE-AC05-76RL01830. A portion of the research was conducted at ESMIL (Environmental Molecular Sciences Laboratory) at Pacific Northwest National Laboratory, operated for the U.S. Department of Energy by Battelle under Contract Number DE-AC05-76RL01830. This work also used the Extreme Science and Engineering Discovery Environment (XSEDE), which is supported by National Science Foundation Grant Number OCI-1053575. We would like to thank Samuel Williams for providing us with the MPI source code of the multigrid application. Tan Nguyen was a fellow of the Vietnam Education Foundation (VEF) while conducting this research, and was supported in part by the VEF. Scott Baden dedicates his portion of this work to Hans Petter Langtangen (1962–2016). References Dan Quinlan is the leader of the ROSE project in the Center for Advanced Scientific Computing. His research is in numerous areas that intersect computer science and numerical analysis. Research interests include object-oriented numerical frameworks, parallel adaptive mesh refinement, parallel multigrid algorithms, semantics-based source code transformations, C++ compiler tools/infrastructure/design, cache-based optimizations, parallel array classes, parallel data distribution mechanisms, and parallel load balancing algorithms. Dr. Quinlan earned his Ph.D. in Computational Mathematics from the University of Colorado. Scott B. Baden is Professor in the Computer Science and Engineering at the University of California, San Diego and is currently on leave at Lawrence Berkeley National Laboratory, where he leads the Computer Languages and Systems Software Group. His research focuses on domain-specific translation, language and run time support for low cost communication, adaptive and irregular applications. Dr. Baden has a Ph.D. in computer science from the University of California, Berkeley. He is a senior member of IEEE, a member of SIAM, and a senior fellow at the San Diego Supercomputer Center.
{"Source-Url": "https://cloudfront.escholarship.org/dist/prd/content/qt8fh786n4/qt8fh786n4.pdf?t=palge2", "len_cl100k_base": 12808, "olmocr-version": "0.1.53", "pdf-total-pages": 14, "total-fallback-pages": 0, "total-input-tokens": 45185, "total-output-tokens": 15112, "length": "2e13", "weborganizer": {"__label__adult": 0.0003559589385986328, "__label__art_design": 0.0005640983581542969, "__label__crime_law": 0.0003979206085205078, "__label__education_jobs": 0.001506805419921875, "__label__entertainment": 0.0001646280288696289, "__label__fashion_beauty": 0.0002200603485107422, "__label__finance_business": 0.00033974647521972656, "__label__food_dining": 0.00038051605224609375, "__label__games": 0.0009613037109375, "__label__hardware": 0.0034084320068359375, "__label__health": 0.0006303787231445312, "__label__history": 0.0006074905395507812, "__label__home_hobbies": 0.00017273426055908203, "__label__industrial": 0.0010156631469726562, "__label__literature": 0.0003063678741455078, "__label__politics": 0.0004453659057617187, "__label__religion": 0.0007185935974121094, "__label__science_tech": 0.46923828125, "__label__social_life": 0.00012767314910888672, "__label__software": 0.01338958740234375, "__label__software_dev": 0.50341796875, "__label__sports_fitness": 0.000431060791015625, "__label__transportation": 0.0011138916015625, "__label__travel": 0.0002639293670654297}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 65417, 0.05677]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 65417, 0.38841]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 65417, 0.89562]], "google_gemma-3-12b-it_contains_pii": [[0, 337, false], [337, 3765, null], [3765, 11298, null], [11298, 16315, null], [16315, 21129, null], [21129, 26750, null], [26750, 33358, null], [33358, 40774, null], [40774, 43857, null], [43857, 49243, null], [49243, 55351, null], [55351, 64205, null], [64205, 64205, null], [64205, 65417, null]], "google_gemma-3-12b-it_is_public_document": [[0, 337, true], [337, 3765, null], [3765, 11298, null], [11298, 16315, null], [16315, 21129, null], [21129, 26750, null], [26750, 33358, null], [33358, 40774, null], [40774, 43857, null], [43857, 49243, null], [49243, 55351, null], [55351, 64205, null], [64205, 64205, null], [64205, 65417, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 65417, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 65417, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 65417, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 65417, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 65417, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 65417, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 65417, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 65417, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 65417, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 65417, null]], "pdf_page_numbers": [[0, 337, 1], [337, 3765, 2], [3765, 11298, 3], [11298, 16315, 4], [16315, 21129, 5], [21129, 26750, 6], [26750, 33358, 7], [33358, 40774, 8], [40774, 43857, 9], [43857, 49243, 10], [49243, 55351, 11], [55351, 64205, 12], [64205, 64205, 13], [64205, 65417, 14]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 65417, 0.16514]]}
olmocr_science_pdfs
2024-12-07
2024-12-07
7ae3d9fa7c71228b4418b153a2f79a2d1603a08b
We are IntechOpen, the world’s leading publisher of Open Access books Built by scientists, for scientists 3,700 Open access books available 108,500 International authors and editors 1.7 M Downloads 154 Countries delivered to TOP 1% Our authors are among the most cited scientists 12.2% Contributors from top 500 universities WEB OF SCIENCE™ Selection of our books indexed in the Book Citation Index in Web of Science™ Core Collection (BKCI) Interested in publishing with us? Contact book.department@intechopen.com Numbers displayed above are based on latest data collected. For more information visit www.intechopen.com Modelling Multi-Agent System using Different Methodologies Vera Maria B. Werneck¹, Rosa Maria E. Moreira Costa¹ and Luiz Marcio Cysneiros² ¹Universidade do Estado do Rio de Janeiro, ²York University, ¹Brazil ²Canada 1. Introduction The increasing use of multi-agent systems brings challenges that have not been studied yet, such as: how we should adapt requirements elicitation to cope with agent properties like autonomy, sociability and proactiveness. The agent-oriented modelling is proposed as a suitable software engineering approach for complex organizational application domains that deal with the need for new applications. These requirements are not broadly considered by current paradigms. Autonomy and sociability aspects such as the dependency of an agent on another, and how critical this condition should be, have to be analysed from the early stages of the software development process (Wooldridge & Jennings, 1997). This research work is included in the Agent-oriented Project that has been developed by the Informatics and Computer Science Department of State University of Rio de Janeiro (UERJ) and the School of Information Technology of York University (Toronto). This project aims at studying and comparing agent-oriented software development methods and techniques based on attributes and norms and by the models construction based on an exemplar. These experiments enabled the development and construction of Multi-Agent Systems applied to Health and Education areas, providing research on Systems (MAS) especially on the agent proliferation of control, communication and availability of information and knowledge in different computing environments. The construction of Multi-Agent Systems allows experiments on the agent-oriented technology in relation to development methodologies with regard to agent-oriented programming environments. It also allows us apply this technology in practical and real applications in Health and Education Domains. The Glycemic Monitor System based on the Guardian Angel for aiding the diabetes treatment (Tavares et al., 2010) and the Educ-MAS (Education Multi-Agent System) (Gago et al., 2009), (Dantas et al., 2007), a learning education environment with multi-agents helping the teaching process on a specific topic, are two examples of Multi-Agent Systems that have been developed in the project Oriented Agents. Many methodologies applying agent-oriented concepts to software development have been proposed however, the evaluation of these methodologies is not an easy task specially to choose the best method to be adopted in a MAS project. In this project, we have used an exemplar proposed by Yu & Cysneiros (2002) to evaluate some methodologies and language methods (Gaia, MESSAGE, Tropos, Adelfe, MAS-CommonKADS, MaSE, Ingenius, KAOS, AUML) (Souza et al., 2010), (Souza et al., 2009), (Werneck et al., 2008), (Werneck et al., 2007), (Werneck et al., 2006), (Coppieters et al., 2005), (Cysneiros et al., 2005). This exemplar is rich and complex enough to guide us to investigate to understand them better. Now we are compiling the experiences we gathered from all the methodologies we evaluated to try and understand where most methodologies need to improve and where most of them are well developed. This knowledge will be modelled into an ontology and will be used to define an Agent-Oriented Methodology Approach based on the Situation Method Engineering (SME) that provides a flexible way of constructing a methodology based on a set of method fragments and the situation of the project requirements. This idea of using SME for constructing Agent-Oriented Methodology was also proposed by Henderson-Sellers & Ralyté (2010) that describes some experiences of using SME in MAS and object oriented methods. This chapter provides a deep modelling overview of two different Multi-agents systems in two different Agent-Oriented Methodologies. Our objective is to demonstrate how modelling the problem with a methodology can improve quality and be a guide for further MAS development. This chapter is organized into 5 sections. Section 2 gives an overview of Multi-Agent Systems methodologies describing the Adelfe (Bernon et al., 2003) (Henderson-Sellers & Giorgini, 2005), and Mase (Deloach, 2001), (O’Malley et al., 2001), (Dileo et al., 2002), (Henderson-Sellers & Giorgini, 2005) methodologies that will be shown in the next two sections. Section 3 describes the modelling of Guardian Angel System in Adelfe focusing on the mains aspects of agent oriented. Section 4 presents the modelling of the Educ-MAS using MaSE. Finally section 5 analyses the systems development with those methodologies concluding the work and also presents correlated and future works. 2. MAS methodologies Many agent-oriented methodologies have been proposed based on a variety of concepts, notations, techniques and methodological guidelines. Some of these methodologies rely on standard methods or modelling languages as CommonKADS (Schreiber et al, 1999) and UML (Rumbaugh et al., 2004). The MAS-CommonKADS (Iglesias & González, 1998), (Henderson-Sellers & Giorgini, 2005) and AUML (2007), (Odell et al., 2001) extended CommonKADS (Schreiber et al., 1999) and UML (Rumbaugh et al., 2004) respectively to meet the multi-agent systems. The agent-oriented methodologies have multiple roots (Figure 1). Some are based on the idea of artificial intelligence coming from the knowledge engineering (KE). Other methods originate from software engineering and they are extensions of object-oriented (OO) paradigm. There are still those that use a mix of concepts based on these two areas and some are derived from other agent-oriented methodologies. Although we are going to present two methodologies based on Object Oriented in this chapter, both Adelfe and MaSE methodologies were chosen because they are based on common agent concepts and they are easy to understand having a good methodology guide and a tool support. A tool is a very important issue that can be a differential in the software development. 2.1 The Adelfe methodology Adelfe is an acronym that translated from French means "framework to develop software with emergent functionality" (Adelfe, 2003), (Bernon et al., 2003), (Henderson-Sellers & Giorgini, 2005) and was developed to deal with open and complex agent problems. These systems work with composed agents that have cooperative interactions with each other and are called Adaptative Multi-Agent Systems (AMAS). Adelfe uses AUML principle (Odell et al., 2001), (AUML, 2007) together with UML (Rumbaugh et al., 2004) to express agent interaction protocols. The development process of Adelfe is based on RUP (Rational Unified Process) (Krutchen, 2000) with some additions considering AMAS Theory specificities. For example, the environment characterization of the system and the identification of cooperation failures are some characteristics included in this process. Adelfe provides some tools including one to estimate the AMAS technology adequacy. This can be a great support to inexperienced developers in the AMAS system field. The adequacy is studied at two levels: the global (the system) and the local (the components). Eight parameters are taken into consideration for the global level while for the components there are other three parameters. Two other tools (Open Tool and Interactive Tool) are available to integrate the framework. The Open tool is a graphic modelling tool which supports Adelfe notation to construct the artefacts proposed in this method such as some UML diagrams and protocols of AUML interaction. The Interactive Tool provides the developer with a guide throughout the process application. The Adelfe process covers all the phases of a classical software process from the requirements to the deployment based on the RUP process adapted to AMAS. Only the work definitions (WD) of requirements, analysis and design require modifications to be adapted for the AMAS. The rest of the RUP can be applied without modifications. 2.1.1 Preliminary and final requirements (WD1 e WD2) The preliminary requirements work definition (WD1) of Adelfe (Adelfe, 2003), (Bernon et al., 2003), (Henderson-Sellers & Giorgini, 2005) is the same as proposed by the RUP. The aim still consists of studying the stakeholders’ needs to produce a document of the stakeholders and the developers’ agreement. The activity of the environment characterization (A6) of the final requirements (WD2) (Table 1) was added to the RUP because the environment is a very important concept in AMAS theory. The environment has to be well comprehended and the A6 activity has the following tasks: determine the entities, define the context and characterize the environment. The characterization begins by the identification of the entities which interact with the system and the restrictions of these interactions (A6-S1). An entity in Adelfe is an actor classified as passive or active. An active entity can act in an autonomous and dynamic way with the system. A passive entity is considered a resource of the system that can be used or modified by active entities. The classification of the entities is essential in AMAS since the agents will be part of the system treated as active entities. Define context (A6-S2) is an activity that analyses the environment through the interaction among entities and the system by defining UML sequence and collaboration diagrams. The information flow of passive entities and the system are expressed by collaboration diagrams, while interactions among active entities and the system are described by sequence diagrams. The Adelfe methodology defines these diagrams based on the result of the previous step (A6-S1) where the entities were pre-defined with the support of the set of keywords provided in (A4). <table> <thead> <tr> <th>WD1: Preliminary Requirements</th> </tr> </thead> <tbody> <tr> <td>A1: Define user requirements</td> </tr> <tr> <td>A2: Validate user requirements</td> </tr> <tr> <td>A3: Define consensual requirements</td> </tr> <tr> <td>A4: Establish keywords-set</td> </tr> <tr> <td>A5: Extract limits constraints</td> </tr> </tbody> </table> <table> <thead> <tr> <th>WD2: Final Requirements</th> </tr> </thead> <tbody> <tr> <td>A6: Characterize environment</td> </tr> <tr> <td>A1: Determine environment</td> </tr> <tr> <td>A2: Define context</td> </tr> <tr> <td>A3: Characterize environment</td> </tr> <tr> <td>A7: Determine use cases</td> </tr> <tr> <td>S1: Draw inventory of use cases</td> </tr> <tr> <td>S2: Identify cooperation failures</td> </tr> <tr> <td>S3: Elaborate sequence diagrams</td> </tr> <tr> <td>A8: Elaborate UI (user interface) prototypes</td> </tr> <tr> <td>A9: Validate UI prototypes</td> </tr> </tbody> </table> Table 1. WD1 and WD2– Preliminary and Final Requirements in Adelfe (2003) Completing the environment characterization, the developer performs the Step A6-S3 describing the environment in terms of being accessible (as opposed to "inaccessible"), continuous (as opposed to "discrete"), deterministic (as opposed to "non-deterministic"), or dynamic (as opposed to "static"). Cooperative agents are a central concept in Adelfe so the developer can be able to construct AMAS. The analysis of all the unexpected and harmful events is important to realize what the causes and consequences of non-cooperative situations are for the agents. These cooperation failures are exceptions. Taking this aspect into account, the determination of the use cases is modified by adding the step (A7-S2) in which cooperation failures must be identified using specific notation. The elaboration of user interface (UI) prototypes activity (A8) models the graphic users interface (GUI) specifications used in the interactions defined in A6 and A7. GUIs are evaluated in A9 as functional or non-functional (ergonomics, design, ...) requirements. Sometimes in this phase it is necessary to go back to activity A8 to improve UI. 2.1.2 Analysis (WD3) Adelfe Analysis phase (Table 2) is composed by three activities: (i) AMAS adequacy verification activity (A11) to identify agents and interaction among the entities, (ii) agents identification activity (A12) to analyse the entities defined in A6 that will be considered an agent in the system and (iii) the study of the interactions between entities activity (A13) to analyse all different types of interactions between active/passive entities, between active entities and between agents (Adelfe, 2003), (Bernon et al., 2003), (Henderson-Sellers & Giorgini, 2005). The Adelfe AMAS technology adequacy verification of the system activity (A11) is performed using the adequacy tool which considers two levels of study: global (A11-S1) and components (A11-S2). The Global analysis answers the question: “Is an AMAS technology implementation to the system necessary?” For the local level the question is “Does any component need to be implemented as AMAS?” If the tool answers the first question positively, the developer can continue applying the process. If the second answer is also affirmative, the Adelfe methodology should be applied on the components considered as AMAS since they require evolution. The developer identifies the components of the system studying use cases and scenarios previously elaborated in the domain analysis (Adelfe, 2003), (Bernon et al., 2003), (Henderson-Sellers & Giorgini, 2005). <table> <thead> <tr> <th>A10: Analyse the Domain</th> </tr> </thead> <tbody> <tr> <td>• S1: Identify classes</td> </tr> <tr> <td>• S2: Study interclass relationships</td> </tr> <tr> <td>• S3: Construct preliminary class diagrams</td> </tr> </tbody> </table> <table> <thead> <tr> <th>A11: Verify the AMAS adequacy</th> </tr> </thead> <tbody> <tr> <td>• S1: Verify it at the global level</td> </tr> <tr> <td>• S2: verify it at the local level.</td> </tr> </tbody> </table> <table> <thead> <tr> <th>A12: Identify Agents</th> </tr> </thead> <tbody> <tr> <td>• S1: Study entities in the domain context</td> </tr> <tr> <td>• S2: Identify potentially cooperative agents</td> </tr> <tr> <td>• S3: Determine agents</td> </tr> </tbody> </table> <table> <thead> <tr> <th>A13: Study Interactions between Entities</th> </tr> </thead> <tbody> <tr> <td>• S1: Study active/passive entities relationships</td> </tr> <tr> <td>• S2: Study active entities relationships</td> </tr> <tr> <td>• S3: Study agents relationships</td> </tr> </tbody> </table> Table 2. WD3 – Analysis in Adelfe (2003) The cooperative agents are a central concept of AMAS system. In Adelfe the agents are cooperative entities that satisfy at least the autonomy requirements, the local objective and the interaction with other entities. After assessing all the possible agents, the classes are marked with the cooperative agent stereotype. In Adelfe, agents are not previously known thus the developer must identify them (A12). Entities which demonstrate properties such as autonomy, local objective to pursue, interaction with other entities, partial view of its environment and the ability to negotiate are the ones to be considered as potential agents. To effectively turn into a cooperative agent, the potential cooperative agent must be prone to cooperation failures. By studying its interactions with its environments and with other entities, the developer has to determine if this entity may encounter such situations that will be considered as non-cooperative situations at the agent level. The entities meeting all these criteria will be identified as agents and the classes related to them marked as agents. The study of the interactions between entities (A13) analyses the interactions between entities and is represented by Collaboration and Sequence Diagrams. The agents’ interactions are described by AUML Protocol Diagram. 2.1.3 Design (WD4) The Adelfe design process (Table 3) starts by analysing the different possibilities of detailed architecture of the system, creating packages sub-systems, objects, agents and the relationships among them and producing the class diagrams with the new elements (Cooperative Agent Class and the Cooperative Agent stereotype) (Adelfe, 2003), (Bernon et al., 2003), (Henderson-Sellers & Giorgini, 2005). ### Table 3. WD4 – Design in Adelfe (2003) <table> <thead> <tr> <th>Activity</th> <th>Description</th> </tr> </thead> </table> | A14: Study detailed architecture and multi-agent model | - S1: Determine packages - S2: Determine classes - S3: Use design-patterns - S4: Elaborate component and class diagrams | | A16: Design Agents | - S1: Define skills - S2: Define aptitudes - S3: Define interaction languages - S4: Define representations - S5: Define Non-cooperative situations A17: FAST Prototyping A18: Complete design diagrams | - S1: Enhance design diagrams - S2: Design dynamic behaviours | In the activity A15 the developer studies the interaction languages to be able to define the protocols used by agents to communicate between themselves. This information exchange between agents has to be described. For each scenario defined in the A7 and A13 activities, these exchanges are described using AUML protocol diagrams. The protocols diagrams are attached to package (not classes) because they are generic. The language definition is not necessary when the agents' communications are via the environment. The Design Agents (A16) activity is an Adelfe methodology specific activity and allows the developer to refine the CooperativeAgent stereotyped classes identified in the A12 and A14 activities. The different modules of an agent must be defined in these activities by describing its skills, aptitudes, interaction languages, design representations, design characteristics and design non-cooperative situations. Methods and attributes can describe the skills of an agent with a stereotyped notation <<skill>>. Skills are the system knowledge that allows the agent to perform an action. The representation of aptitudes, interaction languages, design representations and design characteristics is defined similarly to skills with a stereotyped notation. Aptitudes are the agent’s capability to reason about a specific knowledge of the system or about a real situation. The developer analyses protocols defined in A15 activity and those assigned to an agent are associated to a state-machine. The methods and attributes link with an interaction protocol must be stereotyped <<interaction>>. The methods and attributes related to perception and action phase are represented by <<perception>> and <<action>> respectively in (A16-S3). The step Design Non-Cooperative Situations (NCS) (A16-S6) is the most important in the design agents’ activity (A16), because this is a specific ability of cooperative agents. A model guides the developer in the definitions of all situations that seem to be “harmful” for cooperative social attitude of an agent. The table lists some types of situations like ambiguity, incompetence, uselessness and conflict. The developer should fill up the conditions described for each NCS. The table contains the state of this agent when detecting the NCS, a NCS textual description, conditions permitting local detection of NCS and actions linked to this NCS. The Fast Prototyping activity (A17) uses OpenTool (Adelfe, 2003), (Henderson-Sellers & Giorgini, 2005) to test the agents’ behaviour previously defined. The customized version of OpenTool can automatically transform a protocol diagram into a state-chart that can be run to simulate the agents' behaviour. Some methods can be implemented using a OTscript language that is a set-based action language of OpenTool. The last activity of design is to complete the detailed architecture enriching the class diagrams (A18-S1) and developing the state chart diagrams required to design the dynamic behaviours (A18-S2). The objective is to reflect the different changes of an entity state when it is interacting with others. 2.2 MaSE methodology The Multi-agent System Engineering (MaSE) methodology aims at supporting the designer to catch a set of initial requirements, to analyse models and implement a multi-agent system (MAS). This methodology is independent of any agent’s architecture, programming language, or communication framework. The MaSE’s agents are considered object specializations that instead of simple objects, with methods that can be invoked by other objects, are agents that talk among themselves and act proactively in order to reach goals (MaSE, 2010), (Deloach, 2001). MaSE is a traditional software engineering methodology specialization with two phases (Analysis and Design) and several activities which are shown in Figure 2 (Deloach, 2001). The MaSE Analysis phase has three steps: Capturing Goals, Applying Use Cases, and Refining Roles. The Design phase has four activities: Creating Agent Classes, Constructing Conversations, Assembling Agent Classes and System Design. The highlighted items represent the resulting models of each phase. The first step in MaSE analysis is to capture goals that express what the system is trying to achieve. These goals generally remain stable throughout the rest of the Analysis and Design phases. A decomposition of goals in a hierarchy form is the MaSE goal representation. After the goals were defined, the functional requirements are identified and represented into use cases. Use Cases describe the behaviour of agents for each situation in MAS. In the step Applying Use Cases, situations of the initial requirements are elicited and expressed into Use Cases Diagrams and Descriptions, and UML Sequence Diagrams. The Sequence Diagrams are applied to express the sequences of roles events and they represent the desired system behaviour and its sequences of events. The last step of Analysis phase defines a set of roles (Role Diagram) that can be used to achieve the goals of the system level. A role is an expected abstract description behaviour of each agent that aids in reaching the system goals. These roles are detailed by a series of tasks, which are described by finite-state models (Concurrent Tasks Diagrams). The Role Diagram associates at first the goals to a role by listing them below the role name. Often, these goals are represented by numbers used in the Goal Diagram. Then the Role Diagram is detailed by associating a set of tasks for each role, representing the expected role behaviour. Communications between roles are expressed by the roles’ association and their associate tasks. The tasks definitions are built in Concurrent Tasks Diagrams based on finite automata states. By definition, each task must be executed concurrently, while communicating with other internal or external tasks. A concurrent task is a set of states and transitions. The states represent the internal agent mechanism, while the transitions define tasks communications. Every transition has an origin and a destination state, a trigger, a guard condition and a transmission (Deloach, 2001). In general, the events that are sent as broadcasts or triggers are associated with events sent to work in the same role instance, requiring an internal coordination of each task. The messages representation sent between agents uses two special events: (i) send event that represents the message sent to another agent and is denoted by send (message, agent) and (ii) receive event which defines the message received from another agent denoted by receive (message, agent). The four diagrams proposed in the MaSE Design phase are Agent Classes, Conversations, Agent Architecture and Deployment Diagram. The first step in the design process involves the definition of each agent class in an Agent Class Diagram. The system designer maps each role defined in the Roles Diagram to at least one Agent Class because this guarantees the goals will be implemented in the system and there is at least one agent class responsible for meeting this goal. The agent classes can be thought of as templates defined in terms of the roles they play and as the protocols they use to coordinate with other agents (O’Malley et al., 2001), (Gago, 2008). The next step in the Design phase details the conversations between the agent classes and defines a coordination protocol between two agents. A conversation consists of two Communication Class Diagrams that represent the initiator and the responder. This diagram is a finite state automation defining the conversation states of the two agent classes using a similar syntax of the analysis phase: ``` rec-mess (args1) [cond] / action ^ trans-mess (args2) ``` This syntax defines: “if the message rec-mess is received with the arguments args1 and the condition cond holds, then the method action is called and the message trans-mess is sent with arguments args2. All elements of the transition are optional.” --- Fig. 2. MaSE Methodology Phases (Deloach, 2001) The third step in the Design phase is the definition of the agent architecture that is performed in two steps: (i) definition of the agent architecture and (ii) its components. The designer can choose the agent architecture, such as Belief-Desire-Intention (BDI), Reactive or Knowledge Base (Bryson & Stein, 2001). The last activity in the Design Phase is defining the Deployment Diagram. In MaSE this diagram shows the agents’ number, types and location in the system. The diagram describes a system based on agent classes, and it is very similar to the UML Deployment Diagram. This diagram defines different agents’ configurations and platforms to maximize the processing power and a network bandwidth. MaSE can be developed using the AgenTool (2009) tool created by Air Force Institute of Technology (AFIT). AgenTool helps the system designer to create a series of models, from higher level goals definition to an automatic verification, a semi-automatic generation design and finally code generation. 3. Guardian Angel System Adelfe modelling The Guardian Angel Project (Szolovits, 2004) was proposed as an information system centered on the patient, rather than the service provider. The software agents group explains the name “guardian angels” (GA). This “guardian angels” support functions for the patient’s health, including the patient’s medical considerations, legal and financial information. Each GA is an active process which performs several important functions: (i) verification, interpretation and explanation of patient data collection, relevant facts or medical plans; (ii) recommendations with the acquired experience and patient’s preferences; (iii) feasibility study, regarding the medical effectiveness, diagnostics cost and therapeutic planning; (iv) patient’s health progress monitoring; (v) communications with other service providers software agents; (vi) education, information and support to the patient. All these facilities help to improve the medical diagnosis quality, increases the patient’s commitment and reduces the disease effects and medical errors. The Adelfe Guardian Angel (GA) modelling was developed using the Work Definitions for the early and final requirements, analysis and design, the AMAS Adequacy tool and OpenTool (Adelfe, 2003), (Henderson-Sellers & Giorgini, 2005). The Adelfe models presented in this section were developed by Kano (2007) and they were also improved and presented in Werneck et al. (2007). 3.1 Preliminary requirements The following functional requirements were defined in the preliminary requirements phase: (i) allow the user to make different query to databases; (ii) allow to communicate with others sub-systems connected in the net; (iii) monitor the progress of the patient health conditions and the effect of the treatment; (iv) periodically verify the data integrity to find violations based on the user expectative and collateral effects; (v) expose the collected data from auxiliary bases to user offering a maximal context comprehension to the user involved; (vi) customize services allowing the user objectivity, adequacy and efficiency; (vii) improve education functionalities to the user like access to encyclopaedias and universities researches to find knowledge from their diseases; (viii) provide alert and agenda functions remembering the patients their appointment, dosage and contraindications of medicines; (ix) offer to the patient the possibility to be in contact with support groups, forums and the main medicines laboratories; (x) be able to organize of the illnesses and diseases in a hierarchal structure using decreasing levels of severity, in order to make possible to apply together different techniques to the patients. In this phase, the following non-functional requirements were also defined: (i) to be able to store physical and logical information using an enormous data volume; (ii) to make use of visual, sonorous and touch communication capacity; (iii) the system should be available 24 hours along the 7 days of the week, 365 days per year; (iv) be multi-task and allow to answer to several data request simultaneous at a certain average time; (v) to be conceptually distributed (the small parts inside inhabit all the same environment, however they represent, separately, concepts and well distinct parts); (vi) to allow the sudden appearance and the abrupt disappearance of its components; (vii) to allow the adaptation and evolution of its components. The key words defined in this phase are: Monitoring, GA, Patient, Communication, Health Professional, Insuring, and History Information. One of the GA constraints relates to maintenance routines when the system will not be available. Another restriction is the subnets functionality with which the system interacts. The case of eventual problems in one of these subnets the user will be unable to access them until they become again in operation. 3.2 Final requirements The environment characterization activity (A6) identified the following passive entities: World Wide Web, Library, Hospital Stay, Illness Organism Information, Idiopathic Cause and Therapy. The active entities list are: Patient, Family, Support the Patient Group, Government, Health Plan Insurance, Laboratory, Health Professional, Hospital, Clinic, Pharmaceutical Industry, Ambient Factors and the proper Guardian Angel. The central entity of the Guardian Angel is the Patient that has the ability to activate any events in any circumstance that will be convenient, dynamically interacting with the system. The Family is another entity that can modify the patient treatment routine depending on the treatment results and satisfaction degree, being able to dynamically interact with the system. The Health Professional entity has the power to trace treatment plans, to request examinations and to prescribe medicines, dynamically interacting with the system. The Guardian Angel can be seen as “processing cells” of the system that interact dynamically in accordance with the recurrently perceptions of the environment. This entity was divided in 4 specializations: (i) Analyser - GA directed towards the tasks which require analyses, interpretation and understanding of data in one determined context; (ii) Inspector - GA directed towards the monitoring/inspection of specific states in the system; (iii) Diplomat - GA directed towards the reduction and treatment of Non-Cooperative Situations. The GA Diplomat is responsible for using its "diplomacy" together with a GA Analyser that helps to determine the priorities of the GAs’ execution, and (iv) Worker - the GA worker is the basic processing cell with the physical operations required to modify data/state of the system. The Collaboration Diagrams for passive entities and the Sequence Diagrams for the active entities were built (Kano, 2007) and figure 3 presents an example of Customize Setting to Adapt Treatment to Patient’s Reality. The Guardian Angel system activity of characterizing environment (A6-S3) was classified as: (i) inaccessible because several users can be logged and they can modify data at anytime; (ii) continuous because the users are free to make their own actions; (iii) non-deterministic. because the prescription of a treatment can be different for the same disease in different patients, and (iv) dynamic because the system depends on the environment and that can not be predicted by the system. Fig. 3. Sequence Diagram: Customize Setting to Adapt Treatment to Patient’s Reality (Kano, 2007) Then the use case diagrams were defined and divided in five groups: GA Domain, Patient, Institutions, Administrative and Service. For each group a Use Case Diagram was modeled involving several use cases and then for each Diagram some NCS were identified as shown in Figure 4. 3.3 Analysis In the GA Domain Analysis four new passive entities (Idiopathic Cause, Therapy, Hospital Stay and Disease-Causing Organism) were found and some diagrams and documents developed during previous steps had to be modified. The classes identified in this phase were: User, People, Patient, Family, Health Care Professional, Doctor, Guardian Angel (Analyser, Diplomat, Inspector and Worker), Data Source, Clinic, Insurer, World Wide Web, Library, Government, Laboratory, Pharmacy Industry, Hospital, Patient Support Group, Environmental Factor, Idiopathic Cause, Therapy and Hospital Stay. In the AMAS technology adequacy activity, the GA got the following reply from the tool in relation to the global criterion: "Your application possesses, with a high degree, almost all the characteristics that can justify - without any ambiguity- using AMAS". In the components evaluation the tool reply was: "Even if your application needs using AMAS some of its components must also be designed using this technology. We recommend you to apply as many times as necessary the methodology to specify all those components". The agents identify activity (A12) studied active entities and for each one a form was defined as shown in Table 4. Thus four cooperative agents have been identified. 3.4 Design The Design phase defined the packages and classes by elaborating the classes and collaboration diagrams. No design pattern was applied and the activity A17 of Fast prototype was not realized because the JAVA version of the tool does not work in the project computer because of some incompatibility that we could not fix. Guardian Angel <table> <thead> <tr> <th>Characteristics</th> <th>Details</th> </tr> </thead> <tbody> <tr> <td>Autonomy</td> <td>Has autonomy because can make decisions based only on its knowledge</td> </tr> <tr> <td>Local Goal</td> <td>The local goal is to perform a task that was assigned to it.</td> </tr> <tr> <td>Interactions with other Entities</td> <td>Interact with other Guardian Angels and Patient.</td> </tr> <tr> <td>Environment Partial Overview</td> <td>Limited overview of the system</td> </tr> <tr> <td>Negotiation Abilities</td> <td>Capable to Negotiate with other entities.</td> </tr> <tr> <td>Potential agent</td> <td>An agent in potential according to Adelfe’s definition.</td> </tr> <tr> <td>Dynamic environment</td> <td>Yes – it is not possible to prevent in which circumstances its actions are taken.</td> </tr> <tr> <td>Face NCS</td> <td>Yes - can request a service that is not available</td> </tr> <tr> <td>Treat NCS</td> <td>Yes - For example when a GA does not receive an answer to a feedback request.</td> </tr> </tbody> </table> Table 4. WD4 – Design in Adelfe (Werneck et al., 2007) In the activity A15 the interactions between the agents were studied and for each an AUML Protocol Diagram was defined (an example is shown in figure 5). For each Guardian Angel the abilities, aptitudes, representations and characteristics were identified and also defined the protocols used in A15 activity which will be used by the agents. Finally the NCS in a form (Table 5) were defined. ![Diagram](attachment:image) **Fig. 5. Protocol Diagram of GA (Kano, 2007)** <table> <thead> <tr> <th>Name</th> <th>Permission denied</th> </tr> </thead> <tbody> <tr> <td>State</td> <td>Execute the activity</td> </tr> <tr> <td>Description</td> <td>An agent faces this situation when the activity that it intends to execute cannot be accomplished with the permissions of the user in question</td> </tr> <tr> <td>Conditions</td> <td>User with no knowledge about the system.</td> </tr> <tr> <td>Actions</td> <td>The agent must supply to the user a list of all the users who have connection with this and that they have permission to execute the task.</td> </tr> </tbody> </table> Table 5. The Identification of NCS Form (Kano, 2007) The diagrams in the last activity (A18) were detailed and the dynamic behaviours were also completed by designing the State Chart Diagram where the attributes and methods were specified to express the agents' state, conditions and actions. ### 4. Educ-MAS MaSE modelling The Educ-MAS (Educational Multi-Agent System) is a learning education environment with multi-agents that aims at helping the teaching process on a specific topic. The modelling presented in this chapter was improved from Gago (2008) and Gago et al. (2009). The first step in the MaSE analysis requirements modelling is to define the Goal Hierarchy Diagram. Then the goals are decomposed in sub-goals until they can be expressed as functions as shown in Figure 6. The main goal Promote Individual Learning was structured based on the Intelligent Tutoring Systems classical architecture that considers four models: Pedagogic, Expert, Student and Interface. Each model reflects the ability and the characteristics of the Educational System (Vicari et al., 2003), (Wooldridge & Jennings, 1997): Explore Student, Plan Course, Manage Knowledge and Manage Teaching. The goals are also decomposed into other goals. For example the goal Plan Course was partitioned into two sub-goals (Consult Defined Goals and Define Course Plan) and the sub-goal Define Course Plan has two sub-goals named Define Content of the Modules and Define the Plan Presentation of the Module. Fig. 6. Educ-MAS Goal Diagram adapted from Gago et al (2009) Then the goals and sub-goals were translated into use cases. Figure 7 presents an example of Educ-MAS use case and the respective sequence diagram for the functional requirement Teach Class, its description and also the name of Sequence Diagrams that retracts the scenarios of this use case. The scenarios are Student’s Class, Questions Resolved and Questions Not Resolved. For each one a Sequence Diagram has to be built showing how the system behaves. Figure 8 shows the agent behaviour with the third scenario of the case Teach Class The whole specification of Educ-MAS can be found in Gago (2008). The next activity is to develop a set of roles and tasks showing how the goals are reached based on the Goals, the Use Cases (diagrams and descriptions) and the Sequence Diagrams. Figure 9 represents the Preliminary Role Diagram where the goals were mapped to system roles. For example, the System Administrator role (Fig.9) achieves the goals Explore Student (goal 1.1 in the Goal Diagram), Manage Registration (goal 1.1.1 in the Goal Diagram), Generate Registration (goal 1.1.1.1 in the Goal Diagram), and Monitor (goal 1.1.3 in the Goal Diagram), activities related to student. **Use Cases** - Manage registration - Define Student’s Level - Define lesson plan - Retrieve content of module - Plan class - Teach class - Evaluate the student - Monitor activities of student **Description** **Use case:** Teach class **Agents:** Tutor, Expert, Administrator **Pre-conditions:** 1) There must be a course plan to the student. **Normal flow:** 1) The Tutor asks the Administrator agent to retrieve the course plan, the modules and their content. 2) The Tutor selects and shows the next topic to the student. 3) The student indicates that the topic is finalized, the Tutor goes to step 2. 4) If the topics end up, the Tutor opens concept problem solving session. 5) If the student has a question, the Tutor agent tries to answer it. If the student is not satisfied, the Tutor agent selects another answer with the Expert agent. 6) If the student does not understand the answer, Tutor sends a message to a human teacher responsible for this course. **Alternative flow:** 6) If the student does not understand the answer, Tutor sends a message to a human teacher responsible for this course. ![Fig. 7. Use Case Teach Class adapted from Gago et al (2009)](image1) **Sequence Diagrams** - Student's class - Question resolved - Question opened ![Fig. 8. Question Opened Sequence Diagram adapted from Gago et al (2009)](image2) In the complete Role Diagram the tasks responsible for the roles and the associations among themselves were introduced to reach the responsible goal roles. Continuing the Analysis phase the Concurrence Task diagrams have to be built for each task as shown in Figure 10 for the task Monitor Blackboard. This task is associated to the Expert interface role which is responsible for the goal with the same name. This task monitors the blackboard in order to interface the knowledge base introducing the questions and their contents. In the Design phase the Role Diagram and the Concurrency Task diagrams have to be used to design the individual components of the agent classes as presented in Figure 11. The agent architecture chosen was a simple BDI (Belief-Desire-Intention) agent architecture and Figure 12 presents an example of a Tutor agent class partial structure components. The last step in the Design phase has to develop an overall operational design by designing the Deployment Diagram (Gago et al., 2009). The Tutor, Administrator, Coordinator and Expert Agents are defined in an environment as a system. The Interface (Student Model) starts at the student’s computer while the Database Management and the other part of the system are in network computers. Fig. 11. The Educ-MAS Agent Class Diagram (Gago et al., 2009) Fig. 12. Tutor Agent Class Partial Structure Component (Gago et al., 2009) 5. Conclusions This work is part of a broader project which aims at analysing important aspects of modelling and developing different Multi-Agent Systems using several methodologies. The first system modelled presented was a classical Multi-Agent System case study in a Medical Domain using Adelfe methodology. www.intechopen.com Adelfe is a methodology originated from object orientation based on UML (Rumbaugh et al., 2004) that incorporated AUML (2007) protocols diagram and the development process RUP (Krutchen, 2000). The Adelfe process covers the requirements, analysis and project phases with a well defined process. Adelfe can be a powerful methodology in terms of cooperative agents' concepts centred in Non-Cooperative Situations. This method allows the definition of important agent concepts as autonomy, proactivity and autonomy reason. However, the methodology needs to improve some aspects of characterized environment by adding new diagrams that can model goals, plan and organization. The second Multi-Agent System modelled was a learning education environment in the MaSE that is an object-oriented methodology that supports analysis and design phases using agent-orientated techniques. MaSE can also be considered a powerful methodology in terms of cooperative agents' concepts (definition of autonomy, proactivity and autonomy reason and the agent concepts are centred in the Roles Diagram and in Goal orientation. However, this methodology is not completely defined, especially for the Early Requirements phase it lacks on capturing, understanding and registering terminology. In DiLeo et al. (2002) they propose to integrate ontology representation to MaSE that can solve this weakness. Another point to be improved is related to non-functional requirements that are not mentioned in the methodology and the MaSE protocols representation that is divided into two diagrams so both diagrams have to be seen to understand the agent communications. In the future we are going to compile these experiences from all MAS development and define a knowledge base for an Agent-Oriented Methodology Approach based on the Situation Method Engineering (SME). This knowledge will provide a flexible way of developing a Multi-Agent System using a methodology based on strengths and examples of models of each method fragments and also situations when applying a respective method artefact. 6. Reference A multi-agent system (MAS) is a system composed of multiple interacting intelligent agents. Multi-agent systems can be used to solve problems which are difficult or impossible for an individual agent or monolithic system to solve. Agent systems are open and extensible systems that allow for the deployment of autonomous and proactive software components. Multi-agent systems have been brought up and used in several application domains. How to reference In order to correctly reference this scholarly work, feel free to copy and paste the following: © 2011 The Author(s). Licensee IntechOpen. This chapter is distributed under the terms of the Creative Commons Attribution-NonCommercial-ShareAlike-3.0 License, which permits use, distribution and reproduction for non-commercial purposes, provided the original is properly cited and derivative works building on this content are distributed under the same license.
{"Source-Url": "https://api.intechopen.com/chapter/pdf-download/14487", "len_cl100k_base": 9824, "olmocr-version": "0.1.53", "pdf-total-pages": 23, "total-fallback-pages": 0, "total-input-tokens": 50935, "total-output-tokens": 13207, "length": "2e13", "weborganizer": {"__label__adult": 0.00044608116149902344, "__label__art_design": 0.0007953643798828125, "__label__crime_law": 0.0004897117614746094, "__label__education_jobs": 0.0120849609375, "__label__entertainment": 0.0001304149627685547, "__label__fashion_beauty": 0.00029206275939941406, "__label__finance_business": 0.0007228851318359375, "__label__food_dining": 0.00044417381286621094, "__label__games": 0.0010404586791992188, "__label__hardware": 0.0009708404541015624, "__label__health": 0.0010309219360351562, "__label__history": 0.000701904296875, "__label__home_hobbies": 0.00018656253814697263, "__label__industrial": 0.000705718994140625, "__label__literature": 0.0006875991821289062, "__label__politics": 0.00039005279541015625, "__label__religion": 0.0006117820739746094, "__label__science_tech": 0.1185302734375, "__label__social_life": 0.00022232532501220703, "__label__software": 0.012298583984375, "__label__software_dev": 0.845703125, "__label__sports_fitness": 0.0003707408905029297, "__label__transportation": 0.0007185935974121094, "__label__travel": 0.0003085136413574219}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 52759, 0.04335]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 52759, 0.66968]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 52759, 0.87432]], "google_gemma-3-12b-it_contains_pii": [[0, 629, false], [629, 3185, null], [3185, 6690, null], [6690, 8892, null], [8892, 12321, null], [12321, 15843, null], [15843, 19247, null], [19247, 23006, null], [23006, 24903, null], [24903, 28406, null], [28406, 32128, null], [32128, 34178, null], [34178, 35370, null], [35370, 37050, null], [37050, 39065, null], [39065, 41075, null], [41075, 41812, null], [41812, 42283, null], [42283, 45578, null], [45578, 48793, null], [48793, 51382, null], [51382, 52395, null], [52395, 52759, null]], "google_gemma-3-12b-it_is_public_document": [[0, 629, true], [629, 3185, null], [3185, 6690, null], [6690, 8892, null], [8892, 12321, null], [12321, 15843, null], [15843, 19247, null], [19247, 23006, null], [23006, 24903, null], [24903, 28406, null], [28406, 32128, null], [32128, 34178, null], [34178, 35370, null], [35370, 37050, null], [37050, 39065, null], [39065, 41075, null], [41075, 41812, null], [41812, 42283, null], [42283, 45578, null], [45578, 48793, null], [48793, 51382, null], [51382, 52395, null], [52395, 52759, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 52759, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 52759, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 52759, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 52759, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 52759, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 52759, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 52759, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 52759, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 52759, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 52759, null]], "pdf_page_numbers": [[0, 629, 1], [629, 3185, 2], [3185, 6690, 3], [6690, 8892, 4], [8892, 12321, 5], [12321, 15843, 6], [15843, 19247, 7], [19247, 23006, 8], [23006, 24903, 9], [24903, 28406, 10], [28406, 32128, 11], [32128, 34178, 12], [34178, 35370, 13], [35370, 37050, 14], [37050, 39065, 15], [39065, 41075, 16], [41075, 41812, 17], [41812, 42283, 18], [42283, 45578, 19], [45578, 48793, 20], [48793, 51382, 21], [51382, 52395, 22], [52395, 52759, 23]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 52759, 0.20879]]}
olmocr_science_pdfs
2024-12-11
2024-12-11
748478699420869007f2e0c52902964dc1b28b76
AN ARRAY ASSIGNMENT FOR PROPOSITIONAL DYNAMIC LOGIC by J.A. Makowsky* and M.L. Tiomkin Technical Report #234 March 1982 * The first author was supported by Swiss National Science Foundation Grant No. 82.820.0.80. ABSTRACT We propose an extension of propositional dynamic logic which allows a propositional version of an array assignments. In this logic many notions like equivalence of programs, looping and finitely branching are expressible on a propositional level. In fact we show that the resulting logic is equivalent in expressive power to first order logic augmented by a device to expressive transitive closures. In other words, it is (modulo extra predicate symbols) equivalent to first order dynamic logic. Not surprisingly, therefore, the validity problem for this extension is $\Pi_1$-complete. 1. INTRODUCTION The major issue in logic of programs is finding a language appropriate for reasoning about programs. Usually, we would like a language which is sufficiently powerful to enable one to express in a natural way the kinds of properties one would like to prove about programs, such as correctness, termination, equivalence, various kinds of nontermination, properties of converse programs and many more, yet one would want to focus on logics which are tractable or at least (theoretically) decidable. With that in mind, Fisher and Ladner [FL] introduced propositional dynamic logic (PDL), a logic inspired by model logic. It was shown to have a decision procedure complete in deterministic exponential time and many other decidable properties. Recently various expansions of PDL have been studied. Halpern and Reif [FR] got better decision procedures for deterministic and well-structured programs, and Harel, Pnueli and Stavi [HPS] showed that the border line between decidable and undecidable is very close to PDL by showing that allowing some simple context free programming language rather than regular languages gives us already a \( \Pi_1 \)-complete undecidability. In this paper we study another extension of PDL by adding two propositional versions of 'array assignments'. Not surprisingly this system is far from decidability. On the other hand, we can express in this system almost all properties of programs with unknown structure mentioned before. In fact, in some precise sense, this system embeds first order dynamic logic. In PDL the labelling of states may be very useful for program checking. The unique possibility to do this in PDL is the using of propositional variables. Assignments to propositional variables appear in [MN] in order to express the '*' by 'while'. In their paper they use a 'global assignment' (simultaneously in all states) which does not extend the expressive power by much and is not suited for labelling of states. In this paper we introduce a new kind of atomic programs 'local assignments' which, in the case of first order DL, is similar to array assignment for predicates. Both program types not only map states into states, but rather models into models preserving the domain (the set of states), but changing some predicate (1-st order case) or value of propositional variable respectively. More precisely a global propositional assignment sets the value of some propositional variable (predicate) globally to true or false, whereas local assignment does so only in the current state. Using local and global assignments we can express a lot of readily definable properties of PDL models which are not expressible in PDL such as equivalence of two programs in current state, looping of finitely branching programs, being finitely branching etc. Note that truth of these properties in a state depends only on the states accessible from it. So will be truth of formulas involving global and local assignments. Commonly, all 'programming' notions of PDL must be 'local', i.e. not depending on 'external' states. The authors are very grateful to Professors A. Pnueli (Weizmann Institute, Rehovot) and J. Stavi (Bar-Ilan University, Ramat-Gan) for their fruitful participating in studying the problem. 2. LANGUAGE DEFINITION The language of PDL + GLA (PDL + global and local assignment) is similar to PDL, but we extend it by converse operator $\alpha^-$ for programs (see [Str]) and by new atomic programs for local and global assignment to predicates. We use here $p, q, r$ for predicates (propositional variables) and $\alpha, \beta, \gamma, \ldots$ for program variables. Formally the set of formulas ($\phi, \psi, \ldots$) and program terms ($\alpha, \beta, \gamma, \ldots$) are defined by simultaneous induction as follows: (i) true, false are formulas, (ii) if $p$ — propositional variable, then $p$ is a formula, (iii) if $\phi, \psi$ — formulae, then $\sim\phi, (\phi \& \psi), (\phi \lor \psi), (\phi \rightarrow \psi)$ are formulae, (iv) if $\alpha$ — program variable, then $\alpha$ is a program term, (v) if $\alpha, \beta$ — program terms, $\phi$ — formula, then $(\alpha; \beta), (\alpha \cup \beta), \alpha^*, \alpha^-, \phi?$ are program terms, (vi) if $\alpha$ — program term, $\phi$ — formula, then $<\alpha>\phi, [\alpha]\phi$ are formulae, (vii) if $p$ — propositional variable, then $p:=true, p:=false$ (global assignments), $p+true, p+false$ (local assignments) are program terms. 3. MODELS, SATISFIABILITY IN MODEL For PDL+GLA we use a model definition of PDL. A model is some \[ M = \{M, R_{a_1}, \ldots, R_{a_k}, P_1, \ldots, P_n\} \] where \( M \neq \emptyset \) is a domain (set of states), \[ R_{a_i} \subseteq M^2 \] is an assignment for program variable \( a_i \), and \( P_j \subseteq M \) is an assignment for predicate symbol \( p_j \). Now we define for formula \( \phi \) of PDL+GLA consisting of only program variables \( a_1, \ldots, a_k \) and predicate symbols \( p_1, \ldots, p_n \), model \( M \) and state \( I \in M \) satisfiability of \( \phi \) in \( M \) for state \( I \) \( M \models \phi \) as follows: (i) \( \neg I \models \phi \iff I \models \neg \phi \) (ii) \( \phi \lor \psi \models I \iff \phi \models I \text{ or } \psi \models I \) (iii) \( \chi \land \psi \models I \iff \chi \models I \text{ and } \psi \models I \) \[ M \models [\alpha; \beta] \phi \iff I \models [\alpha][\beta] \phi \] \[ M \models [\alpha \cup \beta] \phi \iff I \models (\langle \alpha \rangle \phi \lor \langle \beta \rangle \phi) \] \[ M \models [\alpha^*] \phi \iff \exists n \geq 0 \ I \models [\alpha] \ldots [\alpha] \phi \] \[ M \models [\alpha^?] \phi \iff \forall J < I,J \in R_{a_i} \text{ and } J \models \phi \] \[ M \models [\alpha_i] \phi \iff \forall J < I,J \in R_{a_i} \text{ if } <J,I> \in R_{a_i} \text{ then } J \models \phi \] \[ M \models \langle \phi \rangle \iff I \models [\phi] \iff I_M \models [\phi] \] \[ M \models \langle \phi \rangle \iff I \models [\phi] \iff I_M \models [\phi] \] \[ M \models \langle \phi \rangle \iff I \models [\phi] \iff I_M \models [\phi] \] \[ M \models \langle \phi \rangle \iff I \models [\phi] \iff I_M \models [\phi] \] \[ M \models \langle \phi \rangle \iff I \models [\phi] \iff I_M \models [\phi] \] \[ M \models \langle \phi \rangle \iff I \models [\phi] \iff I_M \models [\phi] \] where \( M(P | S) \) is the model \( M \) with a set \( S \) instead of \( P \). For converse of the programs which are not program variables, we change all \((a^*)^-\) by \((a^-)^*\), \((a;\beta)^-\) by \((\beta^-;a^-)\), \((a\cup\beta)^-\) by \((a^-\cup\beta^-)\), \(a^-\) by \(a\), \(\phi?^-\) by \(\phi?\), \((p+\text{false})^-\) by \((\neg p;(p+\text{true})\cup\text{true}?))\), \((p+\text{true})^-\) by \((p?;(p+\text{false})\cup\text{true}?))\) and \((p:=S)\) by \(\text{true}?\). **Note:** Here our converse is precise only for the programs without global assignments, but it doesn't matter for our purposes. We really need only a fact, that a relation of such converse is some extension of a converse of a program relation. The problem is that we cannot save a previous value of propositional variable after global assignment to it. 4. EQUVALENCE OF PROGRAMS AS RELATIONS ON STATES First of all note that in PDL program equivalence is not definable because PDL with program equivalence is undecidable. We define for propositional variable \( p \) a program term \( \text{plocltrue} \cdot (p := \text{false}; p := \text{true}) \), which assigns to \( p \) a logical value 'true' in a current state and 'false' in all other states. For the program terms \( \alpha \) and \( \beta \) we want to express in a state \( I \) the following notion: \( \{ J : <I, J> \in R_\alpha \} = \{ J : <I, J> \in R_\beta \} \). We define this as follows: \[ (\alpha \equiv \beta) \quad \text{plocltrue} (\alpha \cdot \text{plocltrue} \cdot \alpha; \beta; p < q) \land (\beta \cdot \text{plocltrue} \cdot \beta; p < q) \] (here \( p \) and \( q \) are different propositional variables which do not appear in \( \alpha, \beta \)). For the proof that it expresses a notion defined above we need only the fact that \( R_\alpha \), \( R_\beta \) are auxiliary extensions of converses of \( R_\alpha \), \( R_\beta \) and don't need a precise notion of converse. 5. SOME INTERESTING NOTIONS OF PROGRAM LOGIC EXPRESSIBLE IN PDL + GLA Here we will write in PDL + GLA some useful definitions of program properties which are not expressible in PDL. P, Q are new propositional variables which don't appear in a (program term). I is a current state a) Unique(a) \[ P \land Q \rightarrow \exists I,J \in E \land R_a \] A result state of a computation from I is uniquely defined. It is not expressible in PDL because by adding to a domain new state J' with the same relations as on J we make a program a not unique in a state I. In spite of this we preserve a satisfiability of every PDL formula in state J. b) FB(a) \[ P \land Q \rightarrow (a \land Q \land P) \rightarrow \exists I,J \in E \land R_a \] Finite - a is finitely branching. It is not expressible in PDL because \( \neg \text{FB}(a) \) holds only in infinite models, whereas for PDL we have always finite model. c) Circle(a) \[ P \land Q \rightarrow \exists I,J \in E \land R_a \] There is a circlic computation of a iterations from a current state. Here we have also a satisfiability of \( ([a^*] \land true) \land \neg \text{Circle}(a) \) only in infinite models. d) Inf(a) \[ \neg \text{FB}(a) \] A is infinitely branching in a current state (see b) above). In all these definitions a may be also auxiliary extension of R\( \alpha \) converse. We can take any such a not consisting of P, Q for a-d). 6. DEFINABILITY OF LOOP(α) Here we wish to define looping of a program consisting of only finitely branching not looping atomic programs (usual case of a program consisting of assignments and tests). We cannot define 'looping' of a program by expression with program variable in dynamic logic, because looping of α depends on syntax of a program term, and not only on Rα (see [MW]), so we define a formula loop(α) by external induction on a term α. For a program variable α or for an assignment we have not looping by our initial assumptions. The unique nontrivial case of induction is loop(α*). We define it as: \[ \text{loop}(α^*) (\langle α^* \rangle \text{loop}(α)) \lor \text{Circle}(α) \lor \text{Inf}(α^*). \] For Circle and Inf we choose new propositional variables which do not appear in α. For a proof see [MW] (1-st order dynamic logic) - if \( \langle α^* \rangle \text{loop}(α) \), then \( \text{loop}(α^*) \), if \([α^*] \sim \text{loop}(α)\), then a tree of α computation is finitely branching, and then \[ \text{loop}(α^*) \leftrightarrow \text{Circle}(α) \lor \text{Inf}(α^*). \] In all definitions above we used a very strange for program logic notion of a program converse α*. Now we will show that this notion is definable, and all our definitions may be done without converse (but with the aid of additional program variables). 7. LOCAL DEFINABILITY OF α− (for α without assignments; we really need converse only on program variables, see Ch. 6) If we have the programs α1, ..., αn and want to express "β ≡ α− in all states accessible from a current state" we can write it as follows: \[ \text{Conv}(\alpha, \beta, \alpha_1, \ldots, \alpha_n) \cdot \left[ (\alpha \cup \beta \cup \alpha_1 \cup \ldots \cup \alpha_n)^* ; \text{Plocttrue}] ([\alpha] < [\beta] \cdot P) \land \right. \] \[ \left. ([\beta] < [\alpha] \cdot P) \right) \Rightarrow " \text{In all accessible from current state by } \alpha, \beta, \alpha_1, \ldots, \alpha_n \text{ states } K, J < K, J > \in R_\alpha \text{ iff } < J, K > \in R_\beta". \] After that we prove that if β is a variable, α does not consist of assignments and does not consist of P, then (i) \[ \vdash \text{Conv}(\alpha, \alpha^-, \alpha_1, \ldots, \alpha_n) \] (ii) For each formula \( \psi(\alpha, \alpha^-, \alpha_1, \ldots, \alpha_n) \), which does not consist of P \[ \vdash \text{Conv}(\alpha, \beta, \alpha_1, \ldots, \alpha_n) \Rightarrow \left( \psi(\alpha, \beta, \alpha_1, \ldots, \alpha_n) \equiv \psi(\alpha, \alpha^-, \alpha_1, \ldots, \alpha_n) \right). \] So, we may use this definition Conv(α, β, α1, ..., αn) for all formulas over α, α1, ..., αn in PDL+GLA (see above a representation of a converse of α by converses of its variables). 8. REPRESENTATION OF NATURAL NUMBERS AND EXPRESSION OF ARITHMETICS RECURSIVELY - (giving $\Delta^1_1$ as a lower bound of complexity of a set of valid formulas). We will write such a formula ($a$ is a program variable): $\text{Nat } (a) \equiv \neg \text{Circle } (a) \land \exists [a^*] \text{ Unique } (a) \Rightarrow \Rightarrow \{J: <I,J> \in R_{a^*}\}$, has a structure of natural numbers with $R_a$ as successor relation. We can also create auxiliary numbers by a program: $N(a,Q) = (\text{Ploctrue; } a^*; Q\text{loctrue; } a^*; P?) -$ where $Q$ will be a random number, and $P$ is a variable for returning to the initial state "zero". Such $Q$ represents a number of iterations of $a$, that we need for reaching true value of $Q$ from the initial state. It may be shown that here we can compute all recursive functions (it is enough to compute "+" and "*"), we can also express quantifications: $\exists n A(n)$ will be translated to $<N(a,Q)> "\text{translation of } A(x)" with $Q$ in a place of $x$". We can also see that a statement $A$ of arithmetics is true iff in PDL+CLA $\models \text{Nat } (a) \supset "\text{translation of } A"$. 9. EQUIVALENCE OF PDL+ GLA TO FIRST ORDER CALCULI WITH TRANSITIVE CLOSURE OPERATOR Here we consider 1-st order predicate calculi with an additional operator of transitive closure: \[ \text{TC } \vec{u} \vec{z} \ (\varphi(\vec{u}, \vec{z}, \ldots)) \ (\vec{x}, \vec{y}) \Rightarrow \] "There is a natural number \( n > 1 \), \( n \) vectors of elements \( \vec{s}^1, \ldots, \vec{s}^n \) such that \( \vec{s}^1 \downarrow \vec{r}, \vec{s}^n \downarrow \vec{r} \) and for every positive \( i < n \) holds \( \varphi(\vec{s}^i, \vec{s}^{i+1}, \ldots) \)." After that we can prove the following: **Proposition 1**: (J. Stavi [1981]). There is recursive embedding of 1-st order calculi with only two-place predicates and transitive closure operator \( \text{TC} \) (PC2 + TC) into our PDL+ GLA with the addition of such program "a", that \( R_\alpha = M^2 \) (there is a computation of "a" from each state to each state). Note, that if we drop "recursive" as a requirement for the embedding then full first order dynamic logic with recursive programs can be embedded into PDL+ GLA using the framework of results of [MPa], [Ma], cf. Section 10. For a proof we construct for a formula \( \varphi \) of PC2 + TC its translation \( \varphi' \) to PDL+ GLA+ \( \{a\} \). We choose for each two-place predicate of \( \varphi \) \( R_1 \) some program variable of PDL \( a_1 \), and for each variable \( x \) of \( \varphi \) a propositional variable \( P_x \) of PDL (before that we change variables in each \( \text{TCu}z(\varphi(\vec{u}, \vec{x}, \ldots))(\vec{x}, \vec{y}) \) in order to have \((\vec{u} \cup \vec{z}) \cap (\vec{x} \cup \vec{y}) = \emptyset \). For a model \( M \) of PC2 + TC we define a model \( M' \) of PDL+GLA+\( \{a\} \) with the same domain, \( (R_1)_M' = (R_1)_M \), and \( (P_x)_M' = \{(x)_M\} \) - an assignment for \( x \) in \( M \). For a variable \( x \) we choose \[ (x)M \in (P)_M \text{ if } (P)_M = 1, \] and choose something for \( x \) in other case, so our \( M \) is not unique. After that for \( \varphi \in \text{Fm (PC2+TC)} \) we define its translation \[ \varphi' \in \text{Fm (PDL+GLA+\{a\})} \text{ by induction on } \varphi: \] (1) \( (R_1(x,y))' \triangleq <a;P_x,?;a_1>_y \) (2) \( (x=y)' \triangleq <a;P_x,?>_y \) (3) \( \neg \varphi' \triangleq \neg(\varphi'), (\varphi \lor \psi)' \triangleq (\varphi') \lor (\psi'), (\varphi \land \psi)' \triangleq (\varphi') \land (\psi') \) (4) \( (\exists x \varphi(x,...))' \triangleq <a;P_{loctrue}>(\varphi(x,...))' - \text{ a satisfiability does not depend on initial value of } P_x \) (5) For \( \forall x \) we only change in (iv) \( \iff \) to \([\] \). (6) \( (TCzu(\psi(z,u,...))(x,y))' \triangleq <z:=x; (u:=?;(\psi(z,u,...))')?;z:=u')^k \) After that we can prove by induction on formula \( \varphi \), that (1) \( M \models \varphi \Rightarrow M' \models \varphi' \) (M model of PC2+TC); (2) if for each \( x \) - free variable of \( \varphi \), \( (P_x)_M = 1 \), then \[ M \models \varphi \Rightarrow M \models \varphi' \text{ (M model of PDL+GLA+\{a\}).} \] And so, if \( \varphi \) - sentence of PC2+TC, we have \[ \text{PC2 + TC} \models \varphi \iff \text{PDL + GLA + \{a\} } \models \varphi' \] Q.E.D. Note: We can express locally a notion of a "common program 'a'". We define for program variables $a, a_1, \ldots, a_n$ and propositional variable $P$: $$\text{COM}(a, a_1, \ldots, a_n) \equiv ((a_1 \cup \ldots \cup a_n) \land \text{Ploctrue};(a_1 \cup \ldots \cup a_n) \land \alpha) <(a)P$$ and prove that if in model $M$ holds $I \models \text{COM}(a, a_1, \ldots, a_n)$ then $${M}^{I \models \text{COM}(a, a_1, \ldots, a_n)}$$ $${M}^{I \models \text{COM}(a, a_1, \ldots, a_n)}$$ is an elementary equivalent submodel of $M$ for formulas on only program variables $a, a_1, \ldots, a_n$, and in this submodel $R_\alpha$ is equal to $R_\alpha$ (see definition of common program 'a' above). So if $\text{PDL+GLA+\{a\}} \models \psi(a, a_1, \ldots, a_n)$ then $\text{PDL+GLA} \models \text{COM}(a, a_1, \ldots, a_n) \models \psi(a|a)$ and trivially if $\text{PDL+GLA} \models \text{COM}(a, a_1, \ldots, a_n) \models \psi(a|a)$ then $\text{PDL+GLA+\{a\}} \models \psi(a, a_1, \ldots, a_n)$ because $\text{PDL+GLA+\{a\}} \models \text{COM}(a, a_1, \ldots, a_n)$. Hence, we have for a sentence $\varphi$ of PC2+TC $$\text{PC2+TC} \models \varphi \iff \text{PDL+GLA} \models \text{COM}(a, a_1, \ldots, a_n) \models \varphi(a|a)$$ - translation from PC2+TC into PDL+GLA, and really in the proposition above it is enough PDL+GLA without "common program" 'a'. Note: We define for program variables $a, a_1, \ldots, a_n$ and propositional variable $P$: $$\text{COM}(a, a_1, \ldots, a_n) \equiv ((a_1 \cup \ldots \cup a_n) \land \text{Ploctrue};(a_1 \cup \ldots \cup a_n) \land \alpha) <(a)P$$ and prove that if in model $M$ holds $I \models \text{COM}(a, a_1, \ldots, a_n)$ then $${M}^{I \models \text{COM}(a, a_1, \ldots, a_n)}$$ is an elementary equivalent submodel of $M$ for formulas on only program variables $a, a_1, \ldots, a_n$, and in this submodel $R_\alpha$ is equal to $R_\alpha$ (see definition of common program 'a' above). So if $\text{PDL+GLA+\{a\}} \models \psi(a, a_1, \ldots, a_n)$ then $\text{PDL+GLA} \models \text{COM}(a, a_1, \ldots, a_n) \models \psi(a|a)$ and trivially if $\text{PDL+GLA} \models \text{COM}(a, a_1, \ldots, a_n) \models \psi(a|a)$ then $\text{PDL+GLA+\{a\}} \models \psi(a, a_1, \ldots, a_n)$ because $\text{PDL+GLA+\{a\}} \models \text{COM}(a, a_1, \ldots, a_n)$. Hence, we have for a sentence $\varphi$ of PC2+TC $$\text{PC2+TC} \models \varphi \iff \text{PDL+GLA} \models \text{COM}(a, a_1, \ldots, a_n) \models \varphi(a|a)$$ - translation from PC2+TC into PDL+GLA, and really in the proposition above it is enough PDL+GLA without "common program" 'a'. Proposition 2: There is recursive embedding of PDL+GLA into PC2+TC. Proof: For each formula \( \phi \) of PDL+GLA we build its translation \( \bar{\phi} \) into PC2+TC with additional predicates \( S(x,y) \) \((y=x+1)\) and \( \text{Mem}_1(s,y), \text{Mem}_2(x,y) \) \((y=(x)_1, y=(x)_2 - \text{pair enumeration})\) and a constant \( x_0 \) (zero). Arithmetics and pair enumeration are finitely axiomatizable in PC2+TC: \[ \forall x \exists ! y \text{Mem}_1(x,y) \& \text{Mem}_2(y,z) \] \[ \text{Right}(S(x,y)) \rightleftharpoons (\forall z \exists ! x \exists ! y \text{Mem}_1(x,z) \& \text{Mem}_2(y,z)) \] \[ \& (\forall xy \exists ! z \text{Mem}_1(x,z) \& \text{Mem}_2(y,z)) \& (\forall x \text{TCuv}(S(u,v))(x_0,x) \Rightarrow \exists ! y S(x,y)) \] \[ \forall xy (\text{TCuv}(S(u,v))(x_0,x) \& S(x,y) \Rightarrow \sim \text{TCuv}(S(u,v))(y,x)) \] In such a system we can also interprete all arithmetics: \[ N(x) \rightleftharpoons \text{TCuv}(S(u,v))(x_0,x) \] \[ \text{Plus}(x,y,z) \rightleftharpoons N(x) \& \text{TCuv}(u_1u_2,v_1v_2)(S(u_1,v_1) \& S(u_2,v_2))(x_0,x;y,z) - x+y=z \] \[ \text{Mult}(x,y,z) \rightleftharpoons N(x) \& \text{TCuv}(u_1u_2,v_1v_2)(S(u_1,v_1) \& \text{Plus}(x,u_2,v_2))(x_0,x_0;y,z) - x\cdot y=z \] and all recursive functions we need. We also define arrays enumeration by pair enumeration. We define \[ \langle x_1, \ldots, x_n \rangle \text{ as } \langle n, \langle \ldots \langle x_1, x_2, x_3 \rangle \ldots \rangle x_n \rangle. \] Here we write \( x = \langle y, z \rangle \) instead of \( \text{Mem}_1(y,x) \& \text{Mem}_2(z,x) \) and arithmetic expressions instead of formulae with \( S \) and \( \text{TC} \). It will be \( \langle x_1, \ldots, x_n, x_{n+1} \rangle = \langle n+1, \langle x_1, \ldots, x_n \rangle, x_{n+1} \rangle \). Then \[ \text{Arrlength}(x, \ell) \rightleftharpoons \exists v \text{TCuv}(y,m;z,n(\exists w z = \langle y, w \rangle \& n=m+1)(v,1;x,\ell)) - x \text{ is an array and } \ell \text{ is its length}. \] \[ \text{Array}(x) \rightleftharpoons \exists \ell x = \langle \ell, y \rangle \& \text{Arrlength}(y, \ell) - x \text{ is array}, \] \[ \text{Length}(x, \ell) \rightleftharpoons \exists y x = \langle \ell, y \rangle \& \text{Arrlength}(y, \ell) - \ell \text{ is a length of } x, \] \[ \text{Member}(x,y,k) \rightleftharpoons \text{Array}(x) \& \exists z \langle z, \ell \rangle \& \exists uv \text{TCuv}(m;v,1),n \] \[ (\exists w. s = \langle t, w \rangle \& N(n) \& m=m+1)(z, \ell; u, k) \& \] \[ \& ((k \geq \ell \& u = \langle v, y \rangle)(v(k+1) = u=y)) - y \text{ is } k\text{-th element of } x, \] \[ \text{Technion - Computer Science Department - Technical Report CS0234 - 1982} \] Cut(x,y,k) \quad Array(x) \& \exists z \& v: x = \langle z, v \rangle \& y = \langle k, v \rangle \& \& TC \ s, m; t, n (\exists w s = \langle t, w \rangle \& n \geq 1 \& m = n+1) (z, \ell; v, k) - - "y is a cutting array of k first elements of x". Now we consider for each propositional variable $P$ of PDL+GLA a predicate $P(x)$ of PC2 and for each program variable $a$ a predicate $R_a(x, y)$ in addition to $S(x)$, $x_0$, Mem_1, Mem_2 and $D(x)$ (the domain of states). In our $\emptyset$ we relativize all variables $x, y, z$ by $D(\cdot)$ and all variables $i, k, \ell, m, n$ by $N(\cdot)$. We define $P_i(x), \Box \phi \psi, \Box \phi, \neg \phi, \neg \neg \phi$. If a program term $\alpha$ consists of atomic programs and tests $\alpha_1, \ldots, \alpha_m,$ it is equivalent to some recursive PR program $\bigcup_{i=1}^{\infty} Q_{i-1}^i, \ldots, Q_{n-1}^i$ - - union of compositions of atomic programs. We consider a recursive function $f_\alpha$, which gives us for a number $i$ and array $\langle k_1^i, \ldots, k_n^i \rangle$. For empty program we shall add to $\alpha_1^i, \ldots, \alpha_m^i$ $\alpha_{m+1}^i \quad$ true? Then $\emptyset(x) \quad \exists y, n(y) = x \& \text{length}(y) = \text{length}(f_\alpha(n)) + 1 \& \& \forall i \leq \text{length}(f_\alpha(n)) \left( \forall a \& f_\alpha^k(n, y, i) \& \phi((y) \text{length}(f_\alpha(n)) + 1(P_j \mid P_j^a(y, f_\alpha(n), \cdot)) \right) (the changing is performed for all $P_j$ from $\alpha$), where $$ \begin{cases} R_{\alpha_k}((y)_i, (y)_{i+1}) & \text{if } \alpha_k \text{ is program variable,} \\ \left( (y)_i = (y)_{i+1} \right) & \text{if } \alpha_k \text{ is assignment; and if } \alpha_k \not= \psi? \end{cases} $$ $P_j^a(y, n, x) : "n belongs to the image of $f_\alpha$, and for each $i$ if $i$ is a last appearance of a code of "$P_j := $" in $n$ and it is $P_j := S$, then if for every $i < k \leq \text{length}(n)$ $(n)_k$ is not $P_j$ or $(y)_k \neq x$, then $S$; for maximal $k$ s.t. $(n)_k$ is $P_j + S_k$ and $(y)_k = x$, $k > i$ we have $S_k$. If there is no appearance of $P_j :=$ in $n$, then if for every $k \leq \text{length}(n)$ $(n)_k$ is not $P_j$ or $(y)_k \neq x$, we have $P(x)$; for maximal $k$ s.t. $(n)_k$ is $P_j + S_k$ and $(y)_k = x$, we have $S_k$. Now we prove: (i) For each model $N = <D, P_1, \ldots, P_k, R_{a_1}, \ldots, R_{a_n}>$ of PDL+GLA we consider such a modification $\bar{N}$ of $N$ — add to $D$ a set of natural numbers. For every new element it will be $\sim P_j(n)$ and $\sim R_j(n, \cdot)$, $\sim R_j(\cdot, n)$; we define a predicate $D(x)$ $x \in D$, a standard predicate $S(x, y) - y = x + 1$ for numbers, and false for others, $x_0 = 0$ and find some pair enumeration $\text{Mem}_1, \text{Mem}_2$, for $\text{DVN}$ — here we use external choice axiom — for $m \geq x_0$, $m^2 = m$. Thus, for a formula $\varphi$ of PDL+GLA we have $$\bar{N} \models \text{Right}(S, x_0, \text{Mem}_1, \text{Mem}_2) \& \exists x D(x)$$ and $$N \models \varphi \Rightarrow \bar{N} \models \forall x (D(x) \Rightarrow \bar{\varphi}(x)).$$ (ii) For a model $M = <D, P_1, \ldots, P_k, R_{a_1}, \ldots, R_{a_n}, S, \text{Mem}_1, \text{Mem}_2>$ of PC2+TC of a signature of $\bar{\varphi}$ we consider a same model for PDL+GLA with a domain $D = \{x : D(x)\}$ and then if $$M \models \text{Right}(S, x_0, \text{Mem}_1, \text{Mem}_2) \& \exists x D(x)$$ then $$M_{\text{PC2+TC}} \models \forall x \bar{\varphi}(x) \Rightarrow M_{\text{PDL+GLA}} \models \varphi$$ so $$\models_{\text{PDL+GLA}} \varphi \Rightarrow \models_{\text{PC2+TC}} (\text{Right}(S, x_0, \text{Mem}_1, \text{Mem}_2) \& \exists x D(x)) \Rightarrow \forall x (D(x) \Rightarrow \bar{\varphi}(x)).$$ Thus, we have a recursive (PR) interpretation of PDL+GLA in PC2+TC, D, S, Mem₁, Mem₂, with 4 new additional predicates. Q.E.D. **Theorem:** PDL+GLA is equivalent in its expressive power to PC2+TC. **Proof:** See Propositions 1 and 2. 10. RELATION TO FIRST ORDER DYNAMIC LOGIC By a classical result in Model Theory [cf. Ma] PC2+TC is not compact, but expressible in \( L^{ck}_{\omega_1 w} \), the recursive infinitary logic, and all non-compact sublogics thereof are equivalent in the following weaker sense: Two logics \( L_1, L_2 \) are \underline{AP-equivalent} if they are intertransmittable via additional predicates. All the first order dynamic logics in [Ma] are AP-equivalent, as is shown in [Ma]. Hence, we have as reformulation of the previous theorem: Theorem: PDL+GLA is AP-equivalent to first order dynamic logic. REFERENCES
{"Source-Url": "http://www.cs.technion.ac.il/users/wwwb/cgi-bin/tr-get.cgi/1982/CS/CS0234.pdf", "len_cl100k_base": 9194, "olmocr-version": "0.1.53", "pdf-total-pages": 21, "total-fallback-pages": 0, "total-input-tokens": 43124, "total-output-tokens": 10907, "length": "2e13", "weborganizer": {"__label__adult": 0.0005702972412109375, "__label__art_design": 0.0005731582641601562, "__label__crime_law": 0.0007510185241699219, "__label__education_jobs": 0.001079559326171875, "__label__entertainment": 0.00016760826110839844, "__label__fashion_beauty": 0.00026702880859375, "__label__finance_business": 0.0005011558532714844, "__label__food_dining": 0.000903606414794922, "__label__games": 0.0010576248168945312, "__label__hardware": 0.0016498565673828125, "__label__health": 0.001399993896484375, "__label__history": 0.0004396438598632813, "__label__home_hobbies": 0.00025582313537597656, "__label__industrial": 0.001148223876953125, "__label__literature": 0.0008306503295898438, "__label__politics": 0.0005517005920410156, "__label__religion": 0.0009007453918457032, "__label__science_tech": 0.2178955078125, "__label__social_life": 0.00016069412231445312, "__label__software": 0.00634002685546875, "__label__software_dev": 0.7607421875, "__label__sports_fitness": 0.0004596710205078125, "__label__transportation": 0.0013093948364257812, "__label__travel": 0.0002732276916503906}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 28823, 0.01545]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 28823, 0.21707]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 28823, 0.73745]], "google_gemma-3-12b-it_contains_pii": [[0, 217, false], [217, 813, null], [813, 2495, null], [2495, 4074, null], [4074, 5284, null], [5284, 7264, null], [7264, 8026, null], [8026, 9138, null], [9138, 10545, null], [10545, 11901, null], [11901, 13275, null], [13275, 14437, null], [14437, 16300, null], [16300, 17651, null], [17651, 20265, null], [20265, 22956, null], [22956, 24737, null], [24737, 26647, null], [26647, 26884, null], [26884, 27480, null], [27480, 28823, null]], "google_gemma-3-12b-it_is_public_document": [[0, 217, true], [217, 813, null], [813, 2495, null], [2495, 4074, null], [4074, 5284, null], [5284, 7264, null], [7264, 8026, null], [8026, 9138, null], [9138, 10545, null], [10545, 11901, null], [11901, 13275, null], [13275, 14437, null], [14437, 16300, null], [16300, 17651, null], [17651, 20265, null], [20265, 22956, null], [22956, 24737, null], [24737, 26647, null], [26647, 26884, null], [26884, 27480, null], [27480, 28823, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 28823, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 28823, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 28823, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 28823, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 28823, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 28823, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 28823, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 28823, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 28823, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 28823, null]], "pdf_page_numbers": [[0, 217, 1], [217, 813, 2], [813, 2495, 3], [2495, 4074, 4], [4074, 5284, 5], [5284, 7264, 6], [7264, 8026, 7], [8026, 9138, 8], [9138, 10545, 9], [10545, 11901, 10], [11901, 13275, 11], [13275, 14437, 12], [14437, 16300, 13], [16300, 17651, 14], [17651, 20265, 15], [20265, 22956, 16], [22956, 24737, 17], [24737, 26647, 18], [26647, 26884, 19], [26884, 27480, 20], [27480, 28823, 21]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 28823, 0.0]]}
olmocr_science_pdfs
2024-12-11
2024-12-11
3f51ba4aeffe6b381306db5bdac8b88943c1d465
A Collaborative Approach to Teaching Software Architecture Arie van Deursen, Maurício Aniche, Joop Aué, Rogier Slag, Michael de Jong, Alex Nederlof, Eric Bouwers Report TUD-SERG-2016-022 A Collaborative Approach to Teaching Software Architecture Arie van Deursen, Maurício Aniche, Joop Aué, Rogier Slag, Michael de Jong, Alex Nederlof, Eric Bouwers Delft University of Technology ABSTRACT Teaching software architecture is hard. The topic is abstract and is best understood by experiencing it, which requires proper scale to fully grasp its complexity. Furthermore, students need to practice both technical and social skills to become good software architects. To overcome these teaching challenges, we developed the Collaborative Software Architecture Course. In this course, participants work together to study and document a large, open source software system of their own choice. In the process, all communication is transparent in order to foster an open learning environment, and the end-result is published as an online book to benefit the larger open source community. We have taught this course during the past four years to classes of 50-100 students each. Our experience suggests that: (1) open source systems can be successfully used to let students gain experience with key software architecture concepts, (2) students are capable of making code contributions to the open source projects, (3) integrators (architects) from open source systems are willing to interact with students about their contributions, (4) working together on a joint book helps teams to look beyond their own work, and study the architectural descriptions produced by the other teams. Keywords software architecture, software engineering education, open learning, collaborative book writing. 1. INTRODUCTION In computer science curricula, software architecture is a key component of a student’s software engineering education. Software architecture refers to the high level structures of a software system, the discipline of creating such structures, and the documentation of these structures [18]. Documenting software architecture facilitates communication between stakeholders, captures early decisions about the high-level design, and allows reuse of design components between projects [18, 8, 2]. To support teaching software architecture, lecturers can choose from a range of text books [2, 18, 4, 21]. Nevertheless, a course on software architecture has to overcome a number of challenges: C1 The theory of software architecture (design principles, tradeoffs, architectural patterns, product lines, etc) is often very abstract and therefore hard for a student to master. C2 The problems of software architecture are only visible at scale, and disappear once small example systems are used. C3 A software architect needs a combination of technical and social skills: software architecture is about communication between stakeholders, and the architect needs to be able to achieve and explain consensus. To address these challenges, we have designed a graduate course on software architecture based on the following principles: P1 Embrace open source: Students pick an open source system of choice and study its architecture. Students use it to learn how to apply architectural theories to realistic systems (C1, C2). P2 Embrace collaboration: Students work in teams of four to study one system in depth (C3). P3 Embrace open learning: Teams share all of their work with other students. Furthermore, students share their main result with the open source community: their architectural description is published as a chapter in an online book resulting from the course (C3). P4 Interact with the architects: Students are required to offer contributions (in the form of GitHub pull requests) to the open source projects, which will expose them to feedback from actual integrators and architects of the open source projects (C1, C2, C3). P5 Combine breadth and depth: Students dive deeply in the system they analyze themselves, and learn broadly from the analyses conducted and presented by other teams (C1, C3). In this paper, we describe the resulting Collaborative Software Architecture Course (CSAC) which has been taught in the past four years (2013-2016) to classes of 50-100 students each. We start the paper by outlining the course objectives and its contents (Section 2). We then present the results of teaching this course, covering course outcomes and student evaluations (Section 3). Furthermore, we describe the resulting book Delft Students on Software Architecture [23], the https://github.com/delftswa2016 GitHub organization, and our 2013 blogpost [22]. we discuss possibilities to the underlying course ideas to other disciplines, as well as additional ideas for further strengthening the course (Section 4). We conclude by summarizing related work and the key contributions of this paper. 2. COURSE DESIGN 2.1 Educational Objectives The Collaborative Software Architecture Course aims at offering students a chance to learn and experience the concepts of designing, modeling, analyzing and evaluating software architectures. In terms of Bloom’s taxonomy [3], the following educational objectives can be distinguished. On the knowledge level, the course aims at enabling students to familiarize themselves with key concepts in software architecture, such as architectural views, perspectives, styles, design principles, software product lines, technical debt, and Conway’s law. On the application level, the course aims at enabling students to apply these theories to concrete, existing systems that are maintained by a team of people and used around the world. On the evaluation level, the course aims at enabling students to assess and discuss the effect of architectural decisions made by (open source) projects. Furthermore, the course aims at enabling students to assess and discuss the relevance of certain architectural theories for a given system. Constraints The course takes 10 weeks and is worth 5 credit points (ECTS), corresponding to 5 \( \times 28 \) = 140 hours of work per student. Each week, there are two lectures of 90 minutes each. The course is a graduate level master course for students who have completed a bachelor in computer science or related field. 2.2 Method In order to achieve its educational objectives, CSAC adopts two central ideas. The first is to let students “adopt” an open source system. They use this system to apply and evaluate architectural theories, thus bridging the knowledge, application, and evaluation levels. To deal with the complexity of realistic systems, students work in teams of four. The second key idea of the course is to open up all communication, so that students can learn as much as possible from each other as well as from the broader open source community. Thus, throughout the course, groups can see the work of other groups, and are encouraged to help each other. Furthermore, results from the course are shared publicly as much as possible, allowing for feedback from and interaction with the broader open source community. On a high level, each week consists of a theoretical lecture that students apply to their own systems in the next week. In this way, each week the students describe certain aspects of the architecture of their system under study, which eventually forms the input for their book chapter. The course follows Nick Rozanski’s and Eoin Woods’ book “Software Systems Architecture: Working With Stakeholders Using Viewpoints and Perspectives” [18]. Based on this book, students conduct, e.g., a stakeholder analysis, and create architectural documentation covering at least a context view, development view, architectural patterns, and an evolution perspective. Furthermore, the course covers selected additional topics in software architecture. In the past years, we have included material on architectural metrics [5], technical debt [12], the use of design sketches for communication [14], and software product lines [1]. For each of these topics, students apply theories presented to their systems under study. The course also includes guest lectures from software architects working in industry. These lectures typically cover the role of the architect in a complex organization. Students usually do not directly apply these lessons from industry to the systems they study; instead, the guest lectures serve to illustrate how the topics covered are relevant outside the scope of open source systems as well. In the following, we present the most important aspects of our methodology, and relate them back to the five principles P1–P5 formulated in the introduction. Group formation and project selection (P1, P2). In the first week of the course, students themselves form groups of 4. We recommend students to form diverse groups so that they can benefit most from their varying cultural and technical backgrounds. In addition, students must choose a project that serves as case study throughout the entire course. Students select a medium to large open source project hosted on GitHub that is still active (developers are working on it every day) and open to external contributions. Such projects typically will have several pull requests from external contributors merged per day. Furthermore, students should be confident that they are able to make a contribution to this project. Although these rules are not strict constraints, each group needs to submit their project for approval. This proposal contains the name of the project, link to the repository, and a paragraph on why they chose this project. Two different teams are not allowed to work on the same project. To help students find a project, we provide a list of the most popular GitHub projects, extracted using GHTorrent [10]. We also suggest systems that we personally believe are interesting (in the 2016 edition, for example, we suggested Ruby on Rails, Tensorflow, or SonicPi). The use of Git and GitHub (P2, P3). Students are required to use Git and GitHub from the start of the course. Even the course contents, schedule, and assignments are made available in a GitHub repository. We set up a dedicated GitHub organization for the course, hosting all repositories used in the course. In the first lecture, we introduce students to Git. We add all students as collaborators to the relevant GitHub repositories. The student repositories are only available to members of the organization, and not to the outside world. Students can choose themselves to make certain results publicly available. After a team chooses their project, we create two repositories: one empty repository to work on the assignments and the book chapter, and a public fork of their chosen project. GitHub’s issues, pull requests, code review comments, milestones, and releases are used for intra and inter-team communication, and for distributing finalized assignments. We highlight the fact that students have access to the repositories of all other teams. We encourage students to take a look at what other students are doing as well as what other teams have done in the past (which was already published in an online book). Students are allowed to “reuse an idea” that belongs to other groups as long as they explicitly mention it in their assignments. Use of Slack for Communication (P2, P3). We introduce Slack2 as a tool for students to communicate among themselves and with the teachers. Within Slack, we used different channels for various course wide discussions, announcements for important messages from the teachers, and to other technical points, such as Git. We also created one channel per group, named after the project studied by that group. We encourage groups to use their channels for all internal group communication, as this enables the teachers to understand their way of working and effort. In case of questions, students can involve teachers (or other students) in their group channel simply by mentioning them in their channel. Again, all student channels are open to all students, allowing students to learn from and help each other. Student presentations (P2, P5). As an exercise in communicating architectural decisions and trade-offs, students present their group’s progress to the full class at two occasions. The first presentation is a project “pitch” around the middle of the course. In the pitch, students should present their project to other students as well as their current findings. Each group has 3 minutes of presentation plus 2 minutes of Q&A from both other students and teachers. The second set of presentations happens at the end of the course. Each group has 15 minutes of presentation plus 10 minutes of questions. In this presentation, groups show all their findings as well as the system contributions they have made throughout the course. All presentations together usually take the entire day (from 9am to 5pm) and may be divided (depending on the number of teams) in two (parallel) sessions. 2.3 Assignments Students face four main assignments which are part of our method as well: 1) applying theory to practice, 2) contributing to the system, 3) integrating their architectural views and perspectives into a single chapter and 4) providing feedback to other students. Applying theory to practice (P5). After each theoretical lecture, students apply what they learned to their system. As an example, one of the first assignments is to conduct a stakeholder analysis: understanding who has an interest in the project, what their interest is, and which possibly conflicting needs exist. To do this, the students follow the approach to identify and engage stakeholders from Rozanski and Woods [18]. They distinguish various stakeholder classes, and recommend looking for stakeholders who are most affected by architectural decisions, such as those who have to use the system, operate or manage it, develop or test it, or pay for it. To find the stakeholders and their architectural concerns, the student teams analyze any information they can find on the web about their project. Besides documentation and mailing lists, this includes an analysis of recent issues and pull requests as posted on GitHub, in order to see what the most pressing concerns of the project at the moment are and which stakeholders play a role in these discussions and the decision to integrate a change [11]. Students deliver the results of their analysis in a readable text file via GitHub, and receive complete feedback (including the grade) from the teachers within one or two weeks after the submission. Thus, students can improve for their next deliverable. Contributing to the system (P1, P4). As a parallel task, students contribute to the system they are analyzing. This helps them in understanding the implications of key architectural decisions, and in establishing contact with the architects and integrators of the system they study. We do not prescribe the number of contributions each team should do. To help students, we teach them how open source development and pull requests work at GitHub. We also suggest to start with something small, such as fixing simple issues or contributing to the documentation. Some open source projects provide explicit open issues that are suitable for newcomers, which also provide a good starting point. Writing a Book Chapter (P3, P5). Inspired by the book series covering the “Architecture of Open Source Applications” [6, 7], the main goal of each team is to compose a chapter describing the architecture of the system they study. At the end of the course, these chapters are bundled into a book [23]. Each group should integrate views, perspectives, assignment results, and their experience in contributing to the system into a single chapter. Each chapter should be around 5000 words, and students are encouraged to include as many diagrams or images as needed. We do not require a prescribed chapter structure, but many teams follow the views and perspectives created in the earlier assignments. The target audience for the chapter are system stakeholders and fellow students. Students can opt to make their chapter public, implying that their chapter should appeal to a wider audience. To control quality, we make it clear to students that chapters will be published only if the group’s chapter grade is higher than 7 (out of 10). To facilitate integrating, sharing, versioning, and reviewing the various chapters and the underlying drafts, all students (and teachers) use Markdown3 for any document they create in the course. This year, we created the final book using Gitbook4, which offers an easy way to generate an online (HTML, EPUB, PDF) book from a GitHub repository containing Markdown sources. Providing feedback to other students (P2, P3). The course embraces collaboration. As one of their assignments, students review a chapter from another group. We take this opportunity to teach students how scientific papers are evaluated and simulate the process with them. Using the conference management system EasyChair5, students identify their conflicts, bid to chapters they are comfortable to review, and submit a full review of the chapter. In the end, each group needs to evaluate their received feedback and improve their chapter accordingly. 2.4 Grading A team grade is based on the following items: 1. Series of intermediate deliverables corresponding to dedicated assignments on, e.g, stakeholder analysis, code metrics, particular views, or design sketches. Each partial result is evaluated using rubrics reflecting content, depth, writing, and originality. We provide the 2016 rubrics in our online appendix [24]. 2. The final report (book chapter) of each team, providing the relevant architectural documentation created by the team, is graded according to the same rubrics. 3. Team presentations that were evaluated by both the teachers and students in the audience (by means of an online questionnaire). The individual grades are additionally based on: 1. The personal reviews to some other group. Students that have been more critical as well as constructive receive more points. 2. Active participation in the lectures. Students consistently asking good questions or initiating useful discussions during the class receive extra points. In addition, we allow students to recommend other students that have done a great job during the lectures. 3https://daringfireball.net/projects/markdown/ 4http://www.gitbook.com/ 5https://easychair.org/ 3. Their workload. Students are required to keep a weekly journal of their activities. In this journal, we expect to see which activities each student performed as well as the amount of time each one required. The effort of each student in a team should amount to the prescribed 140 hours allocated for this course. The latter point implies that all students are required to make a similar time investment in this course, regardless of their background. This reflects the idea that an architect never stops learning. 3. RESULTS OF THE 2016 COURSE We performed a survey with the 104 students of the 2016 edition. As the survey was optional, we obtained 48 answers (response rate of 46%). Students had to answer questions in a Likert scale from 1 (no/I don’t agree at all) to 5 (yes/I completely agree). Thus, whenever we mention that students agree or believe with a statement, it means that more than half of them answered a 4 or a 5 in that question. Due to space constraints, the protocol of the survey as well as full answers and charts can be found in our online appendix [24]. 3.1 Participants’ profile We have a diverse group of students when it comes to their experience. There are both students with and without industry and programming experience. In numbers, 10% of the respondents have less than one year of programming experience, while 45% have 5 or more years of experience. 23% do not have experience in industry, 25% already have more than 3 years of experience. The vast majority (81%) has never contributed to open source before. Half of the students claim to have good knowledge of Git, while the other half believes to know the basics. 3.2 P1: Embrace open source Selecting an appropriate project can be difficult. Nevertheless, more than a half of the students were happy about their choice of open source project. Many said that their projects were “relevant”, “fun”, “interesting”, and “with a welcome community”. This might explain the fact that all students were able to submit at least one pull request to their projects, and two thirds of the participants performed 1 to 3 pull requests. Some students also believe that projects were happy with the achieved results (45.8%) and that the project was open to external contributors (58.3%). 3.3 P2: Embrace collaboration The majority of students affirm they learned much from their own team mates. They provide varying reasons, such as the different levels of experience among team members which fostered discussions, or the learning of technical skills, such as Git and Java, from their peers. We quote a student: “Everyone has something to teach, I was very happy to listen to the constructive criticism of my team mates.” On the other hand, 3 participants did not learn enough (they chose 2 on the scale). One student indicates that there was some friction among the team members, and another complained about a team mate that did not work enough. Concerning collaboration, Slack improves communication among team members, according to 77% of students. In addition, most students (79%) state that Slack helps them to get answers to their questions quickly, from either teachers or fellow students. The usage of Git and GitHub (and its collaborative features such as issues and pull requests) also helps to improve student productivity. Some advantages mentioned by students are that Git and GitHub make it easier for other students to review their work. On the other hand, a few students indicate that more visual (WYSIWYG) document editors, such as Google Documents, can be better for document collaboration as opposed to the combination of Git and Markdown. 3.4 P3: Embrace open learning Most students consider the chapter reviews they received from other students as useful, although 25% thought they were not. Students with positive feedback confirm that reviews helped them to identify flaws as well as to make the document more intuitive and interesting. Some other students indicate that reviews were superficial while others believe that the reviewer did not read the entire text. Interestingly, most students find it useful to write reviews for another groups — and no student disagreed with it at all: “I liked reviewing them, as it gave me the opportunity to see what other groups were doing, and giving me the opportunity to help them out.” Watching presentations about other architectures is also considered useful by a large group of students. Negative points are frequently related to the strict and tight timing (students had 3 minutes to present their work) as well as with the lack of preparation and presentation skills of some groups (to which students had to listen). Publishing a book at the end of the course was well received by the students: 70% of them were very proud of their chapter. In their opinion, it serves as an excellent motivational factor and inspired them to work better: “It’s a must have experience and you learn a lot and it brings responsibility as your work is open and public.” 3.5 P4: Interact with the architects Most students believe that contributing to the project helped them to better understand the system they were analyzing. Only 8 students disagreed. As teachers, we suggest students to submit a pull request before trying to talk/interview the architects. This mostly worked well: 40% of the participants believe this was a good strategy for helping them to get in contact with the senior architects of the project. 3.6 P5: Combine breadth and depth In most lectures, students affirm that they learned much from applying the theoretical concepts to their projects. In Figure 1, we present the results for each theoretical lecture we gave in this edition. The score average is 4 (out of 5), with the exception of the variability topic, for which the median is 3. We highlight a quote from a student: “I learned a lot about how the open source team approach differ problems (technical debt analysis) and how the project interacts with it’s environment and all involved entities around (stakeholder analysis and context view).” On the other hand, some students complained about difficulties in putting the theory to practice. As an example, a student thinks that some concepts are not generalizable, and thus, hard to be applied in their projects: “It was difficult to apply the theory to our project. While I can see its value in other types of projects, it is not generally applicable.” 3.7 Other findings Time spent in the course. Students express that they spent more time in our course when compared to other courses. Only 9% of them spent the required amount of time (140 hours), while 45% spent “a lot more time”. On the other hand, 19% spent around 120 hours (less than required). Points of improvement. Clearly, we can still make improvements to our course. At the end of the survey, we asked students about what we can improve. As an example, some students believe the course could be more technical. Indeed, our textbook treats software architecture in a highly conceptual way: “I was hoping to focus more on architectural aspects of the software than these general exercises that just describe the application in a very broad sense.” 4. DISCUSSION As demonstrated by the above, the current mix of teaching tools and techniques works well for our course on software architecture. As one of our former teaching assistants says: “it is their chance to put hands on real applications that are not greenfield, and learn how real world works”. We believe these ideas could be extended or applied in other contexts in a number of ways: Lectures used is a parameter of the course. The theoretical topics that we present to students during lectures can be replaced by other architectural topics of interest, such as more emphasis on design patterns or system scalability. Mix with industry systems. Although we only made use of open source systems up to now, the course may also use projects from companies (that are most likely to be closed source). This partnership might be good for both students and companies: students can get to know more about the company, and the company can get a complete analysis of its software. On the other hand, teachers and universities have to deal with the arrangements, such as confidentiality agreements. Collaborative book writing and publishing. This feature is clearly not attached to a software architecture course, and can thus easily be applied to any other course. As we presented before, this was one of the points which students were happy and felt motivated about. Gitbook also facilitated the generation of the final book in different versions (PDF, EPUB). Therefore, we suggest other educators to experiment collaborative book writing and publishing in their courses. Contributions to open source. Our students were able to meet real software architects and learn from them. This relationship was initiated by these contributions and the consequent discussions (common in GitHub’s pull requests) with the architects. Thus, this strategy can be used in other related courses where students could benefit from real and more experienced developers, such as software testing courses. 5. RELATED WORK Lago and Van Vliet [13] distinguish two approaches to teaching architecture, one focusing on “programming in the large”, and the other emphasizing the communication aspects of software architecture to a variety of stakeholders. Our course proposes a way to blend these two approaches in a single course. De Boer et al. propose a community of learners approach to teaching software architecture [9]. Students collaborate on the design of a single complex system, and learn from each other. Through its openness, our course also creates a community of learners, yet student teams work on different systems. Pedroni et al. [16] discuss leveraging open source projects to expose students to real life systems. As in our course, they require students to make contributions to open source projects. The course focuses on programming skills as well as on the need to get socially involved with other developers. The authors recommend providing clear instructions on how to contribute – which we indeed cover in the lectures of our course, and which these days are often also provided in contribution guidelines of projects on, e.g., GitHub. Smith et al. [19] discuss challenges and guidelines for selecting open source projects for use in software engineering education. Marmorstein [15] discusses experiences in letting students contribute to open source systems in their class project. GitHub plays a central role in our course: The teams use it to collaborate, to write their book chapter, and to contribute to open source projects. This emerging role of the GitHub platform as a general collaborative tool in education is further discussed by Zagal'sky et al [25]. Our student based book series [23] was directly inspired by the Architecture of Open Source Applications [6, 7] initiated by Brown and Wilson. Based on these books, Robillard and Medvidovic provide an analysis of the dissemination processes in open source architecture [17]. A description of the architectural beauty of open source systems was provided by Spinellis and Gousios [20]. 6. CONCLUSIONS Teaching software architecture should be practical and challenging at the same time. Towards this goal, we propose a course structure that follows five main principles: embrace open source, embrace collaboration, embrace open learning, interact with the architects, and combine breadth and depth. We have applied these ideas in four editions of our Software Architecture course, and students’ feedback have always been positive. In this paper, we report the results of the evaluation with our students in the most recent (2016) edition. Our experience suggests that (1) open source systems can be successfully used to let students gain experience with key software architecture concepts; (2) students are capable of making meaningful code contributions to the open source projects; (3) software architects from open source systems are willing to interact with students about their contributions; (4) working together on a joint book helps teams to look beyond their own work, and study the architectural descriptions produced by the other teams. Thanks to the open nature, results of the course (such as the online book, and contributions to the open source systems made by the students) are available in our online appendix [24]. Based on a blog post covering the first edition of CSAC [22], similar courses have emerged at various universities in Canada, Israel, France, and US. Moreover, we anticipate that our collaborative approach makes sense not only for software architecture courses, but to any other topic in which practice and theory should walk together. Acknowledgments We would like to thank Felienne Hermans and Nicolas Dintzner (TU Delft) for repeatedly offering guest lectures in this course, the various guest speakers from industry and academia, all students participating in the courses, and the open source developers who welcomed our student’s contributions. 7. REFERENCES ### Team Performance (D1.0) <table> <thead> <tr> <th>Rubric</th> <th>0 points</th> <th>1 point</th> <th>2 points</th> <th>3 points</th> </tr> </thead> <tbody> <tr> <td><strong>Use of Issues</strong></td> <td>0 to 2</td> <td>2 to 4</td> <td>5 to 7</td> <td></td> </tr> <tr> <td>(1) All communication via well-structured issues; (2) People respond to issues; (3) Pull requests solve issues; (4) Issues closed after they're done; (5) At least 10 issues; (6) use of task lists in selected issues. (7) Good use of labels; (8) issues assigned</td> <td></td> <td></td> <td></td> <td></td> </tr> <tr> <td><strong>Use of pull requests</strong></td> <td>&gt;= 2</td> <td>&gt;= 5</td> <td></td> <td></td> </tr> <tr> <td>(6) At least 10 merged pull requests (1) All .md via pull requests; (2) PRs are reviewed (majority has &gt;= 1 comment); (3) PRs contain coherent units; (4) PRs are well described; (5) Reference issue; (6) no self merges.</td> <td></td> <td></td> <td></td> <td></td> </tr> <tr> <td><strong>Git branching</strong></td> <td>More than one commit to master</td> <td>1-2 point</td> <td>3-4 points</td> <td></td> </tr> <tr> <td>(2) good handling / avoiding of conflicts; (3) no commits to master; (4) Branches closed; (5) branch names</td> <td></td> <td></td> <td></td> <td></td> </tr> <tr> <td><strong>Git commit messages</strong></td> <td>25% of commits has meaningless message like update foo.md</td> <td>For 50% of commits one of the two points</td> <td>For 50% most recent commits all points</td> <td>For all commits (1) Short title + explanations (2) Commits tell a story.</td> </tr> <tr> <td>(7) Good use of labels; (8) issues assigned</td> <td></td> <td></td> <td></td> <td></td> </tr> <tr> <td><strong>Repo understandability</strong></td> <td></td> <td></td> <td></td> <td></td> </tr> <tr> <td>README.md gives good pointers; issues + PRs give good overview; Repository is well organized</td> <td></td> <td></td> <td></td> <td></td> </tr> <tr> <td><strong>Planning</strong></td> <td>no milestones, but clear issues; or milestone without issues</td> <td>milestone for current deliverable only</td> <td></td> <td></td> </tr> <tr> <td>(0) Compelling, concise and clear. (1) Hours per person + (2) Indication of what has been done. (3) Hours for all weeks. (4) Honest.</td> <td></td> <td></td> <td></td> <td></td> </tr> <tr> <td><strong>Journal</strong></td> <td>1 of 3</td> <td>2 of 3</td> <td></td> <td></td> </tr> <tr> <td>All team members spend &gt;= 14 hours per week and actively participate</td> <td></td> <td></td> <td></td> <td></td> </tr> <tr> <td><strong>Distribution of work</strong></td> <td>&lt; 14h, unequal distribution of work</td> <td>evenly distributed effort, but &lt; 14h</td> <td>All team members spend &gt;= 14 hours per week and actively participate</td> <td>Strong deviations: Ask</td> </tr> <tr> <td><strong>Language/Communication</strong></td> <td>no use of slack</td> <td>poor slack communication</td> <td>Clear, constructive, and understandable communication via github. Grammatically correct sentences with punctuation; they use slack to exchange information</td> <td></td> </tr> <tr> <td><strong>Release</strong></td> <td>just git tag</td> <td>git release + tag</td> <td>git tag + described release + reference to all issues in milestone + files attached + in time</td> <td></td> </tr> <tr> <td><strong>Team Description</strong></td> <td>data missing</td> <td>poor data</td> <td>all data</td> <td>complete with pictures</td> </tr> </tbody> </table> ### Stakeholders (D1.1) | Issue analysis | >= 10 analyzed, but superficially | >= 10 interesting issues analyzed, but superficially | >= 10 rich and diverse issues analyzed; each covered in depth | | PR analysis | >= 10 analyzed, but superficially | >= 10 interesting PRs analyzed, but superficially | >= 10 rich and diverse pull requests analyzed, each covered in depth | | R&W stakeholders identified | Only ones that apply are discussed | all categories of R&W addressed, but superficially | all categories of R&W thoroughly addressed | ### Other stakeholders identified - 1 or 2 described - >= 3 superficially described - >= 3 additional categories meaningfully described, or compelling explanation why this is not needed ### Stakeholder involvement - 1 - 2 - (1) explain what sort of stakeholders are involved, (2) what their interest in the system is, (3) and how they are trying to influence the development of the system, e.g., through Stakeholder power interest grid ### Integrators identified - named - named, and challenges or strategies - (1) integrators named; (2) challenges identified; (3) merge decision strategies named ### Contact persons identified - 1 person - 2 persons - >= 3 persons to be contacted ### Sources used indicated - PRs + issues mentioned, but not more - PRs + issues + some documentation - Clear where "all" information comes from ### Well structured document - Acceptable structure - Well structured, but lengthy. - intro; conclusions; overview of all stakeholders; discussion per stakeholder; tradeoffs. To the point ### Well written document - <= 1 typos per 50 words - <= 1 error per 100 words - <= 1 error per 200 words ### Context View (D1.2) - **Scope / Responsibilities** - Only one mentioned - Scope & responsibilities both mentioned, but superficially - Scope & responsibilities clearly articulated. Perhaps some history? - **External entities** - Some relevant external entities covered - Most relevant external entities covered - Systems, organizations, external data, explicitly listed - **External interfaces** - Some - Most - Interfaces explicitly discussed - **Stakeholders** - Stakeholders are referenced/shown in context view - Context view and stakeholder connections are well explained - **Relevant context diagram** - Acceptable diagram, no explanation - Acceptable diagram, with explanation - Appealing diagram, addresses key entities, explained in text; legend - **Sources used indicated** - Just some url's at the end - PRs + issues + some documentation - Clear where "all" information comes from, in line links - **Well structured document** - Acceptable structure - Well structured, but lengthy. - intro; conclusions; key content properly connected to each other. To the point. - **Well written document** - <= 1 typos per 50 words - <= 1 error per 100 words - <= 1 error per 200 words ### Development View (D2.1) - **Relevant Diagram(s)** - 1 reasonable diagram - 1 good diagram - Illustration with two or more relevant (generated, reused, or self-created documents) - **Component overview / module structure** - Key modules covered, no dependencies - Key modules, superficial dependency analysis - Key modules (or packages, components) covered, their dependencies, and their organization (e.g. layers) ### Common design models Relevant common approaches covered. ### Codeline models / dev process - directory structure shown - discussion of test and dev process. - Mapping of components to code level organization; build and test processes ### Document quality - Acceptable document - Good document - Excellent document: Well structured, sources mentioned, good grammar + spelling ### Technical debt - no contribution files and < 14 hours on average - Amazing contribution file + clear journal + all > 14 hours on average ### D3: Variability Perspective | Identification | just list | list + superficial | 20 features or really good ones and explanation + key characteristics | |----------------|-----------|-------------------|------------------------------------------------|-----------------| | Technical description | (2/3) or superficial | dependencies + conflicts + binding time | Configurability (design patterns, config files) + implementation details | | Implementation strategy | only configurability | | | | FeatureIDE model | Only diagram | Diagram + weak explanation | Diagram + explanation | | Evolution history | 2/3 or superficial | variability mechanism + configurable features + analysis of issues/PRs | | | Document quality | Acceptable document | Good document | Excellent document: Well structured, sources mentioned, good grammar + spelling | ### Contributions <table> <thead> <tr> <th>Quality of the contribution</th> <th>0-2: Nothing useful</th> <th>3-6: Contribution to documentation only</th> <th>7-8: Nice code contribution</th> <th>9-10: Amazing code contribution</th> </tr> </thead> </table> ### Review <table> <thead> <tr> <th>Review</th> <th>0: didn't do it</th> <th>1: did everything</th> </tr> </thead> <tbody> <tr> <td>-1: didn't do it</td> <td>-1: didn't do it</td> <td>1: did everything</td> </tr> </tbody> </table> <table> <thead> <tr> <th>Final chapter</th> </tr> </thead> <tbody> <tr> <td>Improved previous deliverables</td> </tr> <tr> <td>New perspective and viewpoint</td> </tr> <tr> <td>Document quality</td> </tr> <tr> <td>Team performance</td> </tr> <tr> <td>Personal opinion</td> </tr> </tbody> </table> --- TUD-SERG-2016-022 9 Your feedback to the SWA course Background Team name. (Optional. We will not use it to identify you) Choose Your master programme - CS / Software Technology - CS / Data Science - SEPAM - ES - Other: Years of programming experience - Less than 1 year - 1 year - 2 years - 3 years - 4 years - 5 years - 6 years - 7 years - 8 years - 9 years - 10+ years Do you have industry experience? - No, I don't have - For less than 1 year - For 1 year - For 2 years - For 3 years - For 4 years - For 5+ years Have you done any contribution to open source projects before the project? - No, I haven't done any. - Yes, 1 contribution - Yes, 2 contributions - Yes, 3+ contributions What was your level of expertise in Git before the course? - Nothing - 1 - 2 - 3 - 4 - 5 - Guru Compared to other courses, on this course I spent - A lot less time - A little less time - The same amount of time - Somewhat more time - A lot more time In terms of the required 140 hours, I spent - < 100 hours - around 120 hours - around 140 hours - around 160 hours - > 180 hours Any other relevant information about your background? Your answer Your feedback to the SWA course Applying theory to open source projects The underlying learning philosophy of the course is that you can learn about existing theories (views, perspectives, variability, ...) on software architecture by trying to apply them to open source systems. How much did you learn from applying these views and analyses to your open source system? <table> <thead> <tr> <th></th> <th>Useless. Learned nothing from it.</th> <th>Learned something, but not enough given the effort.</th> <th>Neutral. Learned just enough.</th> <th>Good: Useful exercise.</th> <th>Great way to learn about this.</th> </tr> </thead> <tbody> <tr> <td>Stakeholder Analysis</td> <td>☐</td> <td>☐</td> <td>☐</td> <td>☐</td> <td>☐</td> </tr> <tr> <td>Context View</td> <td>☐</td> <td>☐</td> <td>☐</td> <td>☐</td> <td>☐</td> </tr> <tr> <td>GitHub Issue Analysis</td> <td>☐</td> <td>☐</td> <td>☐</td> <td>☐</td> <td>☐</td> </tr> <tr> <td>Development View</td> <td>☐</td> <td>☐</td> <td>☐</td> <td>☐</td> <td>☐</td> </tr> <tr> <td>Technical Debt Analysis</td> <td>☐</td> <td>☐</td> <td>☐</td> <td>☐</td> <td>☐</td> </tr> <tr> <td>Variability Analysis</td> <td>☐</td> <td>☐</td> <td>☐</td> <td>☐</td> <td>☐</td> </tr> </tbody> </table> Please provide some explanation of your answers Your answer The book by Rozanski & Woods was 1 2 3 4 5 Hopeless ☐ ☐ ☐ ☐ ☐ Great Your feedback to the SWA course Your Project I was happy with the choice of my open source project 1 2 3 4 5 No, not at all Yes, very much Please explain your answer Your answer How many pull requests did you do for your project? 1 2 3 4 5 6 7 8 9 10 How many contributions were eventually merged? 1 2 3 4 5 6 7 8 9 10 Did being forced to contribute help you better understand the system you were analyzing? 1 2 3 4 5 Not at all Yes, very much Trying to make contributions is best described by: (you can tick multiple answers) - The project did not care about our work - The project was happy with our results - The project was open to external contributors - The project was too complex to contribute to in a course like this - We only managed to do simple / superficial changes (1 or 2 lines in documentation) - We provided meaningful contributions to the project - Making a PR helped us interact with senior developers - Other: Never submit passwords through Google Forms. Your feedback to the SWA course Learning from others How useful were the chapter reviews you received from other students? 1 2 3 4 5 Not useful ○ ○ ○ ○ ○ Very useful Please explain your answer. Your answer Did you find writing a chapter review for your peer students useful? 1 2 3 4 5 Not at all ○ ○ ○ ○ ○ Very much Please explain your answer Your answer How useful were the teams' presentations? 1 2 3 4 5 Not useful ○ ○ ○ ○ ○ Very useful What was the best and the worst thing about the team presentations? Your answer How much did you learn from your own team mates? 1 2 3 4 5 Nothing ○ ○ ○ ○ ○ A lot! Please explain your answer Your answer Maintaining a journal was A waste of time ○ ○ ○ ○ ○ A good way to reflect on what we did Your feedback to the SWA course Guest lectures How much did you learn from the guest lectures? 1 2 3 4 5 6 7 8 9 10 Nothing at all ○ ○ ○ ○ ○ ○ ○ ○ ○ Very much In your opinion, what are the advantages of having guest lectures? And the disadvantages? Your answer What was the most interesting thing that you learned from the guest speakers? Your answer Google Forms Your feedback to the SWA course Using GitHub Did you think the use of Git, Github and Github flow (pull requests, issues, ...) to work on your chapters improved your productivity? 1 2 3 4 5 I don't think so 〇 〇 〇 〇 〇 I completely think so What were the advantages of using Git and Github? And the disadvantages? Your answer How much did you learn about Git during the course? 1 2 3 4 5 Nothing at all 〇 〇 〇 〇 〇 Everything I currently know Do you think using Markdown to write the chapters helped? Why? Why not? Your answer Never submit passwords through Google Forms. A Collaborative Approach to Teaching Software Architecture Google Forms Your feedback to the SWA course Using slack Did you think the usage of Slack increased the communication with your peers and colleagues? 1 2 3 4 5 It didn't increase ○ ○ ○ ○ ○ It increased very much Do you think Slack helped you to get your questions answered quickly? 1 2 3 4 5 I don't agree ○ ○ ○ ○ ○ I very much agree What were the advantages of using Slack? And the disadvantages? Your answer BACK NEXT Never submit passwords through Google Forms. This content is neither created nor endorsed by Google. Report Abuse - Terms of Service - Additional Terms Google Forms Your feedback to the SWA course Publishing a book How did you like the idea of publishing your work as a book? 1 2 3 4 5 Didn't like it at all ○ ○ ○ ○ ○ I liked it very much In terms of learning, do you see any advantages or disadvantages of publishing the chapters as a book? Your answer How proud are you about your chapter? 1 2 3 4 5 Not proud at all ○ ○ ○ ○ ○ Very proud Were you happy about the final book? 1 2 3 4 5 Not happy at all ○ ○ ○ ○ ○ Very happy Never submit passwords through Google Forms. Your feedback to the SWA course Final thoughts In general, did you like the course? [ ] 1 2 3 4 5 6 7 8 9 10 Not at all [ ] [ ] [ ] [ ] [ ] [ ] [ ] [ ] Very much How likely is it that you would recommend this course to a friend or a colleague? [ ] 1 2 3 4 5 6 7 8 9 10 Not at all likely [ ] [ ] [ ] [ ] [ ] [ ] [ ] [ ] Extremely likely What did you like the most in the course? Your answer What did you dislike the most in the course? Your answer How can we improve the course for the next year? Your answer Please leave your final thoughts. Anything that you want to share and we did not ask! Your answer Can we interview you about your answers? If so, leave us your e-mail. Your answer BACK SUBMIT Never submit passwords through Google Forms. This content is neither created nor endorsed by Google. Report Abuse - Terms of Service - Additional Terms Google Forms
{"Source-Url": "https://pure.tudelft.nl/portal/files/11926392/TUD_SERG_2016_022.pdf", "len_cl100k_base": 10911, "olmocr-version": "0.1.53", "pdf-total-pages": 33, "total-fallback-pages": 0, "total-input-tokens": 65324, "total-output-tokens": 13360, "length": "2e13", "weborganizer": {"__label__adult": 0.0011472702026367188, "__label__art_design": 0.0030307769775390625, "__label__crime_law": 0.0008540153503417969, "__label__education_jobs": 0.1766357421875, "__label__entertainment": 0.00030517578125, "__label__fashion_beauty": 0.0006594657897949219, "__label__finance_business": 0.0010480880737304688, "__label__food_dining": 0.001148223876953125, "__label__games": 0.0020313262939453125, "__label__hardware": 0.001209259033203125, "__label__health": 0.001155853271484375, "__label__history": 0.000988006591796875, "__label__home_hobbies": 0.00036025047302246094, "__label__industrial": 0.0008692741394042969, "__label__literature": 0.00116729736328125, "__label__politics": 0.0008912086486816406, "__label__religion": 0.0015134811401367188, "__label__science_tech": 0.009307861328125, "__label__social_life": 0.0004916191101074219, "__label__software": 0.00939178466796875, "__label__software_dev": 0.78271484375, "__label__sports_fitness": 0.0011301040649414062, "__label__transportation": 0.0012826919555664062, "__label__travel": 0.0006422996520996094}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 53582, 0.04527]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 53582, 0.23847]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 53582, 0.93645]], "google_gemma-3-12b-it_contains_pii": [[0, 0, null], [0, 189, false], [189, 189, null], [189, 4669, null], [4669, 11865, null], [11865, 18562, null], [18562, 24870, null], [24870, 29833, null], [29833, 36209, null], [36209, 40086, null], [40086, 42878, null], [42878, 45483, null], [45483, 45686, null], [45686, 45986, null], [45986, 46542, null], [46542, 46609, null], [46609, 48769, null], [48769, 48769, null], [48769, 49228, null], [49228, 49762, null], [49762, 50246, null], [50246, 50546, null], [50546, 50938, null], [50938, 51516, null], [51516, 51589, null], [51589, 52174, null], [52174, 52695, null], [52695, 52695, null], [52695, 53314, null], [53314, 53582, null], [53582, 53582, null], [53582, 53582, null], [53582, 53582, null]], "google_gemma-3-12b-it_is_public_document": [[0, 0, null], [0, 189, true], [189, 189, null], [189, 4669, null], [4669, 11865, null], [11865, 18562, null], [18562, 24870, null], [24870, 29833, null], [29833, 36209, null], [36209, 40086, null], [40086, 42878, null], [42878, 45483, null], [45483, 45686, null], [45686, 45986, null], [45986, 46542, null], [46542, 46609, null], [46609, 48769, null], [48769, 48769, null], [48769, 49228, null], [49228, 49762, null], [49762, 50246, null], [50246, 50546, null], [50546, 50938, null], [50938, 51516, null], [51516, 51589, null], [51589, 52174, null], [52174, 52695, null], [52695, 52695, null], [52695, 53314, null], [53314, 53582, null], [53582, 53582, null], [53582, 53582, null], [53582, 53582, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 53582, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 53582, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 53582, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 53582, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 53582, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 53582, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 53582, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 53582, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 53582, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 53582, null]], "pdf_page_numbers": [[0, 0, 1], [0, 189, 2], [189, 189, 3], [189, 4669, 4], [4669, 11865, 5], [11865, 18562, 6], [18562, 24870, 7], [24870, 29833, 8], [29833, 36209, 9], [36209, 40086, 10], [40086, 42878, 11], [42878, 45483, 12], [45483, 45686, 13], [45686, 45986, 14], [45986, 46542, 15], [46542, 46609, 16], [46609, 48769, 17], [48769, 48769, 18], [48769, 49228, 19], [49228, 49762, 20], [49762, 50246, 21], [50246, 50546, 22], [50546, 50938, 23], [50938, 51516, 24], [51516, 51589, 25], [51589, 52174, 26], [52174, 52695, 27], [52695, 52695, 28], [52695, 53314, 29], [53314, 53582, 30], [53582, 53582, 31], [53582, 53582, 32], [53582, 53582, 33]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 53582, 0.10246]]}
olmocr_science_pdfs
2024-12-06
2024-12-06
9497c40530016d5df960a6c19908a35f5cdafdb1
[REMOVED]
{"Source-Url": "http://web.cse.ohio-state.edu/~weide.1/rsrg/documents/2012/12TZW.pdf", "len_cl100k_base": 9543, "olmocr-version": "0.1.50", "pdf-total-pages": 15, "total-fallback-pages": 0, "total-input-tokens": 42988, "total-output-tokens": 11634, "length": "2e13", "weborganizer": {"__label__adult": 0.00033211708068847656, "__label__art_design": 0.0002918243408203125, "__label__crime_law": 0.0003819465637207031, "__label__education_jobs": 0.0007295608520507812, "__label__entertainment": 6.222724914550781e-05, "__label__fashion_beauty": 0.000156402587890625, "__label__finance_business": 0.00021016597747802737, "__label__food_dining": 0.0003809928894042969, "__label__games": 0.00052642822265625, "__label__hardware": 0.0007801055908203125, "__label__health": 0.0006117820739746094, "__label__history": 0.0002005100250244141, "__label__home_hobbies": 9.012222290039062e-05, "__label__industrial": 0.0003719329833984375, "__label__literature": 0.0002963542938232422, "__label__politics": 0.0002474784851074219, "__label__religion": 0.0004489421844482422, "__label__science_tech": 0.0302734375, "__label__social_life": 8.988380432128906e-05, "__label__software": 0.0059967041015625, "__label__software_dev": 0.95654296875, "__label__sports_fitness": 0.0003311634063720703, "__label__transportation": 0.0005202293395996094, "__label__travel": 0.0001829862594604492}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 43439, 0.03481]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 43439, 0.47334]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 43439, 0.88106]], "google_gemma-3-12b-it_contains_pii": [[0, 2470, false], [2470, 4374, null], [4374, 7729, null], [7729, 11024, null], [11024, 14224, null], [14224, 17568, null], [17568, 20553, null], [20553, 23699, null], [23699, 26224, null], [26224, 29464, null], [29464, 32059, null], [32059, 34664, null], [34664, 38303, null], [38303, 41272, null], [41272, 43439, null]], "google_gemma-3-12b-it_is_public_document": [[0, 2470, true], [2470, 4374, null], [4374, 7729, null], [7729, 11024, null], [11024, 14224, null], [14224, 17568, null], [17568, 20553, null], [20553, 23699, null], [23699, 26224, null], [26224, 29464, null], [29464, 32059, null], [32059, 34664, null], [34664, 38303, null], [38303, 41272, null], [41272, 43439, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 43439, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 43439, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 43439, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 43439, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 43439, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 43439, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 43439, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 43439, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 43439, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 43439, null]], "pdf_page_numbers": [[0, 2470, 1], [2470, 4374, 2], [4374, 7729, 3], [7729, 11024, 4], [11024, 14224, 5], [14224, 17568, 6], [17568, 20553, 7], [20553, 23699, 8], [23699, 26224, 9], [26224, 29464, 10], [29464, 32059, 11], [32059, 34664, 12], [34664, 38303, 13], [38303, 41272, 14], [41272, 43439, 15]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 43439, 0.05282]]}
olmocr_science_pdfs
2024-12-01
2024-12-01